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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Is=Object.defineProperty;var As=(r,e,s)=>e in r?Is(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 p=(r=>(r.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",r.AUTH_FAILED="AUTH_FAILED",r.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",r.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",r.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",r.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))(p||{});class _ extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,_.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const je={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},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 _(p.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 _(p.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 _(p.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 _(p.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:g}=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,g);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 _(p.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 _(p.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===p.MIGRATION_BACKUP_EXISTS)f.log("[CROSSx][Migration Phase 2] Gateway -10012 감지 → needsMigration = true"),n=!0;else{if(o instanceof _&&(o.code===p.PROJECT_NOT_REGISTERED||o.code===p.PROJECT_ID_MISSING||o.code===p.ORIGIN_NOT_ALLOWED))throw 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 _(p.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 _(p.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,Tt=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.2 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 _(p.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 _(p.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:n}=await this.createWallet(),o=await this.getAddresses();return{...s,address:n,needsMigration:!1,addresses:o}}const t=await this.getAddresses();return{...s,addresses:t}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new _(p.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 _(p.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 _(p.MIGRATION_FAILED,"Wallet migration failed",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new _(p.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 _(p.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 getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof _?e:new _(p.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 _(p.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 _(p.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===p.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 _(p.MIGRATION_FAILED,"Migration skipped by user")}throw e}}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(p.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 _(p.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 _(p.SIGNATURE_FAILED,`Message signing failed (${e})`,c)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"User ID not found");if(!this.walletProvider.signTypedData)throw new _(p.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 _(p.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 _(p.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 _(p.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 _(p.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 _(p.SIGNATURE_FAILED,`Transaction signing failed (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(p.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 _(p.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 _(p.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 _(p.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),g=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:g,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:g,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 _(p.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 _(p.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 _(p.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 _(p.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 _(p.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 _(p.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(Tt),n=s/t,i=(s%t).toString().padStart(Tt,"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 _(p.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===p.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&&(f.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출"),c.nonce=await this.getNonce(s),f.log("[CROSSx] nonce 결과:",c.nonce)),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 _(p.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 _(p.TYPED_DATA_CHAIN_ID_MISMATCH,`On-chain signing (${e}) requires typedData.domain.chainId to be present`);if(t!==o)throw new _(p.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 _(p.SIGNATURE_FAILED,"Invalid signature: not a valid hex string");if(s.length!==St)throw new _(p.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 _(p.SIGNATURE_FAILED,"Invalid signedTx: not a valid hex string");if(s.length<2)throw new _(p.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 _(p.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 _(p.AUTH_NOT_INITIALIZED,"SDK is not initialized. Call initialize() first.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new _(p.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",It="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,It);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Le,It,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 Te(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 Ie(...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){Te(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){Te(this),Yt(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Ie(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let g=i;g<n;g++)s[g]=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 g=0;g<l;g++)a.setUint32(4*g,d[g],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]),ge=new Uint32Array(64);class gr 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 g=0;g<16;g++,s+=4)ge[g]=e.getUint32(s,!1);for(let g=16;g<64;g++){const m=ge[g-15],x=ge[g-2],w=oe(m,7)^oe(m,18)^m>>>3,b=oe(x,17)^oe(x,19)^x>>>10;ge[g]=b+ge[g-7]+w+ge[g-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let g=0;g<64;g++){const m=oe(a,6)^oe(a,11)^oe(a,25),x=d+m+nr(a,c,l)+fr[g]+ge[g]|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(){Ie(ge)}destroy(){this.set(0,0,0,0,0,0,0,0),Ie(this.buffer)}}class pr extends gr{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 pr,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 g=()=>{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)=>{g(),x(S);let q;for(;!(q=E(w()));)x();return g(),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 Tr(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 g=a.mul(l,n),m=a.mul(l,o),x=a.eql(a.sqr(d),c),w=a.eql(a.sqr(g),c);l=a.cmov(l,d,x),d=a.cmov(m,g,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,g=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(g,S);d=w,g=c.sqr(E),m=c.mul(m,g),x=c.mul(x,E)}return x}}function Ir(r){return r%ns===rs?cs:r%is===os?Er:r%as===Sr?Tr(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=Ir(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,g=a===0,m=a<0,x=e%2!==0;return{nextN:c,offset:d,isZero:g,isNeg:m,isNegF:x,offsetF:l}}const Qe=new WeakMap,gs=new WeakMap;function et(r){return gs.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:g,isNegF:m,offsetF:x}=Dt(t,a,i);t=c,d?o=o.add(qe(m,s[x])):n=n.add(qe(g,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 g=s[c];n=n.add(d?g.negate():g)}}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),gs.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 ps{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),Ie(n)}update(e){return Te(this),this.iHash.update(e),this}digestInto(e){Te(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 ps(r,e).update(s).digest();_s.create=(r,e)=>new ps(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 g=l<le,m=d<le;g&&(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:g,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 pe={Err:Br,_tlv:{encode:(r,e)=>{const{Err:s}=pe;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}=pe;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}=pe;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}=pe;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}=pe,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}=pe,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 g(P,u,h){const{x:y,y:I}=u.toAffine(),R=t.toBytes(y);if(Ge(h,"isCompressed"),h){d();const A=!t.isOdd(I);return _e(ms(A),R)}else return _e(Uint8Array.of(4),R,t.toBytes(I))}function m(P){F(P,void 0,"Point");const{publicKey:u,publicKeyUncompressed:h}=l,y=P.length,I=P[0],R=P.subarray(1);if(y===u&&(I===2||I===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 T;try{T=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(T);return(I&1)===1!==C&&(T=t.neg(T)),{x:A,y:T}}else if(y===h&&I===4){const A=t.BYTES,O=t.fromBytes(R.subarray(0,A)),T=t.fromBytes(R.subarray(A,A*2));if(!S(O,T))throw new Error("bad point: is not on curve");return{x:O,y:T}}else throw new Error(`bad point: got length ${y}, expected compressed=${u} or uncompressed=${h}`)}const x=e.toBytes||g,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:I}=P;if(t.eql(I,t.ONE))return{x:h,y};const R=P.is0();u==null&&(u=R?t.ONE:t.inv(I));const A=t.mul(h,u),O=t.mul(y,u),T=t.mul(I,u);if(R)return{x:t.ZERO,y:t.ZERO};if(!t.eql(T,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,I){return h=new Z(t.mul(h.X,P),h.Y,h.Z),u=qe(y,u),h=qe(I,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:I}=this,{X:R,Y:A,Z:O}=u,T=t.eql(t.mul(h,O),t.mul(R,I)),C=t.eql(t.mul(y,O),t.mul(A,I));return T&&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:I,Y:R,Z:A}=this;let O=t.ZERO,T=t.ZERO,C=t.ZERO,N=t.mul(I,I),W=t.mul(R,R),U=t.mul(A,A),k=t.mul(I,R);return k=t.add(k,k),C=t.mul(I,A),C=t.add(C,C),O=t.mul(u,C),T=t.mul(y,U),T=t.add(O,T),O=t.sub(W,T),T=t.add(W,T),T=t.mul(O,T),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),T=t.add(T,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,T,C)}add(u){D(u);const{X:h,Y:y,Z:I}=this,{X:R,Y:A,Z:O}=u;let T=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(I,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,I);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,I),T=t.add(A,O),K=t.mul(K,T),T=t.add(j,V),K=t.sub(K,T),N=t.mul(W,H),T=t.mul(U,V),N=t.add(T,N),T=t.sub(j,N),N=t.add(j,N),C=t.mul(T,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),T=t.mul(ee,T),T=t.sub(T,k),k=t.mul(ee,j),N=t.mul(K,N),N=t.add(N,k),new L(T,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,I;const R=A=>ne.cached(this,A,O=>Lt(L,O));if(h){const{k1neg:A,k1:O,k2neg:T,k2:C}=M(u),{p:N,f:W}=R(O),{p:U,f:k}=R(C);I=W.add(k),y=he(h.beta,N,U,A,T)}else{const{p:A,f:O}=R(u);y=A,I=O}return Lt(L,[y,I])[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:I,k1:R,k2neg:A,k2:O}=M(u),{p1:T,p2:C}=Lr(L,y,R,O);return he(h.beta,T,C,I,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 g={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=$r(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:r,utils:g,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:g,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,I=h==="compact"?y:h==="recovered"?y+1:void 0;return F(u,I)}class D{constructor(h,y,I){v(this,"r");v(this,"s");v(this,"recovery");if(this.r=E("r",h),this.s=E("s",y),I!=null){if(q(),![0,1,2,3].includes(I))throw new Error("invalid recovery id");this.recovery=I}Object.freeze(this)}static fromBytes(h,y=w.format){B(h,y);let I;if(y==="der"){const{r:T,s:C}=pe.toSig(F(h));return new D(T,C)}y==="recovered"&&(I=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),I)}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:I}=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),T=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(I*C),k=r.BASE.multiplyUnsafe(W).add(T.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(pe.hexFromSig(this));const{r:y,s:I}=this,R=i.toBytes(y),A=i.toBytes(I);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),I=h.length*8-c;return I>0?y>>BigInt(I):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:I,prehash:R,extraEntropy:A}=tt(y,w);u=Z(u,R);const O=Q(u),T=i.fromBytes(h);if(!i.isValidNot0(T))throw new Error("invalid private key");const C=[he(T),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*T));if(K===le)return;let xt=(ee.x===H?0:2)|Number(ee.y&Ee),mt=K;return I&&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:I,k2sig:R}=xe(u,h,y);return br(e.outputLen,i.BYTES,n)(I,R).toBytes(y.format)}function L(u,h,y,I={}){const{lowS:R,prehash:A,format:O}=tt(I,w);if(y=F(y,void 0,"publicKey"),h=Z(h,A),!at(u)){const T=u instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}B(u,O);try{const T=D.fromBytes(u,O),C=r.fromBytes(y);if(R&&T.hasHighS())return!1;const{r:N,s:W}=T,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:I}=tt(y,w);return h=Z(h,I),D.fromBytes(u,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:g,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,g=se(d,s,e)*d%e,m=se(g,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],g=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]^=g,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]}Ie(s)}class gt{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){Te(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){Te(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,Ie(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new gt(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const tn=(r,e,s,t={})=>Xt(()=>new gt(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
- ${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),g=c[64],m=g>=27?g-27:g,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 pt{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=pt.generateState(),l=e.authUrl.includes("?")?"&":"?",d=`${e.authUrl}${l}state=${c}`,g=window.open(d,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!g){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{g.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 _(p.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 _(p.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 g=d.message||d.data||"API request failed";f.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:g,url:o,method:e,fullResponse:d});const m=We.mapGatewayError(d.code),x=We.getGatewayErrorMessage(d.code,g),w=new _(m,x);throw w.gatewayCode=d.code,w.gatewayMessage=g,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,g=d.message||d.data||"API request failed",m=d.code||"UNKNOWN";throw f.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:m,message:g,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new _(p.UNKNOWN_ERROR,`Wallet Gateway error (${m}): ${g}`)}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 _(p.TX_INVALID_PARAMS,"prepare: tx is required");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new _(p.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 _(p.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 p.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10006:return"Internal server error. Please try again later.";case-10008:return"Another operation is in progress. Please try again later.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin is not in the allowed list. Register the current domain in the management console.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";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 _(p.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 p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.APP_IDENTIFIER_MISSING;case-10025:return p.INVALID_APP_TYPE;default:return p.UNKNOWN_ERROR}}}const 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=`
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:
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
 
5
5
  #${te} {
@@ -74,12 +74,14 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
74
74
  outline: none;
75
75
  }
76
76
  .__crossx-close:hover,
77
- .__crossx-close:focus {
78
- background: none;
79
- box-shadow: none;
80
- outline: none;
81
- filter: none;
82
- transform: none;
77
+ .__crossx-close:focus,
78
+ .__crossx-close:active {
79
+ background: none !important;
80
+ box-shadow: none !important;
81
+ outline: none !important;
82
+ filter: none !important;
83
+ transform: none !important;
84
+ opacity: 1 !important;
83
85
  }
84
86
  .__crossx-close svg { display: block; }
85
87
 
@@ -146,9 +148,17 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
146
148
  align-items: center;
147
149
  flex-shrink: 0;
148
150
  opacity: 0.7;
149
- transition: opacity 0.12s;
150
151
  }
151
- .__crossx-copy-btn:hover { opacity: 1; }
152
+ .__crossx-copy-btn:hover,
153
+ .__crossx-copy-btn:focus,
154
+ .__crossx-copy-btn:active {
155
+ opacity: 0.7 !important;
156
+ box-shadow: none !important;
157
+ outline: none !important;
158
+ filter: none !important;
159
+ transform: none !important;
160
+ background: none !important;
161
+ }
152
162
 
153
163
  /* Amount pill */
154
164
  .__crossx-pill {
@@ -248,14 +258,15 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
248
258
  outline: none;
249
259
  }
250
260
  .__crossx-recover-btn:hover,
251
- .__crossx-recover-btn:focus {
252
- background: var(--cx-pill-bg);
253
- border-color: var(--cx-pill-bg);
254
- opacity: 1;
255
- box-shadow: none;
256
- outline: none;
257
- filter: none;
258
- transform: none;
261
+ .__crossx-recover-btn:focus,
262
+ .__crossx-recover-btn:active {
263
+ background: var(--cx-pill-bg) !important;
264
+ border-color: var(--cx-pill-bg) !important;
265
+ opacity: 1 !important;
266
+ box-shadow: none !important;
267
+ outline: none !important;
268
+ filter: none !important;
269
+ transform: none !important;
259
270
  }
260
271
  .__crossx-recover-label {
261
272
  font-size: 18px;
@@ -285,15 +296,16 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
285
296
  outline: none;
286
297
  }
287
298
  .__crossx-skip-btn:hover,
288
- .__crossx-skip-btn:focus {
289
- background: none;
290
- color: var(--cx-subtitle);
291
- opacity: 1;
292
- box-shadow: none;
293
- outline: none;
294
- filter: none;
295
- transform: none;
296
- text-decoration: underline;
299
+ .__crossx-skip-btn:focus,
300
+ .__crossx-skip-btn:active {
301
+ background: none !important;
302
+ color: var(--cx-subtitle) !important;
303
+ opacity: 1 !important;
304
+ box-shadow: none !important;
305
+ outline: none !important;
306
+ filter: none !important;
307
+ transform: none !important;
308
+ text-decoration: underline !important;
297
309
  }
298
310
 
299
311
  /* ── PIN Input Modal ───────────────────────────────────────────── */
@@ -464,10 +476,18 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
464
476
  font-weight: 700;
465
477
  line-height: 1.3;
466
478
  cursor: pointer;
467
- transition: opacity 0.12s, transform 0.1s;
468
479
  }
469
- .__crossx-approve-btn:hover { opacity: 0.9; }
470
- .__crossx-approve-btn:active { transform: scale(0.98); }
480
+ .__crossx-approve-btn:hover,
481
+ .__crossx-approve-btn:focus,
482
+ .__crossx-approve-btn:active {
483
+ opacity: 1 !important;
484
+ box-shadow: none !important;
485
+ outline: none !important;
486
+ filter: none !important;
487
+ transform: none !important;
488
+ background: var(--cx-primary) !important;
489
+ color: var(--cx-on-primary) !important;
490
+ }
471
491
  .__crossx-btn-row {
472
492
  display: flex;
473
493
  gap: 8px;
@@ -485,9 +505,18 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
485
505
  font-weight: 700;
486
506
  line-height: 1.3;
487
507
  cursor: pointer;
488
- transition: opacity 0.12s;
489
508
  }
490
- .__crossx-cancel-btn:hover { opacity: 0.8; }
509
+ .__crossx-cancel-btn:hover,
510
+ .__crossx-cancel-btn:focus,
511
+ .__crossx-cancel-btn:active {
512
+ opacity: 1 !important;
513
+ box-shadow: none !important;
514
+ outline: none !important;
515
+ filter: none !important;
516
+ transform: none !important;
517
+ background: none !important;
518
+ color: var(--cx-primary) !important;
519
+ }
491
520
  .__crossx-confirm-btn {
492
521
  flex: 1;
493
522
  padding: 16px;
@@ -500,10 +529,18 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
500
529
  font-weight: 700;
501
530
  line-height: 1.3;
502
531
  cursor: pointer;
503
- transition: opacity 0.12s, transform 0.1s;
504
532
  }
505
- .__crossx-confirm-btn:hover { opacity: 0.9; }
506
- .__crossx-confirm-btn:active { transform: scale(0.98); }
533
+ .__crossx-confirm-btn:hover,
534
+ .__crossx-confirm-btn:focus,
535
+ .__crossx-confirm-btn:active {
536
+ opacity: 1 !important;
537
+ box-shadow: none !important;
538
+ outline: none !important;
539
+ filter: none !important;
540
+ transform: none !important;
541
+ background: var(--cx-primary) !important;
542
+ color: var(--cx-on-primary) !important;
543
+ }
507
544
 
508
545
  /* ── Transaction Progress / Complete Modal ─────────────────── */
509
546
  @keyframes __crossx-spinner {
@@ -584,13 +621,17 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
584
621
  -webkit-tap-highlight-color: transparent;
585
622
  box-shadow: none;
586
623
  outline: none;
587
- transition: opacity 0.12s;
588
624
  min-width: 0;
589
625
  }
590
- .__crossx-login-btn:hover { opacity: 0.8; }
591
- .__crossx-login-btn:focus {
592
- outline: none;
593
- box-shadow: none;
626
+ .__crossx-login-btn:hover,
627
+ .__crossx-login-btn:focus,
628
+ .__crossx-login-btn:active {
629
+ opacity: 1 !important;
630
+ box-shadow: none !important;
631
+ outline: none !important;
632
+ filter: none !important;
633
+ transform: none !important;
634
+ background: var(--cx-pill-bg) !important;
594
635
  }
595
636
  .__crossx-login-btn-label {
596
637
  font-size: 18px;
@@ -624,14 +665,16 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
624
665
  text-decoration: none;
625
666
  }
626
667
  .__crossx-login-terms-link:hover,
627
- .__crossx-login-terms-link:focus {
628
- color: var(--cx-primary);
629
- text-decoration: none;
630
- opacity: 1;
631
- background: none;
632
- box-shadow: none;
633
- outline: none;
634
- filter: none;
668
+ .__crossx-login-terms-link:focus,
669
+ .__crossx-login-terms-link:active {
670
+ color: var(--cx-primary) !important;
671
+ text-decoration: none !important;
672
+ opacity: 1 !important;
673
+ background: none !important;
674
+ box-shadow: none !important;
675
+ outline: none !important;
676
+ filter: none !important;
677
+ transform: none !important;
635
678
  }
636
679
 
637
680
  /* ── Wallet Selector Modal ─────────────────────────────────── */
@@ -666,11 +709,18 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
666
709
  box-shadow: none;
667
710
  outline: none;
668
711
  width: 100%;
669
- transition: opacity 0.12s;
670
712
  font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
671
713
  }
672
- .__crossx-wallet-item:hover { opacity: 0.8; }
673
- .__crossx-wallet-item:focus { outline: none; box-shadow: none; }
714
+ .__crossx-wallet-item:hover,
715
+ .__crossx-wallet-item:focus,
716
+ .__crossx-wallet-item:active {
717
+ opacity: 1 !important;
718
+ box-shadow: none !important;
719
+ outline: none !important;
720
+ filter: none !important;
721
+ transform: none !important;
722
+ background: var(--cx-pill-bg) !important;
723
+ }
674
724
  .__crossx-wallet-addr {
675
725
  font-size: 16px;
676
726
  font-weight: 600;
@@ -694,12 +744,19 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
694
744
  outline: none;
695
745
  background: none;
696
746
  width: 100%;
697
- transition: opacity 0.12s;
698
747
  flex-shrink: 0;
699
748
  font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
700
749
  }
701
- .__crossx-wallet-add:hover { opacity: 0.8; }
702
- .__crossx-wallet-add:focus { outline: none; box-shadow: none; }
750
+ .__crossx-wallet-add:hover,
751
+ .__crossx-wallet-add:focus,
752
+ .__crossx-wallet-add:active {
753
+ opacity: 1 !important;
754
+ box-shadow: none !important;
755
+ outline: none !important;
756
+ filter: none !important;
757
+ transform: none !important;
758
+ background: none !important;
759
+ }
703
760
  .__crossx-wallet-add:disabled { opacity: 0.5; cursor: not-allowed; }
704
761
  .__crossx-wallet-add-icon {
705
762
  width: 24px;
@@ -845,7 +902,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
845
902
  }
846
903
  .__crossx-card--wallet-selector .__crossx-wallet-add { flex-shrink: 0; }
847
904
  }
848
- `;function me(){let r=document.getElementById(Wt);r||(r=document.createElement("style"),r.id=Wt,document.head.appendChild(r)),r.textContent=ln}function Y(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function dn(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const n=it(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Vt={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Es(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Vt[e]?Vt[e]:r}function it(r,e){if(r===0n)return"0";const s=10n**BigInt(e),t=r/s,i=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function st(r){try{const e=BigInt(r),s=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${s}.${n}`:`${s}`}catch{return r}}function un(r){try{return BigInt(r).toLocaleString()}catch{return r}}function hn(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:o="ETH",nativeDecimals:i=18}=r;if(!e)return null;try{const a=BigInt(e),c=un(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${it(l,i)} ${o}`,maxFeeGwei:st(t),maxPriorityFeeGwei:n?st(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${it(l,i)} ${o}`,gasPriceGwei:st(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Ts(r){const e=hn(r);if(!e)return G("Estimated fee","<span>—</span>");let s=G("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=G("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=G("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=G("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=G("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}const de=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
905
+ `;function me(){let r=document.getElementById(Wt);r||(r=document.createElement("style"),r.id=Wt,document.head.appendChild(r)),r.textContent=ln}function Y(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function dn(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const n=it(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Vt={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Es(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Vt[e]?Vt[e]:r}function it(r,e){if(r===0n)return"0";const s=10n**BigInt(e),t=r/s,i=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function st(r){try{const e=BigInt(r),s=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${s}.${n}`:`${s}`}catch{return r}}function un(r){try{return BigInt(r).toLocaleString()}catch{return r}}function hn(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:o="ETH",nativeDecimals:i=18}=r;if(!e)return null;try{const a=BigInt(e),c=un(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${it(l,i)} ${o}`,maxFeeGwei:st(t),maxPriorityFeeGwei:n?st(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${it(l,i)} ${o}`,gasPriceGwei:st(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Is(r){const e=hn(r);if(!e)return G("Estimated fee","<span>—</span>");let s=G("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=G("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=G("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=G("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=G("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}const de=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
849
906
  <rect x="9" y="9" width="13" height="13" rx="2"/>
850
907
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
851
908
  </svg>`,ie=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
@@ -858,9 +915,9 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
858
915
  <rect x="2" y="5" width="16" height="12" rx="2" stroke="currentColor" stroke-width="1.5"/>
859
916
  <path d="M2 9h16" stroke="currentColor" stroke-width="1.5"/>
860
917
  <rect x="12.5" y="11.5" width="3.5" height="2.5" rx="0.75" fill="currentColor"/>
861
- </svg>`,gn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
862
- <path d="M12 0C18.6274 0 24 5.37258 24 12C23.9999 18.6273 18.6274 24 12 24C5.37264 24 9.89594e-05 18.6273 0 12C0 5.37258 5.37258 0 12 0ZM10.875 15.127V17.377H13.125V15.127H10.875ZM10.875 6.62207V13.627H13.125V6.62207H10.875Z" fill="var(--cx-secondary)"/>
863
918
  </svg>`,pn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
919
+ <path d="M12 0C18.6274 0 24 5.37258 24 12C23.9999 18.6273 18.6274 24 12 24C5.37264 24 9.89594e-05 18.6273 0 12C0 5.37258 5.37258 0 12 0ZM10.875 15.127V17.377H13.125V15.127H10.875ZM10.875 6.62207V13.627H13.125V6.62207H10.875Z" fill="var(--cx-secondary)"/>
920
+ </svg>`,gn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
864
921
  <circle cx="12" cy="12" r="12" fill="var(--cx-secondary)"/>
865
922
  <circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
866
923
  <path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
@@ -869,7 +926,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
869
926
  <span class="__crossx-row-label">${r}</span>
870
927
  <div class="__crossx-row-value">${e}</div>
871
928
  </div>`}function _n(r,e){const s=e,t=ze(),n=r.to?`<span class="__crossx-addr-text">${Y(r.to)}</span>
872
- <button class="__crossx-copy-btn" data-copy="${$(r.to)}" title="Copy address">${de}</button>`:"<span>—</span>",o=Ts(r),i=r.data&&r.data!=="0x"?r.data:"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
929
+ <button class="__crossx-copy-btn" data-copy="${$(r.to)}" title="Copy address">${de}</button>`:"<span>—</span>",o=Is(r),i=r.data&&r.data!=="0x"?r.data:"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
873
930
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
874
931
  <div class="__crossx-header">
875
932
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
@@ -903,7 +960,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
903
960
  </div>
904
961
  </div>
905
962
  `,a}function xn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=ze(),i=r.to?`<span class="__crossx-addr-text">${Y(r.to)}</span>
906
- <button class="__crossx-copy-btn" data-copy="${$(r.to)}" title="Copy address">${de}</button>`:"<span>—</span>",a=Ts(r),l=dn(r.value,t,n)??"—",d=document.createElement("div");return d.id=te,d.innerHTML=`
963
+ <button class="__crossx-copy-btn" data-copy="${$(r.to)}" title="Copy address">${de}</button>`:"<span>—</span>",a=Is(r),l=dn(r.value,t,n)??"—",d=document.createElement("div");return d.id=te,d.innerHTML=`
907
964
  <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
908
965
  <div class="__crossx-header">
909
966
  <p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
@@ -966,9 +1023,9 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
966
1023
  </div>
967
1024
  </div>
968
1025
  </div>
969
- `,s}function vn(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",o=r.querySelector("#__crossx-ttl"),i=r.querySelector(".__crossx-header");if(o){const w=n?pn:t?"":gn,b=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";w?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${w}<span>${b}</span>`):o.textContent=b}if(i&&!r.querySelector("#__crossx-close-btn")){const w=document.createElement("button");w.className="__crossx-close",w.id="__crossx-close-btn",w.setAttribute("aria-label","Close"),w.innerHTML=ie,i.appendChild(w)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?G("From",`<span class="__crossx-addr-text">${Y(e.from)}</span>
1026
+ `,s}function vn(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",o=r.querySelector("#__crossx-ttl"),i=r.querySelector(".__crossx-header");if(o){const w=n?gn:t?"":pn,b=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";w?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${w}<span>${b}</span>`):o.textContent=b}if(i&&!r.querySelector("#__crossx-close-btn")){const w=document.createElement("button");w.className="__crossx-close",w.id="__crossx-close-btn",w.setAttribute("aria-label","Close"),w.innerHTML=ie,i.appendChild(w)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?G("From",`<span class="__crossx-addr-text">${Y(e.from)}</span>
970
1027
  <button class="__crossx-copy-btn" data-copy="${$(e.from)}" title="Copy address">${de}</button>`):"",l=e.to?G("To",`<span class="__crossx-addr-text">${Y(e.to)}</span>
971
- <button class="__crossx-copy-btn" data-copy="${$(e.to)}" title="Copy address">${de}</button>`):"",d=e.amount?G("Transfer",`<span>${$(e.amount)}</span>`):"",g=e.fees?G("Tx Fee",`<span>${$(e.fees)}</span>`):"",m=e.txHash?G("Tx Hash",`<span class="__crossx-addr-text">${Y(e.txHash)}</span>
1028
+ <button class="__crossx-copy-btn" data-copy="${$(e.to)}" title="Copy address">${de}</button>`):"",d=e.amount?G("Transfer",`<span>${$(e.amount)}</span>`):"",p=e.fees?G("Tx Fee",`<span>${$(e.fees)}</span>`):"",m=e.txHash?G("Tx Hash",`<span class="__crossx-addr-text">${Y(e.txHash)}</span>
972
1029
  <button class="__crossx-copy-btn" data-copy="${$(e.txHash)}" title="Copy hash">${de}</button>`):"",x=e.total?`<div class="__crossx-total-pill">
973
1030
  <span class="__crossx-total-label">Total<br>(including fees)</span>
974
1031
  <span class="__crossx-total-amount">${$(e.total)}</span>
@@ -977,7 +1034,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
977
1034
  ${c}
978
1035
  ${l}
979
1036
  ${d}
980
- ${g}
1037
+ ${p}
981
1038
  ${m}
982
1039
  </div>
983
1040
  ${x}
@@ -1014,8 +1071,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1014
1071
  <div class="__crossx-td-row">
1015
1072
  <span class="__crossx-td-label">Primary Type</span>
1016
1073
  <span class="__crossx-td-value">${$(o)}</span>
1017
- </div>`;for(const[l,d]of Object.entries(i)){const g=wn(d),x=mn(d)?`<span class="__crossx-addr-text">${Y(d)}</span>
1018
- <button class="__crossx-copy-btn" data-copy="${$(String(d))}" title="Copy">${de}</button>`:`<span>${g}</span>`;a+=`
1074
+ </div>`;for(const[l,d]of Object.entries(i)){const p=wn(d),x=mn(d)?`<span class="__crossx-addr-text">${Y(d)}</span>
1075
+ <button class="__crossx-copy-btn" data-copy="${$(String(d))}" title="Copy">${de}</button>`:`<span>${p}</span>`;a+=`
1019
1076
  <div class="__crossx-td-row">
1020
1077
  <span class="__crossx-td-label">${$(l)}</span>
1021
1078
  <div class="__crossx-td-value">${x}</div>
@@ -1047,10 +1104,10 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1047
1104
  </div>
1048
1105
  </div>
1049
1106
  </div>
1050
- `,c}const Tn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
1107
+ `,c}const In=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
1051
1108
  <line x1="12" y1="5" x2="12" y2="19"/>
1052
1109
  <line x1="5" y1="12" x2="19" y2="12"/>
1053
- </svg>`;function In(r,e){const s=r.map(n=>`<button class="__crossx-wallet-item" data-wallet-index="${n.index}" data-wallet-address="${$(n.address)}">
1110
+ </svg>`;function Tn(r,e){const s=r.map(n=>`<button class="__crossx-wallet-item" data-wallet-index="${n.index}" data-wallet-address="${$(n.address)}">
1054
1111
  <span class="__crossx-wallet-addr">${Y(n.address)}</span>
1055
1112
  </button>`).join(""),t=document.createElement("div");return t.id=te,t.innerHTML=`
1056
1113
  <div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
@@ -1076,7 +1133,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1076
1133
  ${s}
1077
1134
  </div>
1078
1135
  <button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
1079
- <span class="__crossx-wallet-add-icon">${Tn}</span>
1136
+ <span class="__crossx-wallet-add-icon">${In}</span>
1080
1137
  <span class="__crossx-wallet-add-label">add a wallet</span>
1081
1138
  </button>
1082
1139
  </div>
@@ -1156,4 +1213,4 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1156
1213
  ${t}
1157
1214
  </div>
1158
1215
  </div>
1159
- `,n}function Nn(r,e,s){var n;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,i)=>{o.addEventListener("input",()=>{const a=o.value.replace(/\D/g,"");o.value=a?a[0]:"",a&&i<3&&t[i+1].focus();const c=Array.from(t).map(l=>l.value).join("");c.length===4&&setTimeout(()=>e(c),200)}),o.addEventListener("keydown",a=>{a.key==="Backspace"&&!o.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&s()}),o.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),o.addEventListener("paste",a=>{var d;a.preventDefault();const c=(((d=a.clipboardData)==null?void 0:d.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!c)return;c.split("").forEach((g,m)=>{t[m]&&(t[m].value=g)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(n=t[0])==null||n.focus()}class Pn{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=jt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=jt(e,this.overrides)}getTheme(){return this.theme}showWalletSelector(e,s){return new Promise(t=>{var w;me();const n=[...e],o=In(n,this.tokens),i=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(o);let a=!1;const c=()=>{a||(a=!0,o.remove(),document.body.style.overflow=i)},l=b=>{c(),t(b)},d=()=>{c(),t(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(b=>{b.addEventListener("click",()=>{const S=b.dataset.walletAddress??"",E=parseInt(b.dataset.walletIndex??"0",10);l({address:S,index:E})})})})();const m=o.querySelector("#__crossx-add-wallet-btn");m&&m.addEventListener("click",async()=>{m.disabled=!0;try{const b=await s();n.push(b);const S=o.querySelector("#__crossx-wallet-list");if(S){const E=document.createElement("button");E.className="__crossx-wallet-item",E.dataset.walletIndex=String(b.index),E.dataset.walletAddress=b.address,E.innerHTML=`<span class="__crossx-wallet-addr">${Y(b.address)}</span>`,E.addEventListener("click",()=>l(b)),S.appendChild(E),E.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{m.disabled=!1}}),(w=o.querySelector("#__crossx-close-btn"))==null||w.addEventListener("click",d),o.addEventListener("click",b=>{b.target===o&&d()});const x=b=>{b.key==="Escape"&&(document.removeEventListener("keydown",x),d())};document.addEventListener("keydown",x)})}showLoginSelector(){return new Promise(e=>{var a,c,l;me();const s=On(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=d=>{t(),e(d)},o=()=>{t(),e(null)};(a=s.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>n("apple")),(c=s.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>n("google")),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()}),s.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",g=>g.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;me();const s=Cn(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=()=>{t(),e("recover")},o=()=>{t(),e("skip")};(a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),(c=s.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",o),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showPinInputPrompt(e){return new Promise(s=>{var a;me();const t=kn(this.tokens,e);document.body.appendChild(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};Nn(t,o,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;me();const t=yn(e,this.tokens);document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var m;d.stopPropagation();const g=l.dataset.copy;g&&((m=navigator.clipboard)==null||m.writeText(g).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{me();const n=bn(e,this.tokens);document.body.appendChild(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var d,g;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(g=n.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",a),n.addEventListener("click",m=>{m.target===n&&a()});const l=m=>{m.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(vn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;me();let t;e.type==="sign-message"?t=Sn(e,this.tokens):e.type==="sign-typed-data"?t=En(e,this.tokens):e.type==="sign"?t=_n(e,this.tokens):t=xn(e,this.tokens),document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s(!0)},i=()=>{n(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",o),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(d=t.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",m=>{var w;m.stopPropagation();const x=g.dataset.copy;x&&((w=navigator.clipboard)==null||w.writeText(x).catch(()=>{}))})}),t.addEventListener("click",g=>{g.target===t&&i()});const a=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class Ln{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}function Dn(r){r.debug;const e=Ue.production,s={...r,oauthServiceUrl:e.oauthServiceUrl,authApiUrl:e.authApiUrl,walletGatewayUrl:e.walletGatewayUrl},t={gatewayUrl:e.walletGatewayUrl,projectId:r.projectId},o=s.authMode!=="cookie"&&At.isAvailable()?new At:new zs,i=new sn,a=new on,c=new pt,l=new Ln;let d;r.useMockWallet?(f.log("[CROSSx] Mock Wallet Provider 사용"),d=new an(o)):(f.log("[CROSSx] Remote Wallet Provider 사용"),d=new We(t,o,a,l));const g=new Ce(t,a),m=new Pn(r.theme??"light",r.themeTokens);return new Fe(s,t,o,i,a,c,d,l,m,g)}exports.CROSSxError=_;exports.CROSSxEthereumProvider=Kt;exports.CROSSxSDK=Fe;exports.ChainId=Os;exports.ErrorCode=p;exports.createCROSSxSDK=Dn;
1216
+ `,n}function Nn(r,e,s){var n;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,i)=>{o.addEventListener("input",()=>{const a=o.value.replace(/\D/g,"");o.value=a?a[0]:"",a&&i<3&&t[i+1].focus();const c=Array.from(t).map(l=>l.value).join("");c.length===4&&setTimeout(()=>e(c),200)}),o.addEventListener("keydown",a=>{a.key==="Backspace"&&!o.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&s()}),o.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),o.addEventListener("paste",a=>{var d;a.preventDefault();const c=(((d=a.clipboardData)==null?void 0:d.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!c)return;c.split("").forEach((p,m)=>{t[m]&&(t[m].value=p)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(n=t[0])==null||n.focus()}class Pn{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=jt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=jt(e,this.overrides)}getTheme(){return this.theme}showWalletSelector(e,s){return new Promise(t=>{var w;me();const n=[...e],o=Tn(n,this.tokens),i=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(o);let a=!1;const c=()=>{a||(a=!0,o.remove(),document.body.style.overflow=i)},l=b=>{c(),t(b)},d=()=>{c(),t(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(b=>{b.addEventListener("click",()=>{const S=b.dataset.walletAddress??"",E=parseInt(b.dataset.walletIndex??"0",10);l({address:S,index:E})})})})();const m=o.querySelector("#__crossx-add-wallet-btn");m&&m.addEventListener("click",async()=>{m.disabled=!0;try{const b=await s();n.push(b);const S=o.querySelector("#__crossx-wallet-list");if(S){const E=document.createElement("button");E.className="__crossx-wallet-item",E.dataset.walletIndex=String(b.index),E.dataset.walletAddress=b.address,E.innerHTML=`<span class="__crossx-wallet-addr">${Y(b.address)}</span>`,E.addEventListener("click",()=>l(b)),S.appendChild(E),E.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{m.disabled=!1}}),(w=o.querySelector("#__crossx-close-btn"))==null||w.addEventListener("click",d),o.addEventListener("click",b=>{b.target===o&&d()});const x=b=>{b.key==="Escape"&&(document.removeEventListener("keydown",x),d())};document.addEventListener("keydown",x)})}showLoginSelector(){return new Promise(e=>{var a,c,l;me();const s=On(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=d=>{t(),e(d)},o=()=>{t(),e(null)};(a=s.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>n("apple")),(c=s.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>n("google")),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()}),s.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",p=>p.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;me();const s=Cn(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=()=>{t(),e("recover")},o=()=>{t(),e("skip")};(a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),(c=s.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",o),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showPinInputPrompt(e){return new Promise(s=>{var a;me();const t=kn(this.tokens,e);document.body.appendChild(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};Nn(t,o,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;me();const t=yn(e,this.tokens);document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var m;d.stopPropagation();const p=l.dataset.copy;p&&((m=navigator.clipboard)==null||m.writeText(p).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{me();const n=bn(e,this.tokens);document.body.appendChild(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var d,p;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),n.addEventListener("click",m=>{m.target===n&&a()});const l=m=>{m.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(vn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;me();let t;e.type==="sign-message"?t=Sn(e,this.tokens):e.type==="sign-typed-data"?t=En(e,this.tokens):e.type==="sign"?t=_n(e,this.tokens):t=xn(e,this.tokens),document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s(!0)},i=()=>{n(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",o),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(d=t.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(p=>{p.addEventListener("click",m=>{var w;m.stopPropagation();const x=p.dataset.copy;x&&((w=navigator.clipboard)==null||w.writeText(x).catch(()=>{}))})}),t.addEventListener("click",p=>{p.target===t&&i()});const a=p=>{p.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class Ln{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}function Dn(r){r.debug;const e=Ue.production,s={...r,oauthServiceUrl:e.oauthServiceUrl,authApiUrl:e.authApiUrl,walletGatewayUrl:e.walletGatewayUrl},t={gatewayUrl:e.walletGatewayUrl,projectId:r.projectId},o=s.authMode!=="cookie"&&At.isAvailable()?new At:new zs,i=new sn,a=new on,c=new gt,l=new Ln;let d;r.useMockWallet?(f.log("[CROSSx] Mock Wallet Provider 사용"),d=new an(o)):(f.log("[CROSSx] Remote Wallet Provider 사용"),d=new We(t,o,a,l));const p=new Ce(t,a),m=new Pn(r.theme??"light",r.themeTokens);return new Fe(s,t,o,i,a,c,d,l,m,p)}exports.CROSSxError=_;exports.CROSSxEthereumProvider=Kt;exports.CROSSxSDK=Fe;exports.ChainId=Os;exports.ErrorCode=g;exports.createCROSSxSDK=Dn;