@nexus-cross/crossx-sdk-core 1.0.7 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +3 -0
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
- package/dist/core/config/environments.d.ts.map +1 -1
- package/dist/core/i18n/index.d.ts +14 -0
- package/dist/core/i18n/index.d.ts.map +1 -0
- package/dist/core/i18n/messages.en.d.ts +4 -0
- package/dist/core/i18n/messages.en.d.ts.map +1 -0
- package/dist/core/i18n/messages.ko.d.ts +4 -0
- package/dist/core/i18n/messages.ko.d.ts.map +1 -0
- package/dist/core/i18n/types.d.ts +31 -0
- package/dist/core/i18n/types.d.ts.map +1 -0
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/ports/ConfirmationPort.d.ts +6 -0
- package/dist/core/ports/ConfirmationPort.d.ts.map +1 -1
- package/dist/core/types/index.d.ts +8 -0
- package/dist/core/types/index.d.ts.map +1 -1
- package/dist/index.cjs +30 -30
- package/dist/index.js +487 -390
- package/dist/sdk/CROSSxSDK.d.ts +11 -0
- package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
- package/package.json +2 -1
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var Ts=Object.defineProperty;var As=(r,e,s)=>e in r?Ts(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var v=(r,e,s)=>As(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Rs=require("jose");var g=(r=>(r.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",r.AUTH_FAILED="AUTH_FAILED",r.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",r.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",r.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",r.WALLET_NOT_FOUND="WALLET_NOT_FOUND",r.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(g||{});class 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(g.NOT_IMPLEMENTED,`${e} is not yet supported. Use sdk.signMessage() directly.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new x(g.NOT_IMPLEMENTED,`${e} is not yet supported. Use sdk.signTypedData() or sdk.signTypedDataOffchain() directly.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...s))}_caip2ToHex(e){const s=e.split(":");return`0x${parseInt(s[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let we=null;function wt(r){we=r}const p={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(g.AUTH_FAILED,`${s} failed (code ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const n=t;if(n.code&&n.code!==200&&n.code>0)throw new x(g.AUTH_FAILED,`${s} failed (code ${n.code}): ${n.message}`)}}async execute(e){var n,o,i,a;let s,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:f}=this.config,w=`${d}${l}`;p.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인):`,w);const _=await this.oauth.openAuth({authUrl:w,expectedOrigin:new URL(d).origin});p.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",_.length,")");const{accessToken:m,refreshToken:A}=await this.exchangeFirebaseToken(_,f);let y,I;try{const U=this.crypto.decodeJWT(_);I=(n=U.firebase)==null?void 0:n.sign_in_provider;const $=((o=U.firebase)==null?void 0:o.identities)??{};I==="google.com"?y=(i=$["google.com"])==null?void 0:i[0]:I==="apple.com"&&(y=(a=$["apple.com"])==null?void 0:a[0]),p.log("[CROSSx] OAuth provider sub 추출 — provider:",I,"hasProviderSub:",!!y)}catch{p.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(m){const U=this.crypto.decodeJWT(m);p.log("[CROSSx] access_token 디코딩 — sub:",U.sub,"exp:",U.exp);const $=await this.crypto.verifyJWT(m);if(t=$.signatureVerified??!1,!$.valid)throw p.error("[CROSSx] access_token 검증 실패"),new Error("Invalid access token");const B=$.payload;s={id:B.sub,email:B.email,signInProvider:I,providerSub:y},this.tokenStore.set(m),this.useCookieAuth||(await this.storage.set(Ze,m),A&&await this.storage.set(Ne,A))}else{const U=this.crypto.decodeJWT(_);s={id:U.sub,email:U.email,signInProvider:I,providerSub:y},p.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}p.log("[CROSSx] 사용자 정보 — id:",s.id);const L=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Pe,L),p.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return p.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return p.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`;p.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"}:{}});p.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return p.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(g.AUTH_FAILED,"access_token not found in exchange response");p.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 p.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){p.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(p.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return p.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);p.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(Pe);if(p.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;p.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return p.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return p.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"}:{}});p.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){p.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new x(g.AUTH_FAILED,"Silent refresh failed: no token in response");if(this.tokenStore.set(c),!t){await this.storage.set(Ze,c);const l=this.extractRefreshToken(a);l&&await this.storage.set(Ne,l)}return p.log("[CROSSx] silentRefresh 성공"),c}async loadWallet(e,s){let t,n=!1;try{p.log("[CROSSx][Migration Phase 2] POST /mnemonic/create 호출 — userId:",e.id),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,p.log("[CROSSx][Migration Phase 2] 지갑 로드 완료 (기존 백업 없음) — address:",t)}catch(o){if(o instanceof x&&o.code===g.MIGRATION_BACKUP_EXISTS)p.log("[CROSSx][Migration Phase 2] Gateway -10012 감지 → needsMigration = true"),n=!0;else{if(o instanceof x&&(o.code===g.PROJECT_NOT_REGISTERED||o.code===g.PROJECT_ID_MISSING||o.code===g.ORIGIN_NOT_ALLOWED))throw p.error("[CROSSx][Migration Phase 2] 프로젝트 설정 에러:",o.message),o;p.warn("[CROSSx][Migration Phase 2] 지갑 로드 실패 (로그인은 유지):",o)}}return p.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(g.NOT_IMPLEMENTED,"Migration is not supported in the current environment");p.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return p.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(g.UNKNOWN_ERROR,`RPC error [${e}] (${t}): ${a.error.message} (code: ${a.error.code})`);return a==null?void 0:a.result}}class Us{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}const Ue={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}},Fs="/crossx.config.json";function yt(r){const e=r.environment;return e&&e in Ue?Ue[e]:null}async function Hs(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=yt(r);if(e)return e}}catch{}try{const r=await fetch(Fs);if(r.ok){const e=await r.json(),s=yt(e);if(s)return s}}catch{}return Ue.production}const Gs=2e3,bt=6e4,qs=1e3,Ws=1e4,js="0x77359400",vt="0x3B9ACA00",St=130,Et=6,It=18,Vs=0,Ks=30*1e3,X=class X extends Us{constructor(e,s,t,n,o,i,a,c,l,d){super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this.authenticated=!1,this.userId=null,this.address=null,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&wt(e.logger),this.confirmation=l,this.chainRegistry=d,this.jsonRpc=new Bs(d,o),this.signInUseCase=new Ns(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new $s(this.internalConfig,t,c),this.migrateWalletUseCase=new Ms(t,a)}get config(){return this._config}async initialize(){if(this.initialized)return this.authenticated?{success:!0,address:this.address??void 0}:null;console.log("[CROSSx SDK] v1.0.7 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(g.AUTH_NOT_INITIALIZED,"SDK initialization failed",e)}}async signIn(e){this.ensureInitialized();let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector();if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new x(g.AUTH_FAILED,"Sign in failed",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};if(s.needsMigration||!s.address){const{address:o}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:t}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(g.UNKNOWN_ERROR,"Sign out failed",e)}}isAuthenticated(){return this.authenticated}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();return e!=null&&e.success?(this.applyAuthResult(e),!0):!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"User ID not found");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.emit("addressChanged",{address:s.address,index:0}),p.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof x?s:new x(g.MIGRATION_FAILED,"Wallet migration failed",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"User ID not found");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:0}}async getAddresses(){return this.ensureAuthenticated(),this.userId?this.walletProvider.getAddresses(this.userId):[]}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const s=await this.walletProvider.getAddresses(this.userId),t=await this.confirmation.showWalletSelector(s,async()=>{const n=s.length,i={address:(await this.walletProvider.getAddress(this.userId,n)).address,index:n};return s.push(i),i},e);return t&&(this.address=t.address,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof x?e:new x(g.UNKNOWN_ERROR,"Failed to fetch chains",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof x?s:new x(g.CHAIN_NOT_SUPPORTED,`Failed to fetch chain: ${e}`,s)}}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"User ID not found");p.log("[CROSSx] 지갑 생성 시작");try{const e=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=e.address,this.emit("addressChanged",{address:e.address,index:0}),p.log("[CROSSx] 지갑 생성 완료:",e.address),{address:e.address}}catch(e){if(e instanceof x&&e.code===g.MIGRATION_BACKUP_EXISTS){const s=this.providerSub??this.userId;p.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(g.MIGRATION_FAILED,"Migration skipped by user")}throw e}}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=t==null?void 0:t.index,o=await this.walletProvider.getAddress(this.userId,n??0);let i;if(this.walletProvider.prepare&&(i=(await this.walletProvider.prepare("sign-message",{message:s,from:o.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:o.address,message:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new x(g.USER_REJECTED,"User rejected message signing");try{const c=await this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,i,o.address);return this.verifySignatureSigner(s,c.signature,o.address),{chainId:e,signature:c.signature,message:s,address:o.address}}catch(c){throw c instanceof x?c:new x(g.SIGNATURE_FAILED,`Message signing failed (${e})`,c)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"User ID not found");if(!this.walletProvider.signTypedData)throw new x(g.NOT_IMPLEMENTED,"signTypedData is not implemented");X.validateTypedDataChainId(e,s);const n=await this.walletProvider.getAddress(this.userId,(t==null?void 0:t.index)??0);let o;if(this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new x(g.USER_REJECTED,"User rejected typed data signing");try{const a=await this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address);return X.validateSignatureFormat(a.signature),{chainId:e,signature:a.signature,address:n.address}}catch(a){throw a instanceof x?a:new x(g.SIGNATURE_FAILED,`Typed data signing failed (${e})`,a)}}async signTypedDataOffchain(e,s){return this.signTypedData(X.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=await this.withResolvedGasAndFee(s,e);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign",{tx:n})).uuid);const i=Ye(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new x(g.USER_REJECTED,"User rejected transaction signing");try{const c=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o);return X.validateSignedTxFormat(c.signature),{chainId:e,signedTx:c.signature,txHash:c.txHash??""}}catch(c){if(c instanceof x)throw c;const l=c instanceof Error?c.message:String(c);throw new x(g.SIGNATURE_FAILED,`Transaction signing failed (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=await this.withResolvedGasAndFee(s,e);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("send",{tx:n})).uuid);const i=Ye(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new x(g.USER_REJECTED,"User rejected transaction");try{let c;if(this.walletProvider.sendTransaction)c=(await this.walletProvider.sendTransaction(this.userId,e,n,o)).txHash;else{const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o);c=l.txHash??l.signature}return{chainId:e,txHash:c,status:"pending"}}catch(c){const l=c instanceof Error?c.message:String(c);throw new x(g.TRANSACTION_FAILED,`Transaction failed (${e}): ${l}`,c)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??qs,o=Ws,i=t.timeoutMs??bt,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,o)}throw new x(g.UNKNOWN_ERROR,`Transaction receipt timeout (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var A,y;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((A=this._config.receiptPolling)==null?void 0:A.intervalMs)??Gs,l=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??bt,d=Ye(e),f=s.from??"";let w,_;const m=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(I=>{w=I;const L=BigInt(I.gasUsed)*BigInt(I.effectiveGasPrice),U=s.value?BigInt(s.value):0n,$=X.formatTxAmount(s.value,d.symbol,d.decimals),B=X.formatTxAmount("0x"+L.toString(16),d.symbol,d.decimals),Q=X.formatTxAmount("0x"+(U+L).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:I.from,to:I.to??s.to,amount:$,fees:B,total:Q,nativeSymbol:d.symbol,status:I.status==="0x1"?"success":"reverted"}}).catch(I=>(_=I instanceof Error?I:new Error(String(I)),{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 _;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(g.GAS_ESTIMATION_FAILED,`Failed to get gas price (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const o=n instanceof Error?n.message:String(n);throw new x(g.GAS_ESTIMATION_FAILED,`Failed to estimate gas (${s}): ${o}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(g.GAS_ESTIMATION_FAILED,`Failed to get baseFeePerGas (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(g.GAS_ESTIMATION_FAILED,`Failed to get maxPriorityFeePerGas (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(g.UNKNOWN_ERROR,`Failed to get nonce: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:X.formatWei(n),chainId:e}}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(g.UNKNOWN_ERROR,`Failed to get balance (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt(It),n=s/t,i=(s%t).toString().padStart(It,"0").replace(/0+$/,"").slice(0,Et);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Kt(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof x)throw n;const o=n instanceof Error?n.message:String(n);throw new x(g.UNKNOWN_ERROR,`walletRpc failed [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const o=10n**BigInt(t),i=n/o,c=(n%o).toString().padStart(t,"0").slice(0,Et).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){p.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(p.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return p.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0;for(;;){n++,p.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n})`,t?`— 이전 에러: ${t}`:"");const o=await this.confirmation.showPinInputPrompt(t);if(o===null)return p.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;p.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${o.length}자리), Gateway 마이그레이션 API 호출`);try{const i=await this.migrateWalletUseCase.execute(o,e);return p.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",i.address),i}catch(i){if(i instanceof x&&i.code===g.MIGRATION_FAILED){p.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 #${n}) — 재시도 요청`),t="Incorrect PIN. Please try again.";continue}throw p.error("[CROSSx][Migration Phase 4] 마이그레이션 실패 (복구 불가):",i),i}}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e};if(n){const l=c.from??this.address;if(l){p.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),p.log("[CROSSx] nonce 결과:",c.nonce)}}if(o&&(p.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),p.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){p.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,p.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=js,p.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=vt,p.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(g.TYPED_DATA_CHAIN_ID_MISMATCH,`Off-chain signing (chainId=0) requires typedData.domain.chainId to be absent or 0, got ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new x(g.TYPED_DATA_CHAIN_ID_MISMATCH,`On-chain signing (${e}) requires typedData.domain.chainId to be present`);if(t!==o)throw new x(g.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t}) does not match chainId (${e}, expected ${o})`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new x(g.SIGNATURE_FAILED,"Invalid signature: not a valid hex string");if(s.length!==St)throw new x(g.SIGNATURE_FAILED,`Invalid signature length: expected ${St} hex chars (65 bytes), got ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new x(g.SIGNATURE_FAILED,"Invalid signedTx: not a valid hex string");if(s.length<2)throw new x(g.SIGNATURE_FAILED,"Invalid signedTx: too short")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw p.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new x(g.SIGNATURE_SIGNER_MISMATCH,`Signature signer mismatch: expected ${t}, recovered ${n}`);p.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;p.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(g.AUTH_NOT_INITIALIZED,"SDK is not initialized. Call initialize() first.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new x(g.AUTH_NOT_AUTHENTICATED,"Not authenticated. Call signIn() first.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.initialized=!1,this.removeAllListeners(),wt(null)}};X.OFFCHAIN_CHAIN_ID="0";let Fe=X;class zs{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw p.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 p.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw p.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw p.error("Storage clear error:",e),e}}}const Ys="crossx-sdk",Zs=1,Se="data",Le="keys",Tt="aes-primary",Xs=12;class At{constructor(){this.db=null,this.cryptoKey=null,this.initPromise=null}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,s)=>{const t=indexedDB.open(Ys,Zs);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Se)||n.createObjectStore(Se),n.objectStoreNames.contains(Le)||n.createObjectStore(Le)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Le,Tt);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Le,Tt,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(Xs);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(Se,e,n)}catch(t){throw p.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 p.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Se,e)}catch(s){throw p.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Se)}catch(e){throw p.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 H(r,e,s=""){const t=at(r),n=r==null?void 0:r.length,o=e!==void 0;if(!t||o&&n!==e){const i=s&&`"${s}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function zt(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ue(r.outputLen),ue(r.blockLen)}function Ie(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Yt(r,e){H(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function Js(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Te(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Xe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function oe(r,e){return r<<32-e|r>>>e}const Qs=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function er(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function tr(r){for(let e=0;e<r.length;e++)r[e]=er(r[e]);return r}const Rt=Qs?r=>r:tr,Zt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",sr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ke(r){if(H(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];H(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const o=r[t];s.set(o,n),n+=o.length}return s}function Xt(r,e={}){const s=(n,o)=>r(o).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function Jt(r=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}const rr=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function nr(r,e,s){return r&e^~r&s}function or(r,e,s){return r&e^r&s^e&s}class ir{constructor(e,s,t,n){v(this,"blockLen");v(this,"outputLen");v(this,"padOffset");v(this,"isLE");v(this,"buffer");v(this,"view");v(this,"finished",!1);v(this,"length",0);v(this,"pos",0);v(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Xe(this.buffer)}update(e){Ie(this),H(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=Xe(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ie(this),Yt(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Te(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let 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]),pe=new Uint32Array(64);class pr extends ir{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,s,t,n,o,i,a,c]}set(e,s,t,n,o,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,s){for(let f=0;f<16;f++,s+=4)pe[f]=e.getUint32(s,!1);for(let f=16;f<64;f++){const w=pe[f-15],_=pe[f-2],m=oe(w,7)^oe(w,18)^w>>>3,A=oe(_,17)^oe(_,19)^_>>>10;pe[f]=A+pe[f-7]+m+pe[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),_=d+w+nr(a,c,l)+fr[f]+pe[f]|0,A=(oe(t,2)^oe(t,13)^oe(t,22))+or(t,n,o)|0;d=l,l=c,c=a,a=i+_|0,i=o,o=n,n=t,t=_+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(){Te(pe)}destroy(){this.set(0,0,0,0,0,0,0,0),Te(this.buffer)}}class gr extends pr{constructor(){super(32);v(this,"A",fe[0]|0);v(this,"B",fe[1]|0);v(this,"C",fe[2]|0);v(this,"D",fe[3]|0);v(this,"E",fe[4]|0);v(this,"F",fe[5]|0);v(this,"G",fe[6]|0);v(this,"H",fe[7]|0)}}const _r=Xt(()=>new gr,rr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ct=BigInt(0),rt=BigInt(1);function Ge(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Qt(r){if(typeof r=="bigint"){if(!Be(r))throw new Error("positive bigint expected, got "+r)}else ue(r);return r}function $e(r){const e=Qt(r).toString(16);return e.length&1?"0"+e:e}function es(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ct:BigInt("0x"+r)}function Ve(r){return es(ke(r))}function ts(r){return es(ke(xr(H(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=y=>new Uint8Array(y),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const f=()=>{c.fill(1),l.fill(0),d=0},w=(...y)=>s(l,_e(c,...y)),_=(y=n)=>{l=w(o,y),c=w(),y.length!==0&&(l=w(i,y),c=w())},m=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const I=[];for(;y<e;){c=w();const L=c.slice();I.push(L),y+=c.length}return _e(...I)};return(y,I)=>{f(),_(y);let L;for(;!(L=I(m()));)_();return f(),L}}function ut(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(o,i,a){const c=r[o];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}const n=(o,i)=>Object.entries(o).forEach(([a,c])=>t(a,c,i));n(e,!1),n(s,!0)}function kt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const J=BigInt(0),z=BigInt(1),ye=BigInt(2),rs=BigInt(3),ns=BigInt(4),os=BigInt(5),vr=BigInt(7),is=BigInt(8),Sr=BigInt(9),as=BigInt(16);function re(r,e){const s=r%e;return s>=J?s:e+s}function se(r,e,s){let t=r;for(;e-- >J;)t*=t,t%=s;return t}function Nt(r,e){if(r===J)throw new Error("invert: expected non-zero number");if(e<=J)throw new Error("invert: expected positive modulus, got "+e);let s=re(r,e),t=e,n=J,o=z;for(;s!==J;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==z)throw new Error("invert: does not exist");return re(n,e)}function ht(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function cs(r,e){const s=(r.ORDER+z)/ns,t=r.pow(e,s);return ht(r,t,e),t}function Er(r,e){const s=(r.ORDER-os)/is,t=r.mul(e,ye),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,ye),n),a=r.mul(o,r.sub(i,r.ONE));return ht(r,a,e),a}function Ir(r){const e=Ke(r),s=ls(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+vr)/as;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const f=a.mul(l,n),w=a.mul(l,o),_=a.eql(a.sqr(d),c),m=a.eql(a.sqr(f),c);l=a.cmov(l,d,_),d=a.cmov(w,f,m);const A=a.eql(a.sqr(d),c),y=a.cmov(l,d,A);return ht(a,y,c),y}}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),_=c.pow(l,i);for(;!c.eql(w,c.ONE);){if(c.is0(w))return c.ZERO;let m=1,A=c.sqr(w);for(;!c.eql(A,c.ONE);)if(m++,A=c.sqr(A),m===d)throw new Error("Cannot find square root");const y=z<<BigInt(d-m-1),I=c.pow(f,y);d=m,f=c.sqr(I),w=c.mul(w,f),_=c.mul(_,I)}return _}}function Tr(r){return r%ns===rs?cs:r%is===os?Er:r%as===Sr?Ir(r):ls(r)}const Ar=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Ar.reduce((t,n)=>(t[n]="function",t),e);return ut(r,s),r}function Or(r,e,s){if(s<J)throw new Error("invalid exponent, negatives unsupported");if(s===J)return r.ONE;if(s===z)return e;let t=r.ONE,n=e;for(;s>J;)s&z&&(t=r.mul(t,n)),n=r.sqr(n),s>>=z;return t}function ds(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),o),t}function Pt(r,e){const s=(r.ORDER-z)/ye,t=r.pow(e,s),n=r.eql(t,r.ONE),o=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function Cr(r,e){e!==void 0&&ue(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class kr{constructor(e,s={}){v(this,"ORDER");v(this,"BITS");v(this,"BYTES");v(this,"isLE");v(this,"ZERO",J);v(this,"ONE",z);v(this,"_lengths");v(this,"_sqrt");v(this,"_mod");var i;if(e<=J)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=Cr(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return J<=e&&e<this.ORDER}is0(e){return e===J}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&z)===z}neg(e){return re(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return re(e*e,this.ORDER)}add(e,s){return re(e+s,this.ORDER)}sub(e,s){return re(e-s,this.ORDER)}mul(e,s){return re(e*s,this.ORDER)}pow(e,s){return Or(this,e,s)}div(e,s){return re(e*Nt(s,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,s){return e+s}subN(e,s){return e-s}mulN(e,s){return e*s}inv(e){return Nt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Tr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?ss(e,this.BYTES):lt(e,this.BYTES)}fromBytes(e,s=!1){H(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){H(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,_=e%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:w,isNegF:_,offsetF:l}}const Qe=new WeakMap,ps=new WeakMap;function et(r){return ps.get(r)||1}function $t(r){if(r!==Ae)throw new Error("invalid wNAF")}class Pr{constructor(e,s){v(this,"BASE");v(this,"ZERO");v(this,"Fn");v(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>Ae;)s&be&&(t=t.add(n)),n=n.double(),s>>=be;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=Je(s,this.bits),o=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=Je(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:f,isNegF:w,offsetF:_}=Dt(t,a,i);t=c,d?o=o.add(qe(w,s[_])):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),ps.set(e,s),Qe.delete(e)}hasCache(e){return et(e)!==1}}function Lr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>Ae||t>Ae;)s&be&&(o=o.add(n)),t&be&&(i=i.add(n)),n=n.double(),s>>=be,t>>=be;return{p1:o,p2:i}}function Mt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Rr(e),e}else return Ke(r,{isLE:s})}function Dr(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Ae))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Mt(e.p,s.Fp,t),o=Mt(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}function $r(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class gs{constructor(e,s){v(this,"oHash");v(this,"iHash");v(this,"blockLen");v(this,"outputLen");v(this,"finished",!1);v(this,"destroyed",!1);if(zt(e),H(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Te(n)}update(e){return Ie(this),this.iHash.update(e),this}digestInto(e){Ie(this),H(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const _s=(r,e,s)=>new gs(r,e).update(s).digest();_s.create=(r,e)=>new gs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Bt=(r,e)=>(r+(r>=0?e:-e)/xs)/e;function Mr(r,e,s){const[[t,n],[o,i]]=e,a=Bt(i*r,s),c=Bt(-n*r,s);let l=r-a*t-c*o,d=-a*n-c*i;const f=l<le,w=d<le;f&&(l=-l),w&&(d=-d);const _=dt(Math.ceil(yr(s)/2))+Ee;if(l<le||l>=_||d<le||d>=_)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 ge={Err:Br,_tlv:{encode:(r,e)=>{const{Err:s}=ge;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=$e(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?$e(n.length/2|128):"";return $e(r)+o+n+e},decode(r,e){const{Err:s}=ge;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=ge;if(r<le)throw new e("integer: negative integers are not allowed");let s=$e(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=ge;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ve(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=ge,n=H(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=ge,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},le=BigInt(0),Ee=BigInt(1),xs=BigInt(2),Me=BigInt(3),Ur=BigInt(4);function Fr(r,e={}){const s=Dr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;ut(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=ws(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(P,u,h){const{x:b,y:E}=u.toAffine(),R=t.toBytes(b);if(Ge(h,"isCompressed"),h){d();const T=!t.isOdd(E);return _e(ms(T),R)}else return _e(Uint8Array.of(4),R,t.toBytes(E))}function w(P){H(P,void 0,"Point");const{publicKey:u,publicKeyUncompressed:h}=l,b=P.length,E=P[0],R=P.subarray(1);if(b===u&&(E===2||E===3)){const T=t.fromBytes(R);if(!t.isValid(T))throw new Error("bad point: is not on curve, wrong x");const O=A(T);let S;try{S=t.sqrt(O)}catch(W){const F=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}d();const C=t.isOdd(S);return(E&1)===1!==C&&(S=t.neg(S)),{x:T,y:S}}else if(b===h&&E===4){const T=t.BYTES,O=t.fromBytes(R.subarray(0,T)),S=t.fromBytes(R.subarray(T,T*2));if(!y(O,S))throw new Error("bad point: is not on curve");return{x:O,y:S}}else throw new Error(`bad point: got length ${b}, expected compressed=${u} or uncompressed=${h}`)}const _=e.toBytes||f,m=e.fromBytes||w;function A(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 y(P,u){const h=t.sqr(u),b=A(P);return t.eql(h,b)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const I=t.mul(t.pow(o.a,Me),Ur),L=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(I,L)))throw new Error("bad curve params: a or b");function U(P,u,h=!1){if(!t.isValid(u)||h&&t.is0(u))throw new Error(`bad point coordinate ${P}`);return u}function $(P){if(!(P instanceof Z))throw new Error("Weierstrass Point expected")}function B(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:b,Z:E}=P;if(t.eql(E,t.ONE))return{x:h,y:b};const R=P.is0();u==null&&(u=R?t.ONE:t.inv(E));const T=t.mul(h,u),O=t.mul(b,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:T,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(!y(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,b,E){return h=new Z(t.mul(h.X,P),h.Y,h.Z),u=qe(b,u),h=qe(E,h),u.add(h)}const D=class D{constructor(u,h,b){v(this,"X");v(this,"Y");v(this,"Z");this.X=U("x",u),this.Y=U("y",h,!0),this.Z=U("z",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(u){const{x:h,y:b}=u||{};if(!u||!t.isValid(h)||!t.isValid(b))throw new Error("invalid affine point");if(u instanceof D)throw new Error("projective point not allowed");return t.is0(h)&&t.is0(b)?D.ZERO:new D(h,b,t.ONE)}static fromBytes(u){const h=D.fromAffine(m(H(u,void 0,"point")));return h.assertValidity(),h}static fromHex(u){return D.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){$(u);const{X:h,Y:b,Z:E}=this,{X:R,Y:T,Z:O}=u,S=t.eql(t.mul(h,O),t.mul(R,E)),C=t.eql(t.mul(b,O),t.mul(T,E));return S&&C}negate(){return new D(this.X,t.neg(this.Y),this.Z)}double(){const{a:u,b:h}=o,b=t.mul(h,Me),{X:E,Y:R,Z:T}=this;let O=t.ZERO,S=t.ZERO,C=t.ZERO,N=t.mul(E,E),W=t.mul(R,R),F=t.mul(T,T),k=t.mul(E,R);return k=t.add(k,k),C=t.mul(E,T),C=t.add(C,C),O=t.mul(u,C),S=t.mul(b,F),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(b,C),F=t.mul(u,F),k=t.sub(N,F),k=t.mul(u,k),k=t.add(k,C),C=t.add(N,N),N=t.add(C,N),N=t.add(N,F),N=t.mul(N,k),S=t.add(S,N),F=t.mul(R,T),F=t.add(F,F),N=t.mul(F,k),O=t.sub(O,N),C=t.mul(F,W),C=t.add(C,C),C=t.add(C,C),new D(O,S,C)}add(u){$(u);const{X:h,Y:b,Z:E}=this,{X:R,Y:T,Z:O}=u;let S=t.ZERO,C=t.ZERO,N=t.ZERO;const W=o.a,F=t.mul(o.b,Me);let k=t.mul(h,R),j=t.mul(b,T),V=t.mul(E,O),ee=t.add(h,b),G=t.add(R,T);ee=t.mul(ee,G),G=t.add(k,j),ee=t.sub(ee,G),G=t.add(h,E);let K=t.add(R,O);return G=t.mul(G,K),K=t.add(k,V),G=t.sub(G,K),K=t.add(b,E),S=t.add(T,O),K=t.mul(K,S),S=t.add(j,V),K=t.sub(K,S),N=t.mul(W,G),S=t.mul(F,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),G=t.mul(F,G),j=t.add(j,V),V=t.sub(k,V),V=t.mul(W,V),G=t.add(G,V),k=t.mul(j,G),C=t.add(C,k),k=t.mul(K,G),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 D(S,C,N)}subtract(u){return this.add(u.negate())}is0(){return this.equals(D.ZERO)}multiply(u){const{endo:h}=e;if(!n.isValidNot0(u))throw new Error("invalid scalar: out of range");let b,E;const R=T=>ne.cached(this,T,O=>Lt(D,O));if(h){const{k1neg:T,k1:O,k2neg:S,k2:C}=B(u),{p:N,f:W}=R(O),{p:F,f:k}=R(C);E=W.add(k),b=he(h.beta,N,F,T,S)}else{const{p:T,f:O}=R(u);b=T,E=O}return Lt(D,[b,E])[0]}multiplyUnsafe(u){const{endo:h}=e,b=this;if(!n.isValid(u))throw new Error("invalid scalar: out of range");if(u===le||b.is0())return D.ZERO;if(u===Ee)return b;if(ne.hasCache(this))return this.multiply(u);if(h){const{k1neg:E,k1:R,k2neg:T,k2:O}=B(u),{p1:S,p2:C}=Lr(D,b,R,O);return he(h.beta,S,C,E,T)}else return ne.unsafe(b,u)}toAffine(u){return Q(this,u)}isTorsionFree(){const{isTorsionFree:u}=e;return i===Ee?!0:u?u(D,this):ne.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:u}=e;return i===Ee?this:u?u(D,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(u=!0){return Ge(u,"isCompressed"),this.assertValidity(),_(D,this,u)}toHex(u=!0){return ke(this.toBytes(u))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};v(D,"BASE",new D(o.Gx,o.Gy,t.ONE)),v(D,"ZERO",new D(t.ZERO,t.ONE,t.ZERO)),v(D,"Fp",t),v(D,"Fn",n);let Z=D;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(_){try{const m=s.fromBytes(_);return s.isValidNot0(m)}catch{return!1}}function i(_,m){const{publicKey:A,publicKeyUncompressed:y}=n;try{const I=_.length;return m===!0&&I!==A||m===!1&&I!==y?!1:!!r.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return Nr(H(_,n.seed,"seed"),s.ORDER)}function c(_,m=!0){return r.BASE.multiply(s.fromBytes(_)).toBytes(m)}function l(_){const{secretKey:m,publicKey:A,publicKeyUncompressed:y}=n;if(!at(_)||"_lengths"in s&&s._lengths||m===A)return;const I=H(_,void 0,"key").length;return I===A||I===y}function d(_,m,A=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");const y=s.fromBytes(_);return r.fromBytes(m).multiply(y).toBytes(A)}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:_}=Hr(r,s),m={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},A=a*xs<o.ORDER;function y(u){const h=a>>Ee;return u>h}function I(u,h){if(!i.isValidNot0(h))throw new Error(`invalid signature ${u}: out of range 1..Point.Fn.ORDER`);return h}function L(){if(A)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(u,h){nt(h);const b=_.signature,E=h==="compact"?b:h==="recovered"?b+1:void 0;return H(u,E)}class ${constructor(h,b,E){v(this,"r");v(this,"s");v(this,"recovery");if(this.r=I("r",h),this.s=I("s",b),E!=null){if(L(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(h,b=m.format){U(h,b);let E;if(b==="der"){const{r:S,s:C}=ge.toSig(H(h));return new $(S,C)}b==="recovered"&&(E=h[0],b="compact",h=h.subarray(1));const R=_.signature/2,T=h.subarray(0,R),O=h.subarray(R,R*2);return new $(i.fromBytes(T),i.fromBytes(O),E)}static fromHex(h,b){return this.fromBytes(He(h),b)}assertRecovery(){const{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new $(this.r,this.s,h)}recoverPublicKey(h){const{r:b,s:E}=this,R=this.assertRecovery(),T=R===2||R===3?b+a:b;if(!o.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const O=o.toBytes(T),S=r.fromBytes(_e(ms((R&1)===0),O)),C=i.inv(T),N=Q(H(h,void 0,"msgHash")),W=i.create(-N*C),F=i.create(E*C),k=r.BASE.multiplyUnsafe(W).add(S.multiplyUnsafe(F));if(k.is0())throw new Error("invalid recovery: point at infinify");return k.assertValidity(),k}hasHighS(){return y(this.s)}toBytes(h=m.format){if(nt(h),h==="der")return He(ge.hexFromSig(this));const{r:b,s:E}=this,R=i.toBytes(b),T=i.toBytes(E);return h==="recovered"?(L(),_e(Uint8Array.of(this.assertRecovery()),R,T)):_e(R,T)}toHex(h){return ke(this.toBytes(h))}}const B=s.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");const b=Ve(h),E=h.length*8-c;return E>0?b>>BigInt(E):b},Q=s.bits2int_modN||function(h){return i.create(B(h))},ve=dt(c);function he(u){return wr("num < 2^"+c,u,le,ve),i.toBytes(u)}function Z(u,h){return H(u,void 0,"message"),h?H(e(u),void 0,"prehashed message"):u}function xe(u,h,b){const{lowS:E,prehash:R,extraEntropy:T}=tt(b,m);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(T!=null&&T!==!1){const k=T===!0?t(_.secretKey):T;C.push(H(k,void 0,"extraEntropy"))}const N=_e(...C),W=O;function F(k){const j=B(k);if(!i.isValidNot0(j))return;const V=i.inv(j),ee=r.BASE.multiply(j).toAffine(),G=i.create(ee.x);if(G===le)return;const K=i.create(V*i.create(W+G*S));if(K===le)return;let xt=(ee.x===G?0:2)|Number(ee.y&Ee),mt=K;return E&&y(K)&&(mt=i.neg(K),xt^=1),new $(G,mt,A?void 0:xt)}return{seed:N,k2sig:F}}function ne(u,h,b={}){const{seed:E,k2sig:R}=xe(u,h,b);return br(e.outputLen,i.BYTES,n)(E,R).toBytes(b.format)}function D(u,h,b,E={}){const{lowS:R,prehash:T,format:O}=tt(E,m);if(b=H(b,void 0,"publicKey"),h=Z(h,T),!at(u)){const S=u instanceof $?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+S)}U(u,O);try{const S=$.fromBytes(u,O),C=r.fromBytes(b);if(R&&S.hasHighS())return!1;const{r:N,s:W}=S,F=Q(h),k=i.inv(W),j=i.create(F*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,b={}){const{prehash:E}=tt(b,m);return h=Z(h,E),$.fromBytes(u,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:f,utils:w,lengths:_,Point:r,sign:ne,verify:D,recoverPublicKey:P,Signature:$,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,_=se(w,Ut,e)*l%e,m=se(_,n,e)*_%e,A=se(m,o,e)*m%e,y=se(A,a,e)*A%e,I=se(y,c,e)*y%e,L=se(I,a,e)*A%e,U=se(L,s,e)*d%e,$=se(U,i,e)*m%e,B=se($,t,e)*l%e,Q=se(B,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 _=0;_<50;_+=10)r[i+_]^=f,r[i+_+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]}Te(s)}class pt{constructor(e,s,t,n=!1,o=24){v(this,"state");v(this,"pos",0);v(this,"posOut",0);v(this,"finished",!1);v(this,"state32");v(this,"destroyed",!1);v(this,"blockLen");v(this,"suffix");v(this,"outputLen");v(this,"enableXOF",!1);v(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,ue(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Js(this.state)}clone(){return this._cloneInto()}keccak(){Rt(this.state32),en(this.state32,this.rounds),Rt(this.state32),this.posOut=0,this.pos=0}update(e){Ie(this),H(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ie(this,!1),H(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ue(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Yt(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Te(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new pt(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const tn=(r,e,s,t={})=>Xt(()=>new pt(e,r,s),t),Gt=tn(1,136,32);class sn{async verifyJWT(e,s){try{const t=this.decodeJWT(e);p.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?(p.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(p.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(p.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw p.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,A=new Vr.Signature(qt(l),qt(d)).addRecoveryBit(w).recoverPublicKey(i).toBytes(!1).slice(1),y=Gt(A);return"0x"+ke(y.slice(12))}}function rn(r){const e=new Uint8Array(r.length/2);for(let s=0;s<e.length;s++)e[s]=parseInt(r.substring(s*2,s*2+2),16);return e}function qt(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const nn=3e4;class on{async request(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??nn);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}class gt{static generateState(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}openAuth(e){return new Promise((s,t)=>{const n=e.width??500,o=e.height??600,i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=gt.generateState(),l=e.authUrl.includes("?")?"&":"?",d=`${e.authUrl}${l}state=${c}`,f=window.open(d,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!f){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const w=setTimeout(()=>{p.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),U(),t(new Error("Authentication timeout"))},5*60*1e3),_=10,m=30;let A=0,y=null;const I=()=>{clearInterval(L),p.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+m+"초간 대기합니다"),y=setTimeout(()=>{U(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},m*1e3)},L=setInterval(()=>{A++;try{f.closed&&(A<=_?I():(U(),t(new Error("로그인이 취소되었습니다"))))}catch{I()}},1e3),U=()=>{clearTimeout(w),clearInterval(L),y&&clearTimeout(y),window.removeEventListener("message",$)},$=B=>{var ve,he,Z,xe,ne,D,P;if(B.origin!==e.expectedOrigin)return;U(),p.log("[CROSSx] OAuth postMessage 수신 — status:",B.data.status);const Q=B.data.state??((ve=B.data.data)==null?void 0:ve.state);if(!Q||Q!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(B.data.status==="success"){const u=((he=B.data.data)==null?void 0:he.accessToken)||((Z=B.data.data)==null?void 0:Z.idToken);p.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!((xe=B.data.data)!=null&&xe.accessToken),hasIdToken:!!((ne=B.data.data)!=null&&ne.idToken)}),u?s(u):(p.error("[CROSSx] 토큰을 찾을 수 없음:",B.data),t(new Error("Token not found in response")))}else p.error("[CROSSx] OAuth 실패:",(D=B.data.data)==null?void 0:D.error),t(new Error(((P=B.data.data)==null?void 0:P.error)||"Authentication failed"))};window.addEventListener("message",$)})}}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(g.WALLET_CREATION_FAILED,"Wallet creation failed",s)}}async getAddresses(e){const s=await this.storage.get(Oe);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return p.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 p.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 p.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){p.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 p.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){p.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){p.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(g.AUTH_NOT_AUTHENTICATED,"No auth token found. Please sign in first.");return e}async request(e,s,t){var a,c;const n=this.getAuthToken(),o=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const f=d.message||d.data||"API request failed";p.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:f,url:o,method:e,fullResponse:d});const w=We.mapGatewayError(d.code),_=We.getGatewayErrorMessage(d.code,f),m=new x(w,_);throw m.gatewayCode=d.code,m.gatewayMessage=f,m}return p.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 p.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(g.UNKNOWN_ERROR,`Wallet Gateway error (${w}): ${f}`)}throw l}}async getOrCreateWallet(e){var s;p.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 p.log("[CROSSx][Migration Phase 2] 기존 지갑 발견 — address:",n),{id:e,address:n,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}}catch{p.log("[CROSSx][Migration Phase 2] 기존 지갑 없음, POST /mnemonic/create 진행")}p.log("[CROSSx][Migration Phase 2] POST /mnemonic/create — ignoreBackup: false");try{const t={ignoreBackup:!1},n=await this.request("POST","/mnemonic/create",t);return p.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")){p.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&&p.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 p.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(g.TX_INVALID_PARAMS,"prepare: tx is required");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new x(g.TX_INVALID_PARAMS,"prepare: message is required");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new x(g.TX_INVALID_PARAMS,"prepare: typedData is required");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t)};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t)};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).txHash}}async recoverWallet(e,s){const t={shareC:s},n=await this.request("POST","/mnemonic/recover",t);return{id:e,address:n.address,newShareC:n.newShareC,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async migrateWallet(e,s){p.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 p.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}static mapGatewayError(e){switch(e){case-10002:return g.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return g.UNKNOWN_ERROR;case-10006:return g.GATEWAY_INTERNAL_ERROR;case-10008:return g.GATEWAY_LOCK_CONFLICT;case-10010:return g.MIGRATION_FAILED;case-10012:return g.MIGRATION_BACKUP_EXISTS;case-10022:return g.PROJECT_NOT_REGISTERED;case-10023:return g.PROJECT_ID_MISSING;case-10024:return g.ORIGIN_NOT_ALLOWED;case-10026:return g.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return g.PREPARE_FAILED;case-10016:return g.PREPARE_EXPIRED;case-10017:case-10018:return g.PREPARE_MISMATCH;default:return g.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10006:return"Internal server error. Please try again later.";case-10008:return"Another operation is in progress. Please try again later.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin is not in the allowed list. Register the current domain in the management console.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";default:return`Request failed (${e}): ${s}`}}}class Ce{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=Ce.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?Ks:Vs;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"Chain registry request failed";throw new x(Ce.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Ce.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new x(g.CHAIN_NOT_SUPPORTED,`Unsupported chain: ${e}`)}static fallbackChains(){return Object.values(je).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return g.CHAIN_NOT_SUPPORTED;case-10021:return g.INVALID_CHAIN;case-10022:return g.PROJECT_NOT_REGISTERED;case-10023:return g.PROJECT_ID_MISSING;case-10024:return g.APP_IDENTIFIER_MISSING;case-10025:return g.INVALID_APP_TYPE;default:return g.UNKNOWN_ERROR}}}const Wt="__crossx-confirm-style",te="__crossx-confirm-overlay",cn={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"#FFFFFF",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"#121212",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",onPrimary:"#FFFFFF"}};function jt(r,e){const s=cn[r],t=e==null?void 0:e[r];return t?{...s,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault},...t.bg!==void 0&&{bg:t.bg,inputBg:t.bg}}:s}const ln=`
|
|
1
|
+
"use strict";var Rs=Object.defineProperty;var Os=(r,e,s)=>e in r?Rs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var v=(r,e,s)=>Os(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Cs=require("jose");var g=(r=>(r.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",r.AUTH_FAILED="AUTH_FAILED",r.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",r.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",r.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",r.WALLET_NOT_FOUND="WALLET_NOT_FOUND",r.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(g||{});class 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}},ks=Object.fromEntries(Object.entries(je).map(([r,e])=>[r,e.caipId])),Ns=new Map(Object.values(je).map(r=>[r.caipId,r]));new Map(Object.values(je).map(r=>[r.chainId,r]));const Ps={symbol:"",decimals:18};function Ye(r){var e;return((e=Ns.get(r))==null?void 0:e.nativeCurrency)??Ps}class zt{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new x(g.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new x(g.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(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 p={log(...r){if(we){we.log(...r);return}},warn(...r){if(we){we.warn(...r);return}},error(...r){if(we){we.error(...r);return}}},Ls={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",pinInput_title:"PIN 입력",pinInput_placeholder:"4자리 PIN을 입력하세요",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨"},Yt={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",pinInput_title:"Enter PIN",pinInput_placeholder:"Enter your 4-digit PIN",pinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected"},Ds={ko:Ls,en:Yt};function yt(r="en",e){return Ds[r]??Yt}const Ze="crossx_access_token",Ne="crossx_refresh_token",Pe="crossx_user_info";class $s{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(g.AUTH_FAILED,`${s} 실패 (코드 ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const n=t;if(n.code&&n.code!==200&&n.code>0)throw new x(g.AUTH_FAILED,`${s} 실패 (코드 ${n.code}): ${n.message}`)}}async execute(e){var n,o,i,a;let s,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:f}=this.config,w=`${d}${l}`;p.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인):`,w);const _=await this.oauth.openAuth({authUrl:w,expectedOrigin:new URL(d).origin});p.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",_.length,")");const{accessToken:m,refreshToken:A}=await this.exchangeFirebaseToken(_,f);let y,I;try{const F=this.crypto.decodeJWT(_);I=(n=F.firebase)==null?void 0:n.sign_in_provider;const $=((o=F.firebase)==null?void 0:o.identities)??{};I==="google.com"?y=(i=$["google.com"])==null?void 0:i[0]:I==="apple.com"&&(y=(a=$["apple.com"])==null?void 0:a[0]),p.log("[CROSSx] OAuth provider sub 추출 — provider:",I,"hasProviderSub:",!!y)}catch{p.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(m){const F=this.crypto.decodeJWT(m);p.log("[CROSSx] access_token 디코딩 — sub:",F.sub,"exp:",F.exp);const $=await this.crypto.verifyJWT(m);if(t=$.signatureVerified??!1,!$.valid)throw p.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const B=$.payload;s={id:B.sub,email:B.email,signInProvider:I,providerSub:y},this.tokenStore.set(m),this.useCookieAuth||(await this.storage.set(Ze,m),A&&await this.storage.set(Ne,A))}else{const F=this.crypto.decodeJWT(_);s={id:F.sub,email:F.email,signInProvider:I,providerSub:y},p.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}p.log("[CROSSx] 사용자 정보 — id:",s.id);const L=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Pe,L),p.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return p.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return p.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`;p.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"}:{}});p.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return p.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(g.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");p.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 p.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){p.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(p.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return p.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);p.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(Pe);if(p.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;p.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return p.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return p.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"}:{}});p.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){p.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new x(g.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");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 p.log("[CROSSx] silentRefresh 성공"),c}async loadWallet(e,s){let t,n=!1;try{p.log("[CROSSx][Migration Phase 2] POST /mnemonic/create 호출 — userId:",e.id),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,p.log("[CROSSx][Migration Phase 2] 지갑 로드 완료 (기존 백업 없음) — address:",t)}catch(o){if(o instanceof x&&o.code===g.MIGRATION_BACKUP_EXISTS)p.log("[CROSSx][Migration Phase 2] Gateway -10012 감지 → needsMigration = true"),n=!0;else{if(o instanceof x&&(o.code===g.PROJECT_NOT_REGISTERED||o.code===g.PROJECT_ID_MISSING||o.code===g.ORIGIN_NOT_ALLOWED))throw p.error("[CROSSx][Migration Phase 2] 프로젝트 설정 에러:",o.message),o;p.warn("[CROSSx][Migration Phase 2] 지갑 로드 실패 (로그인은 유지):",o)}}return p.log("[CROSSx][Migration Phase 2] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}}const Ms="crossx_access_token",Bs="crossx_refresh_token",Fs="crossx_user_info";class Us{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(Ms),await this.storage.remove(Bs)),await this.storage.remove(Fs)}}class Hs{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new x(g.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");p.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return p.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Gs{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(g.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class qs{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 Fe={production:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}},Ws="/crossx.config.json";function bt(r){const e=r.environment;return e&&e in Fe?Fe[e]:null}async function js(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=bt(r);if(e)return e}}catch{}try{const r=await fetch(Ws);if(r.ok){const e=await r.json(),s=bt(e);if(s)return s}}catch{}return Fe.production}const Vs=2e3,vt=6e4,Ks=1e3,zs=1e4,Ys="0x77359400",St="0x3B9ACA00",Et=130,It=6,Tt=18,Zs=0,Xs=30*1e3,X=class X extends qs{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 Gs(d,o),this.signInUseCase=new $s(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Us(this.internalConfig,t,c),this.migrateWalletUseCase=new Hs(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.8 초기화 중..."),this.confirmation.setMessages(yt(this._config.locale));try{const e=await js();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(g.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",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(g.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};if(s.needsMigration||!s.address){const{address:o}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:t}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(g.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();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(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.emit("addressChanged",{address:s.address,index:0}),p.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof x?s:new x(g.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:0}}async getAddresses(){return this.ensureAuthenticated(),this.userId?this.walletProvider.getAddresses(this.userId):[]}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const s=await this.walletProvider.getAddresses(this.userId),t=await this.confirmation.showWalletSelector(s,async()=>{const n=s.length,i={address:(await this.walletProvider.getAddress(this.userId,n)).address,index:n};return s.push(i),i},e);return t&&(this.address=t.address,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof x?e:new x(g.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof x?s:new x(g.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(yt(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");p.log("[CROSSx] 지갑 생성 시작");try{const e=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=e.address,this.emit("addressChanged",{address:e.address,index:0}),p.log("[CROSSx] 지갑 생성 완료:",e.address),{address:e.address}}catch(e){if(e instanceof x&&e.code===g.MIGRATION_BACKUP_EXISTS){const s=this.providerSub??this.userId;p.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(g.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw e}}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");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(g.USER_REJECTED,"사용자가 메시지 서명을 거부했습니다");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(g.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,c)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new x(g.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");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(g.USER_REJECTED,"사용자가 타입 데이터 서명을 거부했습니다");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(g.SIGNATURE_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(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");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(g.USER_REJECTED,"사용자가 트랜잭션 서명을 거부했습니다");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(g.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");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(g.USER_REJECTED,"사용자가 트랜잭션을 거부했습니다");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(g.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${l}`,c)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??Ks,o=zs,i=t.timeoutMs??vt,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(g.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var A,y;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((A=this._config.receiptPolling)==null?void 0:A.intervalMs)??Vs,l=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??vt,d=Ye(e),f=s.from??"";let w,_;const m=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(I=>{w=I;const L=BigInt(I.gasUsed)*BigInt(I.effectiveGasPrice),F=s.value?BigInt(s.value):0n,$=X.formatTxAmount(s.value,d.symbol,d.decimals),B=X.formatTxAmount("0x"+L.toString(16),d.symbol,d.decimals),Q=X.formatTxAmount("0x"+(F+L).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:I.from,to:I.to??s.to,amount:$,fees:B,total:Q,nativeSymbol:d.symbol,status:I.status==="0x1"?"success":"reverted"}}).catch(I=>(_=I instanceof Error?I:new Error(String(I)),{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 _;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(g.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const o=n instanceof Error?n.message:String(n);throw new x(g.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${o}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(g.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(g.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(g.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted: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(g.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt(Tt),n=s/t,i=(s%t).toString().padStart(Tt,"0").replace(/0+$/,"").slice(0,It);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new zt(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof x)throw n;const o=n instanceof Error?n.message:String(n);throw new x(g.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const o=10n**BigInt(t),i=n/o,c=(n%o).toString().padStart(t,"0").slice(0,It).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){p.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(p.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return p.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0;for(;;){n++,p.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n})`,t?`— 이전 에러: ${t}`:"");const o=await this.confirmation.showPinInputPrompt(t);if(o===null)return p.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;p.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${o.length}자리), Gateway 마이그레이션 API 호출`);try{const i=await this.migrateWalletUseCase.execute(o,e);return p.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",i.address),i}catch(i){if(i instanceof x&&i.code===g.MIGRATION_FAILED){p.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 #${n}) — 재시도 요청`),t="PIN이 올바르지 않습니다. 다시 시도해 주세요.";continue}throw p.error("[CROSSx][Migration Phase 4] 마이그레이션 실패 (복구 불가):",i),i}}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e};if(n){const l=c.from??this.address;if(l){p.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),p.log("[CROSSx] nonce 결과:",c.nonce)}}if(o&&(p.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),p.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){p.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=St;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,p.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Ys,p.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=St,p.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(g.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new x(g.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new x(g.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${o})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new x(g.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==Et)throw new x(g.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Et} hex 문자(65 바이트) 예상, 현재 ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new x(g.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new x(g.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw p.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new x(g.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);p.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;p.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(g.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new x(g.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.initialized=!1,this.removeAllListeners(),wt(null)}};X.OFFCHAIN_CHAIN_ID="0";let Ue=X;class Js{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw p.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 p.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw p.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw p.error("Storage clear error:",e),e}}}const Qs="crossx-sdk",er=1,Se="data",Le="keys",At="aes-primary",tr=12;class Rt{constructor(){this.db=null,this.cryptoKey=null,this.initPromise=null}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,s)=>{const t=indexedDB.open(Qs,er);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,At);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Le,At,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(tr);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 p.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 p.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Se,e)}catch(s){throw p.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Se)}catch(e){throw p.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 H(r,e,s=""){const t=at(r),n=r==null?void 0:r.length,o=e!==void 0;if(!t||o&&n!==e){const i=s&&`"${s}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Zt(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ue(r.outputLen),ue(r.blockLen)}function Ie(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Xt(r,e){H(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 sr(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Te(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Xe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function oe(r,e){return r<<32-e|r>>>e}const rr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function nr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function or(r){for(let e=0;e<r.length;e++)r[e]=nr(r[e]);return r}const Ot=rr?r=>r:or,Jt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ir=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function ke(r){if(H(r),Jt)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=ir[r[s]];return e}const ce={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ct(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(Jt)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,o=0;n<s;n++,o+=2){const i=Ct(r.charCodeAt(o)),a=Ct(r.charCodeAt(o+1));if(i===void 0||a===void 0){const c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function _e(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];H(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 Qt(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 es(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 ar=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function cr(r,e,s){return r&e^~r&s}function lr(r,e,s){return r&e^r&s^e&s}class dr{constructor(e,s,t,n){v(this,"blockLen");v(this,"outputLen");v(this,"padOffset");v(this,"isLE");v(this,"buffer");v(this,"view");v(this,"finished",!1);v(this,"length",0);v(this,"pos",0);v(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Xe(this.buffer)}update(e){Ie(this),H(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=Xe(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ie(this),Xt(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Te(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let 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),kt=BigInt(32);function ur(r,e=!1){return e?{h:Number(r&De),l:Number(r>>kt&De)}:{h:Number(r>>kt&De)|0,l:Number(r&De)|0}}function hr(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}=ur(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const fr=(r,e,s)=>r<<s|e>>>32-s,pr=(r,e,s)=>e<<s|r>>>32-s,gr=(r,e,s)=>e<<s-32|r>>>64-s,_r=(r,e,s)=>r<<s-32|e>>>64-s,xr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),pe=new Uint32Array(64);class mr extends dr{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)pe[f]=e.getUint32(s,!1);for(let f=16;f<64;f++){const w=pe[f-15],_=pe[f-2],m=oe(w,7)^oe(w,18)^w>>>3,A=oe(_,17)^oe(_,19)^_>>>10;pe[f]=A+pe[f-7]+m+pe[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),_=d+w+cr(a,c,l)+xr[f]+pe[f]|0,A=(oe(t,2)^oe(t,13)^oe(t,22))+lr(t,n,o)|0;d=l,l=c,c=a,a=i+_|0,i=o,o=n,n=t,t=_+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(){Te(pe)}destroy(){this.set(0,0,0,0,0,0,0,0),Te(this.buffer)}}class wr extends mr{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 yr=Qt(()=>new wr,ar(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 ts(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=ts(r).toString(16);return e.length&1?"0"+e:e}function ss(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ct:BigInt("0x"+r)}function Ve(r){return ss(ke(r))}function rs(r){return ss(ke(br(H(r)).reverse()))}function lt(r,e){ue(e),r=ts(r);const s=He(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function ns(r,e){return lt(r,e).reverse()}function br(r){return Uint8Array.from(r)}const Be=r=>typeof r=="bigint"&&ct<=r;function vr(r,e,s){return Be(r)&&Be(e)&&Be(s)&&e<=r&&r<s}function Sr(r,e,s,t){if(!vr(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Er(r){let e;for(e=0;r>ct;r>>=rt,e+=1);return e}const dt=r=>(rt<<BigInt(r))-rt;function Ir(r,e,s){if(ue(r,"hashLen"),ue(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const f=()=>{c.fill(1),l.fill(0),d=0},w=(...y)=>s(l,_e(c,...y)),_=(y=n)=>{l=w(o,y),c=w(),y.length!==0&&(l=w(i,y),c=w())},m=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const I=[];for(;y<e;){c=w();const L=c.slice();I.push(L),y+=c.length}return _e(...I)};return(y,I)=>{f(),_(y);let L;for(;!(L=I(m()));)_();return f(),L}}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 Nt(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),os=BigInt(3),is=BigInt(4),as=BigInt(5),Tr=BigInt(7),cs=BigInt(8),Ar=BigInt(9),ls=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 Pt(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 ds(r,e){const s=(r.ORDER+z)/is,t=r.pow(e,s);return ht(r,t,e),t}function Rr(r,e){const s=(r.ORDER-as)/cs,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 Or(r){const e=Ke(r),s=us(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+Tr)/ls;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),_=a.eql(a.sqr(d),c),m=a.eql(a.sqr(f),c);l=a.cmov(l,d,_),d=a.cmov(w,f,m);const A=a.eql(a.sqr(d),c),y=a.cmov(l,d,A);return ht(a,y,c),y}}function us(r){if(r<os)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(;Lt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return ds;let o=n.pow(t,e);const i=(e+z)/ye;return function(c,l){if(c.is0(l))return l;if(Lt(c,l)!==1)throw new Error("Cannot find square root");let d=s,f=c.mul(c.ONE,o),w=c.pow(l,e),_=c.pow(l,i);for(;!c.eql(w,c.ONE);){if(c.is0(w))return c.ZERO;let m=1,A=c.sqr(w);for(;!c.eql(A,c.ONE);)if(m++,A=c.sqr(A),m===d)throw new Error("Cannot find square root");const y=z<<BigInt(d-m-1),I=c.pow(f,y);d=m,f=c.sqr(I),w=c.mul(w,f),_=c.mul(_,I)}return _}}function Cr(r){return r%is===os?ds:r%cs===as?Rr:r%ls===Ar?Or(r):us(r)}const kr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Nr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=kr.reduce((t,n)=>(t[n]="function",t),e);return ut(r,s),r}function Pr(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 hs(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 Lt(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 Lr(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 Dr{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}=Lr(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 Pr(this,e,s)}div(e,s){return re(e*Pt(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 Pt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Cr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?ns(e,this.BYTES):lt(e,this.BYTES)}fromBytes(e,s=!1){H(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?rs(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 hs(this,e)}cmov(e,s,t){return t?s:e}}function Ke(r,e={}){return new Dr(r,e)}function fs(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 ps(r){const e=fs(r);return e+Math.ceil(e/2)}function $r(r,e,s=!1){H(r);const t=r.length,n=fs(e),o=ps(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?rs(r):Ve(r),a=re(i,e-z)+z;return s?ns(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 Dt(r,e){const s=hs(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function gs(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){gs(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 $t(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,_=e%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:w,isNegF:_,offsetF:l}}const Qe=new WeakMap,_s=new WeakMap;function et(r){return _s.get(r)||1}function Mt(r){if(r!==Ae)throw new Error("invalid wNAF")}class Mr{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:_}=$t(t,a,i);t=c,d?o=o.add(qe(w,s[_])):n=n.add(qe(f,s[l]))}return Mt(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}=$t(t,i,o);if(t=a,!l){const f=s[c];n=n.add(d?f.negate():f)}}return Mt(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){gs(s,this.bits),_s.set(e,s),Qe.delete(e)}hasCache(e){return et(e)!==1}}function Br(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 Bt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Nr(e),e}else return Ke(r,{isLE:s})}function Fr(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=Bt(e.p,s.Fp,t),o=Bt(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 Ur(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class xs{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),H(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Te(n)}update(e){return Ie(this),this.iHash.update(e),this}digestInto(e){Ie(this),H(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 ms=(r,e,s)=>new xs(r,e).update(s).digest();ms.create=(r,e)=>new xs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ft=(r,e)=>(r+(r>=0?e:-e)/ws)/e;function Hr(r,e,s){const[[t,n],[o,i]]=e,a=Ft(i*r,s),c=Ft(-n*r,s);let l=r-a*t-c*o,d=-a*n-c*i;const f=l<le,w=d<le;f&&(l=-l),w&&(d=-d);const _=dt(Math.ceil(Er(s)/2))+Ee;if(l<le||l>=_||d<le||d>=_)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 Gr extends Error{constructor(e=""){super(e)}}const ge={Err:Gr,_tlv:{encode:(r,e)=>{const{Err:s}=ge;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=$e(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?$e(n.length/2|128):"";return $e(r)+o+n+e},decode(r,e){const{Err:s}=ge;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=ge;if(r<le)throw new e("integer: negative integers are not allowed");let s=$e(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=ge;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ve(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=ge,n=H(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=ge,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},le=BigInt(0),Ee=BigInt(1),ws=BigInt(2),Me=BigInt(3),qr=BigInt(4);function Wr(r,e={}){const s=Fr("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=bs(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:b,y:E}=u.toAffine(),R=t.toBytes(b);if(Ge(h,"isCompressed"),h){d();const T=!t.isOdd(E);return _e(ys(T),R)}else return _e(Uint8Array.of(4),R,t.toBytes(E))}function w(P){H(P,void 0,"Point");const{publicKey:u,publicKeyUncompressed:h}=l,b=P.length,E=P[0],R=P.subarray(1);if(b===u&&(E===2||E===3)){const T=t.fromBytes(R);if(!t.isValid(T))throw new Error("bad point: is not on curve, wrong x");const O=A(T);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:T,y:S}}else if(b===h&&E===4){const T=t.BYTES,O=t.fromBytes(R.subarray(0,T)),S=t.fromBytes(R.subarray(T,T*2));if(!y(O,S))throw new Error("bad point: is not on curve");return{x:O,y:S}}else throw new Error(`bad point: got length ${b}, expected compressed=${u} or uncompressed=${h}`)}const _=e.toBytes||f,m=e.fromBytes||w;function A(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 y(P,u){const h=t.sqr(u),b=A(P);return t.eql(h,b)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const I=t.mul(t.pow(o.a,Me),qr),L=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(I,L)))throw new Error("bad curve params: a or b");function F(P,u,h=!1){if(!t.isValid(u)||h&&t.is0(u))throw new Error(`bad point coordinate ${P}`);return u}function $(P){if(!(P instanceof Z))throw new Error("Weierstrass Point expected")}function B(P){if(!c||!c.basises)throw new Error("no endo");return Hr(P,c.basises,n.ORDER)}const Q=Nt((P,u)=>{const{X:h,Y:b,Z:E}=P;if(t.eql(E,t.ONE))return{x:h,y:b};const R=P.is0();u==null&&(u=R?t.ONE:t.inv(E));const T=t.mul(h,u),O=t.mul(b,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:T,y:O}}),ve=Nt(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(!y(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,b,E){return h=new Z(t.mul(h.X,P),h.Y,h.Z),u=qe(b,u),h=qe(E,h),u.add(h)}const D=class D{constructor(u,h,b){v(this,"X");v(this,"Y");v(this,"Z");this.X=F("x",u),this.Y=F("y",h,!0),this.Z=F("z",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(u){const{x:h,y:b}=u||{};if(!u||!t.isValid(h)||!t.isValid(b))throw new Error("invalid affine point");if(u instanceof D)throw new Error("projective point not allowed");return t.is0(h)&&t.is0(b)?D.ZERO:new D(h,b,t.ONE)}static fromBytes(u){const h=D.fromAffine(m(H(u,void 0,"point")));return h.assertValidity(),h}static fromHex(u){return D.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){$(u);const{X:h,Y:b,Z:E}=this,{X:R,Y:T,Z:O}=u,S=t.eql(t.mul(h,O),t.mul(R,E)),C=t.eql(t.mul(b,O),t.mul(T,E));return S&&C}negate(){return new D(this.X,t.neg(this.Y),this.Z)}double(){const{a:u,b:h}=o,b=t.mul(h,Me),{X:E,Y:R,Z:T}=this;let O=t.ZERO,S=t.ZERO,C=t.ZERO,N=t.mul(E,E),W=t.mul(R,R),U=t.mul(T,T),k=t.mul(E,R);return k=t.add(k,k),C=t.mul(E,T),C=t.add(C,C),O=t.mul(u,C),S=t.mul(b,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(b,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,T),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 D(O,S,C)}add(u){$(u);const{X:h,Y:b,Z:E}=this,{X:R,Y:T,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(b,T),V=t.mul(E,O),ee=t.add(h,b),G=t.add(R,T);ee=t.mul(ee,G),G=t.add(k,j),ee=t.sub(ee,G),G=t.add(h,E);let K=t.add(R,O);return G=t.mul(G,K),K=t.add(k,V),G=t.sub(G,K),K=t.add(b,E),S=t.add(T,O),K=t.mul(K,S),S=t.add(j,V),K=t.sub(K,S),N=t.mul(W,G),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),G=t.mul(U,G),j=t.add(j,V),V=t.sub(k,V),V=t.mul(W,V),G=t.add(G,V),k=t.mul(j,G),C=t.add(C,k),k=t.mul(K,G),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 D(S,C,N)}subtract(u){return this.add(u.negate())}is0(){return this.equals(D.ZERO)}multiply(u){const{endo:h}=e;if(!n.isValidNot0(u))throw new Error("invalid scalar: out of range");let b,E;const R=T=>ne.cached(this,T,O=>Dt(D,O));if(h){const{k1neg:T,k1:O,k2neg:S,k2:C}=B(u),{p:N,f:W}=R(O),{p:U,f:k}=R(C);E=W.add(k),b=he(h.beta,N,U,T,S)}else{const{p:T,f:O}=R(u);b=T,E=O}return Dt(D,[b,E])[0]}multiplyUnsafe(u){const{endo:h}=e,b=this;if(!n.isValid(u))throw new Error("invalid scalar: out of range");if(u===le||b.is0())return D.ZERO;if(u===Ee)return b;if(ne.hasCache(this))return this.multiply(u);if(h){const{k1neg:E,k1:R,k2neg:T,k2:O}=B(u),{p1:S,p2:C}=Br(D,b,R,O);return he(h.beta,S,C,E,T)}else return ne.unsafe(b,u)}toAffine(u){return Q(this,u)}isTorsionFree(){const{isTorsionFree:u}=e;return i===Ee?!0:u?u(D,this):ne.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:u}=e;return i===Ee?this:u?u(D,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(u=!0){return Ge(u,"isCompressed"),this.assertValidity(),_(D,this,u)}toHex(u=!0){return ke(this.toBytes(u))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};v(D,"BASE",new D(o.Gx,o.Gy,t.ONE)),v(D,"ZERO",new D(t.ZERO,t.ONE,t.ZERO)),v(D,"Fp",t),v(D,"Fn",n);let Z=D;const xe=n.BITS,ne=new Mr(Z,e.endo?Math.ceil(xe/2):xe);return Z.BASE.precompute(8),Z}function ys(r){return Uint8Array.of(r?2:3)}function bs(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function jr(r,e={}){const{Fn:s}=r,t=e.randomBytes||es,n=Object.assign(bs(r.Fp,s),{seed:ps(s.ORDER)});function o(_){try{const m=s.fromBytes(_);return s.isValidNot0(m)}catch{return!1}}function i(_,m){const{publicKey:A,publicKeyUncompressed:y}=n;try{const I=_.length;return m===!0&&I!==A||m===!1&&I!==y?!1:!!r.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return $r(H(_,n.seed,"seed"),s.ORDER)}function c(_,m=!0){return r.BASE.multiply(s.fromBytes(_)).toBytes(m)}function l(_){const{secretKey:m,publicKey:A,publicKeyUncompressed:y}=n;if(!at(_)||"_lengths"in s&&s._lengths||m===A)return;const I=H(_,void 0,"key").length;return I===A||I===y}function d(_,m,A=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");const y=s.fromBytes(_);return r.fromBytes(m).multiply(y).toBytes(A)}const f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},w=Ur(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:w,Point:r,utils:f,lengths:n})}function Vr(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||es,n=s.hmac||((u,h)=>ms(e,u,h)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:f,utils:w,lengths:_}=jr(r,s),m={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},A=a*ws<o.ORDER;function y(u){const h=a>>Ee;return u>h}function I(u,h){if(!i.isValidNot0(h))throw new Error(`invalid signature ${u}: out of range 1..Point.Fn.ORDER`);return h}function L(){if(A)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function F(u,h){nt(h);const b=_.signature,E=h==="compact"?b:h==="recovered"?b+1:void 0;return H(u,E)}class ${constructor(h,b,E){v(this,"r");v(this,"s");v(this,"recovery");if(this.r=I("r",h),this.s=I("s",b),E!=null){if(L(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(h,b=m.format){F(h,b);let E;if(b==="der"){const{r:S,s:C}=ge.toSig(H(h));return new $(S,C)}b==="recovered"&&(E=h[0],b="compact",h=h.subarray(1));const R=_.signature/2,T=h.subarray(0,R),O=h.subarray(R,R*2);return new $(i.fromBytes(T),i.fromBytes(O),E)}static fromHex(h,b){return this.fromBytes(He(h),b)}assertRecovery(){const{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new $(this.r,this.s,h)}recoverPublicKey(h){const{r:b,s:E}=this,R=this.assertRecovery(),T=R===2||R===3?b+a:b;if(!o.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const O=o.toBytes(T),S=r.fromBytes(_e(ys((R&1)===0),O)),C=i.inv(T),N=Q(H(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 y(this.s)}toBytes(h=m.format){if(nt(h),h==="der")return He(ge.hexFromSig(this));const{r:b,s:E}=this,R=i.toBytes(b),T=i.toBytes(E);return h==="recovered"?(L(),_e(Uint8Array.of(this.assertRecovery()),R,T)):_e(R,T)}toHex(h){return ke(this.toBytes(h))}}const B=s.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");const b=Ve(h),E=h.length*8-c;return E>0?b>>BigInt(E):b},Q=s.bits2int_modN||function(h){return i.create(B(h))},ve=dt(c);function he(u){return Sr("num < 2^"+c,u,le,ve),i.toBytes(u)}function Z(u,h){return H(u,void 0,"message"),h?H(e(u),void 0,"prehashed message"):u}function xe(u,h,b){const{lowS:E,prehash:R,extraEntropy:T}=tt(b,m);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(T!=null&&T!==!1){const k=T===!0?t(_.secretKey):T;C.push(H(k,void 0,"extraEntropy"))}const N=_e(...C),W=O;function U(k){const j=B(k);if(!i.isValidNot0(j))return;const V=i.inv(j),ee=r.BASE.multiply(j).toAffine(),G=i.create(ee.x);if(G===le)return;const K=i.create(V*i.create(W+G*S));if(K===le)return;let xt=(ee.x===G?0:2)|Number(ee.y&Ee),mt=K;return E&&y(K)&&(mt=i.neg(K),xt^=1),new $(G,mt,A?void 0:xt)}return{seed:N,k2sig:U}}function ne(u,h,b={}){const{seed:E,k2sig:R}=xe(u,h,b);return Ir(e.outputLen,i.BYTES,n)(E,R).toBytes(b.format)}function D(u,h,b,E={}){const{lowS:R,prehash:T,format:O}=tt(E,m);if(b=H(b,void 0,"publicKey"),h=Z(h,T),!at(u)){const S=u instanceof $?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+S)}F(u,O);try{const S=$.fromBytes(u,O),C=r.fromBytes(b);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,b={}){const{prehash:E}=tt(b,m);return h=Z(h,E),$.fromBytes(u,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:f,utils:w,lengths:_,Point:r,sign:ne,verify:D,recoverPublicKey:P,Signature:$,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")},Kr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ut=BigInt(2);function zr(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,_=se(w,Ut,e)*l%e,m=se(_,n,e)*_%e,A=se(m,o,e)*m%e,y=se(A,a,e)*A%e,I=se(y,c,e)*y%e,L=se(I,a,e)*A%e,F=se(L,s,e)*d%e,$=se(F,i,e)*m%e,B=se($,t,e)*l%e,Q=se(B,Ut,e);if(!ot.eql(ot.sqr(Q),r))throw new Error("Cannot find square root");return Q}const ot=Ke(ft.p,{sqrt:zr}),Yr=Wr(ft,{Fp:ot,endo:Kr}),Zr=Vr(Yr,yr),Xr=BigInt(0),Re=BigInt(1),Jr=BigInt(2),Qr=BigInt(7),en=BigInt(256),tn=BigInt(113),vs=[],Ss=[],Es=[];for(let r=0,e=Re,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],vs.push(2*(5*t+s)),Ss.push((r+1)*(r+2)/2%64);let n=Xr;for(let o=0;o<7;o++)e=(e<<Re^(e>>Qr)*tn)%en,e&Jr&&(n^=Re<<(Re<<BigInt(o))-Re);Es.push(n)}const Is=hr(Es,!0),sn=Is[0],rn=Is[1],Ht=(r,e,s)=>s>32?gr(r,e,s):fr(r,e,s),Gt=(r,e,s)=>s>32?_r(r,e,s):pr(r,e,s);function nn(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=Ht(l,d,1)^s[a],w=Gt(l,d,1)^s[a+1];for(let _=0;_<50;_+=10)r[i+_]^=f,r[i+_+1]^=w}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=Ss[i],c=Ht(n,o,a),l=Gt(n,o,a),d=vs[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]^=sn[t],r[1]^=rn[t]}Te(s)}class pt{constructor(e,s,t,n=!1,o=24){v(this,"state");v(this,"pos",0);v(this,"posOut",0);v(this,"finished",!1);v(this,"state32");v(this,"destroyed",!1);v(this,"blockLen");v(this,"suffix");v(this,"outputLen");v(this,"enableXOF",!1);v(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,ue(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=sr(this.state)}clone(){return this._cloneInto()}keccak(){Ot(this.state32),nn(this.state32,this.rounds),Ot(this.state32),this.posOut=0,this.pos=0}update(e){Ie(this),H(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ie(this,!1),H(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(Xt(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Te(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new pt(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const on=(r,e,s,t={})=>Qt(()=>new pt(e,r,s),t),qt=on(1,136,32);class an{async verifyJWT(e,s){try{const t=this.decodeJWT(e);p.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?(p.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(p.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(p.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw p.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Cs.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=qt(o),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=cn(a),l=c.slice(0,32),d=c.slice(32,64),f=c[64],w=f>=27?f-27:f,A=new Zr.Signature(Wt(l),Wt(d)).addRecoveryBit(w).recoverPublicKey(i).toBytes(!1).slice(1),y=qt(A);return"0x"+ke(y.slice(12))}}function cn(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 Wt(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const ln=3e4;class dn{async request(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??ln);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=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=gt.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(()=>{p.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),F(),t(new Error("Authentication timeout"))},5*60*1e3),_=10,m=30;let A=0,y=null;const I=()=>{clearInterval(L),p.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+m+"초간 대기합니다"),y=setTimeout(()=>{F(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},m*1e3)},L=setInterval(()=>{A++;try{f.closed&&(A<=_?I():(F(),t(new Error("로그인이 취소되었습니다"))))}catch{I()}},1e3),F=()=>{clearTimeout(w),clearInterval(L),y&&clearTimeout(y),window.removeEventListener("message",$)},$=B=>{var ve,he,Z,xe,ne,D,P;if(B.origin!==e.expectedOrigin)return;F(),p.log("[CROSSx] OAuth postMessage 수신 — status:",B.data.status);const Q=B.data.state??((ve=B.data.data)==null?void 0:ve.state);if(!Q||Q!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(B.data.status==="success"){const u=((he=B.data.data)==null?void 0:he.accessToken)||((Z=B.data.data)==null?void 0:Z.idToken);p.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!((xe=B.data.data)!=null&&xe.accessToken),hasIdToken:!!((ne=B.data.data)!=null&&ne.idToken)}),u?s(u):(p.error("[CROSSx] 토큰을 찾을 수 없음:",B.data),t(new Error("Token not found in response")))}else p.error("[CROSSx] OAuth 실패:",(D=B.data.data)==null?void 0:D.error),t(new Error(((P=B.data.data)==null?void 0:P.error)||"Authentication failed"))};window.addEventListener("message",$)})}}const Oe="crossx_wallet_data";class un{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(g.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 p.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 p.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 p.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){p.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 p.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){p.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){p.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(g.AUTH_NOT_AUTHENTICATED,"인증 토큰을 찾을 수 없습니다. 먼저 로그인해 주세요.");return e}async request(e,s,t){var a,c;const n=this.getAuthToken(),o=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const f=d.message||d.data||"API 요청에 실패했습니다";p.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:f,url:o,method:e,fullResponse:d});const w=We.mapGatewayError(d.code),_=We.getGatewayErrorMessage(d.code,f),m=new x(w,_);throw m.gatewayCode=d.code,m.gatewayMessage=f,m}return p.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 요청에 실패했습니다",w=d.code||"UNKNOWN";throw p.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(g.UNKNOWN_ERROR,`Wallet Gateway 오류 (${w}): ${f}`)}throw l}}async getOrCreateWallet(e){var s;p.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 p.log("[CROSSx][Migration Phase 2] 기존 지갑 발견 — address:",n),{id:e,address:n,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}}catch{p.log("[CROSSx][Migration Phase 2] 기존 지갑 없음, POST /mnemonic/create 진행")}p.log("[CROSSx][Migration Phase 2] POST /mnemonic/create — ignoreBackup: false");try{const t={ignoreBackup:!1},n=await this.request("POST","/mnemonic/create",t);return p.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")){p.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&&p.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 p.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(g.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new x(g.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new x(g.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t};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){p.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 p.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}static mapGatewayError(e){switch(e){case-10002:return g.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return g.UNKNOWN_ERROR;case-10006:return g.GATEWAY_INTERNAL_ERROR;case-10008:return g.GATEWAY_LOCK_CONFLICT;case-10010:return g.MIGRATION_FAILED;case-10012:return g.MIGRATION_BACKUP_EXISTS;case-10022:return g.PROJECT_NOT_REGISTERED;case-10023:return g.PROJECT_ID_MISSING;case-10024:return g.ORIGIN_NOT_ALLOWED;case-10026:return g.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return g.PREPARE_FAILED;case-10016:return g.PREPARE_EXPIRED;case-10017:case-10018:return g.PREPARE_MISMATCH;default:return g.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10006:return"Internal server error. Please try again later.";case-10008:return"Another operation is in progress. Please try again later.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin is not in the allowed list. Register the current domain in the management console.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";default:return`Request failed (${e}): ${s}`}}}class Ce{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=Ce.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?Xs:Zs;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new x(Ce.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Ce.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new x(g.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(je).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return g.CHAIN_NOT_SUPPORTED;case-10021:return g.INVALID_CHAIN;case-10022:return g.PROJECT_NOT_REGISTERED;case-10023:return g.PROJECT_ID_MISSING;case-10024:return g.APP_IDENTIFIER_MISSING;case-10025:return g.INVALID_APP_TYPE;default:return g.UNKNOWN_ERROR}}}const jt="__crossx-confirm-style",te="__crossx-confirm-overlay",hn={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 Vt(r,e){const s=hn[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 fn=`
|
|
3
3
|
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
4
4
|
|
|
5
5
|
#${te} {
|
|
@@ -914,22 +914,22 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
914
914
|
}
|
|
915
915
|
.__crossx-card--wallet-selector .__crossx-wallet-add { flex-shrink: 0; }
|
|
916
916
|
}
|
|
917
|
-
`;function me(){let r=document.getElementById(
|
|
917
|
+
`;function me(){let r=document.getElementById(jt);r||(r=document.createElement("style"),r.id=jt,document.head.appendChild(r)),r.textContent=fn}function Y(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function pn(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 Kt={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 Ts(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Kt[e]?Kt[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 gn(r){try{return BigInt(r).toLocaleString()}catch{return r}}function _n(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=gn(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 As(r){const e=_n(r);if(!e)return q("Estimated fee","<span>—</span>");let s=q("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=q("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=q("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=q("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=q("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">
|
|
918
918
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
919
919
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
920
920
|
</svg>`,ie=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
921
921
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
922
922
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
923
|
-
</svg>`;function
|
|
923
|
+
</svg>`;function xn(r){return`<svg width="28" height="28" viewBox="0 0 28 28" fill="none">
|
|
924
924
|
<circle cx="14" cy="14" r="14" fill="${r}"/>
|
|
925
925
|
<path d="M14 7.5L19.2 10.5V16.5L14 19.5L8.8 16.5V10.5L14 7.5Z" fill="white" opacity="0.9"/>
|
|
926
926
|
</svg>`}const _t=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
|
927
927
|
<rect x="2" y="5" width="16" height="12" rx="2" stroke="currentColor" stroke-width="1.5"/>
|
|
928
928
|
<path d="M2 9h16" stroke="currentColor" stroke-width="1.5"/>
|
|
929
929
|
<rect x="12.5" y="11.5" width="3.5" height="2.5" rx="0.75" fill="currentColor"/>
|
|
930
|
-
</svg>`,
|
|
930
|
+
</svg>`,mn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
931
931
|
<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)"/>
|
|
932
|
-
</svg>`,
|
|
932
|
+
</svg>`,wn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
933
933
|
<circle cx="12" cy="12" r="12" fill="var(--cx-secondary)"/>
|
|
934
934
|
<circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
|
|
935
935
|
<path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
|
|
@@ -937,8 +937,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
937
937
|
<div class="__crossx-row">
|
|
938
938
|
<span class="__crossx-row-label">${r}</span>
|
|
939
939
|
<div class="__crossx-row-value">${e}</div>
|
|
940
|
-
</div>`}function
|
|
941
|
-
<button class="__crossx-copy-btn" data-copy="${M(r.to)}" title="Copy address">${de}</button>`:"<span>—</span>",o=
|
|
940
|
+
</div>`}function yn(r,e){const s=e,t=ze(),n=r.to?`<span class="__crossx-addr-text">${Y(r.to)}</span>
|
|
941
|
+
<button class="__crossx-copy-btn" data-copy="${M(r.to)}" title="Copy address">${de}</button>`:"<span>—</span>",o=As(r),i=r.data&&r.data!=="0x"?r.data:"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
|
|
942
942
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
943
943
|
<div class="__crossx-header">
|
|
944
944
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -959,7 +959,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
959
959
|
<hr class="__crossx-divider">
|
|
960
960
|
<div class="__crossx-rows">
|
|
961
961
|
${q("To",n)}
|
|
962
|
-
${q("Network",`<span>${
|
|
962
|
+
${q("Network",`<span>${Ts(r.chainId)}</span>`)}
|
|
963
963
|
${o}
|
|
964
964
|
</div>
|
|
965
965
|
</div>
|
|
@@ -971,8 +971,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
971
971
|
</div>
|
|
972
972
|
</div>
|
|
973
973
|
</div>
|
|
974
|
-
`,a}function
|
|
975
|
-
<button class="__crossx-copy-btn" data-copy="${M(r.to)}" title="Copy address">${de}</button>`:"<span>—</span>",a=
|
|
974
|
+
`,a}function bn(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>
|
|
975
|
+
<button class="__crossx-copy-btn" data-copy="${M(r.to)}" title="Copy address">${de}</button>`:"<span>—</span>",a=As(r),l=pn(r.value,t,n)??"—",d=document.createElement("div");return d.id=te,d.innerHTML=`
|
|
976
976
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
977
977
|
<div class="__crossx-header">
|
|
978
978
|
<p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
|
|
@@ -986,7 +986,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
986
986
|
<div class="__crossx-body-cols">
|
|
987
987
|
<div class="__crossx-rows">
|
|
988
988
|
${q("To",i)}
|
|
989
|
-
${q("Network",`<span>${
|
|
989
|
+
${q("Network",`<span>${Ts(r.chainId)}</span>`)}
|
|
990
990
|
${a}
|
|
991
991
|
</div>
|
|
992
992
|
<div class="__crossx-pill">
|
|
@@ -997,7 +997,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
997
997
|
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
|
|
998
998
|
</div>
|
|
999
999
|
</div>
|
|
1000
|
-
`,d}function ze(){var r;try{return((r=window.location)==null?void 0:r.hostname)||"This site"}catch{return"This site"}}function M(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function
|
|
1000
|
+
`,d}function ze(){var r;try{return((r=window.location)==null?void 0:r.hostname)||"This site"}catch{return"This site"}}function M(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function vn(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function Sn(r){if(typeof r=="string")return M(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return M(JSON.stringify(r))}catch{return String(r)}}function En(r,e){const s=q("From",`<span class="__crossx-addr-text">${Y(r.from)}</span>
|
|
1001
1001
|
<button class="__crossx-copy-btn" data-copy="${M(r.from)}" title="Copy address">${de}</button>`),t=r.to?q("To",`<span class="__crossx-addr-text">${Y(r.to)}</span>
|
|
1002
1002
|
<button class="__crossx-copy-btn" data-copy="${M(r.to)}" title="Copy address">${de}</button>`):"",n=r.amount?q("Transfer",`<span>${M(r.amount)}</span>`):"",o=r.fees?q("Tx Fee",`<span>${M(r.fees)}</span>`):"",i=r.txHash?q("Tx Hash",`<span class="__crossx-addr-text">${Y(r.txHash)}</span>
|
|
1003
1003
|
<button class="__crossx-copy-btn" data-copy="${M(r.txHash)}" title="Copy hash">${de}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
|
|
@@ -1022,7 +1022,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1022
1022
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
|
|
1023
1023
|
</div>
|
|
1024
1024
|
</div>
|
|
1025
|
-
`,c}function
|
|
1025
|
+
`,c}function In(r,e){const s=document.createElement("div");return s.id=te,s.innerHTML=`
|
|
1026
1026
|
<div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1027
1027
|
<div class="__crossx-header">
|
|
1028
1028
|
<p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
|
|
@@ -1035,7 +1035,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1035
1035
|
</div>
|
|
1036
1036
|
</div>
|
|
1037
1037
|
</div>
|
|
1038
|
-
`,s}function
|
|
1038
|
+
`,s}function Tn(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 m=n?wn:t?"":mn,A=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";m?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${m}<span>${A}</span>`):o.textContent=A}if(i&&!r.querySelector("#__crossx-close-btn")){const m=document.createElement("button");m.className="__crossx-close",m.id="__crossx-close-btn",m.setAttribute("aria-label","Close"),m.innerHTML=ie,i.appendChild(m)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?q("From",`<span class="__crossx-addr-text">${Y(e.from)}</span>
|
|
1039
1039
|
<button class="__crossx-copy-btn" data-copy="${M(e.from)}" title="Copy address">${de}</button>`):"",l=e.to?q("To",`<span class="__crossx-addr-text">${Y(e.to)}</span>
|
|
1040
1040
|
<button class="__crossx-copy-btn" data-copy="${M(e.to)}" title="Copy address">${de}</button>`):"",d=e.amount?q("Transfer",`<span>${M(e.amount)}</span>`):"",f=e.fees?q("Tx Fee",`<span>${M(e.fees)}</span>`):"",w=e.txHash?q("Tx Hash",`<span class="__crossx-addr-text">${Y(e.txHash)}</span>
|
|
1041
1041
|
<button class="__crossx-copy-btn" data-copy="${M(e.txHash)}" title="Copy hash">${de}</button>`):"",_=e.total?`<div class="__crossx-total-pill">
|
|
@@ -1051,7 +1051,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1051
1051
|
</div>
|
|
1052
1052
|
${_}
|
|
1053
1053
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
|
|
1054
|
-
`,a.querySelectorAll(".__crossx-copy-btn").forEach(m=>{m.addEventListener("click",A=>{var I;A.stopPropagation();const y=m.dataset.copy;y&&((I=navigator.clipboard)==null||I.writeText(y).catch(()=>{}))})})}function
|
|
1054
|
+
`,a.querySelectorAll(".__crossx-copy-btn").forEach(m=>{m.addEventListener("click",A=>{var I;A.stopPropagation();const y=m.dataset.copy;y&&((I=navigator.clipboard)==null||I.writeText(y).catch(()=>{}))})})}function An(r,e){const s=e,t=ze(),n=M(r.message),o=document.createElement("div");return o.id=te,o.innerHTML=`
|
|
1055
1055
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1056
1056
|
<div class="__crossx-header">
|
|
1057
1057
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1079,11 +1079,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1079
1079
|
</div>
|
|
1080
1080
|
</div>
|
|
1081
1081
|
</div>
|
|
1082
|
-
`,o}function
|
|
1082
|
+
`,o}function Rn(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=`
|
|
1083
1083
|
<div class="__crossx-td-row">
|
|
1084
1084
|
<span class="__crossx-td-label">Primary Type</span>
|
|
1085
1085
|
<span class="__crossx-td-value">${M(o)}</span>
|
|
1086
|
-
</div>`;for(const[l,d]of Object.entries(i)){const f=
|
|
1086
|
+
</div>`;for(const[l,d]of Object.entries(i)){const f=Sn(d),_=vn(d)?`<span class="__crossx-addr-text">${Y(d)}</span>
|
|
1087
1087
|
<button class="__crossx-copy-btn" data-copy="${M(String(d))}" title="Copy">${de}</button>`:`<span>${f}</span>`;a+=`
|
|
1088
1088
|
<div class="__crossx-td-row">
|
|
1089
1089
|
<span class="__crossx-td-label">${M(l)}</span>
|
|
@@ -1116,10 +1116,10 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1116
1116
|
</div>
|
|
1117
1117
|
</div>
|
|
1118
1118
|
</div>
|
|
1119
|
-
`,c}const
|
|
1119
|
+
`,c}const On=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
1120
1120
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
1121
1121
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
1122
|
-
</svg>`;function
|
|
1122
|
+
</svg>`;function Cn(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(i=>{const a=t&&i.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${i.index}" data-wallet-address="${M(i.address)}">
|
|
1123
1123
|
<span class="__crossx-wallet-addr">${Y(i.address)}</span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
|
|
1124
1124
|
</button>`}).join(""),o=document.createElement("div");return o.id=te,o.innerHTML=`
|
|
1125
1125
|
<div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
@@ -1145,22 +1145,22 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1145
1145
|
${n}
|
|
1146
1146
|
</div>
|
|
1147
1147
|
<button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
|
|
1148
|
-
<span class="__crossx-wallet-add-icon">${
|
|
1148
|
+
<span class="__crossx-wallet-add-icon">${On}</span>
|
|
1149
1149
|
<span class="__crossx-wallet-add-label">add a wallet</span>
|
|
1150
1150
|
</button>
|
|
1151
1151
|
</div>
|
|
1152
1152
|
</div>
|
|
1153
1153
|
</div>
|
|
1154
1154
|
</div>
|
|
1155
|
-
`,o}const
|
|
1155
|
+
`,o}const kn=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1156
1156
|
<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"/>
|
|
1157
1157
|
<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"/>
|
|
1158
|
-
</svg>`,
|
|
1158
|
+
</svg>`,Nn=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1159
1159
|
<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"/>
|
|
1160
1160
|
<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"/>
|
|
1161
1161
|
<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"/>
|
|
1162
1162
|
<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"/>
|
|
1163
|
-
</svg>`;function
|
|
1163
|
+
</svg>`;function Pn(r){const e=r,s=document.createElement("div");return s.id=te,s.innerHTML=`
|
|
1164
1164
|
<div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1165
1165
|
<div class="__crossx-header">
|
|
1166
1166
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -1173,11 +1173,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1173
1173
|
<div class="__crossx-body">
|
|
1174
1174
|
<div class="__crossx-login-btn-row">
|
|
1175
1175
|
<button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
|
|
1176
|
-
<span class="__crossx-login-icon" style="color:var(--cx-value);">${
|
|
1176
|
+
<span class="__crossx-login-icon" style="color:var(--cx-value);">${kn}</span>
|
|
1177
1177
|
<span class="__crossx-login-btn-label">Sign in with Apple</span>
|
|
1178
1178
|
</button>
|
|
1179
1179
|
<button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
|
|
1180
|
-
<span class="__crossx-login-icon">${
|
|
1180
|
+
<span class="__crossx-login-icon">${Nn}</span>
|
|
1181
1181
|
<span class="__crossx-login-btn-label">Sign in with Google</span>
|
|
1182
1182
|
</button>
|
|
1183
1183
|
</div>
|
|
@@ -1187,7 +1187,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1187
1187
|
</p>
|
|
1188
1188
|
</div>
|
|
1189
1189
|
</div>
|
|
1190
|
-
`,s}function
|
|
1190
|
+
`,s}function Ln(r){const e=r,s=document.createElement("div");return s.id=te,s.innerHTML=`
|
|
1191
1191
|
<div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1192
1192
|
<div class="__crossx-header">
|
|
1193
1193
|
<p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
|
|
@@ -1201,13 +1201,13 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1201
1201
|
<p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
|
|
1202
1202
|
</div>
|
|
1203
1203
|
<button class="__crossx-recover-btn" id="__crossx-recover-btn">
|
|
1204
|
-
<span>${
|
|
1204
|
+
<span>${xn(e.primary)}</span>
|
|
1205
1205
|
<span class="__crossx-recover-label">Recover My Wallet</span>
|
|
1206
1206
|
</button>
|
|
1207
1207
|
<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>
|
|
1208
1208
|
</div>
|
|
1209
1209
|
</div>
|
|
1210
|
-
`,s}function
|
|
1210
|
+
`,s}function Dn(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=`
|
|
1211
1211
|
<div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1212
1212
|
<div class="__crossx-header">
|
|
1213
1213
|
<p class="__crossx-title" id="__crossx-ttl">Recover My Wallet</p>
|
|
@@ -1225,4 +1225,4 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1225
1225
|
${t}
|
|
1226
1226
|
</div>
|
|
1227
1227
|
</div>
|
|
1228
|
-
`,n}function
|
|
1228
|
+
`,n}function $n(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 Mn{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=Vt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=Vt(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var A;me();const o=[...e],i=Cn(o,this.tokens,t),a=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},d=y=>{l(),n(y)},f=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const I=y.dataset.walletAddress??"",L=parseInt(y.dataset.walletIndex??"0",10);d({address:I,index:L})})})})();const _=i.querySelector("#__crossx-add-wallet-btn");_&&_.addEventListener("click",async()=>{_.disabled=!0;try{const y=await s();o.push(y);const I=i.querySelector("#__crossx-wallet-list");if(I){const L=document.createElement("button");L.className="__crossx-wallet-item",L.dataset.walletIndex=String(y.index),L.dataset.walletAddress=y.address,L.innerHTML=`<span class="__crossx-wallet-addr">${Y(y.address)}</span>`,L.addEventListener("click",()=>d(y)),I.appendChild(L),L.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{_.disabled=!1}}),(A=i.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",f),i.addEventListener("click",y=>{y.target===i&&f()});const m=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",m),f())};document.addEventListener("keydown",m)})}showLoginSelector(){return new Promise(e=>{var a,c,l;me();const s=Pn(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=Ln(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=Dn(this.tokens,e);document.body.appendChild(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};$n(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=En(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=In(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||(Tn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;me();let t;e.type==="sign-message"?t=An(e,this.tokens):e.type==="sign-typed-data"?t=Rn(e,this.tokens):e.type==="sign"?t=yn(e,this.tokens):t=bn(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 m;w.stopPropagation();const _=f.dataset.copy;_&&((m=navigator.clipboard)==null||m.writeText(_).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 Bn{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}function Fn(r){r.debug;const e=Fe.production,s={...r,oauthServiceUrl:e.oauthServiceUrl,authApiUrl:e.authApiUrl,walletGatewayUrl:e.walletGatewayUrl},t={gatewayUrl:e.walletGatewayUrl,projectId:r.projectId},o=s.authMode!=="cookie"&&Rt.isAvailable()?new Rt:new Js,i=new an,a=new dn,c=new gt,l=new Bn;let d;r.useMockWallet?(p.log("[CROSSx] Mock Wallet Provider 사용"),d=new un(o)):(p.log("[CROSSx] Remote Wallet Provider 사용"),d=new We(t,o,a,l));const f=new Ce(t,a),w=new Mn(r.theme??"light",r.themeTokens);return new Ue(s,t,o,i,a,c,d,l,w,f)}exports.CROSSxError=x;exports.CROSSxEthereumProvider=zt;exports.CROSSxSDK=Ue;exports.ChainId=ks;exports.ErrorCode=g;exports.createCROSSxSDK=Fn;
|