@nexus-cross/crossx-sdk-core 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +2 -2
  2. package/dist/__tests__/mocks/MockWalletProviderPort.d.ts +4 -0
  3. package/dist/__tests__/mocks/MockWalletProviderPort.d.ts.map +1 -1
  4. package/dist/adapters/chain/RemoteChainRegistryAdapter.d.ts +2 -1
  5. package/dist/adapters/chain/RemoteChainRegistryAdapter.d.ts.map +1 -1
  6. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +15 -0
  7. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
  8. package/dist/adapters/wallet/MockWalletProviderAdapter.d.ts +4 -0
  9. package/dist/adapters/wallet/MockWalletProviderAdapter.d.ts.map +1 -1
  10. package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts +6 -1
  11. package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts.map +1 -1
  12. package/dist/core/config/environments.d.ts +28 -0
  13. package/dist/core/config/environments.d.ts.map +1 -0
  14. package/dist/core/ports/ConfirmationPort.d.ts +19 -0
  15. package/dist/core/ports/ConfirmationPort.d.ts.map +1 -1
  16. package/dist/core/ports/WalletProviderPort.d.ts +7 -0
  17. package/dist/core/ports/WalletProviderPort.d.ts.map +1 -1
  18. package/dist/core/types/index.d.ts +0 -6
  19. package/dist/core/types/index.d.ts.map +1 -1
  20. package/dist/core/types/internal.d.ts +2 -0
  21. package/dist/core/types/internal.d.ts.map +1 -1
  22. package/dist/core/usecases/SignOutUseCase.d.ts +2 -2
  23. package/dist/core/usecases/SignOutUseCase.d.ts.map +1 -1
  24. package/dist/index.cjs +205 -75
  25. package/dist/index.js +1349 -1089
  26. package/dist/sdk/CROSSxSDK.d.ts +31 -2
  27. package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
  28. package/dist/sdk/factory.d.ts.map +1 -1
  29. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Es=Object.defineProperty;var Ts=(r,e,s)=>e in r?Es(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var b=(r,e,s)=>Ts(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const As=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 We={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}},Is=Object.fromEntries(Object.entries(We).map(([r,e])=>[r,e.caipId])),Rs=new Map(Object.values(We).map(r=>[r.caipId,r]));new Map(Object.values(We).map(r=>[r.chainId,r]));const Os={symbol:"",decimals:18};function ze(r){var e;return((e=Rs.get(r))==null?void 0:e.nativeCurrency)??Os}class jt{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 me=null;function mt(r){me=r}const f={log(...r){if(me){me.log(...r);return}},warn(...r){if(me){me.warn(...r);return}},error(...r){if(me){me.error(...r);return}}},Ye="crossx_access_token",Ne="crossx_refresh_token",Pe="crossx_user_info";class Cs{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!=="token"}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,w=`${d}${l}`;f.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인):`,w);const m=await this.oauth.openAuth({authUrl:w,expectedOrigin:new URL(d).origin});f.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",m.length,")");const{accessToken:x,refreshToken:A}=await this.exchangeFirebaseToken(m,g);let E,C;try{const $=this.crypto.decodeJWT(m);C=(n=$.firebase)==null?void 0:n.sign_in_provider;const B=((o=$.firebase)==null?void 0:o.identities)??{};C==="google.com"?E=(i=B["google.com"])==null?void 0:i[0]:C==="apple.com"&&(E=(a=B["apple.com"])==null?void 0:a[0]),f.log("[CROSSx] OAuth provider sub 추출 — provider:",C,"hasProviderSub:",!!E)}catch{f.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(x){const $=this.crypto.decodeJWT(x);f.log("[CROSSx] access_token 디코딩 — sub:",$.sub,"exp:",$.exp);const B=await this.crypto.verifyJWT(x);if(t=B.signatureVerified??!1,!B.valid)throw f.error("[CROSSx] access_token 검증 실패"),new Error("Invalid access token");const F=B.payload;s={id:F.sub,email:F.email,signInProvider:C,providerSub:E},this.tokenStore.set(x),this.useCookieAuth||(await this.storage.set(Ye,x),A&&await this.storage.set(Ne,A))}else{const $=this.crypto.decodeJWT(m);s={id:$.sub,email:$.email,signInProvider:C,providerSub:E},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(Ye),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(Ye,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 Ns="crossx_access_token",Ps="crossx_refresh_token",ks="crossx_user_info";class Ls{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t}async execute(){this.tokenStore.clear(),this.config.authMode==="token"&&(await this.storage.remove(Ns),await this.storage.remove(Ps)),await this.storage.remove(ks)}}class Ds{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 $s{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 Bs{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 Ms=2e3,wt=6e4,Fs=1e3,Us=1e4,Hs="0x77359400",yt="0x3B9ACA00",bt=130,vt=6,St=18,Gs=0,qs=30*1e3,Z=class Z extends Bs{constructor(e,s,t,n,o,i,a,c,l){super(),this.storage=s,this.crypto=t,this.transport=n,this.oauth=o,this.walletProvider=i,this.tokenStore=a,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}),e.logger&&mt(e.logger),this.confirmation=c,this.chainRegistry=l,this.jsonRpc=new $s(l,n),this.signInUseCase=new Cs(e,s,t,o,n,i,a),this.signOutUseCase=new Ls(e,s,a),this.migrateWalletUseCase=new Ds(s,i)}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.0 initializing...");try{const e=await this.signInUseCase.restoreSession();return e!=null&&e.success&&this.applyAuthResult(e),this.initialized=!0,this.emit("initialized",{restored:!!(e!=null&&e.success)}),e??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 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.address?[{address:this.address,index:0}]:[]}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");Z.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 Z.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(Z.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=ze(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol: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 Z.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=ze(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol: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??Fs,o=Us,i=t.timeoutMs??wt,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 w,m;const{txHash:n}=await this.sendTransaction(e,s),o=t.intervalMs??((w=this._config.receiptPolling)==null?void 0:w.intervalMs)??Ms,i=t.timeoutMs??((m=this._config.receiptPolling)==null?void 0:m.timeoutMs)??wt,a=ze(e),c=s.from??"";let l,d;const g=this.waitForTxAndGetReceipt(n,e,{intervalMs:o,timeoutMs:i}).then(x=>{l=x;const A=BigInt(x.gasUsed)*BigInt(x.effectiveGasPrice),E=s.value?BigInt(s.value):0n,C=Z.formatTxAmount(s.value,a.symbol,a.decimals),q=Z.formatTxAmount("0x"+A.toString(16),a.symbol,a.decimals),$=Z.formatTxAmount("0x"+(E+A).toString(16),a.symbol,a.decimals);return{chainId:e,txHash:n,from:x.from,to:x.to??s.to,amount:C,fees:q,total:$,nativeSymbol:a.symbol,status:x.status==="0x1"?"success":"reverted"}}).catch(x=>(d=x instanceof Error?x:new Error(String(x)),{chainId:e,txHash:n,from:c,to:s.to,amount:Z.formatTxAmount(s.value,a.symbol,a.decimals),nativeSymbol:a.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:n,from:c,to:s.to},g),d)throw d;return{chainId:e,txHash:n,receipt:l}}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:Z.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(St),n=s/t,i=(s%t).toString().padStart(St,"0").replace(/0+$/,"").slice(0,vt);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new jt(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,`rpcRequest 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,vt).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=yt;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=Hs,f.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=yt,f.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=Z.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!==bt)throw new _(p.SIGNATURE_FAILED,`Invalid signature length: expected ${bt} 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=Z.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(),mt(null)}};Z.OFFCHAIN_CHAIN_ID="0";let Fe=Z;class Ws{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 js="crossx-sdk",Vs=1,ve="data",ke="keys",Et="aes-primary",Ks=12;class Tt{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(js,Vs);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(ve)||n.createObjectStore(ve),n.objectStoreNames.contains(ke)||n.createObjectStore(ke)},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(ke,Et);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(ke,Et,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(Ks);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(ve,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(ve,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(ve,e)}catch(s){throw f.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(ve)}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 it(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function le(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function U(r,e,s=""){const t=it(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 Vt(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");le(r.outputLen),le(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 Kt(r,e){U(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 zs(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Ae(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ze(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function oe(r,e){return r<<32-e|r>>>e}const Ys=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Zs(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Xs(r){for(let e=0;e<r.length;e++)r[e]=Zs(r[e]);return r}const At=Ys?r=>r:Xs,zt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Js=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ce(r){if(U(r),zt)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=Js[r[s]];return e}const ie={_0:48,_9:57,A:65,F:70,a:97,f:102};function It(r){if(r>=ie._0&&r<=ie._9)return r-ie._0;if(r>=ie.A&&r<=ie.F)return r-(ie.A-10);if(r>=ie.a&&r<=ie.f)return r-(ie.a-10)}function Ue(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=It(r.charCodeAt(o)),a=It(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 xe(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];U(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 Yt(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 Zt(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 Qs=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function er(r,e,s){return r&e^~r&s}function tr(r,e,s){return r&e^r&s^e&s}class sr{constructor(e,s,t,n){b(this,"blockLen");b(this,"outputLen");b(this,"padOffset");b(this,"isLE");b(this,"buffer");b(this,"view");b(this,"finished",!1);b(this,"length",0);b(this,"pos",0);b(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ze(this.buffer)}update(e){Te(this),U(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=Ze(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),Kt(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Ae(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=Ze(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]),Le=BigInt(2**32-1),Rt=BigInt(32);function rr(r,e=!1){return e?{h:Number(r&Le),l:Number(r>>Rt&Le)}:{h:Number(r>>Rt&Le)|0,l:Number(r&Le)|0}}function nr(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}=rr(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const or=(r,e,s)=>r<<s|e>>>32-s,ir=(r,e,s)=>e<<s|r>>>32-s,ar=(r,e,s)=>e<<s-32|r>>>64-s,cr=(r,e,s)=>r<<s-32|e>>>64-s,lr=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 dr extends sr{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 w=ge[g-15],m=ge[g-2],x=oe(w,7)^oe(w,18)^w>>>3,A=oe(m,17)^oe(m,19)^m>>>10;ge[g]=A+ge[g-7]+x+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 w=oe(a,6)^oe(a,11)^oe(a,25),m=d+w+er(a,c,l)+lr[g]+ge[g]|0,A=(oe(t,2)^oe(t,13)^oe(t,22))+tr(t,n,o)|0;d=l,l=c,c=a,a=i+m|0,i=o,o=n,n=t,t=m+A|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(){Ae(ge)}destroy(){this.set(0,0,0,0,0,0,0,0),Ae(this.buffer)}}class ur extends dr{constructor(){super(32);b(this,"A",fe[0]|0);b(this,"B",fe[1]|0);b(this,"C",fe[2]|0);b(this,"D",fe[3]|0);b(this,"E",fe[4]|0);b(this,"F",fe[5]|0);b(this,"G",fe[6]|0);b(this,"H",fe[7]|0)}}const hr=Yt(()=>new ur,Qs(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const at=BigInt(0),st=BigInt(1);function He(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Xt(r){if(typeof r=="bigint"){if(!Me(r))throw new Error("positive bigint expected, got "+r)}else le(r);return r}function De(r){const e=Xt(r).toString(16);return e.length&1?"0"+e:e}function Jt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?at:BigInt("0x"+r)}function je(r){return Jt(Ce(r))}function Qt(r){return Jt(Ce(fr(U(r)).reverse()))}function ct(r,e){le(e),r=Xt(r);const s=Ue(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function es(r,e){return ct(r,e).reverse()}function fr(r){return Uint8Array.from(r)}const Me=r=>typeof r=="bigint"&&at<=r;function gr(r,e,s){return Me(r)&&Me(e)&&Me(s)&&e<=r&&r<s}function pr(r,e,s,t){if(!gr(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function xr(r){let e;for(e=0;r>at;r>>=st,e+=1);return e}const lt=r=>(st<<BigInt(r))-st;function _r(r,e,s){if(le(r,"hashLen"),le(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=E=>new Uint8Array(E),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},w=(...E)=>s(l,xe(c,...E)),m=(E=n)=>{l=w(o,E),c=w(),E.length!==0&&(l=w(i,E),c=w())},x=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let E=0;const C=[];for(;E<e;){c=w();const q=c.slice();C.push(q),E+=c.length}return xe(...C)};return(E,C)=>{g(),m(E);let q;for(;!(q=C(x()));)m();return g(),q}}function dt(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 Ot(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 X=BigInt(0),z=BigInt(1),we=BigInt(2),ts=BigInt(3),ss=BigInt(4),rs=BigInt(5),mr=BigInt(7),ns=BigInt(8),wr=BigInt(9),os=BigInt(16);function re(r,e){const s=r%e;return s>=X?s:e+s}function ee(r,e,s){let t=r;for(;e-- >X;)t*=t,t%=s;return t}function Ct(r,e){if(r===X)throw new Error("invert: expected non-zero number");if(e<=X)throw new Error("invert: expected positive modulus, got "+e);let s=re(r,e),t=e,n=X,o=z;for(;s!==X;){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 ut(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function is(r,e){const s=(r.ORDER+z)/ss,t=r.pow(e,s);return ut(r,t,e),t}function yr(r,e){const s=(r.ORDER-rs)/ns,t=r.mul(e,we),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,we),n),a=r.mul(o,r.sub(i,r.ONE));return ut(r,a,e),a}function br(r){const e=Ve(r),s=as(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+mr)/os;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const g=a.mul(l,n),w=a.mul(l,o),m=a.eql(a.sqr(d),c),x=a.eql(a.sqr(g),c);l=a.cmov(l,d,m),d=a.cmov(w,g,x);const A=a.eql(a.sqr(d),c),E=a.cmov(l,d,A);return ut(a,E,c),E}}function as(r){if(r<ts)throw new Error("sqrt is not defined for small field");let e=r-z,s=0;for(;e%we===X;)e/=we,s++;let t=we;const n=Ve(r);for(;Nt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return is;let o=n.pow(t,e);const i=(e+z)/we;return function(c,l){if(c.is0(l))return l;if(Nt(c,l)!==1)throw new Error("Cannot find square root");let d=s,g=c.mul(c.ONE,o),w=c.pow(l,e),m=c.pow(l,i);for(;!c.eql(w,c.ONE);){if(c.is0(w))return c.ZERO;let x=1,A=c.sqr(w);for(;!c.eql(A,c.ONE);)if(x++,A=c.sqr(A),x===d)throw new Error("Cannot find square root");const E=z<<BigInt(d-x-1),C=c.pow(g,E);d=x,g=c.sqr(C),w=c.mul(w,g),m=c.mul(m,C)}return m}}function vr(r){return r%ss===ts?is:r%ns===rs?yr:r%os===wr?br(r):as(r)}const Sr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Er(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Sr.reduce((t,n)=>(t[n]="function",t),e);return dt(r,s),r}function Tr(r,e,s){if(s<X)throw new Error("invalid exponent, negatives unsupported");if(s===X)return r.ONE;if(s===z)return e;let t=r.ONE,n=e;for(;s>X;)s&z&&(t=r.mul(t,n)),n=r.sqr(n),s>>=z;return t}function cs(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 Nt(r,e){const s=(r.ORDER-z)/we,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 Ar(r,e){e!==void 0&&le(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Ir{constructor(e,s={}){b(this,"ORDER");b(this,"BITS");b(this,"BYTES");b(this,"isLE");b(this,"ZERO",X);b(this,"ONE",z);b(this,"_lengths");b(this,"_sqrt");b(this,"_mod");var i;if(e<=X)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}=Ar(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 X<=e&&e<this.ORDER}is0(e){return e===X}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 Tr(this,e,s)}div(e,s){return re(e*Ct(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 Ct(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=vr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?es(e,this.BYTES):ct(e,this.BYTES)}fromBytes(e,s=!1){U(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?Qt(e):je(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 cs(this,e)}cmov(e,s,t){return t?s:e}}function Ve(r,e={}){return new Ir(r,e)}function ls(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 ds(r){const e=ls(r);return e+Math.ceil(e/2)}function Rr(r,e,s=!1){U(r);const t=r.length,n=ls(e),o=ds(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?Qt(r):je(r),a=re(i,e-z)+z;return s?es(a,n):ct(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ie=BigInt(0),ye=BigInt(1);function Ge(r,e){const s=e.negate();return r?s:e}function Pt(r,e){const s=cs(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function us(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Xe(r,e){us(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=lt(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function kt(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+=ye);const l=e*t,d=l+Math.abs(a)-1,g=a===0,w=a<0,m=e%2!==0;return{nextN:c,offset:d,isZero:g,isNeg:w,isNegF:m,offsetF:l}}const Je=new WeakMap,hs=new WeakMap;function Qe(r){return hs.get(r)||1}function Lt(r){if(r!==Ie)throw new Error("invalid wNAF")}class Or{constructor(e,s){b(this,"BASE");b(this,"ZERO");b(this,"Fn");b(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>Ie;)s&ye&&(t=t.add(n)),n=n.double(),s>>=ye;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=Xe(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=Xe(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:g,isNegF:w,offsetF:m}=kt(t,a,i);t=c,d?o=o.add(Ge(w,s[m])):n=n.add(Ge(g,s[l]))}return Lt(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=Xe(e,this.bits);for(let i=0;i<o.windows&&t!==Ie;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=kt(t,i,o);if(t=a,!l){const g=s[c];n=n.add(d?g.negate():g)}}return Lt(t),n}getPrecomputes(e,s,t){let n=Je.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),Je.set(s,n))),n}cached(e,s,t){const n=Qe(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=Qe(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){us(s,this.bits),hs.set(e,s),Je.delete(e)}hasCache(e){return Qe(e)!==1}}function Cr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>Ie||t>Ie;)s&ye&&(o=o.add(n)),t&ye&&(i=i.add(n)),n=n.double(),s>>=ye,t>>=ye;return{p1:o,p2:i}}function Dt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Er(e),e}else return Ve(r,{isLE:s})}function Nr(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>Ie))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Dt(e.p,s.Fp,t),o=Dt(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 Pr(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class fs{constructor(e,s){b(this,"oHash");b(this,"iHash");b(this,"blockLen");b(this,"outputLen");b(this,"finished",!1);b(this,"destroyed",!1);if(Vt(e),U(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),Ae(n)}update(e){return Te(this),this.iHash.update(e),this}digestInto(e){Te(this),U(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 gs=(r,e,s)=>new fs(r,e).update(s).digest();gs.create=(r,e)=>new fs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $t=(r,e)=>(r+(r>=0?e:-e)/ps)/e;function kr(r,e,s){const[[t,n],[o,i]]=e,a=$t(i*r,s),c=$t(-n*r,s);let l=r-a*t-c*o,d=-a*n-c*i;const g=l<ae,w=d<ae;g&&(l=-l),w&&(d=-d);const m=lt(Math.ceil(xr(s)/2))+Ee;if(l<ae||l>=m||d<ae||d>=m)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:g,k1:l,k2neg:w,k2:d}}function rt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function et(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return He(s.lowS,"lowS"),He(s.prehash,"prehash"),s.format!==void 0&&rt(s.format),s}class Lr extends Error{constructor(e=""){super(e)}}const pe={Err:Lr,_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=De(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?De(n.length/2|128):"";return De(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<ae)throw new e("integer: negative integers are not allowed");let s=De(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 je(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=pe,n=U(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)}},ae=BigInt(0),Ee=BigInt(1),ps=BigInt(2),$e=BigInt(3),Dr=BigInt(4);function $r(r,e={}){const s=Nr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;dt(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=_s(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function g(k,u,h){const{x:y,y:S}=u.toAffine(),I=t.toBytes(y);if(He(h,"isCompressed"),h){d();const T=!t.isOdd(S);return xe(xs(T),I)}else return xe(Uint8Array.of(4),I,t.toBytes(S))}function w(k){U(k,void 0,"Point");const{publicKey:u,publicKeyUncompressed:h}=l,y=k.length,S=k[0],I=k.subarray(1);if(y===u&&(S===2||S===3)){const T=t.fromBytes(I);if(!t.isValid(T))throw new Error("bad point: is not on curve, wrong x");const R=A(T);let v;try{v=t.sqrt(R)}catch(W){const M=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+M)}d();const O=t.isOdd(v);return(S&1)===1!==O&&(v=t.neg(v)),{x:T,y:v}}else if(y===h&&S===4){const T=t.BYTES,R=t.fromBytes(I.subarray(0,T)),v=t.fromBytes(I.subarray(T,T*2));if(!E(R,v))throw new Error("bad point: is not on curve");return{x:R,y:v}}else throw new Error(`bad point: got length ${y}, expected compressed=${u} or uncompressed=${h}`)}const m=e.toBytes||g,x=e.fromBytes||w;function A(k){const u=t.sqr(k),h=t.mul(u,k);return t.add(t.add(h,t.mul(k,o.a)),o.b)}function E(k,u){const h=t.sqr(u),y=A(k);return t.eql(h,y)}if(!E(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const C=t.mul(t.pow(o.a,$e),Dr),q=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(C,q)))throw new Error("bad curve params: a or b");function $(k,u,h=!1){if(!t.isValid(u)||h&&t.is0(u))throw new Error(`bad point coordinate ${k}`);return u}function B(k){if(!(k instanceof Y))throw new Error("Weierstrass Point expected")}function F(k){if(!c||!c.basises)throw new Error("no endo");return kr(k,c.basises,n.ORDER)}const se=Ot((k,u)=>{const{X:h,Y:y,Z:S}=k;if(t.eql(S,t.ONE))return{x:h,y};const I=k.is0();u==null&&(u=I?t.ONE:t.inv(S));const T=t.mul(h,u),R=t.mul(y,u),v=t.mul(S,u);if(I)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:T,y:R}}),be=Ot(k=>{if(k.is0()){if(e.allowInfinityPoint&&!t.is0(k.Y))return;throw new Error("bad point: ZERO")}const{x:u,y:h}=k.toAffine();if(!t.isValid(u)||!t.isValid(h))throw new Error("bad point: x or y not field elements");if(!E(u,h))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function he(k,u,h,y,S){return h=new Y(t.mul(h.X,k),h.Y,h.Z),u=Ge(y,u),h=Ge(S,h),u.add(h)}const L=class L{constructor(u,h,y){b(this,"X");b(this,"Y");b(this,"Z");this.X=$("x",u),this.Y=$("y",h,!0),this.Z=$("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(x(U(u,void 0,"point")));return h.assertValidity(),h}static fromHex(u){return L.fromBytes(Ue(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($e),this}assertValidity(){be(this)}hasEvenY(){const{y:u}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(u)}equals(u){B(u);const{X:h,Y:y,Z:S}=this,{X:I,Y:T,Z:R}=u,v=t.eql(t.mul(h,R),t.mul(I,S)),O=t.eql(t.mul(y,R),t.mul(T,S));return v&&O}negate(){return new L(this.X,t.neg(this.Y),this.Z)}double(){const{a:u,b:h}=o,y=t.mul(h,$e),{X:S,Y:I,Z:T}=this;let R=t.ZERO,v=t.ZERO,O=t.ZERO,P=t.mul(S,S),W=t.mul(I,I),M=t.mul(T,T),N=t.mul(S,I);return N=t.add(N,N),O=t.mul(S,T),O=t.add(O,O),R=t.mul(u,O),v=t.mul(y,M),v=t.add(R,v),R=t.sub(W,v),v=t.add(W,v),v=t.mul(R,v),R=t.mul(N,R),O=t.mul(y,O),M=t.mul(u,M),N=t.sub(P,M),N=t.mul(u,N),N=t.add(N,O),O=t.add(P,P),P=t.add(O,P),P=t.add(P,M),P=t.mul(P,N),v=t.add(v,P),M=t.mul(I,T),M=t.add(M,M),P=t.mul(M,N),R=t.sub(R,P),O=t.mul(M,W),O=t.add(O,O),O=t.add(O,O),new L(R,v,O)}add(u){B(u);const{X:h,Y:y,Z:S}=this,{X:I,Y:T,Z:R}=u;let v=t.ZERO,O=t.ZERO,P=t.ZERO;const W=o.a,M=t.mul(o.b,$e);let N=t.mul(h,I),j=t.mul(y,T),V=t.mul(S,R),J=t.add(h,y),H=t.add(I,T);J=t.mul(J,H),H=t.add(N,j),J=t.sub(J,H),H=t.add(h,S);let K=t.add(I,R);return H=t.mul(H,K),K=t.add(N,V),H=t.sub(H,K),K=t.add(y,S),v=t.add(T,R),K=t.mul(K,v),v=t.add(j,V),K=t.sub(K,v),P=t.mul(W,H),v=t.mul(M,V),P=t.add(v,P),v=t.sub(j,P),P=t.add(j,P),O=t.mul(v,P),j=t.add(N,N),j=t.add(j,N),V=t.mul(W,V),H=t.mul(M,H),j=t.add(j,V),V=t.sub(N,V),V=t.mul(W,V),H=t.add(H,V),N=t.mul(j,H),O=t.add(O,N),N=t.mul(K,H),v=t.mul(J,v),v=t.sub(v,N),N=t.mul(J,j),P=t.mul(K,P),P=t.add(P,N),new L(v,O,P)}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,S;const I=T=>ne.cached(this,T,R=>Pt(L,R));if(h){const{k1neg:T,k1:R,k2neg:v,k2:O}=F(u),{p:P,f:W}=I(R),{p:M,f:N}=I(O);S=W.add(N),y=he(h.beta,P,M,T,v)}else{const{p:T,f:R}=I(u);y=T,S=R}return Pt(L,[y,S])[0]}multiplyUnsafe(u){const{endo:h}=e,y=this;if(!n.isValid(u))throw new Error("invalid scalar: out of range");if(u===ae||y.is0())return L.ZERO;if(u===Ee)return y;if(ne.hasCache(this))return this.multiply(u);if(h){const{k1neg:S,k1:I,k2neg:T,k2:R}=F(u),{p1:v,p2:O}=Cr(L,y,I,R);return he(h.beta,v,O,S,T)}else return ne.unsafe(y,u)}toAffine(u){return se(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 He(u,"isCompressed"),this.assertValidity(),m(L,this,u)}toHex(u=!0){return Ce(this.toBytes(u))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};b(L,"BASE",new L(o.Gx,o.Gy,t.ONE)),b(L,"ZERO",new L(t.ZERO,t.ONE,t.ZERO)),b(L,"Fp",t),b(L,"Fn",n);let Y=L;const _e=n.BITS,ne=new Or(Y,e.endo?Math.ceil(_e/2):_e);return Y.BASE.precompute(8),Y}function xs(r){return Uint8Array.of(r?2:3)}function _s(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Br(r,e={}){const{Fn:s}=r,t=e.randomBytes||Zt,n=Object.assign(_s(r.Fp,s),{seed:ds(s.ORDER)});function o(m){try{const x=s.fromBytes(m);return s.isValidNot0(x)}catch{return!1}}function i(m,x){const{publicKey:A,publicKeyUncompressed:E}=n;try{const C=m.length;return x===!0&&C!==A||x===!1&&C!==E?!1:!!r.fromBytes(m)}catch{return!1}}function a(m=t(n.seed)){return Rr(U(m,n.seed,"seed"),s.ORDER)}function c(m,x=!0){return r.BASE.multiply(s.fromBytes(m)).toBytes(x)}function l(m){const{secretKey:x,publicKey:A,publicKeyUncompressed:E}=n;if(!it(m)||"_lengths"in s&&s._lengths||x===A)return;const C=U(m,void 0,"key").length;return C===A||C===E}function d(m,x,A=!0){if(l(m)===!0)throw new Error("first arg must be private key");if(l(x)===!1)throw new Error("second arg must be public key");const E=s.fromBytes(m);return r.fromBytes(x).multiply(E).toBytes(A)}const g={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},w=Pr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:w,Point:r,utils:g,lengths:n})}function Mr(r,e,s={}){Vt(e),dt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||Zt,n=s.hmac||((u,h)=>gs(e,u,h)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:g,utils:w,lengths:m}=Br(r,s),x={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},A=a*ps<o.ORDER;function E(u){const h=a>>Ee;return u>h}function C(u,h){if(!i.isValidNot0(h))throw new Error(`invalid signature ${u}: out of range 1..Point.Fn.ORDER`);return h}function q(){if(A)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function $(u,h){rt(h);const y=m.signature,S=h==="compact"?y:h==="recovered"?y+1:void 0;return U(u,S)}class B{constructor(h,y,S){b(this,"r");b(this,"s");b(this,"recovery");if(this.r=C("r",h),this.s=C("s",y),S!=null){if(q(),![0,1,2,3].includes(S))throw new Error("invalid recovery id");this.recovery=S}Object.freeze(this)}static fromBytes(h,y=x.format){$(h,y);let S;if(y==="der"){const{r:v,s:O}=pe.toSig(U(h));return new B(v,O)}y==="recovered"&&(S=h[0],y="compact",h=h.subarray(1));const I=m.signature/2,T=h.subarray(0,I),R=h.subarray(I,I*2);return new B(i.fromBytes(T),i.fromBytes(R),S)}static fromHex(h,y){return this.fromBytes(Ue(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 B(this.r,this.s,h)}recoverPublicKey(h){const{r:y,s:S}=this,I=this.assertRecovery(),T=I===2||I===3?y+a:y;if(!o.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const R=o.toBytes(T),v=r.fromBytes(xe(xs((I&1)===0),R)),O=i.inv(T),P=se(U(h,void 0,"msgHash")),W=i.create(-P*O),M=i.create(S*O),N=r.BASE.multiplyUnsafe(W).add(v.multiplyUnsafe(M));if(N.is0())throw new Error("invalid recovery: point at infinify");return N.assertValidity(),N}hasHighS(){return E(this.s)}toBytes(h=x.format){if(rt(h),h==="der")return Ue(pe.hexFromSig(this));const{r:y,s:S}=this,I=i.toBytes(y),T=i.toBytes(S);return h==="recovered"?(q(),xe(Uint8Array.of(this.assertRecovery()),I,T)):xe(I,T)}toHex(h){return Ce(this.toBytes(h))}}const F=s.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");const y=je(h),S=h.length*8-c;return S>0?y>>BigInt(S):y},se=s.bits2int_modN||function(h){return i.create(F(h))},be=lt(c);function he(u){return pr("num < 2^"+c,u,ae,be),i.toBytes(u)}function Y(u,h){return U(u,void 0,"message"),h?U(e(u),void 0,"prehashed message"):u}function _e(u,h,y){const{lowS:S,prehash:I,extraEntropy:T}=et(y,x);u=Y(u,I);const R=se(u),v=i.fromBytes(h);if(!i.isValidNot0(v))throw new Error("invalid private key");const O=[he(v),he(R)];if(T!=null&&T!==!1){const N=T===!0?t(m.secretKey):T;O.push(U(N,void 0,"extraEntropy"))}const P=xe(...O),W=R;function M(N){const j=F(N);if(!i.isValidNot0(j))return;const V=i.inv(j),J=r.BASE.multiply(j).toAffine(),H=i.create(J.x);if(H===ae)return;const K=i.create(V*i.create(W+H*v));if(K===ae)return;let xt=(J.x===H?0:2)|Number(J.y&Ee),_t=K;return S&&E(K)&&(_t=i.neg(K),xt^=1),new B(H,_t,A?void 0:xt)}return{seed:P,k2sig:M}}function ne(u,h,y={}){const{seed:S,k2sig:I}=_e(u,h,y);return _r(e.outputLen,i.BYTES,n)(S,I).toBytes(y.format)}function L(u,h,y,S={}){const{lowS:I,prehash:T,format:R}=et(S,x);if(y=U(y,void 0,"publicKey"),h=Y(h,T),!it(u)){const v=u instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+v)}$(u,R);try{const v=B.fromBytes(u,R),O=r.fromBytes(y);if(I&&v.hasHighS())return!1;const{r:P,s:W}=v,M=se(h),N=i.inv(W),j=i.create(M*N),V=i.create(P*N),J=r.BASE.multiplyUnsafe(j).add(O.multiplyUnsafe(V));return J.is0()?!1:i.create(J.x)===P}catch{return!1}}function k(u,h,y={}){const{prehash:S}=et(y,x);return h=Y(h,S),B.fromBytes(u,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:g,utils:w,lengths:m,Point:r,sign:ne,verify:L,recoverPublicKey:k,Signature:B,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ht={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Fr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Bt=BigInt(2);function Ur(r){const e=ht.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=ee(d,s,e)*d%e,w=ee(g,s,e)*d%e,m=ee(w,Bt,e)*l%e,x=ee(m,n,e)*m%e,A=ee(x,o,e)*x%e,E=ee(A,a,e)*A%e,C=ee(E,c,e)*E%e,q=ee(C,a,e)*A%e,$=ee(q,s,e)*d%e,B=ee($,i,e)*x%e,F=ee(B,t,e)*l%e,se=ee(F,Bt,e);if(!nt.eql(nt.sqr(se),r))throw new Error("Cannot find square root");return se}const nt=Ve(ht.p,{sqrt:Ur}),Hr=$r(ht,{Fp:nt,endo:Fr}),Gr=Mr(Hr,hr),qr=BigInt(0),Re=BigInt(1),Wr=BigInt(2),jr=BigInt(7),Vr=BigInt(256),Kr=BigInt(113),ms=[],ws=[],ys=[];for(let r=0,e=Re,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],ms.push(2*(5*t+s)),ws.push((r+1)*(r+2)/2%64);let n=qr;for(let o=0;o<7;o++)e=(e<<Re^(e>>jr)*Kr)%Vr,e&Wr&&(n^=Re<<(Re<<BigInt(o))-Re);ys.push(n)}const bs=nr(ys,!0),zr=bs[0],Yr=bs[1],Mt=(r,e,s)=>s>32?ar(r,e,s):or(r,e,s),Ft=(r,e,s)=>s>32?cr(r,e,s):ir(r,e,s);function Zr(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=Mt(l,d,1)^s[a],w=Ft(l,d,1)^s[a+1];for(let m=0;m<50;m+=10)r[i+m]^=g,r[i+m+1]^=w}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=ws[i],c=Mt(n,o,a),l=Ft(n,o,a),d=ms[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]^=zr[t],r[1]^=Yr[t]}Ae(s)}class ft{constructor(e,s,t,n=!1,o=24){b(this,"state");b(this,"pos",0);b(this,"posOut",0);b(this,"finished",!1);b(this,"state32");b(this,"destroyed",!1);b(this,"blockLen");b(this,"suffix");b(this,"outputLen");b(this,"enableXOF",!1);b(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,le(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=zs(this.state)}clone(){return this._cloneInto()}keccak(){At(this.state32),Zr(this.state32,this.rounds),At(this.state32),this.posOut=0,this.pos=0}update(e){Te(this),U(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),U(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 le(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Kt(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,Ae(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new ft(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 Xr=(r,e,s,t={})=>Yt(()=>new ft(e,r,s),t),Ut=Xr(1,136,32);class Jr{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 As.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=Ut(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=Qr(a),l=c.slice(0,32),d=c.slice(32,64),g=c[64],w=g>=27?g-27:g,A=new Gr.Signature(Ht(l),Ht(d)).addRecoveryBit(w).recoverPublicKey(i).toBytes(!1).slice(1),E=Ut(A);return"0x"+Ce(E.slice(12))}}function Qr(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 Ht(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const en=3e4;class tn{async request(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??en);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}`,g=window.open(d,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const w=setTimeout(()=>{f.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),$(),t(new Error("Authentication timeout"))},5*60*1e3),m=10,x=30;let A=0,E=null;const C=()=>{clearInterval(q),f.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+x+"초간 대기합니다"),E=setTimeout(()=>{$(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},x*1e3)},q=setInterval(()=>{A++;try{g.closed&&(A<=m?C():($(),t(new Error("로그인이 취소되었습니다"))))}catch{C()}},1e3),$=()=>{clearTimeout(w),clearInterval(q),E&&clearTimeout(E),window.removeEventListener("message",B)},B=F=>{var be,he,Y,_e,ne,L,k;if(F.origin!==e.expectedOrigin)return;$(),f.log("[CROSSx] OAuth postMessage 수신 — status:",F.data.status);const se=F.data.state??((be=F.data.data)==null?void 0:be.state);if(!se||se!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(F.data.status==="success"){const u=((he=F.data.data)==null?void 0:he.accessToken)||((Y=F.data.data)==null?void 0:Y.idToken);f.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!((_e=F.data.data)!=null&&_e.accessToken),hasIdToken:!!((ne=F.data.data)!=null&&ne.idToken)}),u?s(u):(f.error("[CROSSx] 토큰을 찾을 수 없음:",F.data),t(new Error("Token not found in response")))}else f.error("[CROSSx] OAuth 실패:",(L=F.data.data)==null?void 0:L.error),t(new Error(((k=F.data.data)==null?void 0:k.error)||"Authentication failed"))};window.addEventListener("message",B)})}}const Be="crossx_wallet_data";class sn{constructor(e){this.storage=e}async getOrCreateWallet(e){try{const s=await this.storage.get(Be);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(Be,t),t}catch(s){throw new _(p.WALLET_CREATION_FAILED,"Wallet creation failed",s)}}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(Be,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(Be,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 qe{constructor(e,s,t,n){this.baseUrl=e.gatewayUrl,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n}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 w=qe.mapGatewayError(d.code),m=qe.getGatewayErrorMessage(d.code,g),x=new _(w,m);throw x.gatewayCode=d.code,x.gatewayMessage=g,x}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",w=d.code||"UNKNOWN";throw f.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:w,message:g,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new _(p.UNKNOWN_ERROR,`Wallet Gateway error (${w}): ${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 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 Oe{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.baseUrl=e.gatewayUrl,this.projectId=e.projectId,this.transport=s}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=Oe.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?qs:Gs;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 _(Oe.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Oe.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new _(p.CHAIN_NOT_SUPPORTED,`Unsupported chain: ${e}`)}static fallbackChains(){return Object.values(We).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 Gt="__crossx-confirm-style",te="__crossx-confirm-overlay",rn={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 qt(r,e){const s=rn[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 nn=`
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 x extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,x.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const je={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},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 x(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 x(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 g={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 x(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 x(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:f}=this.config,w=`${d}${l}`;g.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인):`,w);const m=await this.oauth.openAuth({authUrl:w,expectedOrigin:new URL(d).origin});g.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",m.length,")");const{accessToken:_,refreshToken:T}=await this.exchangeFirebaseToken(m,f);let b,A;try{const B=this.crypto.decodeJWT(m);A=(n=B.firebase)==null?void 0:n.sign_in_provider;const D=((o=B.firebase)==null?void 0:o.identities)??{};A==="google.com"?b=(i=D["google.com"])==null?void 0:i[0]:A==="apple.com"&&(b=(a=D["apple.com"])==null?void 0:a[0]),g.log("[CROSSx] OAuth provider sub 추출 — provider:",A,"hasProviderSub:",!!b)}catch{g.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(_){const B=this.crypto.decodeJWT(_);g.log("[CROSSx] access_token 디코딩 — sub:",B.sub,"exp:",B.exp);const D=await this.crypto.verifyJWT(_);if(t=D.signatureVerified??!1,!D.valid)throw g.error("[CROSSx] access_token 검증 실패"),new Error("Invalid access token");const M=D.payload;s={id:M.sub,email:M.email,signInProvider:A,providerSub:b},this.tokenStore.set(_),this.useCookieAuth||(await this.storage.set(Ze,_),T&&await this.storage.set(Ne,T))}else{const B=this.crypto.decodeJWT(m);s={id:B.sub,email:B.email,signInProvider:A,providerSub:b},g.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}g.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),g.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return g.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return g.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`;g.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"}:{}});g.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return g.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(p.AUTH_FAILED,"access_token not found in exchange response");g.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 g.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){g.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(g.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return g.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);g.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(Pe);if(g.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;g.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return g.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return g.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"}:{}});g.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){g.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new x(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 g.log("[CROSSx] silentRefresh 성공"),c}async loadWallet(e,s){let t,n=!1;try{g.log("[CROSSx][Migration Phase 2] POST /mnemonic/create 호출 — userId:",e.id),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,g.log("[CROSSx][Migration Phase 2] 지갑 로드 완료 (기존 백업 없음) — address:",t)}catch(o){if(o instanceof x&&o.code===p.MIGRATION_BACKUP_EXISTS)g.log("[CROSSx][Migration Phase 2] Gateway -10012 감지 → needsMigration = true"),n=!0;else{if(o instanceof x&&(o.code===p.PROJECT_NOT_REGISTERED||o.code===p.PROJECT_ID_MISSING||o.code===p.ORIGIN_NOT_ALLOWED))throw g.error("[CROSSx][Migration Phase 2] 프로젝트 설정 에러:",o.message),o;g.warn("[CROSSx][Migration Phase 2] 지갑 로드 실패 (로그인은 유지):",o)}}return g.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 x(p.NOT_IMPLEMENTED,"Migration is not supported in the current environment");g.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return g.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 x(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.1 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 x(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 x(p.AUTH_FAILED,"Sign in failed",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(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 x(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}),g.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof x?s:new x(p.MIGRATION_FAILED,"Wallet migration failed",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(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 x(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 x?e:new x(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 x?s:new x(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 x(p.AUTH_NOT_AUTHENTICATED,"User ID not found");g.log("[CROSSx] 지갑 생성 시작");try{const e=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=e.address,this.emit("addressChanged",{address:e.address,index:0}),g.log("[CROSSx] 지갑 생성 완료:",e.address),{address:e.address}}catch(e){if(e instanceof x&&e.code===p.MIGRATION_BACKUP_EXISTS){const s=this.providerSub??this.userId;g.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 x(p.MIGRATION_FAILED,"Migration skipped by user")}throw e}}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(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 x(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 x?c:new x(p.SIGNATURE_FAILED,`Message signing failed (${e})`,c)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(p.AUTH_NOT_AUTHENTICATED,"User ID not found");if(!this.walletProvider.signTypedData)throw new x(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 x(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 x?a:new x(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 x(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 x(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 x)throw c;const l=c instanceof Error?c.message:String(c);throw new x(p.SIGNATURE_FAILED,`Transaction signing failed (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(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 x(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 x(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 x(p.UNKNOWN_ERROR,`Transaction receipt timeout (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var T,b;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((T=this._config.receiptPolling)==null?void 0:T.intervalMs)??Gs,l=o??((b=this._config.receiptPolling)==null?void 0:b.timeoutMs)??bt,d=Ye(e),f=s.from??"";let w,m;const _=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{w=A;const q=BigInt(A.gasUsed)*BigInt(A.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:A.from,to:A.to??s.to,amount:D,fees:M,total:Q,nativeSymbol:d.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(m=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:f,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:f,to:s.to},_),m)throw m;return{chainId:e,txHash:a,receipt:w}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(p.GAS_ESTIMATION_FAILED,`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 x(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 x(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 x(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 x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(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 x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(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 x)throw n;const o=n instanceof Error?n.message:String(n);throw new x(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){g.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(g.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return g.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0;for(;;){n++,g.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n})`,t?`— 이전 에러: ${t}`:"");const o=await this.confirmation.showPinInputPrompt(t);if(o===null)return g.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;g.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${o.length}자리), Gateway 마이그레이션 API 호출`);try{const i=await this.migrateWalletUseCase.execute(o,e);return g.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",i.address),i}catch(i){if(i instanceof x&&i.code===p.MIGRATION_FAILED){g.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 #${n}) — 재시도 요청`),t="Incorrect PIN. Please try again.";continue}throw g.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&&(g.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출"),c.nonce=await this.getNonce(s),g.log("[CROSSx] nonce 결과:",c.nonce)),o&&(g.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),g.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){g.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,g.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=js,g.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=vt,g.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 x(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 x(p.TYPED_DATA_CHAIN_ID_MISMATCH,`On-chain signing (${e}) requires typedData.domain.chainId to be present`);if(t!==o)throw new x(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 x(p.SIGNATURE_FAILED,"Invalid signature: not a valid hex string");if(s.length!==St)throw new x(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 x(p.SIGNATURE_FAILED,"Invalid signedTx: not a valid hex string");if(s.length<2)throw new x(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 g.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new x(p.SIGNATURE_SIGNER_MISMATCH,`Signature signer mismatch: expected ${t}, recovered ${n}`);g.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;g.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 x(p.AUTH_NOT_INITIALIZED,"SDK is not initialized. Call initialize() first.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new x(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 g.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 g.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw g.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw g.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 g.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 g.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Se,e)}catch(s){throw g.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Se)}catch(e){throw g.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 f=i;f<n;f++)s[f]=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 f=0;f<l;f++)a.setUint32(4*f,d[f],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 f=0;f<16;f++,s+=4)ge[f]=e.getUint32(s,!1);for(let f=16;f<64;f++){const w=ge[f-15],m=ge[f-2],_=oe(w,7)^oe(w,18)^w>>>3,T=oe(m,17)^oe(m,19)^m>>>10;ge[f]=T+ge[f-7]+_+ge[f-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let f=0;f<64;f++){const w=oe(a,6)^oe(a,11)^oe(a,25),m=d+w+nr(a,c,l)+fr[f]+ge[f]|0,T=(oe(t,2)^oe(t,13)^oe(t,22))+or(t,n,o)|0;d=l,l=c,c=a,a=i+m|0,i=o,o=n,n=t,t=m+T|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=b=>new Uint8Array(b),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const f=()=>{c.fill(1),l.fill(0),d=0},w=(...b)=>s(l,_e(c,...b)),m=(b=n)=>{l=w(o,b),c=w(),b.length!==0&&(l=w(i,b),c=w())},_=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let b=0;const A=[];for(;b<e;){c=w();const q=c.slice();A.push(q),b+=c.length}return _e(...A)};return(b,A)=>{f(),m(b);let q;for(;!(q=A(_()));)m();return f(),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 f=a.mul(l,n),w=a.mul(l,o),m=a.eql(a.sqr(d),c),_=a.eql(a.sqr(f),c);l=a.cmov(l,d,m),d=a.cmov(w,f,_);const T=a.eql(a.sqr(d),c),b=a.cmov(l,d,T);return ht(a,b,c),b}}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,f=c.mul(c.ONE,o),w=c.pow(l,e),m=c.pow(l,i);for(;!c.eql(w,c.ONE);){if(c.is0(w))return c.ZERO;let _=1,T=c.sqr(w);for(;!c.eql(T,c.ONE);)if(_++,T=c.sqr(T),_===d)throw new Error("Cannot find square root");const b=z<<BigInt(d-_-1),A=c.pow(f,b);d=_,f=c.sqr(A),w=c.mul(w,f),m=c.mul(m,A)}return m}}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,f=a===0,w=a<0,m=e%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:w,isNegF:m,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:f,isNegF:w,offsetF:m}=Dt(t,a,i);t=c,d?o=o.add(qe(w,s[m])):n=n.add(qe(f,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 f=s[c];n=n.add(d?f.negate():f)}}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 f=l<le,w=d<le;f&&(l=-l),w&&(d=-d);const m=dt(Math.ceil(yr(s)/2))+Ee;if(l<le||l>=m||d<le||d>=m)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:w,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 f(P,u,h){const{x:y,y:E}=u.toAffine(),R=t.toBytes(y);if(Ge(h,"isCompressed"),h){d();const I=!t.isOdd(E);return _e(ms(I),R)}else return _e(Uint8Array.of(4),R,t.toBytes(E))}function w(P){F(P,void 0,"Point");const{publicKey:u,publicKeyUncompressed:h}=l,y=P.length,E=P[0],R=P.subarray(1);if(y===u&&(E===2||E===3)){const I=t.fromBytes(R);if(!t.isValid(I))throw new Error("bad point: is not on curve, wrong x");const O=T(I);let S;try{S=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(S);return(E&1)===1!==C&&(S=t.neg(S)),{x:I,y:S}}else if(y===h&&E===4){const I=t.BYTES,O=t.fromBytes(R.subarray(0,I)),S=t.fromBytes(R.subarray(I,I*2));if(!b(O,S))throw new Error("bad point: is not on curve");return{x:O,y:S}}else throw new Error(`bad point: got length ${y}, expected compressed=${u} or uncompressed=${h}`)}const m=e.toBytes||f,_=e.fromBytes||w;function T(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 b(P,u){const h=t.sqr(u),y=T(P);return t.eql(h,y)}if(!b(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(o.a,Me),Ur),q=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(A,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:E}=P;if(t.eql(E,t.ONE))return{x:h,y};const R=P.is0();u==null&&(u=R?t.ONE:t.inv(E));const I=t.mul(h,u),O=t.mul(y,u),S=t.mul(E,u);if(R)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:I,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(!b(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,E){return h=new Z(t.mul(h.X,P),h.Y,h.Z),u=qe(y,u),h=qe(E,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(_(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:E}=this,{X:R,Y:I,Z:O}=u,S=t.eql(t.mul(h,O),t.mul(R,E)),C=t.eql(t.mul(y,O),t.mul(I,E));return S&&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:E,Y:R,Z:I}=this;let O=t.ZERO,S=t.ZERO,C=t.ZERO,N=t.mul(E,E),W=t.mul(R,R),U=t.mul(I,I),k=t.mul(E,R);return k=t.add(k,k),C=t.mul(E,I),C=t.add(C,C),O=t.mul(u,C),S=t.mul(y,U),S=t.add(O,S),O=t.sub(W,S),S=t.add(W,S),S=t.mul(O,S),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),S=t.add(S,N),U=t.mul(R,I),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,S,C)}add(u){D(u);const{X:h,Y:y,Z:E}=this,{X:R,Y:I,Z:O}=u;let S=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,I),V=t.mul(E,O),ee=t.add(h,y),H=t.add(R,I);ee=t.mul(ee,H),H=t.add(k,j),ee=t.sub(ee,H),H=t.add(h,E);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,E),S=t.add(I,O),K=t.mul(K,S),S=t.add(j,V),K=t.sub(K,S),N=t.mul(W,H),S=t.mul(U,V),N=t.add(S,N),S=t.sub(j,N),N=t.add(j,N),C=t.mul(S,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),S=t.mul(ee,S),S=t.sub(S,k),k=t.mul(ee,j),N=t.mul(K,N),N=t.add(N,k),new L(S,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,E;const R=I=>ne.cached(this,I,O=>Lt(L,O));if(h){const{k1neg:I,k1:O,k2neg:S,k2:C}=M(u),{p:N,f:W}=R(O),{p:U,f:k}=R(C);E=W.add(k),y=he(h.beta,N,U,I,S)}else{const{p:I,f:O}=R(u);y=I,E=O}return Lt(L,[y,E])[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:E,k1:R,k2neg:I,k2:O}=M(u),{p1:S,p2:C}=Lr(L,y,R,O);return he(h.beta,S,C,E,I)}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(),m(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(m){try{const _=s.fromBytes(m);return s.isValidNot0(_)}catch{return!1}}function i(m,_){const{publicKey:T,publicKeyUncompressed:b}=n;try{const A=m.length;return _===!0&&A!==T||_===!1&&A!==b?!1:!!r.fromBytes(m)}catch{return!1}}function a(m=t(n.seed)){return Nr(F(m,n.seed,"seed"),s.ORDER)}function c(m,_=!0){return r.BASE.multiply(s.fromBytes(m)).toBytes(_)}function l(m){const{secretKey:_,publicKey:T,publicKeyUncompressed:b}=n;if(!at(m)||"_lengths"in s&&s._lengths||_===T)return;const A=F(m,void 0,"key").length;return A===T||A===b}function d(m,_,T=!0){if(l(m)===!0)throw new Error("first arg must be private key");if(l(_)===!1)throw new Error("second arg must be public key");const b=s.fromBytes(m);return r.fromBytes(_).multiply(b).toBytes(T)}const f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},w=$r(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:w,Point:r,utils:f,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:f,utils:w,lengths:m}=Hr(r,s),_={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},T=a*xs<o.ORDER;function b(u){const h=a>>Ee;return u>h}function A(u,h){if(!i.isValidNot0(h))throw new Error(`invalid signature ${u}: out of range 1..Point.Fn.ORDER`);return h}function q(){if(T)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(u,h){nt(h);const y=m.signature,E=h==="compact"?y:h==="recovered"?y+1:void 0;return F(u,E)}class D{constructor(h,y,E){v(this,"r");v(this,"s");v(this,"recovery");if(this.r=A("r",h),this.s=A("s",y),E!=null){if(q(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(h,y=_.format){B(h,y);let E;if(y==="der"){const{r:S,s:C}=pe.toSig(F(h));return new D(S,C)}y==="recovered"&&(E=h[0],y="compact",h=h.subarray(1));const R=m.signature/2,I=h.subarray(0,R),O=h.subarray(R,R*2);return new D(i.fromBytes(I),i.fromBytes(O),E)}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:E}=this,R=this.assertRecovery(),I=R===2||R===3?y+a:y;if(!o.isValid(I))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const O=o.toBytes(I),S=r.fromBytes(_e(ms((R&1)===0),O)),C=i.inv(I),N=Q(F(h,void 0,"msgHash")),W=i.create(-N*C),U=i.create(E*C),k=r.BASE.multiplyUnsafe(W).add(S.multiplyUnsafe(U));if(k.is0())throw new Error("invalid recovery: point at infinify");return k.assertValidity(),k}hasHighS(){return b(this.s)}toBytes(h=_.format){if(nt(h),h==="der")return He(pe.hexFromSig(this));const{r:y,s:E}=this,R=i.toBytes(y),I=i.toBytes(E);return h==="recovered"?(q(),_e(Uint8Array.of(this.assertRecovery()),R,I)):_e(R,I)}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),E=h.length*8-c;return E>0?y>>BigInt(E):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:E,prehash:R,extraEntropy:I}=tt(y,_);u=Z(u,R);const O=Q(u),S=i.fromBytes(h);if(!i.isValidNot0(S))throw new Error("invalid private key");const C=[he(S),he(O)];if(I!=null&&I!==!1){const k=I===!0?t(m.secretKey):I;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*S));if(K===le)return;let xt=(ee.x===H?0:2)|Number(ee.y&Ee),mt=K;return E&&b(K)&&(mt=i.neg(K),xt^=1),new D(H,mt,T?void 0:xt)}return{seed:N,k2sig:U}}function ne(u,h,y={}){const{seed:E,k2sig:R}=xe(u,h,y);return br(e.outputLen,i.BYTES,n)(E,R).toBytes(y.format)}function L(u,h,y,E={}){const{lowS:R,prehash:I,format:O}=tt(E,_);if(y=F(y,void 0,"publicKey"),h=Z(h,I),!at(u)){const S=u instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+S)}B(u,O);try{const S=D.fromBytes(u,O),C=r.fromBytes(y);if(R&&S.hasHighS())return!1;const{r:N,s:W}=S,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:E}=tt(y,_);return h=Z(h,E),D.fromBytes(u,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:f,utils:w,lengths:m,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,f=se(d,s,e)*d%e,w=se(f,s,e)*d%e,m=se(w,Ut,e)*l%e,_=se(m,n,e)*m%e,T=se(_,o,e)*_%e,b=se(T,a,e)*T%e,A=se(b,c,e)*b%e,q=se(A,a,e)*T%e,B=se(q,s,e)*d%e,D=se(B,i,e)*_%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],f=Ft(l,d,1)^s[a],w=Ht(l,d,1)^s[a+1];for(let m=0;m<50;m+=10)r[i+m]^=f,r[i+m+1]^=w}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);g.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?(g.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(g.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(g.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw g.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),f=c[64],w=f>=27?f-27:f,T=new Vr.Signature(qt(l),qt(d)).addRecoveryBit(w).recoverPublicKey(i).toBytes(!1).slice(1),b=Gt(T);return"0x"+ke(b.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}`,f=window.open(d,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!f){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const w=setTimeout(()=>{g.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),B(),t(new Error("Authentication timeout"))},5*60*1e3),m=10,_=30;let T=0,b=null;const A=()=>{clearInterval(q),g.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+_+"초간 대기합니다"),b=setTimeout(()=>{B(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},_*1e3)},q=setInterval(()=>{T++;try{f.closed&&(T<=m?A():(B(),t(new Error("로그인이 취소되었습니다"))))}catch{A()}},1e3),B=()=>{clearTimeout(w),clearInterval(q),b&&clearTimeout(b),window.removeEventListener("message",D)},D=M=>{var ve,he,Z,xe,ne,L,P;if(M.origin!==e.expectedOrigin)return;B(),g.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);g.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!((xe=M.data.data)!=null&&xe.accessToken),hasIdToken:!!((ne=M.data.data)!=null&&ne.idToken)}),u?s(u):(g.error("[CROSSx] 토큰을 찾을 수 없음:",M.data),t(new Error("Token not found in response")))}else g.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 x(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 g.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 g.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 g.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){g.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 g.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){g.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){g.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 x(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 f=d.message||d.data||"API request failed";g.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:f,url:o,method:e,fullResponse:d});const w=We.mapGatewayError(d.code),m=We.getGatewayErrorMessage(d.code,f),_=new x(w,m);throw _.gatewayCode=d.code,_.gatewayMessage=f,_}return g.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:o,method:e}),d.data??d}return d}catch(l){if(l instanceof x)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,f=d.message||d.data||"API request failed",w=d.code||"UNKNOWN";throw g.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:w,message:f,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new x(p.UNKNOWN_ERROR,`Wallet Gateway error (${w}): ${f}`)}throw l}}async getOrCreateWallet(e){var s;g.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 g.log("[CROSSx][Migration Phase 2] 기존 지갑 발견 — address:",n),{id:e,address:n,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}}catch{g.log("[CROSSx][Migration Phase 2] 기존 지갑 없음, POST /mnemonic/create 진행")}g.log("[CROSSx][Migration Phase 2] POST /mnemonic/create — ignoreBackup: false");try{const t={ignoreBackup:!1},n=await this.request("POST","/mnemonic/create",t);return g.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")){g.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&&g.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 x&&this.isAddressNotFoundError(t))return g.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 x(p.TX_INVALID_PARAMS,"prepare: tx is required");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new x(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 x(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){g.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 g.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 x(Ce.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Ce.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new x(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=`
3
3
  @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
4
4
 
5
5
  #${te} {
@@ -634,6 +634,85 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
634
634
  filter: none;
635
635
  }
636
636
 
637
+ /* ── Wallet Selector Modal ─────────────────────────────────── */
638
+ .__crossx-wallet-list {
639
+ display: flex;
640
+ flex-direction: column;
641
+ gap: 8px;
642
+ max-height: 320px;
643
+ overflow-y: auto;
644
+ -webkit-overflow-scrolling: touch;
645
+ scrollbar-width: thin;
646
+ }
647
+ .__crossx-wallet-list::-webkit-scrollbar {
648
+ width: 4px;
649
+ }
650
+ .__crossx-wallet-list::-webkit-scrollbar-thumb {
651
+ background: var(--cx-divider);
652
+ border-radius: 2px;
653
+ }
654
+ .__crossx-wallet-item {
655
+ display: flex;
656
+ align-items: center;
657
+ gap: 8px;
658
+ padding: 16px;
659
+ background: var(--cx-pill-bg);
660
+ border: 1px solid var(--cx-border);
661
+ border-radius: 8px;
662
+ cursor: pointer;
663
+ appearance: none;
664
+ -webkit-appearance: none;
665
+ -webkit-tap-highlight-color: transparent;
666
+ box-shadow: none;
667
+ outline: none;
668
+ width: 100%;
669
+ transition: opacity 0.12s;
670
+ font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
671
+ }
672
+ .__crossx-wallet-item:hover { opacity: 0.8; }
673
+ .__crossx-wallet-item:focus { outline: none; box-shadow: none; }
674
+ .__crossx-wallet-addr {
675
+ font-size: 16px;
676
+ font-weight: 600;
677
+ line-height: 1.3;
678
+ color: var(--cx-value);
679
+ white-space: nowrap;
680
+ }
681
+ .__crossx-wallet-add {
682
+ display: flex;
683
+ align-items: center;
684
+ justify-content: center;
685
+ gap: 8px;
686
+ padding: 16px;
687
+ border: 1px dashed var(--cx-divider);
688
+ border-radius: 8px;
689
+ cursor: pointer;
690
+ appearance: none;
691
+ -webkit-appearance: none;
692
+ -webkit-tap-highlight-color: transparent;
693
+ box-shadow: none;
694
+ outline: none;
695
+ background: none;
696
+ width: 100%;
697
+ transition: opacity 0.12s;
698
+ flex-shrink: 0;
699
+ font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
700
+ }
701
+ .__crossx-wallet-add:hover { opacity: 0.8; }
702
+ .__crossx-wallet-add:focus { outline: none; box-shadow: none; }
703
+ .__crossx-wallet-add:disabled { opacity: 0.5; cursor: not-allowed; }
704
+ .__crossx-wallet-add-icon {
705
+ width: 24px;
706
+ height: 24px;
707
+ color: var(--cx-subtitle);
708
+ }
709
+ .__crossx-wallet-add-label {
710
+ font-size: 16px;
711
+ font-weight: 600;
712
+ line-height: 1.3;
713
+ color: var(--cx-subtitle);
714
+ }
715
+
637
716
  /* ── Mobile bottom sheet ───────────────────────────────────── */
638
717
  @media (max-width: 480px) {
639
718
  #${te} { align-items: flex-end; }
@@ -671,6 +750,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
671
750
  gap: 16px;
672
751
  }
673
752
  .__crossx-divider--cols { flex-shrink: 0; }
753
+ .__crossx-col-right-ws {
754
+ display: flex;
755
+ flex-direction: column;
756
+ gap: 8px;
757
+ }
674
758
 
675
759
  /* ── Landscape for signing/transaction modals ──────────── */
676
760
  @media (orientation: landscape) and (max-height: 500px) {
@@ -678,7 +762,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
678
762
  .__crossx-card--send-tx,
679
763
  .__crossx-card--sign-tx,
680
764
  .__crossx-card--sign-msg,
681
- .__crossx-card--sign-typed {
765
+ .__crossx-card--sign-typed,
766
+ .__crossx-card--wallet-selector {
682
767
  width: 600px;
683
768
  max-width: calc(100vw - 32px);
684
769
  border-radius: 24px;
@@ -690,20 +775,23 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
690
775
  .__crossx-card--send-tx .__crossx-header,
691
776
  .__crossx-card--sign-tx .__crossx-header,
692
777
  .__crossx-card--sign-msg .__crossx-header,
693
- .__crossx-card--sign-typed .__crossx-header {
778
+ .__crossx-card--sign-typed .__crossx-header,
779
+ .__crossx-card--wallet-selector .__crossx-header {
694
780
  padding: 16px 24px 12px;
695
781
  }
696
782
  .__crossx-card--send-tx .__crossx-body,
697
783
  .__crossx-card--sign-tx .__crossx-body,
698
784
  .__crossx-card--sign-msg .__crossx-body,
699
- .__crossx-card--sign-typed .__crossx-body {
785
+ .__crossx-card--sign-typed .__crossx-body,
786
+ .__crossx-card--wallet-selector .__crossx-body {
700
787
  padding: 16px 24px 20px;
701
788
  gap: 12px;
702
789
  }
703
790
  .__crossx-card--send-tx .__crossx-body-cols,
704
791
  .__crossx-card--sign-tx .__crossx-body-cols,
705
792
  .__crossx-card--sign-msg .__crossx-body-cols,
706
- .__crossx-card--sign-typed .__crossx-body-cols {
793
+ .__crossx-card--sign-typed .__crossx-body-cols,
794
+ .__crossx-card--wallet-selector .__crossx-body-cols {
707
795
  flex-direction: row;
708
796
  gap: 24px;
709
797
  align-items: flex-start;
@@ -720,57 +808,63 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
720
808
  .__crossx-card--sign-msg .__crossx-msg-box { max-height: 130px; }
721
809
  .__crossx-card--sign-typed .__crossx-td-rows { max-height: 130px; overflow-y: auto; }
722
810
  .__crossx-col-left > .__crossx-divider { display: none; }
811
+ .__crossx-col-right-ws {
812
+ display: flex;
813
+ flex-direction: column;
814
+ gap: 8px;
815
+ }
816
+ .__crossx-card--wallet-selector .__crossx-wallet-list { max-height: 140px; }
723
817
  }
724
- `;function Se(){let r=document.getElementById(Gt);r||(r=document.createElement("style"),r.id=Gt,document.head.appendChild(r)),r.textContent=nn}function Q(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function on(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=ot(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Wt={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 vs(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Wt[e]?Wt[e]:r}function ot(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 tt(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 an(r){try{return BigInt(r).toLocaleString()}catch{return r}}function cn(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=an(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${ot(l,i)} ${o}`,maxFeeGwei:tt(t),maxPriorityFeeGwei:n?tt(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${ot(l,i)} ${o}`,gasPriceGwei:tt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Ss(r){const e=cn(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 ce=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
818
+ `;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">
725
819
  <rect x="9" y="9" width="13" height="13" rx="2"/>
726
820
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
727
- </svg>`,de=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
821
+ </svg>`,ie=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
728
822
  <line x1="18" y1="6" x2="6" y2="18"/>
729
823
  <line x1="6" y1="6" x2="18" y2="18"/>
730
- </svg>`;function ln(r){return`<svg width="28" height="28" viewBox="0 0 28 28" fill="none">
824
+ </svg>`;function fn(r){return`<svg width="28" height="28" viewBox="0 0 28 28" fill="none">
731
825
  <circle cx="14" cy="14" r="14" fill="${r}"/>
732
826
  <path d="M14 7.5L19.2 10.5V16.5L14 19.5L8.8 16.5V10.5L14 7.5Z" fill="white" opacity="0.9"/>
733
- </svg>`}const pt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
827
+ </svg>`}const _t=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
734
828
  <rect x="2" y="5" width="16" height="12" rx="2" stroke="currentColor" stroke-width="1.5"/>
735
829
  <path d="M2 9h16" stroke="currentColor" stroke-width="1.5"/>
736
830
  <rect x="12.5" y="11.5" width="3.5" height="2.5" rx="0.75" fill="currentColor"/>
737
- </svg>`,dn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
831
+ </svg>`,gn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
738
832
  <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)"/>
739
- </svg>`,un=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
833
+ </svg>`,pn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
740
834
  <circle cx="12" cy="12" r="12" fill="var(--cx-secondary)"/>
741
835
  <circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
742
836
  <path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
743
- </svg>`;function ue(r){return[`--cx-bg:${r.bg}`,`--cx-border:${r.border}`,`--cx-title:${r.titleColor}`,`--cx-subtitle:${r.subtitleColor}`,`--cx-label:${r.labelColor}`,`--cx-value:${r.valueColor}`,`--cx-pill-bg:${r.pillBg}`,`--cx-pill-from:${r.pillFromColor}`,`--cx-pill-amt:${r.pillAmtColor}`,`--cx-divider:${r.divider}`,`--cx-close:${r.closeColor}`,`--cx-close-hover:${r.closeHoverBg}`,`--cx-copy:${r.copyColor}`,`--cx-input-bg:${r.inputBg}`,`--cx-input-border:${r.inputBorder}`,`--cx-hint:${r.hintColor}`,`--cx-primary:${r.primary}`,`--cx-primary-glow:${r.primaryGlow}`,`--cx-secondary:${r.secondary}`,`--cx-on-primary:${r.onPrimary}`].join(";")}function G(r,e){return`
837
+ </svg>`;function ae(r){return[`--cx-bg:${r.bg}`,`--cx-border:${r.border}`,`--cx-title:${r.titleColor}`,`--cx-subtitle:${r.subtitleColor}`,`--cx-label:${r.labelColor}`,`--cx-value:${r.valueColor}`,`--cx-pill-bg:${r.pillBg}`,`--cx-pill-from:${r.pillFromColor}`,`--cx-pill-amt:${r.pillAmtColor}`,`--cx-divider:${r.divider}`,`--cx-close:${r.closeColor}`,`--cx-close-hover:${r.closeHoverBg}`,`--cx-copy:${r.copyColor}`,`--cx-input-bg:${r.inputBg}`,`--cx-input-border:${r.inputBorder}`,`--cx-hint:${r.hintColor}`,`--cx-primary:${r.primary}`,`--cx-primary-glow:${r.primaryGlow}`,`--cx-secondary:${r.secondary}`,`--cx-on-primary:${r.onPrimary}`].join(";")}function G(r,e){return`
744
838
  <div class="__crossx-row">
745
839
  <span class="__crossx-row-label">${r}</span>
746
840
  <div class="__crossx-row-value">${e}</div>
747
- </div>`}function hn(r,e){const s=e,t=Ke(),n=r.to?`<span class="__crossx-addr-text">${Q(r.to)}</span>
748
- <button class="__crossx-copy-btn" data-copy="${D(r.to)}" title="Copy address">${ce}</button>`:"<span>—</span>",o=Ss(r),i=r.data&&r.data!=="0x"?r.data:"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
749
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
841
+ </div>`}function _n(r,e){const s=e,t=ze(),n=r.to?`<span class="__crossx-addr-text">${Y(r.to)}</span>
842
+ <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=`
843
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
750
844
  <div class="__crossx-header">
751
845
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
752
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
846
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
753
847
  </div>
754
848
  <hr class="__crossx-divider">
755
849
  <div class="__crossx-body">
756
850
  <div class="__crossx-body-cols">
757
851
  <div class="__crossx-col-left">
758
852
  <p class="__crossx-sig-subtitle">
759
- <span class="__crossx-sig-origin">${D(t)} </span>is requesting a Signature
853
+ <span class="__crossx-sig-origin">${$(t)} </span>is requesting a Signature
760
854
  </p>
761
855
  <div class="__crossx-addr-pill">
762
- ${pt}
763
- <span class="__crossx-addr-pill-text">${Q(r.from)}</span>
856
+ ${_t}
857
+ <span class="__crossx-addr-pill-text">${Y(r.from)}</span>
764
858
  </div>
765
859
  <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
766
860
  <hr class="__crossx-divider">
767
861
  <div class="__crossx-rows">
768
862
  ${G("To",n)}
769
- ${G("Network",`<span>${vs(r.chainId)}</span>`)}
863
+ ${G("Network",`<span>${Es(r.chainId)}</span>`)}
770
864
  ${o}
771
865
  </div>
772
866
  </div>
773
- <pre class="__crossx-raw-tx">${D(i)}</pre>
867
+ <pre class="__crossx-raw-tx">${$(i)}</pre>
774
868
  </div>
775
869
  <div class="__crossx-btn-row">
776
870
  <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">Cancel</button>
@@ -778,43 +872,43 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
778
872
  </div>
779
873
  </div>
780
874
  </div>
781
- `,a}function fn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=Ke(),i=r.to?`<span class="__crossx-addr-text">${Q(r.to)}</span>
782
- <button class="__crossx-copy-btn" data-copy="${D(r.to)}" title="Copy address">${ce}</button>`:"<span>—</span>",a=Ss(r),l=on(r.value,t,n)??"—",d=document.createElement("div");return d.id=te,d.innerHTML=`
783
- <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
875
+ `,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>
876
+ <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=`
877
+ <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
784
878
  <div class="__crossx-header">
785
879
  <p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
786
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
880
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
787
881
  </div>
788
882
  <hr class="__crossx-divider">
789
883
  <div class="__crossx-body">
790
884
  <p class="__crossx-tx-subtitle">
791
- <span class="__crossx-sig-origin">${D(o)}</span> wants your permission to approve the following transaction.
885
+ <span class="__crossx-sig-origin">${$(o)}</span> wants your permission to approve the following transaction.
792
886
  </p>
793
887
  <div class="__crossx-body-cols">
794
888
  <div class="__crossx-rows">
795
889
  ${G("To",i)}
796
- ${G("Network",`<span>${vs(r.chainId)}</span>`)}
890
+ ${G("Network",`<span>${Es(r.chainId)}</span>`)}
797
891
  ${a}
798
892
  </div>
799
893
  <div class="__crossx-pill">
800
- <span class="__crossx-pill-from">${Q(r.from)}</span>
894
+ <span class="__crossx-pill-from">${Y(r.from)}</span>
801
895
  <span class="__crossx-pill-amount">${l}</span>
802
896
  </div>
803
897
  </div>
804
898
  <button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
805
899
  </div>
806
900
  </div>
807
- `,d}function Ke(){var r;try{return((r=window.location)==null?void 0:r.hostname)||"This site"}catch{return"This site"}}function D(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function gn(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function pn(r){if(typeof r=="string")return D(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return D(JSON.stringify(r))}catch{return String(r)}}function xn(r,e){const s=G("From",`<span class="__crossx-addr-text">${Q(r.from)}</span>
808
- <button class="__crossx-copy-btn" data-copy="${D(r.from)}" title="Copy address">${ce}</button>`),t=r.to?G("To",`<span class="__crossx-addr-text">${Q(r.to)}</span>
809
- <button class="__crossx-copy-btn" data-copy="${D(r.to)}" title="Copy address">${ce}</button>`):"",n=r.amount?G("Transfer",`<span>${D(r.amount)}</span>`):"",o=r.fees?G("Tx Fee",`<span>${D(r.fees)}</span>`):"",i=r.txHash?G("Tx Hash",`<span class="__crossx-addr-text">${Q(r.txHash)}</span>
810
- <button class="__crossx-copy-btn" data-copy="${D(r.txHash)}" title="Copy hash">${ce}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
901
+ `,d}function ze(){var r;try{return((r=window.location)==null?void 0:r.hostname)||"This site"}catch{return"This site"}}function $(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function mn(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function wn(r){if(typeof r=="string")return $(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return $(JSON.stringify(r))}catch{return String(r)}}function yn(r,e){const s=G("From",`<span class="__crossx-addr-text">${Y(r.from)}</span>
902
+ <button class="__crossx-copy-btn" data-copy="${$(r.from)}" title="Copy address">${de}</button>`),t=r.to?G("To",`<span class="__crossx-addr-text">${Y(r.to)}</span>
903
+ <button class="__crossx-copy-btn" data-copy="${$(r.to)}" title="Copy address">${de}</button>`):"",n=r.amount?G("Transfer",`<span>${$(r.amount)}</span>`):"",o=r.fees?G("Tx Fee",`<span>${$(r.fees)}</span>`):"",i=r.txHash?G("Tx Hash",`<span class="__crossx-addr-text">${Y(r.txHash)}</span>
904
+ <button class="__crossx-copy-btn" data-copy="${$(r.txHash)}" title="Copy hash">${de}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
811
905
  <span class="__crossx-total-label">Total<br>(including fees)</span>
812
- <span class="__crossx-total-amount">${D(r.total)}</span>
906
+ <span class="__crossx-total-amount">${$(r.total)}</span>
813
907
  </div>`:"",c=document.createElement("div");return c.id=te,c.innerHTML=`
814
- <div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
908
+ <div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
815
909
  <div class="__crossx-header">
816
910
  <p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
817
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
911
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
818
912
  </div>
819
913
  <hr class="__crossx-divider">
820
914
  <div class="__crossx-body">
@@ -829,8 +923,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
829
923
  <button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
830
924
  </div>
831
925
  </div>
832
- `,c}function _n(r,e){const s=document.createElement("div");return s.id=te,s.innerHTML=`
833
- <div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
926
+ `,c}function bn(r,e){const s=document.createElement("div");return s.id=te,s.innerHTML=`
927
+ <div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
834
928
  <div class="__crossx-header">
835
929
  <p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
836
930
  </div>
@@ -842,38 +936,38 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
842
936
  </div>
843
937
  </div>
844
938
  </div>
845
- `,s}function mn(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 x=n?un:t?"":dn,A=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";x?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${x}<span>${A}</span>`):o.textContent=A}if(i&&!r.querySelector("#__crossx-close-btn")){const x=document.createElement("button");x.className="__crossx-close",x.id="__crossx-close-btn",x.setAttribute("aria-label","Close"),x.innerHTML=de,i.appendChild(x)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?G("From",`<span class="__crossx-addr-text">${Q(e.from)}</span>
846
- <button class="__crossx-copy-btn" data-copy="${D(e.from)}" title="Copy address">${ce}</button>`):"",l=e.to?G("To",`<span class="__crossx-addr-text">${Q(e.to)}</span>
847
- <button class="__crossx-copy-btn" data-copy="${D(e.to)}" title="Copy address">${ce}</button>`):"",d=e.amount?G("Transfer",`<span>${D(e.amount)}</span>`):"",g=e.fees?G("Tx Fee",`<span>${D(e.fees)}</span>`):"",w=e.txHash?G("Tx Hash",`<span class="__crossx-addr-text">${Q(e.txHash)}</span>
848
- <button class="__crossx-copy-btn" data-copy="${D(e.txHash)}" title="Copy hash">${ce}</button>`):"",m=e.total?`<div class="__crossx-total-pill">
939
+ `,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 _=n?pn:t?"":gn,T=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";_?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${_}<span>${T}</span>`):o.textContent=T}if(i&&!r.querySelector("#__crossx-close-btn")){const _=document.createElement("button");_.className="__crossx-close",_.id="__crossx-close-btn",_.setAttribute("aria-label","Close"),_.innerHTML=ie,i.appendChild(_)}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>
940
+ <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>
941
+ <button class="__crossx-copy-btn" data-copy="${$(e.to)}" title="Copy address">${de}</button>`):"",d=e.amount?G("Transfer",`<span>${$(e.amount)}</span>`):"",f=e.fees?G("Tx Fee",`<span>${$(e.fees)}</span>`):"",w=e.txHash?G("Tx Hash",`<span class="__crossx-addr-text">${Y(e.txHash)}</span>
942
+ <button class="__crossx-copy-btn" data-copy="${$(e.txHash)}" title="Copy hash">${de}</button>`):"",m=e.total?`<div class="__crossx-total-pill">
849
943
  <span class="__crossx-total-label">Total<br>(including fees)</span>
850
- <span class="__crossx-total-amount">${D(e.total)}</span>
944
+ <span class="__crossx-total-amount">${$(e.total)}</span>
851
945
  </div>`:"";a.innerHTML=`
852
946
  <div class="__crossx-rows">
853
947
  ${c}
854
948
  ${l}
855
949
  ${d}
856
- ${g}
950
+ ${f}
857
951
  ${w}
858
952
  </div>
859
953
  ${m}
860
954
  <button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
861
- `,a.querySelectorAll(".__crossx-copy-btn").forEach(x=>{x.addEventListener("click",A=>{var C;A.stopPropagation();const E=x.dataset.copy;E&&((C=navigator.clipboard)==null||C.writeText(E).catch(()=>{}))})})}function wn(r,e){const s=e,t=Ke(),n=D(r.message),o=document.createElement("div");return o.id=te,o.innerHTML=`
862
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
955
+ `,a.querySelectorAll(".__crossx-copy-btn").forEach(_=>{_.addEventListener("click",T=>{var A;T.stopPropagation();const b=_.dataset.copy;b&&((A=navigator.clipboard)==null||A.writeText(b).catch(()=>{}))})})}function Sn(r,e){const s=e,t=ze(),n=$(r.message),o=document.createElement("div");return o.id=te,o.innerHTML=`
956
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
863
957
  <div class="__crossx-header">
864
958
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
865
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
959
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
866
960
  </div>
867
961
  <hr class="__crossx-divider">
868
962
  <div class="__crossx-body">
869
963
  <div class="__crossx-body-cols">
870
964
  <div class="__crossx-col-left">
871
965
  <p class="__crossx-sig-subtitle">
872
- <span class="__crossx-sig-origin">${D(t)} </span>is requesting a Signature
966
+ <span class="__crossx-sig-origin">${$(t)} </span>is requesting a Signature
873
967
  </p>
874
968
  <div class="__crossx-addr-pill">
875
- ${pt}
876
- <span class="__crossx-addr-pill-text">${Q(r.from)}</span>
969
+ ${_t}
970
+ <span class="__crossx-addr-pill-text">${Y(r.from)}</span>
877
971
  </div>
878
972
  <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
879
973
  </div>
@@ -886,31 +980,31 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
886
980
  </div>
887
981
  </div>
888
982
  </div>
889
- `,o}function yn(r,e){const s=e,t=Ke();let n={};if(typeof r.typedData=="string")try{n=JSON.parse(r.typedData)}catch{}else r.typedData&&typeof r.typedData=="object"&&(n=r.typedData);const o=n.primaryType??"—",i=n.message??{};let a=`
983
+ `,o}function En(r,e){const s=e,t=ze();let n={};if(typeof r.typedData=="string")try{n=JSON.parse(r.typedData)}catch{}else r.typedData&&typeof r.typedData=="object"&&(n=r.typedData);const o=n.primaryType??"—",i=n.message??{};let a=`
890
984
  <div class="__crossx-td-row">
891
985
  <span class="__crossx-td-label">Primary Type</span>
892
- <span class="__crossx-td-value">${D(o)}</span>
893
- </div>`;for(const[l,d]of Object.entries(i)){const g=pn(d),m=gn(d)?`<span class="__crossx-addr-text">${Q(d)}</span>
894
- <button class="__crossx-copy-btn" data-copy="${D(String(d))}" title="Copy">${ce}</button>`:`<span>${g}</span>`;a+=`
986
+ <span class="__crossx-td-value">${$(o)}</span>
987
+ </div>`;for(const[l,d]of Object.entries(i)){const f=wn(d),m=mn(d)?`<span class="__crossx-addr-text">${Y(d)}</span>
988
+ <button class="__crossx-copy-btn" data-copy="${$(String(d))}" title="Copy">${de}</button>`:`<span>${f}</span>`;a+=`
895
989
  <div class="__crossx-td-row">
896
- <span class="__crossx-td-label">${D(l)}</span>
990
+ <span class="__crossx-td-label">${$(l)}</span>
897
991
  <div class="__crossx-td-value">${m}</div>
898
992
  </div>`}const c=document.createElement("div");return c.id=te,c.innerHTML=`
899
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
993
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
900
994
  <div class="__crossx-header">
901
995
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
902
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
996
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
903
997
  </div>
904
998
  <hr class="__crossx-divider">
905
999
  <div class="__crossx-body">
906
1000
  <div class="__crossx-body-cols">
907
1001
  <div class="__crossx-col-left">
908
1002
  <p class="__crossx-sig-subtitle">
909
- <span class="__crossx-sig-origin">${D(t)} </span>is requesting a Signature
1003
+ <span class="__crossx-sig-origin">${$(t)} </span>is requesting a Signature
910
1004
  </p>
911
1005
  <div class="__crossx-addr-pill">
912
- ${pt}
913
- <span class="__crossx-addr-pill-text">${Q(r.from)}</span>
1006
+ ${_t}
1007
+ <span class="__crossx-addr-pill-text">${Y(r.from)}</span>
914
1008
  </div>
915
1009
  <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
916
1010
  </div>
@@ -923,32 +1017,68 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
923
1017
  </div>
924
1018
  </div>
925
1019
  </div>
926
- `,c}const bn=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
1020
+ `,c}const Tn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
1021
+ <line x1="12" y1="5" x2="12" y2="19"/>
1022
+ <line x1="5" y1="12" x2="19" y2="12"/>
1023
+ </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)}">
1024
+ <span class="__crossx-wallet-addr">${Y(n.address)}</span>
1025
+ </button>`).join(""),t=document.createElement("div");return t.id=te,t.innerHTML=`
1026
+ <div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1027
+ <div class="__crossx-header">
1028
+ <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
1029
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">Select Connected Wallet</p>
1030
+ <p class="__crossx-subtitle--body">Please select the wallet you previously used for this game to continue.</p>
1031
+ </div>
1032
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
1033
+ </div>
1034
+ <hr class="__crossx-divider">
1035
+ <div class="__crossx-body">
1036
+ <div class="__crossx-body-cols">
1037
+ <div class="__crossx-col-left">
1038
+ <div class="__crossx-mig-info">
1039
+ <p class="__crossx-mig-info-title">Why do I need to select a wallet?</p>
1040
+ <p class="__crossx-mig-info-desc">Identifying your previously linked wallet ensures your game progress and assets are synced correctly.</p>
1041
+ </div>
1042
+ </div>
1043
+ <hr class="__crossx-divider __crossx-divider--cols">
1044
+ <div class="__crossx-col-right-ws">
1045
+ <div class="__crossx-wallet-list" id="__crossx-wallet-list">
1046
+ ${s}
1047
+ </div>
1048
+ <button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
1049
+ <span class="__crossx-wallet-add-icon">${Tn}</span>
1050
+ <span class="__crossx-wallet-add-label">add a wallet</span>
1051
+ </button>
1052
+ </div>
1053
+ </div>
1054
+ </div>
1055
+ </div>
1056
+ `,t}const An=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
927
1057
  <path d="M26.693 21.193c-.028-3.168 2.587-4.712 2.706-4.786-1.477-2.16-3.77-2.454-4.58-2.484-1.944-.197-3.804 1.148-4.793 1.148-.992 0-2.52-1.12-4.147-1.09-2.13.032-4.1 1.239-5.198 3.133-2.222 3.855-.569 9.562 1.593 12.69 1.061 1.535 2.318 3.258 3.975 3.196 1.6-.064 2.2-1.03 4.133-1.03 1.928 0 2.48 1.03 4.172.997 1.72-.03 2.806-1.56 3.862-3.1 1.211-1.779 1.713-3.495 1.74-3.583-.037-.017-3.427-1.316-3.463-5.09z" fill="currentColor"/>
928
1058
  <path d="M23.527 11.876c.877-1.065 1.471-2.545 1.31-4.024-1.266.053-2.807.845-3.718 1.907-.813.946-1.53 2.468-1.34 3.915 1.41.107 2.852-.716 3.748-1.798z" fill="currentColor"/>
929
- </svg>`,vn=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
1059
+ </svg>`,Rn=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
930
1060
  <path d="M38.06 20.44c0-1.34-.12-2.63-.34-3.87H20.5v7.32h9.84c-.42 2.28-1.71 4.21-3.65 5.51v4.57h5.91c3.46-3.19 5.46-7.88 5.46-13.53z" fill="#4285F4"/>
931
1061
  <path d="M20.5 38.5c4.94 0 9.09-1.64 12.12-4.44l-5.91-4.57c-1.64 1.1-3.73 1.75-6.21 1.75-4.77 0-8.82-3.22-10.26-7.55H4.16v4.72A18.49 18.49 0 0 0 20.5 38.5z" fill="#34A853"/>
932
1062
  <path d="M10.24 23.69A11.16 11.16 0 0 1 9.66 20c0-1.28.22-2.52.58-3.69v-4.72H4.16A18.49 18.49 0 0 0 2 20c0 2.97.71 5.78 1.97 8.28l6.27-4.59z" fill="#FBBC05"/>
933
1063
  <path d="M20.5 8.76c2.69 0 5.1.92 7 2.73l5.24-5.24C29.58 3.36 25.43 1.5 20.5 1.5A18.49 18.49 0 0 0 4.16 11.59l6.08 4.72C11.68 11.98 15.73 8.76 20.5 8.76z" fill="#EA4335"/>
934
- </svg>`;function Sn(r){const e=r,s=document.createElement("div");return s.id=te,s.innerHTML=`
935
- <div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1064
+ </svg>`;function On(r){const e=r,s=document.createElement("div");return s.id=te,s.innerHTML=`
1065
+ <div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
936
1066
  <div class="__crossx-header">
937
1067
  <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
938
1068
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">Welcome onboard</p>
939
1069
  <p class="__crossx-subtitle">Creating CROSSx Embedded Wallet</p>
940
1070
  </div>
941
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
1071
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
942
1072
  </div>
943
1073
  <hr class="__crossx-divider">
944
1074
  <div class="__crossx-body">
945
1075
  <div class="__crossx-login-btn-row">
946
1076
  <button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
947
- <span class="__crossx-login-icon" style="color:var(--cx-value);">${bn}</span>
1077
+ <span class="__crossx-login-icon" style="color:var(--cx-value);">${An}</span>
948
1078
  <span class="__crossx-login-btn-label">Sign in with&nbsp;&nbsp;Apple</span>
949
1079
  </button>
950
1080
  <button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
951
- <span class="__crossx-login-icon">${vn}</span>
1081
+ <span class="__crossx-login-icon">${Rn}</span>
952
1082
  <span class="__crossx-login-btn-label">Sign in with&nbsp;&nbsp;Google</span>
953
1083
  </button>
954
1084
  </div>
@@ -958,12 +1088,12 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
958
1088
  </p>
959
1089
  </div>
960
1090
  </div>
961
- `,s}function En(r){const e=r,s=document.createElement("div");return s.id=te,s.innerHTML=`
962
- <div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1091
+ `,s}function Cn(r){const e=r,s=document.createElement("div");return s.id=te,s.innerHTML=`
1092
+ <div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
963
1093
  <div class="__crossx-header">
964
1094
  <p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
965
1095
  <p class="__crossx-subtitle--body">We found a wallet linked to your social account. Enter your 4-digit PIN to restore your assets.</p>
966
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
1096
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
967
1097
  </div>
968
1098
  <hr class="__crossx-divider">
969
1099
  <div class="__crossx-body">
@@ -972,17 +1102,17 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
972
1102
  <p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
973
1103
  </div>
974
1104
  <button class="__crossx-recover-btn" id="__crossx-recover-btn">
975
- <span>${ln(e.primary)}</span>
1105
+ <span>${fn(e.primary)}</span>
976
1106
  <span class="__crossx-recover-label">Recover My Wallet</span>
977
1107
  </button>
978
1108
  <button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>
979
1109
  </div>
980
1110
  </div>
981
- `,s}function Tn(r,e){const s=r,t=e?`<p class="__crossx-pin-error-text">${e}</p>`:"",n=document.createElement("div");return n.id=te,n.innerHTML=`
982
- <div class="__crossx-card __crossx-card--migration" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1111
+ `,s}function kn(r,e){const s=r,t=e?`<p class="__crossx-pin-error-text">${e}</p>`:"",n=document.createElement("div");return n.id=te,n.innerHTML=`
1112
+ <div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
983
1113
  <div class="__crossx-header">
984
1114
  <p class="__crossx-title" id="__crossx-ttl">Recover My Wallet</p>
985
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
1115
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
986
1116
  </div>
987
1117
  <hr class="__crossx-divider">
988
1118
  <div class="__crossx-pin-center">
@@ -996,4 +1126,4 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
996
1126
  ${t}
997
1127
  </div>
998
1128
  </div>
999
- `,n}function An(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,w)=>{t[w]&&(t[w].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 In{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=qt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=qt(e,this.overrides)}getTheme(){return this.theme}showLoginSelector(){return new Promise(e=>{var a,c,l;Se();const s=Sn(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;Se();const s=En(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;Se();const t=Tn(this.tokens,e);document.body.appendChild(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};An(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;Se();const t=xn(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 w;d.stopPropagation();const g=l.dataset.copy;g&&((w=navigator.clipboard)==null||w.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=>{Se();const n=_n(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",w=>{w.target===n&&a()});const l=w=>{w.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(mn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;Se();let t;e.type==="sign-message"?t=wn(e,this.tokens):e.type==="sign-typed-data"?t=yn(e,this.tokens):e.type==="sign"?t=hn(e,this.tokens):t=fn(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",w=>{var x;w.stopPropagation();const m=g.dataset.copy;m&&((x=navigator.clipboard)==null||x.writeText(m).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 Rn{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}const On="https://cross-wallet-oauth.crosstoken.io",Cn="https://cross-auth.crosstoken.io",Nn="https://embedded-wallet-gateway.crosstoken.io/api/v1";function Pn(){return On}function kn(){return Cn}function Ln(){return Nn}function Dn(r){r.debug;const e=Pn(),s=kn(),t=Ln(),n={...r,oauthServiceUrl:e,authApiUrl:s,walletGatewayUrl:t},i=r.authMode==="token"&&Tt.isAvailable()?new Tt:new Ws,a=new Jr,c=new tn,l=new gt,d=new Rn;let g;r.useMockWallet?(f.log("[CROSSx] Mock Wallet Provider 사용"),g=new sn(i)):(f.log("[CROSSx] Remote Wallet Provider 사용"),g=new qe({gatewayUrl:t,projectId:r.projectId},i,c,d));const w=new Oe({gatewayUrl:t,projectId:r.projectId},c),m=new In(r.theme??"light",r.themeTokens);return new Fe(n,i,a,c,l,g,d,m,w)}exports.CROSSxError=_;exports.CROSSxEthereumProvider=jt;exports.CROSSxSDK=Fe;exports.ChainId=Is;exports.ErrorCode=p;exports.createCROSSxSDK=Dn;
1129
+ `,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((f,w)=>{t[w]&&(t[w].value=f)});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 m;me();const n=[...e],o=In(n,this.tokens);document.body.appendChild(o);let i=!1;const a=()=>{i||(i=!0,o.remove())},c=_=>{a(),t(_)},l=()=>{a(),t(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(_=>{_.addEventListener("click",()=>{const T=_.dataset.walletAddress??"",b=parseInt(_.dataset.walletIndex??"0",10);c({address:T,index:b})})})})();const f=o.querySelector("#__crossx-add-wallet-btn");f&&f.addEventListener("click",async()=>{f.disabled=!0;try{const _=await s();n.push(_);const T=o.querySelector("#__crossx-wallet-list");if(T){const b=document.createElement("button");b.className="__crossx-wallet-item",b.dataset.walletIndex=String(_.index),b.dataset.walletAddress=_.address,b.innerHTML=`<span class="__crossx-wallet-addr">${Y(_.address)}</span>`,b.addEventListener("click",()=>c(_)),T.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{f.disabled=!1}}),(m=o.querySelector("#__crossx-close-btn"))==null||m.addEventListener("click",l),o.addEventListener("click",_=>{_.target===o&&l()});const w=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",w),l())};document.addEventListener("keydown",w)})}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",f=>f.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 w;d.stopPropagation();const f=l.dataset.copy;f&&((w=navigator.clipboard)==null||w.writeText(f).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,f;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(f=n.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),n.addEventListener("click",w=>{w.target===n&&a()});const l=w=>{w.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(f=>{f.addEventListener("click",w=>{var _;w.stopPropagation();const m=f.dataset.copy;m&&((_=navigator.clipboard)==null||_.writeText(m).catch(()=>{}))})}),t.addEventListener("click",f=>{f.target===t&&i()});const a=f=>{f.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?(g.log("[CROSSx] Mock Wallet Provider 사용"),d=new an(o)):(g.log("[CROSSx] Remote Wallet Provider 사용"),d=new We(t,o,a,l));const f=new Ce(t,a),w=new Pn(r.theme??"light",r.themeTokens);return new Fe(s,t,o,i,a,c,d,l,w,f)}exports.CROSSxError=x;exports.CROSSxEthereumProvider=Kt;exports.CROSSxSDK=Fe;exports.ChainId=Os;exports.ErrorCode=p;exports.createCROSSxSDK=Dn;