@nexus-cross/crossx-sdk-core 1.0.5 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ts=Object.defineProperty;var As=(r,e,s)=>e in r?Ts(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var v=(r,e,s)=>As(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Rs=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.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.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.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(g||{});class _ extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,_.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const je={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Os=Object.fromEntries(Object.entries(je).map(([r,e])=>[r,e.caipId])),Cs=new Map(Object.values(je).map(r=>[r.caipId,r]));new Map(Object.values(je).map(r=>[r.chainId,r]));const ks={symbol:"",decimals:18};function Ye(r){var e;return((e=Cs.get(r))==null?void 0:e.nativeCurrency)??ks}class Kt{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new _(g.NOT_IMPLEMENTED,`${e} is not yet supported. Use sdk.signMessage() directly.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new _(g.NOT_IMPLEMENTED,`${e} is not yet supported. Use sdk.signTypedData() or sdk.signTypedDataOffchain() directly.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...s))}_caip2ToHex(e){const s=e.split(":");return`0x${parseInt(s[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let we=null;function wt(r){we=r}const f={log(...r){if(we){we.log(...r);return}},warn(...r){if(we){we.warn(...r);return}},error(...r){if(we){we.error(...r);return}}},Ze="crossx_access_token",Ne="crossx_refresh_token",Pe="crossx_user_info";class Ns{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,s){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new _(g.AUTH_FAILED,`${s} failed (code ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const n=t;if(n.code&&n.code!==200&&n.code>0)throw new _(g.AUTH_FAILED,`${s} failed (code ${n.code}): ${n.message}`)}}async execute(e){var n,o,i,a;let s,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:p}=this.config,m=`${d}${l}`;f.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인):`,m);const x=await this.oauth.openAuth({authUrl:m,expectedOrigin:new URL(d).origin});f.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",x.length,")");const{accessToken:w,refreshToken:b}=await this.exchangeFirebaseToken(x,p);let S,E;try{const B=this.crypto.decodeJWT(x);E=(n=B.firebase)==null?void 0:n.sign_in_provider;const D=((o=B.firebase)==null?void 0:o.identities)??{};E==="google.com"?S=(i=D["google.com"])==null?void 0:i[0]:E==="apple.com"&&(S=(a=D["apple.com"])==null?void 0:a[0]),f.log("[CROSSx] OAuth provider sub 추출 — provider:",E,"hasProviderSub:",!!S)}catch{f.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(w){const B=this.crypto.decodeJWT(w);f.log("[CROSSx] access_token 디코딩 — sub:",B.sub,"exp:",B.exp);const D=await this.crypto.verifyJWT(w);if(t=D.signatureVerified??!1,!D.valid)throw f.error("[CROSSx] access_token 검증 실패"),new Error("Invalid access token");const M=D.payload;s={id:M.sub,email:M.email,signInProvider:E,providerSub:S},this.tokenStore.set(w),this.useCookieAuth||(await this.storage.set(Ze,w),b&&await this.storage.set(Ne,b))}else{const B=this.crypto.decodeJWT(x);s={id:B.sub,email:B.email,signInProvider:E,providerSub:S},f.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}f.log("[CROSSx] 사용자 정보 — id:",s.id);const q=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Pe,q),f.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return f.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return f.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,t)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;f.log("[CROSSx] Firebase 토큰 교환 요청:",n);const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});f.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return f.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new _(g.AUTH_FAILED,"access_token not found in exchange response");f.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(Pe);if(n)return f.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){f.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(Ze),n=await this.storage.get(Ne);if(f.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return f.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);f.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(Pe);if(f.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;f.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return f.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return f.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(Ne),await this.storage.remove(Pe),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,o={};if(!t){const l=this.tokenStore.get()??"";l&&(o.access_token=l),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});f.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){f.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new _(g.AUTH_FAILED,"Silent refresh failed: no token in response");if(this.tokenStore.set(c),!t){await this.storage.set(Ze,c);const l=this.extractRefreshToken(a);l&&await this.storage.set(Ne,l)}return f.log("[CROSSx] silentRefresh 성공"),c}async loadWallet(e,s){let t,n=!1;try{f.log("[CROSSx][Migration Phase 2] POST /mnemonic/create 호출 — userId:",e.id),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,f.log("[CROSSx][Migration Phase 2] 지갑 로드 완료 (기존 백업 없음) — address:",t)}catch(o){if(o instanceof _&&o.code===g.MIGRATION_BACKUP_EXISTS)f.log("[CROSSx][Migration Phase 2] Gateway -10012 감지 → needsMigration = true"),n=!0;else{if(o instanceof _&&(o.code===g.PROJECT_NOT_REGISTERED||o.code===g.PROJECT_ID_MISSING||o.code===g.ORIGIN_NOT_ALLOWED))throw f.error("[CROSSx][Migration Phase 2] 프로젝트 설정 에러:",o.message),o;f.warn("[CROSSx][Migration Phase 2] 지갑 로드 실패 (로그인은 유지):",o)}}return f.log("[CROSSx][Migration Phase 2] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}}const Ps="crossx_access_token",Ls="crossx_refresh_token",Ds="crossx_user_info";class $s{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(Ps),await this.storage.remove(Ls)),await this.storage.remove(Ds)}}class Ms{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new _(g.NOT_IMPLEMENTED,"Migration is not supported in the current environment");f.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return f.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Bs{constructor(e,s){this.chainRegistry=e,this.transport=s}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:s,id:Date.now()},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new _(g.UNKNOWN_ERROR,`RPC error [${e}] (${t}): ${a.error.message} (code: ${a.error.code})`);return a==null?void 0:a.result}}class Us{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}const Ue={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}},Fs="/crossx.config.json";function yt(r){const e=r.environment;return e&&e in Ue?Ue[e]:null}async function Hs(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=yt(r);if(e)return e}}catch{}try{const r=await fetch(Fs);if(r.ok){const e=await r.json(),s=yt(e);if(s)return s}}catch{}return Ue.production}const Gs=2e3,bt=6e4,qs=1e3,Ws=1e4,js="0x77359400",vt="0x3B9ACA00",St=130,Et=6,It=18,Vs=0,Ks=30*1e3,X=class X extends Us{constructor(e,s,t,n,o,i,a,c,l,d){super(),this.storage=t,this.crypto=n,this.transport=o,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._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&wt(e.logger),this.confirmation=l,this.chainRegistry=d,this.jsonRpc=new Bs(d,o),this.signInUseCase=new Ns(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new $s(this.internalConfig,t,c),this.migrateWalletUseCase=new Ms(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.0.5 initializing...");try{const e=await Hs();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();return s!=null&&s.success&&this.applyAuthResult(s),this.initialized=!0,this.emit("initialized",{restored:!!(s!=null&&s.success)}),s??null}catch(e){throw new _(g.AUTH_NOT_INITIALIZED,"SDK initialization failed",e)}}async signIn(e){this.ensureInitialized();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 _(g.AUTH_FAILED,"Sign in failed",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};if(s.needsMigration||!s.address){const{address:o}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:t}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new _(g.UNKNOWN_ERROR,"Sign out failed",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();return e!=null&&e.success?(this.applyAuthResult(e),!0):!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.emit("addressChanged",{address:s.address,index:0}),f.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof _?s:new _(g.MIGRATION_FAILED,"Wallet migration failed",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");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(){return this.ensureAuthenticated(),this.userId?this.walletProvider.getAddresses(this.userId):[]}async selectWallet(){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const e=await this.walletProvider.getAddresses(this.userId);return this.confirmation.showWalletSelector(e,async()=>{const s=e.length,n={address:(await this.walletProvider.getAddress(this.userId,s)).address,index:s};return e.push(n),n})}async selectWalletIfMultiple(e){if(e.length<2)return null;const s=await this.selectWallet();return s&&(this.address=s.address,this.emit("addressChanged",{address:s.address,index:s.index})),s}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof _?e:new _(g.UNKNOWN_ERROR,"Failed to fetch chains",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof _?s:new _(g.CHAIN_NOT_SUPPORTED,`Failed to fetch chain: ${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)}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");f.log("[CROSSx] 지갑 생성 시작");try{const e=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=e.address,this.emit("addressChanged",{address:e.address,index:0}),f.log("[CROSSx] 지갑 생성 완료:",e.address),{address:e.address}}catch(e){if(e instanceof _&&e.code===g.MIGRATION_BACKUP_EXISTS){const s=this.providerSub??this.userId;f.log("[CROSSx][Migration Phase 3] createWallet() — Gateway -10012 감지, 마이그레이션 UI 시작 — migrationSub:",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 _(g.MIGRATION_FAILED,"Migration skipped by user")}throw e}}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=t==null?void 0:t.index,o=await this.walletProvider.getAddress(this.userId,n??0);let i;if(this.walletProvider.prepare&&(i=(await this.walletProvider.prepare("sign-message",{message:s,from:o.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:o.address,message:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(g.USER_REJECTED,"User rejected message signing");try{const c=await this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,i,o.address);return this.verifySignatureSigner(s,c.signature,o.address),{chainId:e,signature:c.signature,message:s,address:o.address}}catch(c){throw c instanceof _?c:new _(g.SIGNATURE_FAILED,`Message signing failed (${e})`,c)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");if(!this.walletProvider.signTypedData)throw new _(g.NOT_IMPLEMENTED,"signTypedData is not implemented");X.validateTypedDataChainId(e,s);const n=await this.walletProvider.getAddress(this.userId,(t==null?void 0:t.index)??0);let o;if(this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(g.USER_REJECTED,"User rejected typed data signing");try{const a=await this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address);return X.validateSignatureFormat(a.signature),{chainId:e,signature:a.signature,address:n.address}}catch(a){throw a instanceof _?a:new _(g.SIGNATURE_FAILED,`Typed data signing failed (${e})`,a)}}async signTypedDataOffchain(e,s){return this.signTypedData(X.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=await this.withResolvedGasAndFee(s,e);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign",{tx:n})).uuid);const i=Ye(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(g.USER_REJECTED,"User rejected transaction signing");try{const c=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o);return X.validateSignedTxFormat(c.signature),{chainId:e,signedTx:c.signature,txHash:c.txHash??""}}catch(c){if(c instanceof _)throw c;const l=c instanceof Error?c.message:String(c);throw new _(g.SIGNATURE_FAILED,`Transaction signing failed (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=await this.withResolvedGasAndFee(s,e);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("send",{tx:n})).uuid);const i=Ye(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(g.USER_REJECTED,"User rejected transaction");try{let c;if(this.walletProvider.sendTransaction)c=(await this.walletProvider.sendTransaction(this.userId,e,n,o)).txHash;else{const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o);c=l.txHash??l.signature}return{chainId:e,txHash:c,status:"pending"}}catch(c){const l=c instanceof Error?c.message:String(c);throw new _(g.TRANSACTION_FAILED,`Transaction failed (${e}): ${l}`,c)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??qs,o=Ws,i=t.timeoutMs??bt,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,o)}throw new _(g.UNKNOWN_ERROR,`Transaction receipt timeout (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var b,S;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((b=this._config.receiptPolling)==null?void 0:b.intervalMs)??Gs,l=o??((S=this._config.receiptPolling)==null?void 0:S.timeoutMs)??bt,d=Ye(e),p=s.from??"";let m,x;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(E=>{m=E;const q=BigInt(E.gasUsed)*BigInt(E.effectiveGasPrice),B=s.value?BigInt(s.value):0n,D=X.formatTxAmount(s.value,d.symbol,d.decimals),M=X.formatTxAmount("0x"+q.toString(16),d.symbol,d.decimals),Q=X.formatTxAmount("0x"+(B+q).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:E.from,to:E.to??s.to,amount:D,fees:M,total:Q,nativeSymbol:d.symbol,status:E.status==="0x1"?"success":"reverted"}}).catch(E=>(x=E instanceof Error?E:new Error(String(E)),{chainId:e,txHash:a,from:p,to:s.to,amount:X.formatTxAmount(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:s.to},w),x)throw x;return{chainId:e,txHash:a,receipt:m}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(g.GAS_ESTIMATION_FAILED,`Failed to get gas price (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const o=n instanceof Error?n.message:String(n);throw new _(g.GAS_ESTIMATION_FAILED,`Failed to estimate gas (${s}): ${o}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(g.GAS_ESTIMATION_FAILED,`Failed to get baseFeePerGas (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(g.GAS_ESTIMATION_FAILED,`Failed to get maxPriorityFeePerGas (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(g.UNKNOWN_ERROR,`Failed to get nonce: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:X.formatWei(n),chainId:e}}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(g.UNKNOWN_ERROR,`Failed to get balance (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt(It),n=s/t,i=(s%t).toString().padStart(It,"0").replace(/0+$/,"").slice(0,Et);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Kt(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof _)throw n;const o=n instanceof Error?n.message:String(n);throw new _(g.UNKNOWN_ERROR,`walletRpc failed [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const o=10n**BigInt(t),i=n/o,c=(n%o).toString().padStart(t,"0").slice(0,Et).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){f.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(f.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return f.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0;for(;;){n++,f.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n})`,t?`— 이전 에러: ${t}`:"");const o=await this.confirmation.showPinInputPrompt(t);if(o===null)return f.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;f.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${o.length}자리), Gateway 마이그레이션 API 호출`);try{const i=await this.migrateWalletUseCase.execute(o,e);return f.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",i.address),i}catch(i){if(i instanceof _&&i.code===g.MIGRATION_FAILED){f.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 #${n}) — 재시도 요청`),t="Incorrect PIN. Please try again.";continue}throw f.error("[CROSSx][Migration Phase 4] 마이그레이션 실패 (복구 불가):",i),i}}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e};if(n){const l=c.from??this.address;if(l){f.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),f.log("[CROSSx] nonce 결과:",c.nonce)}}if(o&&(f.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),f.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){f.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=vt;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,f.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=js,f.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=vt,f.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=X.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new _(g.TYPED_DATA_CHAIN_ID_MISMATCH,`Off-chain signing (chainId=0) requires typedData.domain.chainId to be absent or 0, got ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new _(g.TYPED_DATA_CHAIN_ID_MISMATCH,`On-chain signing (${e}) requires typedData.domain.chainId to be present`);if(t!==o)throw new _(g.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t}) does not match chainId (${e}, expected ${o})`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new _(g.SIGNATURE_FAILED,"Invalid signature: not a valid hex string");if(s.length!==St)throw new _(g.SIGNATURE_FAILED,`Invalid signature length: expected ${St} hex chars (65 bytes), got ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new _(g.SIGNATURE_FAILED,"Invalid signedTx: not a valid hex string");if(s.length<2)throw new _(g.SIGNATURE_FAILED,"Invalid signedTx: too short")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw f.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new _(g.SIGNATURE_SIGNER_MISMATCH,`Signature signer mismatch: expected ${t}, recovered ${n}`);f.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof _)throw n;f.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var s,t,n,o;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=X.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}ensureInitialized(){if(!this.initialized)throw new _(g.AUTH_NOT_INITIALIZED,"SDK is not initialized. Call initialize() first.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new _(g.AUTH_NOT_AUTHENTICATED,"Not authenticated. Call signIn() first.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.initialized=!1,this.removeAllListeners(),wt(null)}};X.OFFCHAIN_CHAIN_ID="0";let Fe=X;class zs{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw f.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 f.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw f.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw f.error("Storage clear error:",e),e}}}const Ys="crossx-sdk",Zs=1,Se="data",Le="keys",Tt="aes-primary",Xs=12;class At{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(Ys,Zs);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Se)||n.createObjectStore(Se),n.objectStoreNames.contains(Le)||n.createObjectStore(Le)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Le,Tt);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Le,Tt,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(Xs);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(Se,e,n)}catch(t){throw f.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 f.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Se,e)}catch(s){throw f.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Se)}catch(e){throw f.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 at(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ue(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=at(r),n=r==null?void 0:r.length,o=e!==void 0;if(!t||o&&n!==e){const i=s&&`"${s}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function zt(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ue(r.outputLen),ue(r.blockLen)}function Ie(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 Yt(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 Js(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 Xe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function oe(r,e){return r<<32-e|r>>>e}const Qs=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function er(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function tr(r){for(let e=0;e<r.length;e++)r[e]=er(r[e]);return r}const Rt=Qs?r=>r:tr,Zt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",sr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ke(r){if(F(r),Zt)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=sr[r[s]];return e}const ce={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ot(r){if(r>=ce._0&&r<=ce._9)return r-ce._0;if(r>=ce.A&&r<=ce.F)return r-(ce.A-10);if(r>=ce.a&&r<=ce.f)return r-(ce.a-10)}function He(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Zt)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,o=0;n<s;n++,o+=2){const i=Ot(r.charCodeAt(o)),a=Ot(r.charCodeAt(o+1));if(i===void 0||a===void 0){const c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function _e(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];F(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const o=r[t];s.set(o,n),n+=o.length}return s}function Xt(r,e={}){const s=(n,o)=>r(o).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function Jt(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 rr=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function nr(r,e,s){return r&e^~r&s}function or(r,e,s){return r&e^r&s^e&s}class ir{constructor(e,s,t,n){v(this,"blockLen");v(this,"outputLen");v(this,"padOffset");v(this,"isLE");v(this,"buffer");v(this,"view");v(this,"finished",!1);v(this,"length",0);v(this,"pos",0);v(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Xe(this.buffer)}update(e){Ie(this),F(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=Xe(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ie(this),Yt(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Te(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let p=i;p<n;p++)s[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=Xe(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 p=0;p<l;p++)a.setUint32(4*p,d[p],o)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const fe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),De=BigInt(2**32-1),Ct=BigInt(32);function ar(r,e=!1){return e?{h:Number(r&De),l:Number(r>>Ct&De)}:{h:Number(r>>Ct&De)|0,l:Number(r&De)|0}}function cr(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let o=0;o<s;o++){const{h:i,l:a}=ar(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const lr=(r,e,s)=>r<<s|e>>>32-s,dr=(r,e,s)=>e<<s|r>>>32-s,ur=(r,e,s)=>e<<s-32|r>>>64-s,hr=(r,e,s)=>r<<s-32|e>>>64-s,fr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),pe=new Uint32Array(64);class pr extends ir{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,s,t,n,o,i,a,c]}set(e,s,t,n,o,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,s){for(let p=0;p<16;p++,s+=4)pe[p]=e.getUint32(s,!1);for(let p=16;p<64;p++){const m=pe[p-15],x=pe[p-2],w=oe(m,7)^oe(m,18)^m>>>3,b=oe(x,17)^oe(x,19)^x>>>10;pe[p]=b+pe[p-7]+w+pe[p-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let p=0;p<64;p++){const m=oe(a,6)^oe(a,11)^oe(a,25),x=d+m+nr(a,c,l)+fr[p]+pe[p]|0,b=(oe(t,2)^oe(t,13)^oe(t,22))+or(t,n,o)|0;d=l,l=c,c=a,a=i+x|0,i=o,o=n,n=t,t=x+b|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,o,i,a,c,l,d)}roundClean(){Te(pe)}destroy(){this.set(0,0,0,0,0,0,0,0),Te(this.buffer)}}class gr extends pr{constructor(){super(32);v(this,"A",fe[0]|0);v(this,"B",fe[1]|0);v(this,"C",fe[2]|0);v(this,"D",fe[3]|0);v(this,"E",fe[4]|0);v(this,"F",fe[5]|0);v(this,"G",fe[6]|0);v(this,"H",fe[7]|0)}}const _r=Xt(()=>new gr,rr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ct=BigInt(0),rt=BigInt(1);function Ge(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Qt(r){if(typeof r=="bigint"){if(!Be(r))throw new Error("positive bigint expected, got "+r)}else ue(r);return r}function $e(r){const e=Qt(r).toString(16);return e.length&1?"0"+e:e}function es(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ct:BigInt("0x"+r)}function Ve(r){return es(ke(r))}function ts(r){return es(ke(xr(F(r)).reverse()))}function lt(r,e){ue(e),r=Qt(r);const s=He(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function ss(r,e){return lt(r,e).reverse()}function xr(r){return Uint8Array.from(r)}const Be=r=>typeof r=="bigint"&&ct<=r;function mr(r,e,s){return Be(r)&&Be(e)&&Be(s)&&e<=r&&r<s}function wr(r,e,s,t){if(!mr(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function yr(r){let e;for(e=0;r>ct;r>>=rt,e+=1);return e}const dt=r=>(rt<<BigInt(r))-rt;function br(r,e,s){if(ue(r,"hashLen"),ue(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=S=>new Uint8Array(S),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const p=()=>{c.fill(1),l.fill(0),d=0},m=(...S)=>s(l,_e(c,...S)),x=(S=n)=>{l=m(o,S),c=m(),S.length!==0&&(l=m(i,S),c=m())},w=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let S=0;const E=[];for(;S<e;){c=m();const q=c.slice();E.push(q),S+=c.length}return _e(...E)};return(S,E)=>{p(),x(S);let q;for(;!(q=E(w()));)x();return p(),q}}function ut(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(o,i,a){const c=r[o];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}const n=(o,i)=>Object.entries(o).forEach(([a,c])=>t(a,c,i));n(e,!1),n(s,!0)}function kt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const J=BigInt(0),z=BigInt(1),ye=BigInt(2),rs=BigInt(3),ns=BigInt(4),os=BigInt(5),vr=BigInt(7),is=BigInt(8),Sr=BigInt(9),as=BigInt(16);function re(r,e){const s=r%e;return s>=J?s:e+s}function se(r,e,s){let t=r;for(;e-- >J;)t*=t,t%=s;return t}function Nt(r,e){if(r===J)throw new Error("invert: expected non-zero number");if(e<=J)throw new Error("invert: expected positive modulus, got "+e);let s=re(r,e),t=e,n=J,o=z;for(;s!==J;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==z)throw new Error("invert: does not exist");return re(n,e)}function ht(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function cs(r,e){const s=(r.ORDER+z)/ns,t=r.pow(e,s);return ht(r,t,e),t}function Er(r,e){const s=(r.ORDER-os)/is,t=r.mul(e,ye),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,ye),n),a=r.mul(o,r.sub(i,r.ONE));return ht(r,a,e),a}function Ir(r){const e=Ke(r),s=ls(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+vr)/as;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const p=a.mul(l,n),m=a.mul(l,o),x=a.eql(a.sqr(d),c),w=a.eql(a.sqr(p),c);l=a.cmov(l,d,x),d=a.cmov(m,p,w);const b=a.eql(a.sqr(d),c),S=a.cmov(l,d,b);return ht(a,S,c),S}}function ls(r){if(r<rs)throw new Error("sqrt is not defined for small field");let e=r-z,s=0;for(;e%ye===J;)e/=ye,s++;let t=ye;const n=Ke(r);for(;Pt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return cs;let o=n.pow(t,e);const i=(e+z)/ye;return function(c,l){if(c.is0(l))return l;if(Pt(c,l)!==1)throw new Error("Cannot find square root");let d=s,p=c.mul(c.ONE,o),m=c.pow(l,e),x=c.pow(l,i);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let w=1,b=c.sqr(m);for(;!c.eql(b,c.ONE);)if(w++,b=c.sqr(b),w===d)throw new Error("Cannot find square root");const S=z<<BigInt(d-w-1),E=c.pow(p,S);d=w,p=c.sqr(E),m=c.mul(m,p),x=c.mul(x,E)}return x}}function Tr(r){return r%ns===rs?cs:r%is===os?Er:r%as===Sr?Ir(r):ls(r)}const Ar=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Ar.reduce((t,n)=>(t[n]="function",t),e);return ut(r,s),r}function Or(r,e,s){if(s<J)throw new Error("invalid exponent, negatives unsupported");if(s===J)return r.ONE;if(s===z)return e;let t=r.ONE,n=e;for(;s>J;)s&z&&(t=r.mul(t,n)),n=r.sqr(n),s>>=z;return t}function ds(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),o),t}function Pt(r,e){const s=(r.ORDER-z)/ye,t=r.pow(e,s),n=r.eql(t,r.ONE),o=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function Cr(r,e){e!==void 0&&ue(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class kr{constructor(e,s={}){v(this,"ORDER");v(this,"BITS");v(this,"BYTES");v(this,"isLE");v(this,"ZERO",J);v(this,"ONE",z);v(this,"_lengths");v(this,"_sqrt");v(this,"_mod");var i;if(e<=J)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=Cr(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return J<=e&&e<this.ORDER}is0(e){return e===J}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&z)===z}neg(e){return re(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return re(e*e,this.ORDER)}add(e,s){return re(e+s,this.ORDER)}sub(e,s){return re(e-s,this.ORDER)}mul(e,s){return re(e*s,this.ORDER)}pow(e,s){return Or(this,e,s)}div(e,s){return re(e*Nt(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 Nt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Tr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?ss(e,this.BYTES):lt(e,this.BYTES)}fromBytes(e,s=!1){F(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?ts(e):Ve(e);if(a&&(c=re(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ds(this,e)}cmov(e,s,t){return t?s:e}}function Ke(r,e={}){return new kr(r,e)}function us(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 hs(r){const e=us(r);return e+Math.ceil(e/2)}function Nr(r,e,s=!1){F(r);const t=r.length,n=us(e),o=hs(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?ts(r):Ve(r),a=re(i,e-z)+z;return s?ss(a,n):lt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ae=BigInt(0),be=BigInt(1);function qe(r,e){const s=e.negate();return r?s:e}function Lt(r,e){const s=ds(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function fs(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Je(r,e){fs(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=dt(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function Dt(r,e,s){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=s;let a=Number(r&n),c=r>>i;a>t&&(a-=o,c+=be);const l=e*t,d=l+Math.abs(a)-1,p=a===0,m=a<0,x=e%2!==0;return{nextN:c,offset:d,isZero:p,isNeg:m,isNegF:x,offsetF:l}}const Qe=new WeakMap,ps=new WeakMap;function et(r){return ps.get(r)||1}function $t(r){if(r!==Ae)throw new Error("invalid wNAF")}class Pr{constructor(e,s){v(this,"BASE");v(this,"ZERO");v(this,"Fn");v(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>Ae;)s&be&&(t=t.add(n)),n=n.double(),s>>=be;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=Je(s,this.bits),o=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=Je(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:p,isNegF:m,offsetF:x}=Dt(t,a,i);t=c,d?o=o.add(qe(m,s[x])):n=n.add(qe(p,s[l]))}return $t(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=Je(e,this.bits);for(let i=0;i<o.windows&&t!==Ae;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Dt(t,i,o);if(t=a,!l){const p=s[c];n=n.add(d?p.negate():p)}}return $t(t),n}getPrecomputes(e,s,t){let n=Qe.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),Qe.set(s,n))),n}cached(e,s,t){const n=et(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=et(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){fs(s,this.bits),ps.set(e,s),Qe.delete(e)}hasCache(e){return et(e)!==1}}function Lr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>Ae||t>Ae;)s&be&&(o=o.add(n)),t&be&&(i=i.add(n)),n=n.double(),s>>=be,t>>=be;return{p1:o,p2:i}}function Mt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Rr(e),e}else return Ke(r,{isLE:s})}function Dr(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>Ae))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Mt(e.p,s.Fp,t),o=Mt(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}function $r(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class gs{constructor(e,s){v(this,"oHash");v(this,"iHash");v(this,"blockLen");v(this,"outputLen");v(this,"finished",!1);v(this,"destroyed",!1);if(zt(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,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Te(n)}update(e){return Ie(this),this.iHash.update(e),this}digestInto(e){Ie(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:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const _s=(r,e,s)=>new gs(r,e).update(s).digest();_s.create=(r,e)=>new gs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Bt=(r,e)=>(r+(r>=0?e:-e)/xs)/e;function Mr(r,e,s){const[[t,n],[o,i]]=e,a=Bt(i*r,s),c=Bt(-n*r,s);let l=r-a*t-c*o,d=-a*n-c*i;const p=l<le,m=d<le;p&&(l=-l),m&&(d=-d);const x=dt(Math.ceil(yr(s)/2))+Ee;if(l<le||l>=x||d<le||d>=x)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:p,k1:l,k2neg:m,k2:d}}function nt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function tt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return Ge(s.lowS,"lowS"),Ge(s.prehash,"prehash"),s.format!==void 0&&nt(s.format),s}class Br extends Error{constructor(e=""){super(e)}}const ge={Err:Br,_tlv:{encode:(r,e)=>{const{Err:s}=ge;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=$e(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?$e(n.length/2|128):"";return $e(r)+o+n+e},decode(r,e){const{Err:s}=ge;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=ge;if(r<le)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}=ge;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 Ve(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=ge,n=F(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=ge,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},le=BigInt(0),Ee=BigInt(1),xs=BigInt(2),Me=BigInt(3),Ur=BigInt(4);function Fr(r,e={}){const s=Dr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;ut(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=ws(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(P,u,h){const{x:y,y:T}=u.toAffine(),R=t.toBytes(y);if(Ge(h,"isCompressed"),h){d();const A=!t.isOdd(T);return _e(ms(A),R)}else return _e(Uint8Array.of(4),R,t.toBytes(T))}function m(P){F(P,void 0,"Point");const{publicKey:u,publicKeyUncompressed:h}=l,y=P.length,T=P[0],R=P.subarray(1);if(y===u&&(T===2||T===3)){const A=t.fromBytes(R);if(!t.isValid(A))throw new Error("bad point: is not on curve, wrong x");const O=b(A);let I;try{I=t.sqrt(O)}catch(W){const U=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+U)}d();const C=t.isOdd(I);return(T&1)===1!==C&&(I=t.neg(I)),{x:A,y:I}}else if(y===h&&T===4){const A=t.BYTES,O=t.fromBytes(R.subarray(0,A)),I=t.fromBytes(R.subarray(A,A*2));if(!S(O,I))throw new Error("bad point: is not on curve");return{x:O,y:I}}else throw new Error(`bad point: got length ${y}, expected compressed=${u} or uncompressed=${h}`)}const x=e.toBytes||p,w=e.fromBytes||m;function b(P){const u=t.sqr(P),h=t.mul(u,P);return t.add(t.add(h,t.mul(P,o.a)),o.b)}function S(P,u){const h=t.sqr(u),y=b(P);return t.eql(h,y)}if(!S(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const E=t.mul(t.pow(o.a,Me),Ur),q=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(E,q)))throw new Error("bad curve params: a or b");function B(P,u,h=!1){if(!t.isValid(u)||h&&t.is0(u))throw new Error(`bad point coordinate ${P}`);return u}function D(P){if(!(P instanceof Z))throw new Error("Weierstrass Point expected")}function M(P){if(!c||!c.basises)throw new Error("no endo");return Mr(P,c.basises,n.ORDER)}const Q=kt((P,u)=>{const{X:h,Y:y,Z:T}=P;if(t.eql(T,t.ONE))return{x:h,y};const R=P.is0();u==null&&(u=R?t.ONE:t.inv(T));const A=t.mul(h,u),O=t.mul(y,u),I=t.mul(T,u);if(R)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:A,y:O}}),ve=kt(P=>{if(P.is0()){if(e.allowInfinityPoint&&!t.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:u,y:h}=P.toAffine();if(!t.isValid(u)||!t.isValid(h))throw new Error("bad point: x or y not field elements");if(!S(u,h))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function he(P,u,h,y,T){return h=new Z(t.mul(h.X,P),h.Y,h.Z),u=qe(y,u),h=qe(T,h),u.add(h)}const L=class L{constructor(u,h,y){v(this,"X");v(this,"Y");v(this,"Z");this.X=B("x",u),this.Y=B("y",h,!0),this.Z=B("z",y),Object.freeze(this)}static CURVE(){return o}static fromAffine(u){const{x:h,y}=u||{};if(!u||!t.isValid(h)||!t.isValid(y))throw new Error("invalid affine point");if(u instanceof L)throw new Error("projective point not allowed");return t.is0(h)&&t.is0(y)?L.ZERO:new L(h,y,t.ONE)}static fromBytes(u){const h=L.fromAffine(w(F(u,void 0,"point")));return h.assertValidity(),h}static fromHex(u){return L.fromBytes(He(u))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(u=8,h=!0){return ne.createCache(this,u),h||this.multiply(Me),this}assertValidity(){ve(this)}hasEvenY(){const{y:u}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(u)}equals(u){D(u);const{X:h,Y:y,Z:T}=this,{X:R,Y:A,Z:O}=u,I=t.eql(t.mul(h,O),t.mul(R,T)),C=t.eql(t.mul(y,O),t.mul(A,T));return I&&C}negate(){return new L(this.X,t.neg(this.Y),this.Z)}double(){const{a:u,b:h}=o,y=t.mul(h,Me),{X:T,Y:R,Z:A}=this;let O=t.ZERO,I=t.ZERO,C=t.ZERO,N=t.mul(T,T),W=t.mul(R,R),U=t.mul(A,A),k=t.mul(T,R);return k=t.add(k,k),C=t.mul(T,A),C=t.add(C,C),O=t.mul(u,C),I=t.mul(y,U),I=t.add(O,I),O=t.sub(W,I),I=t.add(W,I),I=t.mul(O,I),O=t.mul(k,O),C=t.mul(y,C),U=t.mul(u,U),k=t.sub(N,U),k=t.mul(u,k),k=t.add(k,C),C=t.add(N,N),N=t.add(C,N),N=t.add(N,U),N=t.mul(N,k),I=t.add(I,N),U=t.mul(R,A),U=t.add(U,U),N=t.mul(U,k),O=t.sub(O,N),C=t.mul(U,W),C=t.add(C,C),C=t.add(C,C),new L(O,I,C)}add(u){D(u);const{X:h,Y:y,Z:T}=this,{X:R,Y:A,Z:O}=u;let I=t.ZERO,C=t.ZERO,N=t.ZERO;const W=o.a,U=t.mul(o.b,Me);let k=t.mul(h,R),j=t.mul(y,A),V=t.mul(T,O),ee=t.add(h,y),H=t.add(R,A);ee=t.mul(ee,H),H=t.add(k,j),ee=t.sub(ee,H),H=t.add(h,T);let K=t.add(R,O);return H=t.mul(H,K),K=t.add(k,V),H=t.sub(H,K),K=t.add(y,T),I=t.add(A,O),K=t.mul(K,I),I=t.add(j,V),K=t.sub(K,I),N=t.mul(W,H),I=t.mul(U,V),N=t.add(I,N),I=t.sub(j,N),N=t.add(j,N),C=t.mul(I,N),j=t.add(k,k),j=t.add(j,k),V=t.mul(W,V),H=t.mul(U,H),j=t.add(j,V),V=t.sub(k,V),V=t.mul(W,V),H=t.add(H,V),k=t.mul(j,H),C=t.add(C,k),k=t.mul(K,H),I=t.mul(ee,I),I=t.sub(I,k),k=t.mul(ee,j),N=t.mul(K,N),N=t.add(N,k),new L(I,C,N)}subtract(u){return this.add(u.negate())}is0(){return this.equals(L.ZERO)}multiply(u){const{endo:h}=e;if(!n.isValidNot0(u))throw new Error("invalid scalar: out of range");let y,T;const R=A=>ne.cached(this,A,O=>Lt(L,O));if(h){const{k1neg:A,k1:O,k2neg:I,k2:C}=M(u),{p:N,f:W}=R(O),{p:U,f:k}=R(C);T=W.add(k),y=he(h.beta,N,U,A,I)}else{const{p:A,f:O}=R(u);y=A,T=O}return Lt(L,[y,T])[0]}multiplyUnsafe(u){const{endo:h}=e,y=this;if(!n.isValid(u))throw new Error("invalid scalar: out of range");if(u===le||y.is0())return L.ZERO;if(u===Ee)return y;if(ne.hasCache(this))return this.multiply(u);if(h){const{k1neg:T,k1:R,k2neg:A,k2:O}=M(u),{p1:I,p2:C}=Lr(L,y,R,O);return he(h.beta,I,C,T,A)}else return ne.unsafe(y,u)}toAffine(u){return Q(this,u)}isTorsionFree(){const{isTorsionFree:u}=e;return i===Ee?!0:u?u(L,this):ne.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:u}=e;return i===Ee?this:u?u(L,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(u=!0){return Ge(u,"isCompressed"),this.assertValidity(),x(L,this,u)}toHex(u=!0){return ke(this.toBytes(u))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};v(L,"BASE",new L(o.Gx,o.Gy,t.ONE)),v(L,"ZERO",new L(t.ZERO,t.ONE,t.ZERO)),v(L,"Fp",t),v(L,"Fn",n);let Z=L;const xe=n.BITS,ne=new Pr(Z,e.endo?Math.ceil(xe/2):xe);return Z.BASE.precompute(8),Z}function ms(r){return Uint8Array.of(r?2:3)}function ws(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Hr(r,e={}){const{Fn:s}=r,t=e.randomBytes||Jt,n=Object.assign(ws(r.Fp,s),{seed:hs(s.ORDER)});function o(x){try{const w=s.fromBytes(x);return s.isValidNot0(w)}catch{return!1}}function i(x,w){const{publicKey:b,publicKeyUncompressed:S}=n;try{const E=x.length;return w===!0&&E!==b||w===!1&&E!==S?!1:!!r.fromBytes(x)}catch{return!1}}function a(x=t(n.seed)){return Nr(F(x,n.seed,"seed"),s.ORDER)}function c(x,w=!0){return r.BASE.multiply(s.fromBytes(x)).toBytes(w)}function l(x){const{secretKey:w,publicKey:b,publicKeyUncompressed:S}=n;if(!at(x)||"_lengths"in s&&s._lengths||w===b)return;const E=F(x,void 0,"key").length;return E===b||E===S}function d(x,w,b=!0){if(l(x)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const S=s.fromBytes(x);return r.fromBytes(w).multiply(S).toBytes(b)}const p={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=$r(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:r,utils:p,lengths:n})}function Gr(r,e,s={}){zt(e),ut(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||Jt,n=s.hmac||((u,h)=>_s(e,u,h)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:p,utils:m,lengths:x}=Hr(r,s),w={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},b=a*xs<o.ORDER;function S(u){const h=a>>Ee;return u>h}function E(u,h){if(!i.isValidNot0(h))throw new Error(`invalid signature ${u}: out of range 1..Point.Fn.ORDER`);return h}function q(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(u,h){nt(h);const y=x.signature,T=h==="compact"?y:h==="recovered"?y+1:void 0;return F(u,T)}class D{constructor(h,y,T){v(this,"r");v(this,"s");v(this,"recovery");if(this.r=E("r",h),this.s=E("s",y),T!=null){if(q(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(h,y=w.format){B(h,y);let T;if(y==="der"){const{r:I,s:C}=ge.toSig(F(h));return new D(I,C)}y==="recovered"&&(T=h[0],y="compact",h=h.subarray(1));const R=x.signature/2,A=h.subarray(0,R),O=h.subarray(R,R*2);return new D(i.fromBytes(A),i.fromBytes(O),T)}static fromHex(h,y){return this.fromBytes(He(h),y)}assertRecovery(){const{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new D(this.r,this.s,h)}recoverPublicKey(h){const{r:y,s:T}=this,R=this.assertRecovery(),A=R===2||R===3?y+a:y;if(!o.isValid(A))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const O=o.toBytes(A),I=r.fromBytes(_e(ms((R&1)===0),O)),C=i.inv(A),N=Q(F(h,void 0,"msgHash")),W=i.create(-N*C),U=i.create(T*C),k=r.BASE.multiplyUnsafe(W).add(I.multiplyUnsafe(U));if(k.is0())throw new Error("invalid recovery: point at infinify");return k.assertValidity(),k}hasHighS(){return S(this.s)}toBytes(h=w.format){if(nt(h),h==="der")return He(ge.hexFromSig(this));const{r:y,s:T}=this,R=i.toBytes(y),A=i.toBytes(T);return h==="recovered"?(q(),_e(Uint8Array.of(this.assertRecovery()),R,A)):_e(R,A)}toHex(h){return ke(this.toBytes(h))}}const M=s.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");const y=Ve(h),T=h.length*8-c;return T>0?y>>BigInt(T):y},Q=s.bits2int_modN||function(h){return i.create(M(h))},ve=dt(c);function he(u){return wr("num < 2^"+c,u,le,ve),i.toBytes(u)}function Z(u,h){return F(u,void 0,"message"),h?F(e(u),void 0,"prehashed message"):u}function xe(u,h,y){const{lowS:T,prehash:R,extraEntropy:A}=tt(y,w);u=Z(u,R);const O=Q(u),I=i.fromBytes(h);if(!i.isValidNot0(I))throw new Error("invalid private key");const C=[he(I),he(O)];if(A!=null&&A!==!1){const k=A===!0?t(x.secretKey):A;C.push(F(k,void 0,"extraEntropy"))}const N=_e(...C),W=O;function U(k){const j=M(k);if(!i.isValidNot0(j))return;const V=i.inv(j),ee=r.BASE.multiply(j).toAffine(),H=i.create(ee.x);if(H===le)return;const K=i.create(V*i.create(W+H*I));if(K===le)return;let xt=(ee.x===H?0:2)|Number(ee.y&Ee),mt=K;return T&&S(K)&&(mt=i.neg(K),xt^=1),new D(H,mt,b?void 0:xt)}return{seed:N,k2sig:U}}function ne(u,h,y={}){const{seed:T,k2sig:R}=xe(u,h,y);return br(e.outputLen,i.BYTES,n)(T,R).toBytes(y.format)}function L(u,h,y,T={}){const{lowS:R,prehash:A,format:O}=tt(T,w);if(y=F(y,void 0,"publicKey"),h=Z(h,A),!at(u)){const I=u instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+I)}B(u,O);try{const I=D.fromBytes(u,O),C=r.fromBytes(y);if(R&&I.hasHighS())return!1;const{r:N,s:W}=I,U=Q(h),k=i.inv(W),j=i.create(U*k),V=i.create(N*k),ee=r.BASE.multiplyUnsafe(j).add(C.multiplyUnsafe(V));return ee.is0()?!1:i.create(ee.x)===N}catch{return!1}}function P(u,h,y={}){const{prehash:T}=tt(y,w);return h=Z(h,T),D.fromBytes(u,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:p,utils:m,lengths:x,Point:r,sign:ne,verify:L,recoverPublicKey:P,Signature:D,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ft={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},qr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ut=BigInt(2);function Wr(r){const e=ft.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,p=se(d,s,e)*d%e,m=se(p,s,e)*d%e,x=se(m,Ut,e)*l%e,w=se(x,n,e)*x%e,b=se(w,o,e)*w%e,S=se(b,a,e)*b%e,E=se(S,c,e)*S%e,q=se(E,a,e)*b%e,B=se(q,s,e)*d%e,D=se(B,i,e)*w%e,M=se(D,t,e)*l%e,Q=se(M,Ut,e);if(!ot.eql(ot.sqr(Q),r))throw new Error("Cannot find square root");return Q}const ot=Ke(ft.p,{sqrt:Wr}),jr=Fr(ft,{Fp:ot,endo:qr}),Vr=Gr(jr,_r),Kr=BigInt(0),Re=BigInt(1),zr=BigInt(2),Yr=BigInt(7),Zr=BigInt(256),Xr=BigInt(113),ys=[],bs=[],vs=[];for(let r=0,e=Re,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],ys.push(2*(5*t+s)),bs.push((r+1)*(r+2)/2%64);let n=Kr;for(let o=0;o<7;o++)e=(e<<Re^(e>>Yr)*Xr)%Zr,e&zr&&(n^=Re<<(Re<<BigInt(o))-Re);vs.push(n)}const Ss=cr(vs,!0),Jr=Ss[0],Qr=Ss[1],Ft=(r,e,s)=>s>32?ur(r,e,s):lr(r,e,s),Ht=(r,e,s)=>s>32?hr(r,e,s):dr(r,e,s);function en(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],p=Ft(l,d,1)^s[a],m=Ht(l,d,1)^s[a+1];for(let x=0;x<50;x+=10)r[i+x]^=p,r[i+x+1]^=m}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=bs[i],c=Ft(n,o,a),l=Ht(n,o,a),d=ys[i];n=r[d],o=r[d+1],r[d]=c,r[d+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=Jr[t],r[1]^=Qr[t]}Te(s)}class pt{constructor(e,s,t,n=!1,o=24){v(this,"state");v(this,"pos",0);v(this,"posOut",0);v(this,"finished",!1);v(this,"state32");v(this,"destroyed",!1);v(this,"blockLen");v(this,"suffix");v(this,"outputLen");v(this,"enableXOF",!1);v(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,ue(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Js(this.state)}clone(){return this._cloneInto()}keccak(){Rt(this.state32),en(this.state32,this.rounds),Rt(this.state32),this.posOut=0,this.pos=0}update(e){Ie(this),F(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ie(this,!1),F(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ue(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Yt(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:n,rounds:o,enableXOF:i}=this;return e||(e=new pt(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const tn=(r,e,s,t={})=>Xt(()=>new pt(e,r,s),t),Gt=tn(1,136,32);class sn{async verifyJWT(e,s){try{const t=this.decodeJWT(e);f.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const n=Math.floor(Date.now()/1e3);return t.exp&&t.exp<n?(f.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(f.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(f.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw f.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Rs.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
1
+ "use strict";var Ts=Object.defineProperty;var As=(r,e,s)=>e in r?Ts(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var v=(r,e,s)=>As(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Rs=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.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.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.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(g||{});class _ extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,_.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const je={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Os=Object.fromEntries(Object.entries(je).map(([r,e])=>[r,e.caipId])),Cs=new Map(Object.values(je).map(r=>[r.caipId,r]));new Map(Object.values(je).map(r=>[r.chainId,r]));const ks={symbol:"",decimals:18};function Ye(r){var e;return((e=Cs.get(r))==null?void 0:e.nativeCurrency)??ks}class Kt{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new _(g.NOT_IMPLEMENTED,`${e} is not yet supported. Use sdk.signMessage() directly.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new _(g.NOT_IMPLEMENTED,`${e} is not yet supported. Use sdk.signTypedData() or sdk.signTypedDataOffchain() directly.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...s))}_caip2ToHex(e){const s=e.split(":");return`0x${parseInt(s[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let we=null;function wt(r){we=r}const f={log(...r){if(we){we.log(...r);return}},warn(...r){if(we){we.warn(...r);return}},error(...r){if(we){we.error(...r);return}}},Ze="crossx_access_token",Ne="crossx_refresh_token",Pe="crossx_user_info";class Ns{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,s){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new _(g.AUTH_FAILED,`${s} failed (code ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const n=t;if(n.code&&n.code!==200&&n.code>0)throw new _(g.AUTH_FAILED,`${s} failed (code ${n.code}): ${n.message}`)}}async execute(e){var n,o,i,a;let s,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:p}=this.config,m=`${d}${l}`;f.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인):`,m);const x=await this.oauth.openAuth({authUrl:m,expectedOrigin:new URL(d).origin});f.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",x.length,")");const{accessToken:w,refreshToken:b}=await this.exchangeFirebaseToken(x,p);let S,E;try{const B=this.crypto.decodeJWT(x);E=(n=B.firebase)==null?void 0:n.sign_in_provider;const D=((o=B.firebase)==null?void 0:o.identities)??{};E==="google.com"?S=(i=D["google.com"])==null?void 0:i[0]:E==="apple.com"&&(S=(a=D["apple.com"])==null?void 0:a[0]),f.log("[CROSSx] OAuth provider sub 추출 — provider:",E,"hasProviderSub:",!!S)}catch{f.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(w){const B=this.crypto.decodeJWT(w);f.log("[CROSSx] access_token 디코딩 — sub:",B.sub,"exp:",B.exp);const D=await this.crypto.verifyJWT(w);if(t=D.signatureVerified??!1,!D.valid)throw f.error("[CROSSx] access_token 검증 실패"),new Error("Invalid access token");const M=D.payload;s={id:M.sub,email:M.email,signInProvider:E,providerSub:S},this.tokenStore.set(w),this.useCookieAuth||(await this.storage.set(Ze,w),b&&await this.storage.set(Ne,b))}else{const B=this.crypto.decodeJWT(x);s={id:B.sub,email:B.email,signInProvider:E,providerSub:S},f.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}f.log("[CROSSx] 사용자 정보 — id:",s.id);const q=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Pe,q),f.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return f.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return f.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,t)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;f.log("[CROSSx] Firebase 토큰 교환 요청:",n);const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});f.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return f.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new _(g.AUTH_FAILED,"access_token not found in exchange response");f.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(Pe);if(n)return f.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){f.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(Ze),n=await this.storage.get(Ne);if(f.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return f.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);f.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(Pe);if(f.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;f.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return f.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return f.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(Ne),await this.storage.remove(Pe),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,o={};if(!t){const l=this.tokenStore.get()??"";l&&(o.access_token=l),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});f.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){f.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new _(g.AUTH_FAILED,"Silent refresh failed: no token in response");if(this.tokenStore.set(c),!t){await this.storage.set(Ze,c);const l=this.extractRefreshToken(a);l&&await this.storage.set(Ne,l)}return f.log("[CROSSx] silentRefresh 성공"),c}async loadWallet(e,s){let t,n=!1;try{f.log("[CROSSx][Migration Phase 2] POST /mnemonic/create 호출 — userId:",e.id),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,f.log("[CROSSx][Migration Phase 2] 지갑 로드 완료 (기존 백업 없음) — address:",t)}catch(o){if(o instanceof _&&o.code===g.MIGRATION_BACKUP_EXISTS)f.log("[CROSSx][Migration Phase 2] Gateway -10012 감지 → needsMigration = true"),n=!0;else{if(o instanceof _&&(o.code===g.PROJECT_NOT_REGISTERED||o.code===g.PROJECT_ID_MISSING||o.code===g.ORIGIN_NOT_ALLOWED))throw f.error("[CROSSx][Migration Phase 2] 프로젝트 설정 에러:",o.message),o;f.warn("[CROSSx][Migration Phase 2] 지갑 로드 실패 (로그인은 유지):",o)}}return f.log("[CROSSx][Migration Phase 2] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}}const Ps="crossx_access_token",Ls="crossx_refresh_token",Ds="crossx_user_info";class $s{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(Ps),await this.storage.remove(Ls)),await this.storage.remove(Ds)}}class Ms{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new _(g.NOT_IMPLEMENTED,"Migration is not supported in the current environment");f.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return f.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Bs{constructor(e,s){this.chainRegistry=e,this.transport=s}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:s,id:Date.now()},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new _(g.UNKNOWN_ERROR,`RPC error [${e}] (${t}): ${a.error.message} (code: ${a.error.code})`);return a==null?void 0:a.result}}class Us{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}const Ue={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}},Fs="/crossx.config.json";function yt(r){const e=r.environment;return e&&e in Ue?Ue[e]:null}async function Hs(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=yt(r);if(e)return e}}catch{}try{const r=await fetch(Fs);if(r.ok){const e=await r.json(),s=yt(e);if(s)return s}}catch{}return Ue.production}const Gs=2e3,bt=6e4,qs=1e3,Ws=1e4,js="0x77359400",vt="0x3B9ACA00",St=130,Et=6,It=18,Vs=0,Ks=30*1e3,X=class X extends Us{constructor(e,s,t,n,o,i,a,c,l,d){super(),this.storage=t,this.crypto=n,this.transport=o,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._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&wt(e.logger),this.confirmation=l,this.chainRegistry=d,this.jsonRpc=new Bs(d,o),this.signInUseCase=new Ns(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new $s(this.internalConfig,t,c),this.migrateWalletUseCase=new Ms(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.0.6 initializing...");try{const e=await Hs();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();return s!=null&&s.success&&this.applyAuthResult(s),this.initialized=!0,this.emit("initialized",{restored:!!(s!=null&&s.success)}),s??null}catch(e){throw new _(g.AUTH_NOT_INITIALIZED,"SDK initialization failed",e)}}async signIn(e){this.ensureInitialized();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 _(g.AUTH_FAILED,"Sign in failed",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};if(s.needsMigration||!s.address){const{address:o}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:t}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new _(g.UNKNOWN_ERROR,"Sign out failed",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();return e!=null&&e.success?(this.applyAuthResult(e),!0):!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.emit("addressChanged",{address:s.address,index:0}),f.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof _?s:new _(g.MIGRATION_FAILED,"Wallet migration failed",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");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(){return this.ensureAuthenticated(),this.userId?this.walletProvider.getAddresses(this.userId):[]}async selectWallet(){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const e=await this.walletProvider.getAddresses(this.userId),s=await this.confirmation.showWalletSelector(e,async()=>{const t=e.length,o={address:(await this.walletProvider.getAddress(this.userId,t)).address,index:t};return e.push(o),o});return s&&(this.address=s.address,this.emit("addressChanged",{address:s.address,index:s.index})),s}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof _?e:new _(g.UNKNOWN_ERROR,"Failed to fetch chains",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof _?s:new _(g.CHAIN_NOT_SUPPORTED,`Failed to fetch chain: ${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)}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");f.log("[CROSSx] 지갑 생성 시작");try{const e=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=e.address,this.emit("addressChanged",{address:e.address,index:0}),f.log("[CROSSx] 지갑 생성 완료:",e.address),{address:e.address}}catch(e){if(e instanceof _&&e.code===g.MIGRATION_BACKUP_EXISTS){const s=this.providerSub??this.userId;f.log("[CROSSx][Migration Phase 3] createWallet() — Gateway -10012 감지, 마이그레이션 UI 시작 — migrationSub:",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 _(g.MIGRATION_FAILED,"Migration skipped by user")}throw e}}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=t==null?void 0:t.index,o=await this.walletProvider.getAddress(this.userId,n??0);let i;if(this.walletProvider.prepare&&(i=(await this.walletProvider.prepare("sign-message",{message:s,from:o.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:o.address,message:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(g.USER_REJECTED,"User rejected message signing");try{const c=await this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,i,o.address);return this.verifySignatureSigner(s,c.signature,o.address),{chainId:e,signature:c.signature,message:s,address:o.address}}catch(c){throw c instanceof _?c:new _(g.SIGNATURE_FAILED,`Message signing failed (${e})`,c)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");if(!this.walletProvider.signTypedData)throw new _(g.NOT_IMPLEMENTED,"signTypedData is not implemented");X.validateTypedDataChainId(e,s);const n=await this.walletProvider.getAddress(this.userId,(t==null?void 0:t.index)??0);let o;if(this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(g.USER_REJECTED,"User rejected typed data signing");try{const a=await this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address);return X.validateSignatureFormat(a.signature),{chainId:e,signature:a.signature,address:n.address}}catch(a){throw a instanceof _?a:new _(g.SIGNATURE_FAILED,`Typed data signing failed (${e})`,a)}}async signTypedDataOffchain(e,s){return this.signTypedData(X.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=await this.withResolvedGasAndFee(s,e);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign",{tx:n})).uuid);const i=Ye(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(g.USER_REJECTED,"User rejected transaction signing");try{const c=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o);return X.validateSignedTxFormat(c.signature),{chainId:e,signedTx:c.signature,txHash:c.txHash??""}}catch(c){if(c instanceof _)throw c;const l=c instanceof Error?c.message:String(c);throw new _(g.SIGNATURE_FAILED,`Transaction signing failed (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=await this.withResolvedGasAndFee(s,e);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("send",{tx:n})).uuid);const i=Ye(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(g.USER_REJECTED,"User rejected transaction");try{let c;if(this.walletProvider.sendTransaction)c=(await this.walletProvider.sendTransaction(this.userId,e,n,o)).txHash;else{const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o);c=l.txHash??l.signature}return{chainId:e,txHash:c,status:"pending"}}catch(c){const l=c instanceof Error?c.message:String(c);throw new _(g.TRANSACTION_FAILED,`Transaction failed (${e}): ${l}`,c)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??qs,o=Ws,i=t.timeoutMs??bt,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,o)}throw new _(g.UNKNOWN_ERROR,`Transaction receipt timeout (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var b,S;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((b=this._config.receiptPolling)==null?void 0:b.intervalMs)??Gs,l=o??((S=this._config.receiptPolling)==null?void 0:S.timeoutMs)??bt,d=Ye(e),p=s.from??"";let m,x;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(E=>{m=E;const q=BigInt(E.gasUsed)*BigInt(E.effectiveGasPrice),B=s.value?BigInt(s.value):0n,D=X.formatTxAmount(s.value,d.symbol,d.decimals),M=X.formatTxAmount("0x"+q.toString(16),d.symbol,d.decimals),Q=X.formatTxAmount("0x"+(B+q).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:E.from,to:E.to??s.to,amount:D,fees:M,total:Q,nativeSymbol:d.symbol,status:E.status==="0x1"?"success":"reverted"}}).catch(E=>(x=E instanceof Error?E:new Error(String(E)),{chainId:e,txHash:a,from:p,to:s.to,amount:X.formatTxAmount(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:s.to},w),x)throw x;return{chainId:e,txHash:a,receipt:m}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(g.GAS_ESTIMATION_FAILED,`Failed to get gas price (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const o=n instanceof Error?n.message:String(n);throw new _(g.GAS_ESTIMATION_FAILED,`Failed to estimate gas (${s}): ${o}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(g.GAS_ESTIMATION_FAILED,`Failed to get baseFeePerGas (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(g.GAS_ESTIMATION_FAILED,`Failed to get maxPriorityFeePerGas (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(g.UNKNOWN_ERROR,`Failed to get nonce: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:X.formatWei(n),chainId:e}}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(g.UNKNOWN_ERROR,`Failed to get balance (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt(It),n=s/t,i=(s%t).toString().padStart(It,"0").replace(/0+$/,"").slice(0,Et);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Kt(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof _)throw n;const o=n instanceof Error?n.message:String(n);throw new _(g.UNKNOWN_ERROR,`walletRpc failed [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const o=10n**BigInt(t),i=n/o,c=(n%o).toString().padStart(t,"0").slice(0,Et).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){f.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(f.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return f.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0;for(;;){n++,f.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n})`,t?`— 이전 에러: ${t}`:"");const o=await this.confirmation.showPinInputPrompt(t);if(o===null)return f.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;f.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${o.length}자리), Gateway 마이그레이션 API 호출`);try{const i=await this.migrateWalletUseCase.execute(o,e);return f.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",i.address),i}catch(i){if(i instanceof _&&i.code===g.MIGRATION_FAILED){f.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 #${n}) — 재시도 요청`),t="Incorrect PIN. Please try again.";continue}throw f.error("[CROSSx][Migration Phase 4] 마이그레이션 실패 (복구 불가):",i),i}}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e};if(n){const l=c.from??this.address;if(l){f.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),f.log("[CROSSx] nonce 결과:",c.nonce)}}if(o&&(f.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),f.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){f.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=vt;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,f.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=js,f.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=vt,f.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=X.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new _(g.TYPED_DATA_CHAIN_ID_MISMATCH,`Off-chain signing (chainId=0) requires typedData.domain.chainId to be absent or 0, got ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new _(g.TYPED_DATA_CHAIN_ID_MISMATCH,`On-chain signing (${e}) requires typedData.domain.chainId to be present`);if(t!==o)throw new _(g.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t}) does not match chainId (${e}, expected ${o})`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new _(g.SIGNATURE_FAILED,"Invalid signature: not a valid hex string");if(s.length!==St)throw new _(g.SIGNATURE_FAILED,`Invalid signature length: expected ${St} hex chars (65 bytes), got ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new _(g.SIGNATURE_FAILED,"Invalid signedTx: not a valid hex string");if(s.length<2)throw new _(g.SIGNATURE_FAILED,"Invalid signedTx: too short")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw f.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new _(g.SIGNATURE_SIGNER_MISMATCH,`Signature signer mismatch: expected ${t}, recovered ${n}`);f.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof _)throw n;f.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var s,t,n,o;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=X.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}ensureInitialized(){if(!this.initialized)throw new _(g.AUTH_NOT_INITIALIZED,"SDK is not initialized. Call initialize() first.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new _(g.AUTH_NOT_AUTHENTICATED,"Not authenticated. Call signIn() first.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.initialized=!1,this.removeAllListeners(),wt(null)}};X.OFFCHAIN_CHAIN_ID="0";let Fe=X;class zs{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw f.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 f.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw f.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw f.error("Storage clear error:",e),e}}}const Ys="crossx-sdk",Zs=1,Se="data",Le="keys",Tt="aes-primary",Xs=12;class At{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(Ys,Zs);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Se)||n.createObjectStore(Se),n.objectStoreNames.contains(Le)||n.createObjectStore(Le)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Le,Tt);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Le,Tt,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(Xs);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(Se,e,n)}catch(t){throw f.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 f.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Se,e)}catch(s){throw f.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Se)}catch(e){throw f.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 at(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ue(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=at(r),n=r==null?void 0:r.length,o=e!==void 0;if(!t||o&&n!==e){const i=s&&`"${s}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function zt(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ue(r.outputLen),ue(r.blockLen)}function Ie(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 Yt(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 Js(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 Xe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function oe(r,e){return r<<32-e|r>>>e}const Qs=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function er(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function tr(r){for(let e=0;e<r.length;e++)r[e]=er(r[e]);return r}const Rt=Qs?r=>r:tr,Zt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",sr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ke(r){if(F(r),Zt)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=sr[r[s]];return e}const ce={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ot(r){if(r>=ce._0&&r<=ce._9)return r-ce._0;if(r>=ce.A&&r<=ce.F)return r-(ce.A-10);if(r>=ce.a&&r<=ce.f)return r-(ce.a-10)}function He(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Zt)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,o=0;n<s;n++,o+=2){const i=Ot(r.charCodeAt(o)),a=Ot(r.charCodeAt(o+1));if(i===void 0||a===void 0){const c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function _e(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];F(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const o=r[t];s.set(o,n),n+=o.length}return s}function Xt(r,e={}){const s=(n,o)=>r(o).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function Jt(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 rr=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function nr(r,e,s){return r&e^~r&s}function or(r,e,s){return r&e^r&s^e&s}class ir{constructor(e,s,t,n){v(this,"blockLen");v(this,"outputLen");v(this,"padOffset");v(this,"isLE");v(this,"buffer");v(this,"view");v(this,"finished",!1);v(this,"length",0);v(this,"pos",0);v(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Xe(this.buffer)}update(e){Ie(this),F(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=Xe(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ie(this),Yt(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Te(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let p=i;p<n;p++)s[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=Xe(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 p=0;p<l;p++)a.setUint32(4*p,d[p],o)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const fe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),De=BigInt(2**32-1),Ct=BigInt(32);function ar(r,e=!1){return e?{h:Number(r&De),l:Number(r>>Ct&De)}:{h:Number(r>>Ct&De)|0,l:Number(r&De)|0}}function cr(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let o=0;o<s;o++){const{h:i,l:a}=ar(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const lr=(r,e,s)=>r<<s|e>>>32-s,dr=(r,e,s)=>e<<s|r>>>32-s,ur=(r,e,s)=>e<<s-32|r>>>64-s,hr=(r,e,s)=>r<<s-32|e>>>64-s,fr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),pe=new Uint32Array(64);class pr extends ir{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,s,t,n,o,i,a,c]}set(e,s,t,n,o,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,s){for(let p=0;p<16;p++,s+=4)pe[p]=e.getUint32(s,!1);for(let p=16;p<64;p++){const m=pe[p-15],x=pe[p-2],w=oe(m,7)^oe(m,18)^m>>>3,b=oe(x,17)^oe(x,19)^x>>>10;pe[p]=b+pe[p-7]+w+pe[p-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let p=0;p<64;p++){const m=oe(a,6)^oe(a,11)^oe(a,25),x=d+m+nr(a,c,l)+fr[p]+pe[p]|0,b=(oe(t,2)^oe(t,13)^oe(t,22))+or(t,n,o)|0;d=l,l=c,c=a,a=i+x|0,i=o,o=n,n=t,t=x+b|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,o,i,a,c,l,d)}roundClean(){Te(pe)}destroy(){this.set(0,0,0,0,0,0,0,0),Te(this.buffer)}}class gr extends pr{constructor(){super(32);v(this,"A",fe[0]|0);v(this,"B",fe[1]|0);v(this,"C",fe[2]|0);v(this,"D",fe[3]|0);v(this,"E",fe[4]|0);v(this,"F",fe[5]|0);v(this,"G",fe[6]|0);v(this,"H",fe[7]|0)}}const _r=Xt(()=>new gr,rr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ct=BigInt(0),rt=BigInt(1);function Ge(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Qt(r){if(typeof r=="bigint"){if(!Be(r))throw new Error("positive bigint expected, got "+r)}else ue(r);return r}function $e(r){const e=Qt(r).toString(16);return e.length&1?"0"+e:e}function es(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ct:BigInt("0x"+r)}function Ve(r){return es(ke(r))}function ts(r){return es(ke(xr(F(r)).reverse()))}function lt(r,e){ue(e),r=Qt(r);const s=He(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function ss(r,e){return lt(r,e).reverse()}function xr(r){return Uint8Array.from(r)}const Be=r=>typeof r=="bigint"&&ct<=r;function mr(r,e,s){return Be(r)&&Be(e)&&Be(s)&&e<=r&&r<s}function wr(r,e,s,t){if(!mr(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function yr(r){let e;for(e=0;r>ct;r>>=rt,e+=1);return e}const dt=r=>(rt<<BigInt(r))-rt;function br(r,e,s){if(ue(r,"hashLen"),ue(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=S=>new Uint8Array(S),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const p=()=>{c.fill(1),l.fill(0),d=0},m=(...S)=>s(l,_e(c,...S)),x=(S=n)=>{l=m(o,S),c=m(),S.length!==0&&(l=m(i,S),c=m())},w=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let S=0;const E=[];for(;S<e;){c=m();const q=c.slice();E.push(q),S+=c.length}return _e(...E)};return(S,E)=>{p(),x(S);let q;for(;!(q=E(w()));)x();return p(),q}}function ut(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(o,i,a){const c=r[o];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}const n=(o,i)=>Object.entries(o).forEach(([a,c])=>t(a,c,i));n(e,!1),n(s,!0)}function kt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const J=BigInt(0),z=BigInt(1),ye=BigInt(2),rs=BigInt(3),ns=BigInt(4),os=BigInt(5),vr=BigInt(7),is=BigInt(8),Sr=BigInt(9),as=BigInt(16);function re(r,e){const s=r%e;return s>=J?s:e+s}function se(r,e,s){let t=r;for(;e-- >J;)t*=t,t%=s;return t}function Nt(r,e){if(r===J)throw new Error("invert: expected non-zero number");if(e<=J)throw new Error("invert: expected positive modulus, got "+e);let s=re(r,e),t=e,n=J,o=z;for(;s!==J;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==z)throw new Error("invert: does not exist");return re(n,e)}function ht(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function cs(r,e){const s=(r.ORDER+z)/ns,t=r.pow(e,s);return ht(r,t,e),t}function Er(r,e){const s=(r.ORDER-os)/is,t=r.mul(e,ye),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,ye),n),a=r.mul(o,r.sub(i,r.ONE));return ht(r,a,e),a}function Ir(r){const e=Ke(r),s=ls(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+vr)/as;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const p=a.mul(l,n),m=a.mul(l,o),x=a.eql(a.sqr(d),c),w=a.eql(a.sqr(p),c);l=a.cmov(l,d,x),d=a.cmov(m,p,w);const b=a.eql(a.sqr(d),c),S=a.cmov(l,d,b);return ht(a,S,c),S}}function ls(r){if(r<rs)throw new Error("sqrt is not defined for small field");let e=r-z,s=0;for(;e%ye===J;)e/=ye,s++;let t=ye;const n=Ke(r);for(;Pt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return cs;let o=n.pow(t,e);const i=(e+z)/ye;return function(c,l){if(c.is0(l))return l;if(Pt(c,l)!==1)throw new Error("Cannot find square root");let d=s,p=c.mul(c.ONE,o),m=c.pow(l,e),x=c.pow(l,i);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let w=1,b=c.sqr(m);for(;!c.eql(b,c.ONE);)if(w++,b=c.sqr(b),w===d)throw new Error("Cannot find square root");const S=z<<BigInt(d-w-1),E=c.pow(p,S);d=w,p=c.sqr(E),m=c.mul(m,p),x=c.mul(x,E)}return x}}function Tr(r){return r%ns===rs?cs:r%is===os?Er:r%as===Sr?Ir(r):ls(r)}const Ar=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Ar.reduce((t,n)=>(t[n]="function",t),e);return ut(r,s),r}function Or(r,e,s){if(s<J)throw new Error("invalid exponent, negatives unsupported");if(s===J)return r.ONE;if(s===z)return e;let t=r.ONE,n=e;for(;s>J;)s&z&&(t=r.mul(t,n)),n=r.sqr(n),s>>=z;return t}function ds(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),o),t}function Pt(r,e){const s=(r.ORDER-z)/ye,t=r.pow(e,s),n=r.eql(t,r.ONE),o=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function Cr(r,e){e!==void 0&&ue(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class kr{constructor(e,s={}){v(this,"ORDER");v(this,"BITS");v(this,"BYTES");v(this,"isLE");v(this,"ZERO",J);v(this,"ONE",z);v(this,"_lengths");v(this,"_sqrt");v(this,"_mod");var i;if(e<=J)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=Cr(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return J<=e&&e<this.ORDER}is0(e){return e===J}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&z)===z}neg(e){return re(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return re(e*e,this.ORDER)}add(e,s){return re(e+s,this.ORDER)}sub(e,s){return re(e-s,this.ORDER)}mul(e,s){return re(e*s,this.ORDER)}pow(e,s){return Or(this,e,s)}div(e,s){return re(e*Nt(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 Nt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Tr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?ss(e,this.BYTES):lt(e,this.BYTES)}fromBytes(e,s=!1){F(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?ts(e):Ve(e);if(a&&(c=re(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ds(this,e)}cmov(e,s,t){return t?s:e}}function Ke(r,e={}){return new kr(r,e)}function us(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 hs(r){const e=us(r);return e+Math.ceil(e/2)}function Nr(r,e,s=!1){F(r);const t=r.length,n=us(e),o=hs(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?ts(r):Ve(r),a=re(i,e-z)+z;return s?ss(a,n):lt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ae=BigInt(0),be=BigInt(1);function qe(r,e){const s=e.negate();return r?s:e}function Lt(r,e){const s=ds(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function fs(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Je(r,e){fs(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=dt(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function Dt(r,e,s){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=s;let a=Number(r&n),c=r>>i;a>t&&(a-=o,c+=be);const l=e*t,d=l+Math.abs(a)-1,p=a===0,m=a<0,x=e%2!==0;return{nextN:c,offset:d,isZero:p,isNeg:m,isNegF:x,offsetF:l}}const Qe=new WeakMap,ps=new WeakMap;function et(r){return ps.get(r)||1}function $t(r){if(r!==Ae)throw new Error("invalid wNAF")}class Pr{constructor(e,s){v(this,"BASE");v(this,"ZERO");v(this,"Fn");v(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>Ae;)s&be&&(t=t.add(n)),n=n.double(),s>>=be;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=Je(s,this.bits),o=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=Je(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:p,isNegF:m,offsetF:x}=Dt(t,a,i);t=c,d?o=o.add(qe(m,s[x])):n=n.add(qe(p,s[l]))}return $t(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=Je(e,this.bits);for(let i=0;i<o.windows&&t!==Ae;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Dt(t,i,o);if(t=a,!l){const p=s[c];n=n.add(d?p.negate():p)}}return $t(t),n}getPrecomputes(e,s,t){let n=Qe.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),Qe.set(s,n))),n}cached(e,s,t){const n=et(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=et(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){fs(s,this.bits),ps.set(e,s),Qe.delete(e)}hasCache(e){return et(e)!==1}}function Lr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>Ae||t>Ae;)s&be&&(o=o.add(n)),t&be&&(i=i.add(n)),n=n.double(),s>>=be,t>>=be;return{p1:o,p2:i}}function Mt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Rr(e),e}else return Ke(r,{isLE:s})}function Dr(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>Ae))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Mt(e.p,s.Fp,t),o=Mt(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}function $r(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class gs{constructor(e,s){v(this,"oHash");v(this,"iHash");v(this,"blockLen");v(this,"outputLen");v(this,"finished",!1);v(this,"destroyed",!1);if(zt(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,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Te(n)}update(e){return Ie(this),this.iHash.update(e),this}digestInto(e){Ie(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:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const _s=(r,e,s)=>new gs(r,e).update(s).digest();_s.create=(r,e)=>new gs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Bt=(r,e)=>(r+(r>=0?e:-e)/xs)/e;function Mr(r,e,s){const[[t,n],[o,i]]=e,a=Bt(i*r,s),c=Bt(-n*r,s);let l=r-a*t-c*o,d=-a*n-c*i;const p=l<le,m=d<le;p&&(l=-l),m&&(d=-d);const x=dt(Math.ceil(yr(s)/2))+Ee;if(l<le||l>=x||d<le||d>=x)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:p,k1:l,k2neg:m,k2:d}}function nt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function tt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return Ge(s.lowS,"lowS"),Ge(s.prehash,"prehash"),s.format!==void 0&&nt(s.format),s}class Br extends Error{constructor(e=""){super(e)}}const ge={Err:Br,_tlv:{encode:(r,e)=>{const{Err:s}=ge;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=$e(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?$e(n.length/2|128):"";return $e(r)+o+n+e},decode(r,e){const{Err:s}=ge;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=ge;if(r<le)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}=ge;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 Ve(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=ge,n=F(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=ge,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},le=BigInt(0),Ee=BigInt(1),xs=BigInt(2),Me=BigInt(3),Ur=BigInt(4);function Fr(r,e={}){const s=Dr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;ut(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=ws(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(P,u,h){const{x:y,y:T}=u.toAffine(),R=t.toBytes(y);if(Ge(h,"isCompressed"),h){d();const A=!t.isOdd(T);return _e(ms(A),R)}else return _e(Uint8Array.of(4),R,t.toBytes(T))}function m(P){F(P,void 0,"Point");const{publicKey:u,publicKeyUncompressed:h}=l,y=P.length,T=P[0],R=P.subarray(1);if(y===u&&(T===2||T===3)){const A=t.fromBytes(R);if(!t.isValid(A))throw new Error("bad point: is not on curve, wrong x");const O=b(A);let I;try{I=t.sqrt(O)}catch(W){const U=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+U)}d();const C=t.isOdd(I);return(T&1)===1!==C&&(I=t.neg(I)),{x:A,y:I}}else if(y===h&&T===4){const A=t.BYTES,O=t.fromBytes(R.subarray(0,A)),I=t.fromBytes(R.subarray(A,A*2));if(!S(O,I))throw new Error("bad point: is not on curve");return{x:O,y:I}}else throw new Error(`bad point: got length ${y}, expected compressed=${u} or uncompressed=${h}`)}const x=e.toBytes||p,w=e.fromBytes||m;function b(P){const u=t.sqr(P),h=t.mul(u,P);return t.add(t.add(h,t.mul(P,o.a)),o.b)}function S(P,u){const h=t.sqr(u),y=b(P);return t.eql(h,y)}if(!S(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const E=t.mul(t.pow(o.a,Me),Ur),q=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(E,q)))throw new Error("bad curve params: a or b");function B(P,u,h=!1){if(!t.isValid(u)||h&&t.is0(u))throw new Error(`bad point coordinate ${P}`);return u}function D(P){if(!(P instanceof Z))throw new Error("Weierstrass Point expected")}function M(P){if(!c||!c.basises)throw new Error("no endo");return Mr(P,c.basises,n.ORDER)}const Q=kt((P,u)=>{const{X:h,Y:y,Z:T}=P;if(t.eql(T,t.ONE))return{x:h,y};const R=P.is0();u==null&&(u=R?t.ONE:t.inv(T));const A=t.mul(h,u),O=t.mul(y,u),I=t.mul(T,u);if(R)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:A,y:O}}),ve=kt(P=>{if(P.is0()){if(e.allowInfinityPoint&&!t.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:u,y:h}=P.toAffine();if(!t.isValid(u)||!t.isValid(h))throw new Error("bad point: x or y not field elements");if(!S(u,h))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function he(P,u,h,y,T){return h=new Z(t.mul(h.X,P),h.Y,h.Z),u=qe(y,u),h=qe(T,h),u.add(h)}const L=class L{constructor(u,h,y){v(this,"X");v(this,"Y");v(this,"Z");this.X=B("x",u),this.Y=B("y",h,!0),this.Z=B("z",y),Object.freeze(this)}static CURVE(){return o}static fromAffine(u){const{x:h,y}=u||{};if(!u||!t.isValid(h)||!t.isValid(y))throw new Error("invalid affine point");if(u instanceof L)throw new Error("projective point not allowed");return t.is0(h)&&t.is0(y)?L.ZERO:new L(h,y,t.ONE)}static fromBytes(u){const h=L.fromAffine(w(F(u,void 0,"point")));return h.assertValidity(),h}static fromHex(u){return L.fromBytes(He(u))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(u=8,h=!0){return ne.createCache(this,u),h||this.multiply(Me),this}assertValidity(){ve(this)}hasEvenY(){const{y:u}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(u)}equals(u){D(u);const{X:h,Y:y,Z:T}=this,{X:R,Y:A,Z:O}=u,I=t.eql(t.mul(h,O),t.mul(R,T)),C=t.eql(t.mul(y,O),t.mul(A,T));return I&&C}negate(){return new L(this.X,t.neg(this.Y),this.Z)}double(){const{a:u,b:h}=o,y=t.mul(h,Me),{X:T,Y:R,Z:A}=this;let O=t.ZERO,I=t.ZERO,C=t.ZERO,N=t.mul(T,T),W=t.mul(R,R),U=t.mul(A,A),k=t.mul(T,R);return k=t.add(k,k),C=t.mul(T,A),C=t.add(C,C),O=t.mul(u,C),I=t.mul(y,U),I=t.add(O,I),O=t.sub(W,I),I=t.add(W,I),I=t.mul(O,I),O=t.mul(k,O),C=t.mul(y,C),U=t.mul(u,U),k=t.sub(N,U),k=t.mul(u,k),k=t.add(k,C),C=t.add(N,N),N=t.add(C,N),N=t.add(N,U),N=t.mul(N,k),I=t.add(I,N),U=t.mul(R,A),U=t.add(U,U),N=t.mul(U,k),O=t.sub(O,N),C=t.mul(U,W),C=t.add(C,C),C=t.add(C,C),new L(O,I,C)}add(u){D(u);const{X:h,Y:y,Z:T}=this,{X:R,Y:A,Z:O}=u;let I=t.ZERO,C=t.ZERO,N=t.ZERO;const W=o.a,U=t.mul(o.b,Me);let k=t.mul(h,R),j=t.mul(y,A),V=t.mul(T,O),ee=t.add(h,y),H=t.add(R,A);ee=t.mul(ee,H),H=t.add(k,j),ee=t.sub(ee,H),H=t.add(h,T);let K=t.add(R,O);return H=t.mul(H,K),K=t.add(k,V),H=t.sub(H,K),K=t.add(y,T),I=t.add(A,O),K=t.mul(K,I),I=t.add(j,V),K=t.sub(K,I),N=t.mul(W,H),I=t.mul(U,V),N=t.add(I,N),I=t.sub(j,N),N=t.add(j,N),C=t.mul(I,N),j=t.add(k,k),j=t.add(j,k),V=t.mul(W,V),H=t.mul(U,H),j=t.add(j,V),V=t.sub(k,V),V=t.mul(W,V),H=t.add(H,V),k=t.mul(j,H),C=t.add(C,k),k=t.mul(K,H),I=t.mul(ee,I),I=t.sub(I,k),k=t.mul(ee,j),N=t.mul(K,N),N=t.add(N,k),new L(I,C,N)}subtract(u){return this.add(u.negate())}is0(){return this.equals(L.ZERO)}multiply(u){const{endo:h}=e;if(!n.isValidNot0(u))throw new Error("invalid scalar: out of range");let y,T;const R=A=>ne.cached(this,A,O=>Lt(L,O));if(h){const{k1neg:A,k1:O,k2neg:I,k2:C}=M(u),{p:N,f:W}=R(O),{p:U,f:k}=R(C);T=W.add(k),y=he(h.beta,N,U,A,I)}else{const{p:A,f:O}=R(u);y=A,T=O}return Lt(L,[y,T])[0]}multiplyUnsafe(u){const{endo:h}=e,y=this;if(!n.isValid(u))throw new Error("invalid scalar: out of range");if(u===le||y.is0())return L.ZERO;if(u===Ee)return y;if(ne.hasCache(this))return this.multiply(u);if(h){const{k1neg:T,k1:R,k2neg:A,k2:O}=M(u),{p1:I,p2:C}=Lr(L,y,R,O);return he(h.beta,I,C,T,A)}else return ne.unsafe(y,u)}toAffine(u){return Q(this,u)}isTorsionFree(){const{isTorsionFree:u}=e;return i===Ee?!0:u?u(L,this):ne.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:u}=e;return i===Ee?this:u?u(L,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(u=!0){return Ge(u,"isCompressed"),this.assertValidity(),x(L,this,u)}toHex(u=!0){return ke(this.toBytes(u))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};v(L,"BASE",new L(o.Gx,o.Gy,t.ONE)),v(L,"ZERO",new L(t.ZERO,t.ONE,t.ZERO)),v(L,"Fp",t),v(L,"Fn",n);let Z=L;const xe=n.BITS,ne=new Pr(Z,e.endo?Math.ceil(xe/2):xe);return Z.BASE.precompute(8),Z}function ms(r){return Uint8Array.of(r?2:3)}function ws(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Hr(r,e={}){const{Fn:s}=r,t=e.randomBytes||Jt,n=Object.assign(ws(r.Fp,s),{seed:hs(s.ORDER)});function o(x){try{const w=s.fromBytes(x);return s.isValidNot0(w)}catch{return!1}}function i(x,w){const{publicKey:b,publicKeyUncompressed:S}=n;try{const E=x.length;return w===!0&&E!==b||w===!1&&E!==S?!1:!!r.fromBytes(x)}catch{return!1}}function a(x=t(n.seed)){return Nr(F(x,n.seed,"seed"),s.ORDER)}function c(x,w=!0){return r.BASE.multiply(s.fromBytes(x)).toBytes(w)}function l(x){const{secretKey:w,publicKey:b,publicKeyUncompressed:S}=n;if(!at(x)||"_lengths"in s&&s._lengths||w===b)return;const E=F(x,void 0,"key").length;return E===b||E===S}function d(x,w,b=!0){if(l(x)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const S=s.fromBytes(x);return r.fromBytes(w).multiply(S).toBytes(b)}const p={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=$r(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:r,utils:p,lengths:n})}function Gr(r,e,s={}){zt(e),ut(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||Jt,n=s.hmac||((u,h)=>_s(e,u,h)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:p,utils:m,lengths:x}=Hr(r,s),w={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},b=a*xs<o.ORDER;function S(u){const h=a>>Ee;return u>h}function E(u,h){if(!i.isValidNot0(h))throw new Error(`invalid signature ${u}: out of range 1..Point.Fn.ORDER`);return h}function q(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(u,h){nt(h);const y=x.signature,T=h==="compact"?y:h==="recovered"?y+1:void 0;return F(u,T)}class D{constructor(h,y,T){v(this,"r");v(this,"s");v(this,"recovery");if(this.r=E("r",h),this.s=E("s",y),T!=null){if(q(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(h,y=w.format){B(h,y);let T;if(y==="der"){const{r:I,s:C}=ge.toSig(F(h));return new D(I,C)}y==="recovered"&&(T=h[0],y="compact",h=h.subarray(1));const R=x.signature/2,A=h.subarray(0,R),O=h.subarray(R,R*2);return new D(i.fromBytes(A),i.fromBytes(O),T)}static fromHex(h,y){return this.fromBytes(He(h),y)}assertRecovery(){const{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new D(this.r,this.s,h)}recoverPublicKey(h){const{r:y,s:T}=this,R=this.assertRecovery(),A=R===2||R===3?y+a:y;if(!o.isValid(A))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const O=o.toBytes(A),I=r.fromBytes(_e(ms((R&1)===0),O)),C=i.inv(A),N=Q(F(h,void 0,"msgHash")),W=i.create(-N*C),U=i.create(T*C),k=r.BASE.multiplyUnsafe(W).add(I.multiplyUnsafe(U));if(k.is0())throw new Error("invalid recovery: point at infinify");return k.assertValidity(),k}hasHighS(){return S(this.s)}toBytes(h=w.format){if(nt(h),h==="der")return He(ge.hexFromSig(this));const{r:y,s:T}=this,R=i.toBytes(y),A=i.toBytes(T);return h==="recovered"?(q(),_e(Uint8Array.of(this.assertRecovery()),R,A)):_e(R,A)}toHex(h){return ke(this.toBytes(h))}}const M=s.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");const y=Ve(h),T=h.length*8-c;return T>0?y>>BigInt(T):y},Q=s.bits2int_modN||function(h){return i.create(M(h))},ve=dt(c);function he(u){return wr("num < 2^"+c,u,le,ve),i.toBytes(u)}function Z(u,h){return F(u,void 0,"message"),h?F(e(u),void 0,"prehashed message"):u}function xe(u,h,y){const{lowS:T,prehash:R,extraEntropy:A}=tt(y,w);u=Z(u,R);const O=Q(u),I=i.fromBytes(h);if(!i.isValidNot0(I))throw new Error("invalid private key");const C=[he(I),he(O)];if(A!=null&&A!==!1){const k=A===!0?t(x.secretKey):A;C.push(F(k,void 0,"extraEntropy"))}const N=_e(...C),W=O;function U(k){const j=M(k);if(!i.isValidNot0(j))return;const V=i.inv(j),ee=r.BASE.multiply(j).toAffine(),H=i.create(ee.x);if(H===le)return;const K=i.create(V*i.create(W+H*I));if(K===le)return;let xt=(ee.x===H?0:2)|Number(ee.y&Ee),mt=K;return T&&S(K)&&(mt=i.neg(K),xt^=1),new D(H,mt,b?void 0:xt)}return{seed:N,k2sig:U}}function ne(u,h,y={}){const{seed:T,k2sig:R}=xe(u,h,y);return br(e.outputLen,i.BYTES,n)(T,R).toBytes(y.format)}function L(u,h,y,T={}){const{lowS:R,prehash:A,format:O}=tt(T,w);if(y=F(y,void 0,"publicKey"),h=Z(h,A),!at(u)){const I=u instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+I)}B(u,O);try{const I=D.fromBytes(u,O),C=r.fromBytes(y);if(R&&I.hasHighS())return!1;const{r:N,s:W}=I,U=Q(h),k=i.inv(W),j=i.create(U*k),V=i.create(N*k),ee=r.BASE.multiplyUnsafe(j).add(C.multiplyUnsafe(V));return ee.is0()?!1:i.create(ee.x)===N}catch{return!1}}function P(u,h,y={}){const{prehash:T}=tt(y,w);return h=Z(h,T),D.fromBytes(u,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:p,utils:m,lengths:x,Point:r,sign:ne,verify:L,recoverPublicKey:P,Signature:D,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ft={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},qr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ut=BigInt(2);function Wr(r){const e=ft.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,p=se(d,s,e)*d%e,m=se(p,s,e)*d%e,x=se(m,Ut,e)*l%e,w=se(x,n,e)*x%e,b=se(w,o,e)*w%e,S=se(b,a,e)*b%e,E=se(S,c,e)*S%e,q=se(E,a,e)*b%e,B=se(q,s,e)*d%e,D=se(B,i,e)*w%e,M=se(D,t,e)*l%e,Q=se(M,Ut,e);if(!ot.eql(ot.sqr(Q),r))throw new Error("Cannot find square root");return Q}const ot=Ke(ft.p,{sqrt:Wr}),jr=Fr(ft,{Fp:ot,endo:qr}),Vr=Gr(jr,_r),Kr=BigInt(0),Re=BigInt(1),zr=BigInt(2),Yr=BigInt(7),Zr=BigInt(256),Xr=BigInt(113),ys=[],bs=[],vs=[];for(let r=0,e=Re,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],ys.push(2*(5*t+s)),bs.push((r+1)*(r+2)/2%64);let n=Kr;for(let o=0;o<7;o++)e=(e<<Re^(e>>Yr)*Xr)%Zr,e&zr&&(n^=Re<<(Re<<BigInt(o))-Re);vs.push(n)}const Ss=cr(vs,!0),Jr=Ss[0],Qr=Ss[1],Ft=(r,e,s)=>s>32?ur(r,e,s):lr(r,e,s),Ht=(r,e,s)=>s>32?hr(r,e,s):dr(r,e,s);function en(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],p=Ft(l,d,1)^s[a],m=Ht(l,d,1)^s[a+1];for(let x=0;x<50;x+=10)r[i+x]^=p,r[i+x+1]^=m}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=bs[i],c=Ft(n,o,a),l=Ht(n,o,a),d=ys[i];n=r[d],o=r[d+1],r[d]=c,r[d+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=Jr[t],r[1]^=Qr[t]}Te(s)}class pt{constructor(e,s,t,n=!1,o=24){v(this,"state");v(this,"pos",0);v(this,"posOut",0);v(this,"finished",!1);v(this,"state32");v(this,"destroyed",!1);v(this,"blockLen");v(this,"suffix");v(this,"outputLen");v(this,"enableXOF",!1);v(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,ue(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Js(this.state)}clone(){return this._cloneInto()}keccak(){Rt(this.state32),en(this.state32,this.rounds),Rt(this.state32),this.posOut=0,this.pos=0}update(e){Ie(this),F(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ie(this,!1),F(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ue(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Yt(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:n,rounds:o,enableXOF:i}=this;return e||(e=new pt(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const tn=(r,e,s,t={})=>Xt(()=>new pt(e,r,s),t),Gt=tn(1,136,32);class sn{async verifyJWT(e,s){try{const t=this.decodeJWT(e);f.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const n=Math.floor(Date.now()/1e3);return t.exp&&t.exp<n?(f.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(f.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(f.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw f.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Rs.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
2
2
  ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);const i=Gt(o),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`Invalid signature length: expected 130 hex chars, got ${a.length}`);const c=rn(a),l=c.slice(0,32),d=c.slice(32,64),p=c[64],m=p>=27?p-27:p,b=new Vr.Signature(qt(l),qt(d)).addRecoveryBit(m).recoverPublicKey(i).toBytes(!1).slice(1),S=Gt(b);return"0x"+ke(S.slice(12))}}function rn(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 qt(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const nn=3e4;class on{async request(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??nn);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}class gt{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 n=e.width??500,o=e.height??600,i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=gt.generateState(),l=e.authUrl.includes("?")?"&":"?",d=`${e.authUrl}${l}state=${c}`,p=window.open(d,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!p){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const m=setTimeout(()=>{f.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),B(),t(new Error("Authentication timeout"))},5*60*1e3),x=10,w=30;let b=0,S=null;const E=()=>{clearInterval(q),f.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+w+"초간 대기합니다"),S=setTimeout(()=>{B(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},w*1e3)},q=setInterval(()=>{b++;try{p.closed&&(b<=x?E():(B(),t(new Error("로그인이 취소되었습니다"))))}catch{E()}},1e3),B=()=>{clearTimeout(m),clearInterval(q),S&&clearTimeout(S),window.removeEventListener("message",D)},D=M=>{var ve,he,Z,xe,ne,L,P;if(M.origin!==e.expectedOrigin)return;B(),f.log("[CROSSx] OAuth postMessage 수신 — status:",M.data.status);const Q=M.data.state??((ve=M.data.data)==null?void 0:ve.state);if(!Q||Q!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(M.data.status==="success"){const u=((he=M.data.data)==null?void 0:he.accessToken)||((Z=M.data.data)==null?void 0:Z.idToken);f.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!((xe=M.data.data)!=null&&xe.accessToken),hasIdToken:!!((ne=M.data.data)!=null&&ne.idToken)}),u?s(u):(f.error("[CROSSx] 토큰을 찾을 수 없음:",M.data),t(new Error("Token not found in response")))}else f.error("[CROSSx] OAuth 실패:",(L=M.data.data)==null?void 0:L.error),t(new Error(((P=M.data.data)==null?void 0:P.error)||"Authentication failed"))};window.addEventListener("message",D)})}}const Oe="crossx_wallet_data";class an{constructor(e){this.storage=e}async getOrCreateWallet(e){try{const s=await this.storage.get(Oe);if(s)return s;const t={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};return await this.storage.set(Oe,t),t}catch(s){throw new _(g.WALLET_CREATION_FAILED,"Wallet creation failed",s)}}async getAddresses(e){const s=await this.storage.get(Oe);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return f.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,s,t,n=0,o,i){return f.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return f.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){f.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,format:"hex"}}async sendTransaction(e,s,t,n){return f.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async recoverWallet(e,s){f.log("[Mock] recoverWallet");const t={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};return await this.storage.set(Oe,t),t}async migrateWallet(e,s){f.log(`[Mock] migrateWallet pin=${e} sub=${s}`);const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};return await this.storage.set(Oe,t),t}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 We{constructor(e,s,t,n){this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n}get baseUrl(){return this.adapterConfig.gatewayUrl}getAuthToken(){const e=this.tokenStore.get();if(!e)throw new _(g.AUTH_NOT_AUTHENTICATED,"No auth token found. Please sign in first.");return e}async request(e,s,t){var a,c;const n=this.getAuthToken(),o=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const p=d.message||d.data||"API request failed";f.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:p,url:o,method:e,fullResponse:d});const m=We.mapGatewayError(d.code),x=We.getGatewayErrorMessage(d.code,p),w=new _(m,x);throw w.gatewayCode=d.code,w.gatewayMessage=p,w}return f.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:o,method:e}),d.data??d}return d}catch(l){if(l instanceof _)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,p=d.message||d.data||"API request failed",m=d.code||"UNKNOWN";throw f.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:m,message:p,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new _(g.UNKNOWN_ERROR,`Wallet Gateway error (${m}): ${p}`)}throw l}}async getOrCreateWallet(e){var s;f.log("[CROSSx][Migration Phase 2] GET /mnemonic/addresses — 기존 지갑 조회");try{const t=await this.request("GET","/mnemonic/addresses");if(t.addresses&&t.addresses.length>0){const{address:n}=t.addresses[0];return f.log("[CROSSx][Migration Phase 2] 기존 지갑 발견 — address:",n),{id:e,address:n,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}}catch{f.log("[CROSSx][Migration Phase 2] 기존 지갑 없음, POST /mnemonic/create 진행")}f.log("[CROSSx][Migration Phase 2] POST /mnemonic/create — ignoreBackup: false");try{const t={ignoreBackup:!1},n=await this.request("POST","/mnemonic/create",t);return f.log("[CROSSx][Migration Phase 2] /mnemonic/create 성공 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}catch(t){if((t==null?void 0:t.gatewayCode)===-10004||(s=t==null?void 0:t.message)!=null&&s.includes("-10004")){f.log("[CROSSx][Migration Phase 2] 지갑 이미 존재 (-10004), 주소 재조회");const n=await this.request("GET","/mnemonic/addresses");if(n.addresses&&n.addresses.length>0)return{id:e,address:n.addresses[0].address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}throw(t==null?void 0:t.gatewayCode)===-10012&&f.log("[CROSSx][Migration Phase 2] Gateway -10012 수신 → MIGRATION_BACKUP_EXISTS throw"),t}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,s){try{return{address:(await this.request("GET",`/mnemonic/address?index=${s}`)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}catch(t){if(t instanceof _&&this.isAddressNotFoundError(t))return f.log(`[CROSSx] index ${s} 주소 없음, 파생 중...`),{address:(await this.request("GET",`/mnemonic/address?index=${s}&derive=true`)).address,derivationPath:`m/44'/60'/0'/0/${s}`};throw t}}isAddressNotFoundError(e){const s=e.message.toLowerCase();return s.includes("404")||s.includes("not found")||s.includes("찾을 수 없")||s.includes("does not exist")||s.includes("no address")}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new _(g.TX_INVALID_PARAMS,"prepare: tx is required");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new _(g.TX_INVALID_PARAMS,"prepare: message is required");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new _(g.TX_INVALID_PARAMS,"prepare: typedData is required");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t)};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t)};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).txHash}}async recoverWallet(e,s){const t={shareC:s},n=await this.request("POST","/mnemonic/recover",t);return{id:e,address:n.address,newShareC:n.newShareC,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async migrateWallet(e,s){f.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출 — sub:",s);const t={pin:e,sub:s},n=await this.request("POST","/mnemonic/migrate",t);return f.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}static mapGatewayError(e){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-10022:return g.PROJECT_NOT_REGISTERED;case-10023:return g.PROJECT_ID_MISSING;case-10024:return g.ORIGIN_NOT_ALLOWED;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.";default:return`Request failed (${e}): ${s}`}}}class Ce{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=Ce.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?Ks:Vs;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??"Chain registry request failed";throw new _(Ce.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Ce.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new _(g.CHAIN_NOT_SUPPORTED,`Unsupported chain: ${e}`)}static fallbackChains(){return Object.values(je).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 Wt="__crossx-confirm-style",te="__crossx-confirm-overlay",cn={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:"#FFFFFF",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#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:"#121212",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",onPrimary:"#FFFFFF"}};function jt(r,e){const s=cn[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},...t.bg!==void 0&&{bg:t.bg,inputBg:t.bg}}:s}const ln=`
3
3
  @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
4
4
 
package/dist/index.js CHANGED
@@ -602,7 +602,7 @@ const Hs = 2e3, bt = 6e4, Gs = 1e3, qs = 1e4, Ws = "0x77359400", vt = "0x3B9ACA0
602
602
  */
603
603
  async initialize() {
604
604
  if (this.initialized) return this.authenticated ? { success: !0, address: this.address ?? void 0 } : null;
605
- console.log("[CROSSx SDK] v1.0.5 initializing...");
605
+ console.log("[CROSSx SDK] v1.0.6 initializing...");
606
606
  try {
607
607
  const e = await Fs();
608
608
  this.internalConfig.oauthServiceUrl = e.oauthServiceUrl, this.internalConfig.authApiUrl = e.authApiUrl, this.internalConfig.walletGatewayUrl = e.walletGatewayUrl, this.adapterConfig.gatewayUrl = e.walletGatewayUrl;
@@ -798,23 +798,22 @@ const Hs = 2e3, bt = 6e4, Gs = 1e3, qs = 1e4, Ws = "0x77359400", vt = "0x3B9ACA0
798
798
  async selectWallet() {
799
799
  if (this.ensureAuthenticated(), !this.userId)
800
800
  throw new _(g.AUTH_NOT_AUTHENTICATED, "User ID not found");
801
- const e = await this.walletProvider.getAddresses(this.userId);
802
- return this.confirmation.showWalletSelector(
801
+ const e = await this.walletProvider.getAddresses(this.userId), s = await this.confirmation.showWalletSelector(
803
802
  e,
804
803
  async () => {
805
- const s = e.length, n = { address: (await this.walletProvider.getAddress(this.userId, s)).address, index: s };
806
- return e.push(n), n;
804
+ const t = e.length, o = { address: (await this.walletProvider.getAddress(this.userId, t)).address, index: t };
805
+ return e.push(o), o;
807
806
  }
808
807
  );
808
+ return s && (this.address = s.address, this.emit("addressChanged", { address: s.address, index: s.index })), s;
809
809
  }
810
810
  /**
811
- * 지갑이 2개 이상이면 selectWallet()을 호출하고, 선택 결과를 내부 상태에 반영합니다.
811
+ * 지갑이 2개 이상이면 selectWallet()을 호출합니다.
812
+ * selectWallet() 내부에서 this.address 설정 및 addressChanged 이벤트를 처리합니다.
812
813
  * 지갑이 1개 이하이거나 사용자가 취소하면 null을 반환합니다.
813
814
  */
814
815
  async selectWalletIfMultiple(e) {
815
- if (e.length < 2) return null;
816
- const s = await this.selectWallet();
817
- return s && (this.address = s.address, this.emit("addressChanged", { address: s.address, index: s.index })), s;
816
+ return e.length < 2 ? null : this.selectWallet();
818
817
  }
819
818
  // ============================================================================
820
819
  // 체인 조회
@@ -162,7 +162,8 @@ export declare class CROSSxSDK extends TypedEventEmitter<SDKEventMap> {
162
162
  index: number;
163
163
  } | null>;
164
164
  /**
165
- * 지갑이 2개 이상이면 selectWallet()을 호출하고, 선택 결과를 내부 상태에 반영합니다.
165
+ * 지갑이 2개 이상이면 selectWallet()을 호출합니다.
166
+ * selectWallet() 내부에서 this.address 설정 및 addressChanged 이벤트를 처리합니다.
166
167
  * 지갑이 1개 이하이거나 사용자가 취소하면 null을 반환합니다.
167
168
  */
168
169
  private selectWalletIfMultiple;
@@ -1 +1 @@
1
- {"version":3,"file":"CROSSxSDK.d.ts","sourceRoot":"","sources":["../../src/sdk/CROSSxSDK.ts"],"names":[],"mappings":"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"}
1
+ {"version":3,"file":"CROSSxSDK.d.ts","sourceRoot":"","sources":["../../src/sdk/CROSSxSDK.ts"],"names":[],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexus-cross/crossx-sdk-core",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "CROSSx Core SDK - Vanilla JavaScript Embedded Wallet SDK",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",