@nexus-cross/crossx-sdk-core 0.0.0-beta.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +129 -83
  2. package/dist/__tests__/adapters/IndexedDBStorageAdapter.test.d.ts +2 -0
  3. package/dist/__tests__/adapters/IndexedDBStorageAdapter.test.d.ts.map +1 -0
  4. package/dist/__tests__/mocks/MockChainRegistryPort.d.ts +9 -0
  5. package/dist/__tests__/mocks/MockChainRegistryPort.d.ts.map +1 -0
  6. package/dist/__tests__/mocks/MockTransportPort.d.ts +10 -5
  7. package/dist/__tests__/mocks/MockTransportPort.d.ts.map +1 -1
  8. package/dist/__tests__/mocks/MockWalletProviderPort.d.ts +3 -8
  9. package/dist/__tests__/mocks/MockWalletProviderPort.d.ts.map +1 -1
  10. package/dist/adapters/chain/RemoteChainRegistryAdapter.d.ts +29 -0
  11. package/dist/adapters/chain/RemoteChainRegistryAdapter.d.ts.map +1 -0
  12. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +6 -1
  13. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
  14. package/dist/adapters/oauth/BrowserOAuthAdapter.d.ts.map +1 -1
  15. package/dist/adapters/storage/IndexedDBStorageAdapter.d.ts +25 -0
  16. package/dist/adapters/storage/IndexedDBStorageAdapter.d.ts.map +1 -0
  17. package/dist/adapters/transport/FetchTransportAdapter.d.ts.map +1 -1
  18. package/dist/adapters/wallet/MockWalletProviderAdapter.d.ts +1 -6
  19. package/dist/adapters/wallet/MockWalletProviderAdapter.d.ts.map +1 -1
  20. package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts +1 -11
  21. package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts.map +1 -1
  22. package/dist/adapters/wallet/types.d.ts +0 -6
  23. package/dist/adapters/wallet/types.d.ts.map +1 -1
  24. package/dist/core/constants.d.ts +27 -0
  25. package/dist/core/constants.d.ts.map +1 -0
  26. package/dist/core/ports/ChainRegistryPort.d.ts +18 -0
  27. package/dist/core/ports/ChainRegistryPort.d.ts.map +1 -0
  28. package/dist/core/ports/ConfirmationPort.d.ts +46 -6
  29. package/dist/core/ports/ConfirmationPort.d.ts.map +1 -1
  30. package/dist/core/ports/TransportPort.d.ts +2 -0
  31. package/dist/core/ports/TransportPort.d.ts.map +1 -1
  32. package/dist/core/ports/WalletProviderPort.d.ts +3 -28
  33. package/dist/core/ports/WalletProviderPort.d.ts.map +1 -1
  34. package/dist/core/ports/index.d.ts +1 -0
  35. package/dist/core/ports/index.d.ts.map +1 -1
  36. package/dist/core/services/JsonRpcService.d.ts +18 -0
  37. package/dist/core/services/JsonRpcService.d.ts.map +1 -0
  38. package/dist/core/services/TypedEventEmitter.d.ts +23 -0
  39. package/dist/core/services/TypedEventEmitter.d.ts.map +1 -0
  40. package/dist/core/types/chain.d.ts +102 -17
  41. package/dist/core/types/chain.d.ts.map +1 -1
  42. package/dist/core/types/errors.d.ts +8 -3
  43. package/dist/core/types/errors.d.ts.map +1 -1
  44. package/dist/core/types/events.d.ts +23 -0
  45. package/dist/core/types/events.d.ts.map +1 -0
  46. package/dist/core/types/index.d.ts +8 -15
  47. package/dist/core/types/index.d.ts.map +1 -1
  48. package/dist/core/types/internal.d.ts +39 -0
  49. package/dist/core/types/internal.d.ts.map +1 -0
  50. package/dist/core/usecases/SignInUseCase.d.ts +32 -7
  51. package/dist/core/usecases/SignInUseCase.d.ts.map +1 -1
  52. package/dist/core/usecases/SignOutUseCase.d.ts +3 -1
  53. package/dist/core/usecases/SignOutUseCase.d.ts.map +1 -1
  54. package/dist/core/usecases/index.d.ts +0 -1
  55. package/dist/core/usecases/index.d.ts.map +1 -1
  56. package/dist/index.cjs +263 -203
  57. package/dist/index.d.ts +2 -2
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +5128 -4410
  60. package/dist/sdk/CROSSxSDK.d.ts +148 -15
  61. package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
  62. package/dist/sdk/EthereumProvider.d.ts.map +1 -1
  63. package/dist/sdk/factory.d.ts.map +1 -1
  64. package/package.json +2 -1
  65. package/dist/__tests__/usecases/WithdrawUseCase.test.d.ts +0 -2
  66. package/dist/__tests__/usecases/WithdrawUseCase.test.d.ts.map +0 -1
  67. package/dist/core/usecases/WithdrawUseCase.d.ts +0 -11
  68. package/dist/core/usecases/WithdrawUseCase.d.ts.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,4 +1,5 @@
1
- "use strict";var ur=Object.defineProperty;var hr=(s,e,r)=>e in s?ur(s,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[e]=r;var w=(s,e,r)=>hr(s,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const fr=require("jose");var p=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_OR_APP_ID_MISSING="ORIGIN_OR_APP_ID_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(p||{});class m extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,m.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}class Pt{constructor(e,r){this.sdk=e,this.chainId=r,this._listeners=new Map}async request({method:e,params:r=[]}){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(r[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new m(p.NOT_IMPLEMENTED,`${e} is not yet supported. Use sdk.signMessage() directly.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new m(p.NOT_IMPLEMENTED,`${e} is not yet supported. Use sdk.signTypedData() directly.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[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)}}}const ht="__crossx-confirm-style",te="__crossx-confirm-overlay",gr={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 ft(s,e){const r=gr[s],t=e==null?void 0:e[s];return t?{...r,...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}}:r}const pr=`
1
+ "use strict";var Es=Object.defineProperty;var Ts=(r,e,s)=>e in r?Es(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var b=(r,e,s)=>Ts(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const As=require("jose");var p=(r=>(r.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",r.AUTH_FAILED="AUTH_FAILED",r.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",r.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",r.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",r.WALLET_NOT_FOUND="WALLET_NOT_FOUND",r.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(p||{});class _ extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,_.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const We={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Is=Object.fromEntries(Object.entries(We).map(([r,e])=>[r,e.caipId])),Rs=new Map(Object.values(We).map(r=>[r.caipId,r]));new Map(Object.values(We).map(r=>[r.chainId,r]));const Os={symbol:"",decimals:18};function ze(r){var e;return((e=Rs.get(r))==null?void 0:e.nativeCurrency)??Os}class jt{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new _(p.NOT_IMPLEMENTED,`${e} is not yet supported. Use sdk.signMessage() directly.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new _(p.NOT_IMPLEMENTED,`${e} is not yet supported. Use sdk.signTypedData() or sdk.signTypedDataOffchain() directly.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...s))}_caip2ToHex(e){const s=e.split(":");return`0x${parseInt(s[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let me=null;function mt(r){me=r}const f={log(...r){if(me){me.log(...r);return}},warn(...r){if(me){me.warn(...r);return}},error(...r){if(me){me.error(...r);return}}},Ye="crossx_access_token",Ne="crossx_refresh_token",Pe="crossx_user_info";class Cs{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null}get useCookieAuth(){return this.config.authMode!=="token"}checkResponseError(e,s){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new _(p.AUTH_FAILED,`${s} failed (code ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const n=t;if(n.code&&n.code!==200&&n.code>0)throw new _(p.AUTH_FAILED,`${s} failed (code ${n.code}): ${n.message}`)}}async execute(e){var n,o,i,a;let s,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:g}=this.config,w=`${d}${l}`;f.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인):`,w);const m=await this.oauth.openAuth({authUrl:w,expectedOrigin:new URL(d).origin});f.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",m.length,")");const{accessToken:x,refreshToken:A}=await this.exchangeFirebaseToken(m,g);let E,C;try{const $=this.crypto.decodeJWT(m);C=(n=$.firebase)==null?void 0:n.sign_in_provider;const B=((o=$.firebase)==null?void 0:o.identities)??{};C==="google.com"?E=(i=B["google.com"])==null?void 0:i[0]:C==="apple.com"&&(E=(a=B["apple.com"])==null?void 0:a[0]),f.log("[CROSSx] OAuth provider sub 추출 — provider:",C,"hasProviderSub:",!!E)}catch{f.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(x){const $=this.crypto.decodeJWT(x);f.log("[CROSSx] access_token 디코딩 — sub:",$.sub,"exp:",$.exp);const B=await this.crypto.verifyJWT(x);if(t=B.signatureVerified??!1,!B.valid)throw f.error("[CROSSx] access_token 검증 실패"),new Error("Invalid access token");const F=B.payload;s={id:F.sub,email:F.email,signInProvider:C,providerSub:E},this.tokenStore.set(x),this.useCookieAuth||(await this.storage.set(Ye,x),A&&await this.storage.set(Ne,A))}else{const $=this.crypto.decodeJWT(m);s={id:$.sub,email:$.email,signInProvider:C,providerSub:E},f.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}f.log("[CROSSx] 사용자 정보 — id:",s.id);const q=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Pe,q),f.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return f.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return f.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,t)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;f.log("[CROSSx] Firebase 토큰 교환 요청:",n);const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});f.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return f.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new _(p.AUTH_FAILED,"access_token not found in exchange response");f.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(Pe);if(n)return f.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){f.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(Ye),n=await this.storage.get(Ne);if(f.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return f.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);f.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(Pe);if(f.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;f.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return f.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return f.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(Ne),await this.storage.remove(Pe),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,o={};if(!t){const l=this.tokenStore.get()??"";l&&(o.access_token=l),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});f.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){f.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new _(p.AUTH_FAILED,"Silent refresh failed: no token in response");if(this.tokenStore.set(c),!t){await this.storage.set(Ye,c);const l=this.extractRefreshToken(a);l&&await this.storage.set(Ne,l)}return f.log("[CROSSx] silentRefresh 성공"),c}async loadWallet(e,s){let t,n=!1;try{f.log("[CROSSx][Migration Phase 2] POST /mnemonic/create 호출 — userId:",e.id),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,f.log("[CROSSx][Migration Phase 2] 지갑 로드 완료 (기존 백업 없음) — address:",t)}catch(o){if(o instanceof _&&o.code===p.MIGRATION_BACKUP_EXISTS)f.log("[CROSSx][Migration Phase 2] Gateway -10012 감지 → needsMigration = true"),n=!0;else{if(o instanceof _&&(o.code===p.PROJECT_NOT_REGISTERED||o.code===p.PROJECT_ID_MISSING||o.code===p.ORIGIN_NOT_ALLOWED))throw f.error("[CROSSx][Migration Phase 2] 프로젝트 설정 에러:",o.message),o;f.warn("[CROSSx][Migration Phase 2] 지갑 로드 실패 (로그인은 유지):",o)}}return f.log("[CROSSx][Migration Phase 2] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}}const Ns="crossx_access_token",Ps="crossx_refresh_token",ks="crossx_user_info";class Ls{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t}async execute(){this.tokenStore.clear(),this.config.authMode==="token"&&(await this.storage.remove(Ns),await this.storage.remove(Ps)),await this.storage.remove(ks)}}class Ds{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new _(p.NOT_IMPLEMENTED,"Migration is not supported in the current environment");f.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return f.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class $s{constructor(e,s){this.chainRegistry=e,this.transport=s}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:s,id:Date.now()},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new _(p.UNKNOWN_ERROR,`RPC error [${e}] (${t}): ${a.error.message} (code: ${a.error.code})`);return a==null?void 0:a.result}}class Bs{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}const Ms=2e3,wt=6e4,Fs=1e3,Us=1e4,Hs="0x77359400",yt="0x3B9ACA00",bt=130,vt=6,St=18,Gs=0,qs=30*1e3,Z=class Z extends Bs{constructor(e,s,t,n,o,i,a,c,l){super(),this.storage=s,this.crypto=t,this.transport=n,this.oauth=o,this.walletProvider=i,this.tokenStore=a,this.initialized=!1,this.authenticated=!1,this.userId=null,this.address=null,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._config=Object.freeze({...e}),e.logger&&mt(e.logger),this.confirmation=c,this.chainRegistry=l,this.jsonRpc=new $s(l,n),this.signInUseCase=new Cs(e,s,t,o,n,i,a),this.signOutUseCase=new Ls(e,s,a),this.migrateWalletUseCase=new Ds(s,i)}get config(){return this._config}async initialize(){if(this.initialized)return this.authenticated?{success:!0,address:this.address??void 0}:null;console.log("[CROSSx SDK] v1.0.0 initializing...");try{const e=await this.signInUseCase.restoreSession();return e!=null&&e.success&&this.applyAuthResult(e),this.initialized=!0,this.emit("initialized",{restored:!!(e!=null&&e.success)}),e??null}catch(e){throw new _(p.AUTH_NOT_INITIALIZED,"SDK initialization failed",e)}}async signIn(e){this.ensureInitialized();let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector();if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new _(p.AUTH_FAILED,"Sign in failed",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new _(p.UNKNOWN_ERROR,"Sign out failed",e)}}isAuthenticated(){return this.authenticated}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();return e!=null&&e.success?(this.applyAuthResult(e),!0):!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"User ID not found");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.emit("addressChanged",{address:s.address,index:0}),f.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof _?s:new _(p.MIGRATION_FAILED,"Wallet migration failed",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"User ID not found");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:0}}async getAddresses(){return this.ensureAuthenticated(),this.address?[{address:this.address,index:0}]:[]}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof _?e:new _(p.UNKNOWN_ERROR,"Failed to fetch chains",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof _?s:new _(p.CHAIN_NOT_SUPPORTED,`Failed to fetch chain: ${e}`,s)}}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"User ID not found");f.log("[CROSSx] 지갑 생성 시작");try{const e=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=e.address,this.emit("addressChanged",{address:e.address,index:0}),f.log("[CROSSx] 지갑 생성 완료:",e.address),{address:e.address}}catch(e){if(e instanceof _&&e.code===p.MIGRATION_BACKUP_EXISTS){const s=this.providerSub??this.userId;f.log("[CROSSx][Migration Phase 3] createWallet() — Gateway -10012 감지, 마이그레이션 UI 시작 — migrationSub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new _(p.MIGRATION_FAILED,"Migration skipped by user")}throw e}}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=t==null?void 0:t.index,o=await this.walletProvider.getAddress(this.userId,n??0);let i;if(this.walletProvider.prepare&&(i=(await this.walletProvider.prepare("sign-message",{message:s,from:o.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:o.address,message:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(p.USER_REJECTED,"User rejected message signing");try{const c=await this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,i,o.address);return this.verifySignatureSigner(s,c.signature,o.address),{chainId:e,signature:c.signature,message:s,address:o.address}}catch(c){throw c instanceof _?c:new _(p.SIGNATURE_FAILED,`Message signing failed (${e})`,c)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"User ID not found");if(!this.walletProvider.signTypedData)throw new _(p.NOT_IMPLEMENTED,"signTypedData is not implemented");Z.validateTypedDataChainId(e,s);const n=await this.walletProvider.getAddress(this.userId,(t==null?void 0:t.index)??0);let o;if(this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(p.USER_REJECTED,"User rejected typed data signing");try{const a=await this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address);return Z.validateSignatureFormat(a.signature),{chainId:e,signature:a.signature,address:n.address}}catch(a){throw a instanceof _?a:new _(p.SIGNATURE_FAILED,`Typed data signing failed (${e})`,a)}}async signTypedDataOffchain(e,s){return this.signTypedData(Z.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=await this.withResolvedGasAndFee(s,e);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign",{tx:n})).uuid);const i=ze(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(p.USER_REJECTED,"User rejected transaction signing");try{const c=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o);return Z.validateSignedTxFormat(c.signature),{chainId:e,signedTx:c.signature,txHash:c.txHash??""}}catch(c){if(c instanceof _)throw c;const l=c instanceof Error?c.message:String(c);throw new _(p.SIGNATURE_FAILED,`Transaction signing failed (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=await this.withResolvedGasAndFee(s,e);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("send",{tx:n})).uuid);const i=ze(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(p.USER_REJECTED,"User rejected transaction");try{let c;if(this.walletProvider.sendTransaction)c=(await this.walletProvider.sendTransaction(this.userId,e,n,o)).txHash;else{const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o);c=l.txHash??l.signature}return{chainId:e,txHash:c,status:"pending"}}catch(c){const l=c instanceof Error?c.message:String(c);throw new _(p.TRANSACTION_FAILED,`Transaction failed (${e}): ${l}`,c)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??Fs,o=Us,i=t.timeoutMs??wt,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,o)}throw new _(p.UNKNOWN_ERROR,`Transaction receipt timeout (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var w,m;const{txHash:n}=await this.sendTransaction(e,s),o=t.intervalMs??((w=this._config.receiptPolling)==null?void 0:w.intervalMs)??Ms,i=t.timeoutMs??((m=this._config.receiptPolling)==null?void 0:m.timeoutMs)??wt,a=ze(e),c=s.from??"";let l,d;const g=this.waitForTxAndGetReceipt(n,e,{intervalMs:o,timeoutMs:i}).then(x=>{l=x;const A=BigInt(x.gasUsed)*BigInt(x.effectiveGasPrice),E=s.value?BigInt(s.value):0n,C=Z.formatTxAmount(s.value,a.symbol,a.decimals),q=Z.formatTxAmount("0x"+A.toString(16),a.symbol,a.decimals),$=Z.formatTxAmount("0x"+(E+A).toString(16),a.symbol,a.decimals);return{chainId:e,txHash:n,from:x.from,to:x.to??s.to,amount:C,fees:q,total:$,nativeSymbol:a.symbol,status:x.status==="0x1"?"success":"reverted"}}).catch(x=>(d=x instanceof Error?x:new Error(String(x)),{chainId:e,txHash:n,from:c,to:s.to,amount:Z.formatTxAmount(s.value,a.symbol,a.decimals),nativeSymbol:a.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:n,from:c,to:s.to},g),d)throw d;return{chainId:e,txHash:n,receipt:l}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(p.GAS_ESTIMATION_FAILED,`Failed to get gas price (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const o=n instanceof Error?n.message:String(n);throw new _(p.GAS_ESTIMATION_FAILED,`Failed to estimate gas (${s}): ${o}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(p.GAS_ESTIMATION_FAILED,`Failed to get baseFeePerGas (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(p.GAS_ESTIMATION_FAILED,`Failed to get maxPriorityFeePerGas (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(p.UNKNOWN_ERROR,`Failed to get nonce: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:Z.formatWei(n),chainId:e}}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(p.UNKNOWN_ERROR,`Failed to get balance (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt(St),n=s/t,i=(s%t).toString().padStart(St,"0").replace(/0+$/,"").slice(0,vt);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new jt(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof _)throw n;const o=n instanceof Error?n.message:String(n);throw new _(p.UNKNOWN_ERROR,`rpcRequest failed [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const o=10n**BigInt(t),i=n/o,c=(n%o).toString().padStart(t,"0").slice(0,vt).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){f.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(f.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return f.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0;for(;;){n++,f.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n})`,t?`— 이전 에러: ${t}`:"");const o=await this.confirmation.showPinInputPrompt(t);if(o===null)return f.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;f.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${o.length}자리), Gateway 마이그레이션 API 호출`);try{const i=await this.migrateWalletUseCase.execute(o,e);return f.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",i.address),i}catch(i){if(i instanceof _&&i.code===p.MIGRATION_FAILED){f.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 #${n}) — 재시도 요청`),t="Incorrect PIN. Please try again.";continue}throw f.error("[CROSSx][Migration Phase 4] 마이그레이션 실패 (복구 불가):",i),i}}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e};if(n&&(f.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출"),c.nonce=await this.getNonce(s),f.log("[CROSSx] nonce 결과:",c.nonce)),o&&(f.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),f.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){f.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=yt;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,f.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Hs,f.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=yt,f.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=Z.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new _(p.TYPED_DATA_CHAIN_ID_MISMATCH,`Off-chain signing (chainId=0) requires typedData.domain.chainId to be absent or 0, got ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new _(p.TYPED_DATA_CHAIN_ID_MISMATCH,`On-chain signing (${e}) requires typedData.domain.chainId to be present`);if(t!==o)throw new _(p.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t}) does not match chainId (${e}, expected ${o})`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new _(p.SIGNATURE_FAILED,"Invalid signature: not a valid hex string");if(s.length!==bt)throw new _(p.SIGNATURE_FAILED,`Invalid signature length: expected ${bt} hex chars (65 bytes), got ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new _(p.SIGNATURE_FAILED,"Invalid signedTx: not a valid hex string");if(s.length<2)throw new _(p.SIGNATURE_FAILED,"Invalid signedTx: too short")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw f.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new _(p.SIGNATURE_SIGNER_MISMATCH,`Signature signer mismatch: expected ${t}, recovered ${n}`);f.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof _)throw n;f.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var s,t,n,o;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=Z.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}ensureInitialized(){if(!this.initialized)throw new _(p.AUTH_NOT_INITIALIZED,"SDK is not initialized. Call initialize() first.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new _(p.AUTH_NOT_AUTHENTICATED,"Not authenticated. Call signIn() first.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.initialized=!1,this.removeAllListeners(),mt(null)}};Z.OFFCHAIN_CHAIN_ID="0";let Fe=Z;class Ws{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw f.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return f.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw f.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw f.error("Storage clear error:",e),e}}}const js="crossx-sdk",Vs=1,ve="data",ke="keys",Et="aes-primary",Ks=12;class Tt{constructor(){this.db=null,this.cryptoKey=null,this.initPromise=null}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,s)=>{const t=indexedDB.open(js,Vs);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(ve)||n.createObjectStore(ve),n.objectStoreNames.contains(ke)||n.createObjectStore(ke)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(ke,Et);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(ke,Et,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(Ks);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(ve,e,n)}catch(t){throw f.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(ve,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return f.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ve,e)}catch(s){throw f.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(ve)}catch(e){throw f.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function it(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function le(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function U(r,e,s=""){const t=it(r),n=r==null?void 0:r.length,o=e!==void 0;if(!t||o&&n!==e){const i=s&&`"${s}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Vt(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");le(r.outputLen),le(r.blockLen)}function Te(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Kt(r,e){U(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function zs(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Ae(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ze(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function oe(r,e){return r<<32-e|r>>>e}const Ys=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Zs(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Xs(r){for(let e=0;e<r.length;e++)r[e]=Zs(r[e]);return r}const At=Ys?r=>r:Xs,zt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Js=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ce(r){if(U(r),zt)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=Js[r[s]];return e}const ie={_0:48,_9:57,A:65,F:70,a:97,f:102};function It(r){if(r>=ie._0&&r<=ie._9)return r-ie._0;if(r>=ie.A&&r<=ie.F)return r-(ie.A-10);if(r>=ie.a&&r<=ie.f)return r-(ie.a-10)}function Ue(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(zt)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,o=0;n<s;n++,o+=2){const i=It(r.charCodeAt(o)),a=It(r.charCodeAt(o+1));if(i===void 0||a===void 0){const c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function xe(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];U(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const o=r[t];s.set(o,n),n+=o.length}return s}function Yt(r,e={}){const s=(n,o)=>r(o).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function Zt(r=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}const Qs=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function er(r,e,s){return r&e^~r&s}function tr(r,e,s){return r&e^r&s^e&s}class sr{constructor(e,s,t,n){b(this,"blockLen");b(this,"outputLen");b(this,"padOffset");b(this,"isLE");b(this,"buffer");b(this,"view");b(this,"finished",!1);b(this,"length",0);b(this,"pos",0);b(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ze(this.buffer)}update(e){Te(this),U(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=Ze(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Te(this),Kt(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Ae(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let g=i;g<n;g++)s[g]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=Ze(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let g=0;g<l;g++)a.setUint32(4*g,d[g],o)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const fe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Le=BigInt(2**32-1),Rt=BigInt(32);function rr(r,e=!1){return e?{h:Number(r&Le),l:Number(r>>Rt&Le)}:{h:Number(r>>Rt&Le)|0,l:Number(r&Le)|0}}function nr(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let o=0;o<s;o++){const{h:i,l:a}=rr(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const or=(r,e,s)=>r<<s|e>>>32-s,ir=(r,e,s)=>e<<s|r>>>32-s,ar=(r,e,s)=>e<<s-32|r>>>64-s,cr=(r,e,s)=>r<<s-32|e>>>64-s,lr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ge=new Uint32Array(64);class dr extends sr{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,s,t,n,o,i,a,c]}set(e,s,t,n,o,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,s){for(let g=0;g<16;g++,s+=4)ge[g]=e.getUint32(s,!1);for(let g=16;g<64;g++){const w=ge[g-15],m=ge[g-2],x=oe(w,7)^oe(w,18)^w>>>3,A=oe(m,17)^oe(m,19)^m>>>10;ge[g]=A+ge[g-7]+x+ge[g-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let g=0;g<64;g++){const w=oe(a,6)^oe(a,11)^oe(a,25),m=d+w+er(a,c,l)+lr[g]+ge[g]|0,A=(oe(t,2)^oe(t,13)^oe(t,22))+tr(t,n,o)|0;d=l,l=c,c=a,a=i+m|0,i=o,o=n,n=t,t=m+A|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,o,i,a,c,l,d)}roundClean(){Ae(ge)}destroy(){this.set(0,0,0,0,0,0,0,0),Ae(this.buffer)}}class ur extends dr{constructor(){super(32);b(this,"A",fe[0]|0);b(this,"B",fe[1]|0);b(this,"C",fe[2]|0);b(this,"D",fe[3]|0);b(this,"E",fe[4]|0);b(this,"F",fe[5]|0);b(this,"G",fe[6]|0);b(this,"H",fe[7]|0)}}const hr=Yt(()=>new ur,Qs(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const at=BigInt(0),st=BigInt(1);function He(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Xt(r){if(typeof r=="bigint"){if(!Me(r))throw new Error("positive bigint expected, got "+r)}else le(r);return r}function De(r){const e=Xt(r).toString(16);return e.length&1?"0"+e:e}function Jt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?at:BigInt("0x"+r)}function je(r){return Jt(Ce(r))}function Qt(r){return Jt(Ce(fr(U(r)).reverse()))}function ct(r,e){le(e),r=Xt(r);const s=Ue(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function es(r,e){return ct(r,e).reverse()}function fr(r){return Uint8Array.from(r)}const Me=r=>typeof r=="bigint"&&at<=r;function gr(r,e,s){return Me(r)&&Me(e)&&Me(s)&&e<=r&&r<s}function pr(r,e,s,t){if(!gr(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function xr(r){let e;for(e=0;r>at;r>>=st,e+=1);return e}const lt=r=>(st<<BigInt(r))-st;function _r(r,e,s){if(le(r,"hashLen"),le(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=E=>new Uint8Array(E),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const g=()=>{c.fill(1),l.fill(0),d=0},w=(...E)=>s(l,xe(c,...E)),m=(E=n)=>{l=w(o,E),c=w(),E.length!==0&&(l=w(i,E),c=w())},x=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let E=0;const C=[];for(;E<e;){c=w();const q=c.slice();C.push(q),E+=c.length}return xe(...C)};return(E,C)=>{g(),m(E);let q;for(;!(q=C(x()));)m();return g(),q}}function dt(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(o,i,a){const c=r[o];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}const n=(o,i)=>Object.entries(o).forEach(([a,c])=>t(a,c,i));n(e,!1),n(s,!0)}function Ot(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const X=BigInt(0),z=BigInt(1),we=BigInt(2),ts=BigInt(3),ss=BigInt(4),rs=BigInt(5),mr=BigInt(7),ns=BigInt(8),wr=BigInt(9),os=BigInt(16);function re(r,e){const s=r%e;return s>=X?s:e+s}function ee(r,e,s){let t=r;for(;e-- >X;)t*=t,t%=s;return t}function Ct(r,e){if(r===X)throw new Error("invert: expected non-zero number");if(e<=X)throw new Error("invert: expected positive modulus, got "+e);let s=re(r,e),t=e,n=X,o=z;for(;s!==X;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==z)throw new Error("invert: does not exist");return re(n,e)}function ut(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function is(r,e){const s=(r.ORDER+z)/ss,t=r.pow(e,s);return ut(r,t,e),t}function yr(r,e){const s=(r.ORDER-rs)/ns,t=r.mul(e,we),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,we),n),a=r.mul(o,r.sub(i,r.ONE));return ut(r,a,e),a}function br(r){const e=Ve(r),s=as(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+mr)/os;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const g=a.mul(l,n),w=a.mul(l,o),m=a.eql(a.sqr(d),c),x=a.eql(a.sqr(g),c);l=a.cmov(l,d,m),d=a.cmov(w,g,x);const A=a.eql(a.sqr(d),c),E=a.cmov(l,d,A);return ut(a,E,c),E}}function as(r){if(r<ts)throw new Error("sqrt is not defined for small field");let e=r-z,s=0;for(;e%we===X;)e/=we,s++;let t=we;const n=Ve(r);for(;Nt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return is;let o=n.pow(t,e);const i=(e+z)/we;return function(c,l){if(c.is0(l))return l;if(Nt(c,l)!==1)throw new Error("Cannot find square root");let d=s,g=c.mul(c.ONE,o),w=c.pow(l,e),m=c.pow(l,i);for(;!c.eql(w,c.ONE);){if(c.is0(w))return c.ZERO;let x=1,A=c.sqr(w);for(;!c.eql(A,c.ONE);)if(x++,A=c.sqr(A),x===d)throw new Error("Cannot find square root");const E=z<<BigInt(d-x-1),C=c.pow(g,E);d=x,g=c.sqr(C),w=c.mul(w,g),m=c.mul(m,C)}return m}}function vr(r){return r%ss===ts?is:r%ns===rs?yr:r%os===wr?br(r):as(r)}const Sr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Er(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Sr.reduce((t,n)=>(t[n]="function",t),e);return dt(r,s),r}function Tr(r,e,s){if(s<X)throw new Error("invalid exponent, negatives unsupported");if(s===X)return r.ONE;if(s===z)return e;let t=r.ONE,n=e;for(;s>X;)s&z&&(t=r.mul(t,n)),n=r.sqr(n),s>>=z;return t}function cs(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),o),t}function Nt(r,e){const s=(r.ORDER-z)/we,t=r.pow(e,s),n=r.eql(t,r.ONE),o=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function Ar(r,e){e!==void 0&&le(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Ir{constructor(e,s={}){b(this,"ORDER");b(this,"BITS");b(this,"BYTES");b(this,"isLE");b(this,"ZERO",X);b(this,"ONE",z);b(this,"_lengths");b(this,"_sqrt");b(this,"_mod");var i;if(e<=X)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=Ar(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return X<=e&&e<this.ORDER}is0(e){return e===X}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&z)===z}neg(e){return re(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return re(e*e,this.ORDER)}add(e,s){return re(e+s,this.ORDER)}sub(e,s){return re(e-s,this.ORDER)}mul(e,s){return re(e*s,this.ORDER)}pow(e,s){return Tr(this,e,s)}div(e,s){return re(e*Ct(s,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,s){return e+s}subN(e,s){return e-s}mulN(e,s){return e*s}inv(e){return Ct(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=vr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?es(e,this.BYTES):ct(e,this.BYTES)}fromBytes(e,s=!1){U(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?Qt(e):je(e);if(a&&(c=re(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return cs(this,e)}cmov(e,s,t){return t?s:e}}function Ve(r,e={}){return new Ir(r,e)}function ls(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function ds(r){const e=ls(r);return e+Math.ceil(e/2)}function Rr(r,e,s=!1){U(r);const t=r.length,n=ls(e),o=ds(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?Qt(r):je(r),a=re(i,e-z)+z;return s?es(a,n):ct(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ie=BigInt(0),ye=BigInt(1);function Ge(r,e){const s=e.negate();return r?s:e}function Pt(r,e){const s=cs(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function us(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Xe(r,e){us(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=lt(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function kt(r,e,s){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=s;let a=Number(r&n),c=r>>i;a>t&&(a-=o,c+=ye);const l=e*t,d=l+Math.abs(a)-1,g=a===0,w=a<0,m=e%2!==0;return{nextN:c,offset:d,isZero:g,isNeg:w,isNegF:m,offsetF:l}}const Je=new WeakMap,hs=new WeakMap;function Qe(r){return hs.get(r)||1}function Lt(r){if(r!==Ie)throw new Error("invalid wNAF")}class Or{constructor(e,s){b(this,"BASE");b(this,"ZERO");b(this,"Fn");b(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>Ie;)s&ye&&(t=t.add(n)),n=n.double(),s>>=ye;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=Xe(s,this.bits),o=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=Xe(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:g,isNegF:w,offsetF:m}=kt(t,a,i);t=c,d?o=o.add(Ge(w,s[m])):n=n.add(Ge(g,s[l]))}return Lt(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=Xe(e,this.bits);for(let i=0;i<o.windows&&t!==Ie;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=kt(t,i,o);if(t=a,!l){const g=s[c];n=n.add(d?g.negate():g)}}return Lt(t),n}getPrecomputes(e,s,t){let n=Je.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),Je.set(s,n))),n}cached(e,s,t){const n=Qe(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=Qe(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){us(s,this.bits),hs.set(e,s),Je.delete(e)}hasCache(e){return Qe(e)!==1}}function Cr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>Ie||t>Ie;)s&ye&&(o=o.add(n)),t&ye&&(i=i.add(n)),n=n.double(),s>>=ye,t>>=ye;return{p1:o,p2:i}}function Dt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Er(e),e}else return Ve(r,{isLE:s})}function Nr(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Ie))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Dt(e.p,s.Fp,t),o=Dt(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}function Pr(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class fs{constructor(e,s){b(this,"oHash");b(this,"iHash");b(this,"blockLen");b(this,"outputLen");b(this,"finished",!1);b(this,"destroyed",!1);if(Vt(e),U(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Ae(n)}update(e){return Te(this),this.iHash.update(e),this}digestInto(e){Te(this),U(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const gs=(r,e,s)=>new fs(r,e).update(s).digest();gs.create=(r,e)=>new fs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $t=(r,e)=>(r+(r>=0?e:-e)/ps)/e;function kr(r,e,s){const[[t,n],[o,i]]=e,a=$t(i*r,s),c=$t(-n*r,s);let l=r-a*t-c*o,d=-a*n-c*i;const g=l<ae,w=d<ae;g&&(l=-l),w&&(d=-d);const m=lt(Math.ceil(xr(s)/2))+Ee;if(l<ae||l>=m||d<ae||d>=m)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:g,k1:l,k2neg:w,k2:d}}function rt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function et(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return He(s.lowS,"lowS"),He(s.prehash,"prehash"),s.format!==void 0&&rt(s.format),s}class Lr extends Error{constructor(e=""){super(e)}}const pe={Err:Lr,_tlv:{encode:(r,e)=>{const{Err:s}=pe;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=De(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?De(n.length/2|128):"";return De(r)+o+n+e},decode(r,e){const{Err:s}=pe;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=pe;if(r<ae)throw new e("integer: negative integers are not allowed");let s=De(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=pe;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return je(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=pe,n=U(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=pe,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},ae=BigInt(0),Ee=BigInt(1),ps=BigInt(2),$e=BigInt(3),Dr=BigInt(4);function $r(r,e={}){const s=Nr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;dt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=_s(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function g(k,u,h){const{x:y,y:S}=u.toAffine(),I=t.toBytes(y);if(He(h,"isCompressed"),h){d();const T=!t.isOdd(S);return xe(xs(T),I)}else return xe(Uint8Array.of(4),I,t.toBytes(S))}function w(k){U(k,void 0,"Point");const{publicKey:u,publicKeyUncompressed:h}=l,y=k.length,S=k[0],I=k.subarray(1);if(y===u&&(S===2||S===3)){const T=t.fromBytes(I);if(!t.isValid(T))throw new Error("bad point: is not on curve, wrong x");const R=A(T);let v;try{v=t.sqrt(R)}catch(W){const M=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+M)}d();const O=t.isOdd(v);return(S&1)===1!==O&&(v=t.neg(v)),{x:T,y:v}}else if(y===h&&S===4){const T=t.BYTES,R=t.fromBytes(I.subarray(0,T)),v=t.fromBytes(I.subarray(T,T*2));if(!E(R,v))throw new Error("bad point: is not on curve");return{x:R,y:v}}else throw new Error(`bad point: got length ${y}, expected compressed=${u} or uncompressed=${h}`)}const m=e.toBytes||g,x=e.fromBytes||w;function A(k){const u=t.sqr(k),h=t.mul(u,k);return t.add(t.add(h,t.mul(k,o.a)),o.b)}function E(k,u){const h=t.sqr(u),y=A(k);return t.eql(h,y)}if(!E(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const C=t.mul(t.pow(o.a,$e),Dr),q=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(C,q)))throw new Error("bad curve params: a or b");function $(k,u,h=!1){if(!t.isValid(u)||h&&t.is0(u))throw new Error(`bad point coordinate ${k}`);return u}function B(k){if(!(k instanceof Y))throw new Error("Weierstrass Point expected")}function F(k){if(!c||!c.basises)throw new Error("no endo");return kr(k,c.basises,n.ORDER)}const se=Ot((k,u)=>{const{X:h,Y:y,Z:S}=k;if(t.eql(S,t.ONE))return{x:h,y};const I=k.is0();u==null&&(u=I?t.ONE:t.inv(S));const T=t.mul(h,u),R=t.mul(y,u),v=t.mul(S,u);if(I)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:T,y:R}}),be=Ot(k=>{if(k.is0()){if(e.allowInfinityPoint&&!t.is0(k.Y))return;throw new Error("bad point: ZERO")}const{x:u,y:h}=k.toAffine();if(!t.isValid(u)||!t.isValid(h))throw new Error("bad point: x or y not field elements");if(!E(u,h))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function he(k,u,h,y,S){return h=new Y(t.mul(h.X,k),h.Y,h.Z),u=Ge(y,u),h=Ge(S,h),u.add(h)}const L=class L{constructor(u,h,y){b(this,"X");b(this,"Y");b(this,"Z");this.X=$("x",u),this.Y=$("y",h,!0),this.Z=$("z",y),Object.freeze(this)}static CURVE(){return o}static fromAffine(u){const{x:h,y}=u||{};if(!u||!t.isValid(h)||!t.isValid(y))throw new Error("invalid affine point");if(u instanceof L)throw new Error("projective point not allowed");return t.is0(h)&&t.is0(y)?L.ZERO:new L(h,y,t.ONE)}static fromBytes(u){const h=L.fromAffine(x(U(u,void 0,"point")));return h.assertValidity(),h}static fromHex(u){return L.fromBytes(Ue(u))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(u=8,h=!0){return ne.createCache(this,u),h||this.multiply($e),this}assertValidity(){be(this)}hasEvenY(){const{y:u}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(u)}equals(u){B(u);const{X:h,Y:y,Z:S}=this,{X:I,Y:T,Z:R}=u,v=t.eql(t.mul(h,R),t.mul(I,S)),O=t.eql(t.mul(y,R),t.mul(T,S));return v&&O}negate(){return new L(this.X,t.neg(this.Y),this.Z)}double(){const{a:u,b:h}=o,y=t.mul(h,$e),{X:S,Y:I,Z:T}=this;let R=t.ZERO,v=t.ZERO,O=t.ZERO,P=t.mul(S,S),W=t.mul(I,I),M=t.mul(T,T),N=t.mul(S,I);return N=t.add(N,N),O=t.mul(S,T),O=t.add(O,O),R=t.mul(u,O),v=t.mul(y,M),v=t.add(R,v),R=t.sub(W,v),v=t.add(W,v),v=t.mul(R,v),R=t.mul(N,R),O=t.mul(y,O),M=t.mul(u,M),N=t.sub(P,M),N=t.mul(u,N),N=t.add(N,O),O=t.add(P,P),P=t.add(O,P),P=t.add(P,M),P=t.mul(P,N),v=t.add(v,P),M=t.mul(I,T),M=t.add(M,M),P=t.mul(M,N),R=t.sub(R,P),O=t.mul(M,W),O=t.add(O,O),O=t.add(O,O),new L(R,v,O)}add(u){B(u);const{X:h,Y:y,Z:S}=this,{X:I,Y:T,Z:R}=u;let v=t.ZERO,O=t.ZERO,P=t.ZERO;const W=o.a,M=t.mul(o.b,$e);let N=t.mul(h,I),j=t.mul(y,T),V=t.mul(S,R),J=t.add(h,y),H=t.add(I,T);J=t.mul(J,H),H=t.add(N,j),J=t.sub(J,H),H=t.add(h,S);let K=t.add(I,R);return H=t.mul(H,K),K=t.add(N,V),H=t.sub(H,K),K=t.add(y,S),v=t.add(T,R),K=t.mul(K,v),v=t.add(j,V),K=t.sub(K,v),P=t.mul(W,H),v=t.mul(M,V),P=t.add(v,P),v=t.sub(j,P),P=t.add(j,P),O=t.mul(v,P),j=t.add(N,N),j=t.add(j,N),V=t.mul(W,V),H=t.mul(M,H),j=t.add(j,V),V=t.sub(N,V),V=t.mul(W,V),H=t.add(H,V),N=t.mul(j,H),O=t.add(O,N),N=t.mul(K,H),v=t.mul(J,v),v=t.sub(v,N),N=t.mul(J,j),P=t.mul(K,P),P=t.add(P,N),new L(v,O,P)}subtract(u){return this.add(u.negate())}is0(){return this.equals(L.ZERO)}multiply(u){const{endo:h}=e;if(!n.isValidNot0(u))throw new Error("invalid scalar: out of range");let y,S;const I=T=>ne.cached(this,T,R=>Pt(L,R));if(h){const{k1neg:T,k1:R,k2neg:v,k2:O}=F(u),{p:P,f:W}=I(R),{p:M,f:N}=I(O);S=W.add(N),y=he(h.beta,P,M,T,v)}else{const{p:T,f:R}=I(u);y=T,S=R}return Pt(L,[y,S])[0]}multiplyUnsafe(u){const{endo:h}=e,y=this;if(!n.isValid(u))throw new Error("invalid scalar: out of range");if(u===ae||y.is0())return L.ZERO;if(u===Ee)return y;if(ne.hasCache(this))return this.multiply(u);if(h){const{k1neg:S,k1:I,k2neg:T,k2:R}=F(u),{p1:v,p2:O}=Cr(L,y,I,R);return he(h.beta,v,O,S,T)}else return ne.unsafe(y,u)}toAffine(u){return se(this,u)}isTorsionFree(){const{isTorsionFree:u}=e;return i===Ee?!0:u?u(L,this):ne.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:u}=e;return i===Ee?this:u?u(L,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(u=!0){return He(u,"isCompressed"),this.assertValidity(),m(L,this,u)}toHex(u=!0){return Ce(this.toBytes(u))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};b(L,"BASE",new L(o.Gx,o.Gy,t.ONE)),b(L,"ZERO",new L(t.ZERO,t.ONE,t.ZERO)),b(L,"Fp",t),b(L,"Fn",n);let Y=L;const _e=n.BITS,ne=new Or(Y,e.endo?Math.ceil(_e/2):_e);return Y.BASE.precompute(8),Y}function xs(r){return Uint8Array.of(r?2:3)}function _s(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Br(r,e={}){const{Fn:s}=r,t=e.randomBytes||Zt,n=Object.assign(_s(r.Fp,s),{seed:ds(s.ORDER)});function o(m){try{const x=s.fromBytes(m);return s.isValidNot0(x)}catch{return!1}}function i(m,x){const{publicKey:A,publicKeyUncompressed:E}=n;try{const C=m.length;return x===!0&&C!==A||x===!1&&C!==E?!1:!!r.fromBytes(m)}catch{return!1}}function a(m=t(n.seed)){return Rr(U(m,n.seed,"seed"),s.ORDER)}function c(m,x=!0){return r.BASE.multiply(s.fromBytes(m)).toBytes(x)}function l(m){const{secretKey:x,publicKey:A,publicKeyUncompressed:E}=n;if(!it(m)||"_lengths"in s&&s._lengths||x===A)return;const C=U(m,void 0,"key").length;return C===A||C===E}function d(m,x,A=!0){if(l(m)===!0)throw new Error("first arg must be private key");if(l(x)===!1)throw new Error("second arg must be public key");const E=s.fromBytes(m);return r.fromBytes(x).multiply(E).toBytes(A)}const g={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},w=Pr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:w,Point:r,utils:g,lengths:n})}function Mr(r,e,s={}){Vt(e),dt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||Zt,n=s.hmac||((u,h)=>gs(e,u,h)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:g,utils:w,lengths:m}=Br(r,s),x={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},A=a*ps<o.ORDER;function E(u){const h=a>>Ee;return u>h}function C(u,h){if(!i.isValidNot0(h))throw new Error(`invalid signature ${u}: out of range 1..Point.Fn.ORDER`);return h}function q(){if(A)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function $(u,h){rt(h);const y=m.signature,S=h==="compact"?y:h==="recovered"?y+1:void 0;return U(u,S)}class B{constructor(h,y,S){b(this,"r");b(this,"s");b(this,"recovery");if(this.r=C("r",h),this.s=C("s",y),S!=null){if(q(),![0,1,2,3].includes(S))throw new Error("invalid recovery id");this.recovery=S}Object.freeze(this)}static fromBytes(h,y=x.format){$(h,y);let S;if(y==="der"){const{r:v,s:O}=pe.toSig(U(h));return new B(v,O)}y==="recovered"&&(S=h[0],y="compact",h=h.subarray(1));const I=m.signature/2,T=h.subarray(0,I),R=h.subarray(I,I*2);return new B(i.fromBytes(T),i.fromBytes(R),S)}static fromHex(h,y){return this.fromBytes(Ue(h),y)}assertRecovery(){const{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new B(this.r,this.s,h)}recoverPublicKey(h){const{r:y,s:S}=this,I=this.assertRecovery(),T=I===2||I===3?y+a:y;if(!o.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const R=o.toBytes(T),v=r.fromBytes(xe(xs((I&1)===0),R)),O=i.inv(T),P=se(U(h,void 0,"msgHash")),W=i.create(-P*O),M=i.create(S*O),N=r.BASE.multiplyUnsafe(W).add(v.multiplyUnsafe(M));if(N.is0())throw new Error("invalid recovery: point at infinify");return N.assertValidity(),N}hasHighS(){return E(this.s)}toBytes(h=x.format){if(rt(h),h==="der")return Ue(pe.hexFromSig(this));const{r:y,s:S}=this,I=i.toBytes(y),T=i.toBytes(S);return h==="recovered"?(q(),xe(Uint8Array.of(this.assertRecovery()),I,T)):xe(I,T)}toHex(h){return Ce(this.toBytes(h))}}const F=s.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");const y=je(h),S=h.length*8-c;return S>0?y>>BigInt(S):y},se=s.bits2int_modN||function(h){return i.create(F(h))},be=lt(c);function he(u){return pr("num < 2^"+c,u,ae,be),i.toBytes(u)}function Y(u,h){return U(u,void 0,"message"),h?U(e(u),void 0,"prehashed message"):u}function _e(u,h,y){const{lowS:S,prehash:I,extraEntropy:T}=et(y,x);u=Y(u,I);const R=se(u),v=i.fromBytes(h);if(!i.isValidNot0(v))throw new Error("invalid private key");const O=[he(v),he(R)];if(T!=null&&T!==!1){const N=T===!0?t(m.secretKey):T;O.push(U(N,void 0,"extraEntropy"))}const P=xe(...O),W=R;function M(N){const j=F(N);if(!i.isValidNot0(j))return;const V=i.inv(j),J=r.BASE.multiply(j).toAffine(),H=i.create(J.x);if(H===ae)return;const K=i.create(V*i.create(W+H*v));if(K===ae)return;let xt=(J.x===H?0:2)|Number(J.y&Ee),_t=K;return S&&E(K)&&(_t=i.neg(K),xt^=1),new B(H,_t,A?void 0:xt)}return{seed:P,k2sig:M}}function ne(u,h,y={}){const{seed:S,k2sig:I}=_e(u,h,y);return _r(e.outputLen,i.BYTES,n)(S,I).toBytes(y.format)}function L(u,h,y,S={}){const{lowS:I,prehash:T,format:R}=et(S,x);if(y=U(y,void 0,"publicKey"),h=Y(h,T),!it(u)){const v=u instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+v)}$(u,R);try{const v=B.fromBytes(u,R),O=r.fromBytes(y);if(I&&v.hasHighS())return!1;const{r:P,s:W}=v,M=se(h),N=i.inv(W),j=i.create(M*N),V=i.create(P*N),J=r.BASE.multiplyUnsafe(j).add(O.multiplyUnsafe(V));return J.is0()?!1:i.create(J.x)===P}catch{return!1}}function k(u,h,y={}){const{prehash:S}=et(y,x);return h=Y(h,S),B.fromBytes(u,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:g,utils:w,lengths:m,Point:r,sign:ne,verify:L,recoverPublicKey:k,Signature:B,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ht={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Fr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Bt=BigInt(2);function Ur(r){const e=ht.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,g=ee(d,s,e)*d%e,w=ee(g,s,e)*d%e,m=ee(w,Bt,e)*l%e,x=ee(m,n,e)*m%e,A=ee(x,o,e)*x%e,E=ee(A,a,e)*A%e,C=ee(E,c,e)*E%e,q=ee(C,a,e)*A%e,$=ee(q,s,e)*d%e,B=ee($,i,e)*x%e,F=ee(B,t,e)*l%e,se=ee(F,Bt,e);if(!nt.eql(nt.sqr(se),r))throw new Error("Cannot find square root");return se}const nt=Ve(ht.p,{sqrt:Ur}),Hr=$r(ht,{Fp:nt,endo:Fr}),Gr=Mr(Hr,hr),qr=BigInt(0),Re=BigInt(1),Wr=BigInt(2),jr=BigInt(7),Vr=BigInt(256),Kr=BigInt(113),ms=[],ws=[],ys=[];for(let r=0,e=Re,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],ms.push(2*(5*t+s)),ws.push((r+1)*(r+2)/2%64);let n=qr;for(let o=0;o<7;o++)e=(e<<Re^(e>>jr)*Kr)%Vr,e&Wr&&(n^=Re<<(Re<<BigInt(o))-Re);ys.push(n)}const bs=nr(ys,!0),zr=bs[0],Yr=bs[1],Mt=(r,e,s)=>s>32?ar(r,e,s):or(r,e,s),Ft=(r,e,s)=>s>32?cr(r,e,s):ir(r,e,s);function Zr(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)s[i]=r[i]^r[i+10]^r[i+20]^r[i+30]^r[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=s[c],d=s[c+1],g=Mt(l,d,1)^s[a],w=Ft(l,d,1)^s[a+1];for(let m=0;m<50;m+=10)r[i+m]^=g,r[i+m+1]^=w}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=ws[i],c=Mt(n,o,a),l=Ft(n,o,a),d=ms[i];n=r[d],o=r[d+1],r[d]=c,r[d+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=zr[t],r[1]^=Yr[t]}Ae(s)}class ft{constructor(e,s,t,n=!1,o=24){b(this,"state");b(this,"pos",0);b(this,"posOut",0);b(this,"finished",!1);b(this,"state32");b(this,"destroyed",!1);b(this,"blockLen");b(this,"suffix");b(this,"outputLen");b(this,"enableXOF",!1);b(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,le(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=zs(this.state)}clone(){return this._cloneInto()}keccak(){At(this.state32),Zr(this.state32,this.rounds),At(this.state32),this.posOut=0,this.pos=0}update(e){Te(this),U(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Te(this,!1),U(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return le(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Kt(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ae(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new ft(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const Xr=(r,e,s,t={})=>Yt(()=>new ft(e,r,s),t),Ut=Xr(1,136,32);class Jr{async verifyJWT(e,s){try{const t=this.decodeJWT(e);f.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const n=Math.floor(Date.now()/1e3);return t.exp&&t.exp<n?(f.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(f.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(f.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw f.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return As.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
2
+ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);const i=Ut(o),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`Invalid signature length: expected 130 hex chars, got ${a.length}`);const c=Qr(a),l=c.slice(0,32),d=c.slice(32,64),g=c[64],w=g>=27?g-27:g,A=new Gr.Signature(Ht(l),Ht(d)).addRecoveryBit(w).recoverPublicKey(i).toBytes(!1).slice(1),E=Ut(A);return"0x"+Ce(E.slice(12))}}function Qr(r){const e=new Uint8Array(r.length/2);for(let s=0;s<e.length;s++)e[s]=parseInt(r.substring(s*2,s*2+2),16);return e}function Ht(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const en=3e4;class tn{async request(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??en);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}class gt{static generateState(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}openAuth(e){return new Promise((s,t)=>{const n=e.width??500,o=e.height??600,i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=gt.generateState(),l=e.authUrl.includes("?")?"&":"?",d=`${e.authUrl}${l}state=${c}`,g=window.open(d,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const w=setTimeout(()=>{f.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),$(),t(new Error("Authentication timeout"))},5*60*1e3),m=10,x=30;let A=0,E=null;const C=()=>{clearInterval(q),f.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+x+"초간 대기합니다"),E=setTimeout(()=>{$(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},x*1e3)},q=setInterval(()=>{A++;try{g.closed&&(A<=m?C():($(),t(new Error("로그인이 취소되었습니다"))))}catch{C()}},1e3),$=()=>{clearTimeout(w),clearInterval(q),E&&clearTimeout(E),window.removeEventListener("message",B)},B=F=>{var be,he,Y,_e,ne,L,k;if(F.origin!==e.expectedOrigin)return;$(),f.log("[CROSSx] OAuth postMessage 수신 — status:",F.data.status);const se=F.data.state??((be=F.data.data)==null?void 0:be.state);if(!se||se!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(F.data.status==="success"){const u=((he=F.data.data)==null?void 0:he.accessToken)||((Y=F.data.data)==null?void 0:Y.idToken);f.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!((_e=F.data.data)!=null&&_e.accessToken),hasIdToken:!!((ne=F.data.data)!=null&&ne.idToken)}),u?s(u):(f.error("[CROSSx] 토큰을 찾을 수 없음:",F.data),t(new Error("Token not found in response")))}else f.error("[CROSSx] OAuth 실패:",(L=F.data.data)==null?void 0:L.error),t(new Error(((k=F.data.data)==null?void 0:k.error)||"Authentication failed"))};window.addEventListener("message",B)})}}const Be="crossx_wallet_data";class sn{constructor(e){this.storage=e}async getOrCreateWallet(e){try{const s=await this.storage.get(Be);if(s)return s;const t={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};return await this.storage.set(Be,t),t}catch(s){throw new _(p.WALLET_CREATION_FAILED,"Wallet creation failed",s)}}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return f.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,s,t,n=0,o,i){return f.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return f.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){f.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,format:"hex"}}async sendTransaction(e,s,t,n){return f.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async recoverWallet(e,s){f.log("[Mock] recoverWallet");const t={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};return await this.storage.set(Be,t),t}async migrateWallet(e,s){f.log(`[Mock] migrateWallet pin=${e} sub=${s}`);const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};return await this.storage.set(Be,t),t}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class qe{constructor(e,s,t,n){this.baseUrl=e.gatewayUrl,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n}getAuthToken(){const e=this.tokenStore.get();if(!e)throw new _(p.AUTH_NOT_AUTHENTICATED,"No auth token found. Please sign in first.");return e}async request(e,s,t){var a,c;const n=this.getAuthToken(),o=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const g=d.message||d.data||"API request failed";f.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:g,url:o,method:e,fullResponse:d});const w=qe.mapGatewayError(d.code),m=qe.getGatewayErrorMessage(d.code,g),x=new _(w,m);throw x.gatewayCode=d.code,x.gatewayMessage=g,x}return f.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:o,method:e}),d.data??d}return d}catch(l){if(l instanceof _)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,g=d.message||d.data||"API request failed",w=d.code||"UNKNOWN";throw f.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:w,message:g,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new _(p.UNKNOWN_ERROR,`Wallet Gateway error (${w}): ${g}`)}throw l}}async getOrCreateWallet(e){var s;f.log("[CROSSx][Migration Phase 2] GET /mnemonic/addresses — 기존 지갑 조회");try{const t=await this.request("GET","/mnemonic/addresses");if(t.addresses&&t.addresses.length>0){const{address:n}=t.addresses[0];return f.log("[CROSSx][Migration Phase 2] 기존 지갑 발견 — address:",n),{id:e,address:n,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}}catch{f.log("[CROSSx][Migration Phase 2] 기존 지갑 없음, POST /mnemonic/create 진행")}f.log("[CROSSx][Migration Phase 2] POST /mnemonic/create — ignoreBackup: false");try{const t={ignoreBackup:!1},n=await this.request("POST","/mnemonic/create",t);return f.log("[CROSSx][Migration Phase 2] /mnemonic/create 성공 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}catch(t){if((t==null?void 0:t.gatewayCode)===-10004||(s=t==null?void 0:t.message)!=null&&s.includes("-10004")){f.log("[CROSSx][Migration Phase 2] 지갑 이미 존재 (-10004), 주소 재조회");const n=await this.request("GET","/mnemonic/addresses");if(n.addresses&&n.addresses.length>0)return{id:e,address:n.addresses[0].address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}throw(t==null?void 0:t.gatewayCode)===-10012&&f.log("[CROSSx][Migration Phase 2] Gateway -10012 수신 → MIGRATION_BACKUP_EXISTS throw"),t}}async getAddress(e,s){try{return{address:(await this.request("GET",`/mnemonic/address?index=${s}`)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}catch(t){if(t instanceof _&&this.isAddressNotFoundError(t))return f.log(`[CROSSx] index ${s} 주소 없음, 파생 중...`),{address:(await this.request("GET",`/mnemonic/address?index=${s}&derive=true`)).address,derivationPath:`m/44'/60'/0'/0/${s}`};throw t}}isAddressNotFoundError(e){const s=e.message.toLowerCase();return s.includes("404")||s.includes("not found")||s.includes("찾을 수 없")||s.includes("does not exist")||s.includes("no address")}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new _(p.TX_INVALID_PARAMS,"prepare: tx is required");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new _(p.TX_INVALID_PARAMS,"prepare: message is required");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new _(p.TX_INVALID_PARAMS,"prepare: typedData is required");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t)};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t)};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).txHash}}async recoverWallet(e,s){const t={shareC:s},n=await this.request("POST","/mnemonic/recover",t);return{id:e,address:n.address,newShareC:n.newShareC,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async migrateWallet(e,s){f.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출 — sub:",s);const t={pin:e,sub:s},n=await this.request("POST","/mnemonic/migrate",t);return f.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}static mapGatewayError(e){switch(e){case-10002:return p.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10006:return"Internal server error. Please try again later.";case-10008:return"Another operation is in progress. Please try again later.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin is not in the allowed list. Register the current domain in the management console.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";default:return`Request failed (${e}): ${s}`}}}class Oe{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.baseUrl=e.gatewayUrl,this.projectId=e.projectId,this.transport=s}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=Oe.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?qs:Gs;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"Chain registry request failed";throw new _(Oe.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Oe.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new _(p.CHAIN_NOT_SUPPORTED,`Unsupported chain: ${e}`)}static fallbackChains(){return Object.values(We).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.APP_IDENTIFIER_MISSING;case-10025:return p.INVALID_APP_TYPE;default:return p.UNKNOWN_ERROR}}}const Gt="__crossx-confirm-style",te="__crossx-confirm-overlay",rn={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"#FFFFFF",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"#121212",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",onPrimary:"#FFFFFF"}};function qt(r,e){const s=rn[r],t=e==null?void 0:e[r];return t?{...s,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault},...t.bg!==void 0&&{bg:t.bg,inputBg:t.bg}}:s}const nn=`
2
3
  @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
3
4
 
4
5
  #${te} {
@@ -504,116 +505,61 @@
504
505
  .__crossx-confirm-btn:hover { opacity: 0.9; }
505
506
  .__crossx-confirm-btn:active { transform: scale(0.98); }
506
507
 
507
- /* ── Transaction Complete Modal ────────────────────────────── */
508
- .__crossx-complete-body {
509
- padding: 32px 24px 24px;
510
- display: flex;
511
- flex-direction: column;
512
- align-items: center;
513
- gap: 20px;
514
- }
515
- .__crossx-check-wrap {
516
- width: 72px;
517
- height: 72px;
518
- border-radius: 50%;
519
- background: var(--cx-primary);
520
- display: flex;
521
- align-items: center;
522
- justify-content: center;
523
- flex-shrink: 0;
524
- animation: __crossx-pop-in 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
525
- }
526
- @keyframes __crossx-pop-in {
527
- from { transform: scale(0.5); opacity: 0; }
528
- to { transform: scale(1); opacity: 1; }
508
+ /* ── Transaction Progress / Complete Modal ─────────────────── */
509
+ @keyframes __crossx-spinner {
510
+ to { transform: rotate(360deg); }
529
511
  }
530
- .__crossx-complete-texts {
512
+ .__crossx-progress-center {
531
513
  display: flex;
532
514
  flex-direction: column;
533
515
  align-items: center;
534
- gap: 6px;
535
- text-align: center;
516
+ justify-content: center;
517
+ gap: 16px;
518
+ padding: 24px 0;
519
+ min-height: 280px;
536
520
  }
537
- .__crossx-complete-title {
538
- font-size: 22px;
539
- font-weight: 700;
540
- line-height: 1.3;
541
- color: var(--cx-title);
542
- margin: 0;
543
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
521
+ .__crossx-spinner {
522
+ width: 48px;
523
+ height: 48px;
524
+ border: 4px solid var(--cx-border);
525
+ border-top-color: var(--cx-primary);
526
+ border-radius: 50%;
527
+ animation: __crossx-spinner 0.8s linear infinite;
544
528
  }
545
- .__crossx-complete-subtitle {
529
+ .__crossx-progress-text {
546
530
  font-size: 14px;
547
531
  font-weight: 400;
548
- line-height: 1.5;
549
- color: var(--cx-subtitle);
532
+ line-height: 1.4;
533
+ color: var(--cx-label);
534
+ text-align: center;
550
535
  margin: 0;
551
536
  }
552
- .__crossx-complete-rows {
553
- width: 100%;
554
- display: flex;
555
- flex-direction: column;
556
- gap: 4px;
557
- }
558
- .__crossx-complete-amount {
559
- width: 100%;
537
+ .__crossx-total-pill {
560
538
  background: var(--cx-pill-bg);
561
539
  border-radius: 12px;
562
540
  padding: 16px;
563
- font-size: 20px;
564
- font-weight: 700;
565
- line-height: 1.3;
566
- color: var(--cx-title);
567
- text-align: center;
568
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
569
- }
570
- .__crossx-complete-btn-col {
571
541
  display: flex;
572
- flex-direction: column;
542
+ align-items: center;
543
+ justify-content: space-between;
573
544
  gap: 8px;
574
- width: 100%;
575
545
  }
576
- .__crossx-explorer-btn {
577
- width: 100%;
578
- padding: 16px;
579
- border: 1px solid var(--cx-primary);
580
- border-radius: 12px;
581
- background: none;
582
- color: var(--cx-primary);
583
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
584
- font-size: 18px;
585
- font-weight: 700;
586
- line-height: 1.3;
587
- cursor: pointer;
588
- text-decoration: none;
589
- display: flex;
590
- align-items: center;
591
- justify-content: center;
592
- gap: 6px;
593
- transition: opacity 0.12s;
594
- box-sizing: border-box;
595
- appearance: none;
596
- -webkit-appearance: none;
546
+ .__crossx-total-label {
547
+ font-size: 14px;
548
+ font-weight: 600;
549
+ line-height: 1.4;
550
+ color: var(--cx-pill-from);
551
+ font-family: 'Sora', 'Pretendard', -apple-system, sans-serif;
597
552
  }
598
- .__crossx-explorer-btn:hover { opacity: 0.8; }
599
- .__crossx-done-btn {
600
- width: 100%;
601
- padding: 16px;
602
- border: 1px solid rgba(18,18,18,0.05);
603
- border-radius: 12px;
604
- background: var(--cx-primary);
605
- color: var(--cx-on-primary);
606
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
607
- font-size: 18px;
608
- font-weight: 700;
553
+ .__crossx-total-amount {
554
+ font-size: 16px;
555
+ font-weight: 600;
609
556
  line-height: 1.3;
610
- cursor: pointer;
611
- transition: opacity 0.12s, transform 0.1s;
612
- appearance: none;
613
- -webkit-appearance: none;
557
+ color: var(--cx-pill-amt);
558
+ text-align: right;
559
+ white-space: nowrap;
560
+ flex-shrink: 0;
561
+ font-family: 'Sora', 'Pretendard', -apple-system, sans-serif;
614
562
  }
615
- .__crossx-done-btn:hover { opacity: 0.9; }
616
- .__crossx-done-btn:active { transform: scale(0.98); }
617
563
 
618
564
  /* ── Login Selector Modal ──────────────────────────────────── */
619
565
  .__crossx-login-btn-row {
@@ -677,6 +623,16 @@
677
623
  color: var(--cx-primary);
678
624
  text-decoration: none;
679
625
  }
626
+ .__crossx-login-terms-link:hover,
627
+ .__crossx-login-terms-link:focus {
628
+ color: var(--cx-primary);
629
+ text-decoration: none;
630
+ opacity: 1;
631
+ background: none;
632
+ box-shadow: none;
633
+ outline: none;
634
+ filter: none;
635
+ }
680
636
 
681
637
  /* ── Mobile bottom sheet ───────────────────────────────────── */
682
638
  @media (max-width: 480px) {
@@ -701,208 +657,313 @@
701
657
  from { transform: translateY(100%); }
702
658
  to { transform: translateY(0); }
703
659
  }
704
- `;function Se(){let s=document.getElementById(ht);s||(s=document.createElement("style"),s.id=ht,document.head.appendChild(s)),s.textContent=pr}function he(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function xr(s,e="CROSS",r=18){if(!s||s==="0x"||s==="0x0")return null;try{const t=BigInt(s);if(t===0n)return null;const n=10**r,o=Number(t)/n;return o===0?null:`${o.toPrecision(6).replace(/\.?0+$/,"")} ${e}`}catch{return null}}const gt={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",612044:"CROSS Testnet",612055:"CROSS Mainnet"},_r={1:"https://etherscan.io",5:"https://goerli.etherscan.io",11155111:"https://sepolia.etherscan.io",17e3:"https://holesky.etherscan.io",10:"https://optimistic.etherscan.io",420:"https://goerli-optimism.etherscan.io",42161:"https://arbiscan.io",421614:"https://sepolia.arbiscan.io",8453:"https://basescan.org",84532:"https://sepolia.basescan.org",137:"https://polygonscan.com",80002:"https://amoy.polygonscan.com",56:"https://bscscan.com",97:"https://testnet.bscscan.com",43114:"https://snowtrace.io",43113:"https://testnet.snowtrace.io",612044:"https://explorer-testnet.crossx.ai",612055:"https://explorer.crossx.ai"};function mr(s,e){const r=parseInt(s.split(":")[1]??"",10),t=isNaN(r)?void 0:_r[r];return t?`${t}/tx/${e}`:null}function Qe(s){const e=parseInt(s.split(":")[1]??"",10);return!isNaN(e)&&gt[e]?gt[e]:s}function pt(s,e){if(s===0n)return"0";const r=10n**BigInt(e),t=s/r,i=(s%r).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function Lt(s){const{gasLimit:e,gasPrice:r,maxFeePerGas:t,nativeSymbol:n="ETH",nativeDecimals:o=18}=s;if(!e)return"—";try{const i=BigInt(e);if(t){const a=i*BigInt(t);return`${pt(a,o)} ${n}`}if(r){const a=i*BigInt(r);return`${pt(a,o)} ${n}`}return`${i.toLocaleString()} gas`}catch{return e}}const Ie=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
660
+
661
+ /* ── 2-column wrapper (portrait: column, landscape: row) ── */
662
+ .__crossx-body-cols {
663
+ display: flex;
664
+ flex-direction: column;
665
+ gap: 16px;
666
+ width: 100%;
667
+ }
668
+ .__crossx-col-left {
669
+ display: flex;
670
+ flex-direction: column;
671
+ gap: 16px;
672
+ }
673
+ .__crossx-divider--cols { flex-shrink: 0; }
674
+
675
+ /* ── Landscape for signing/transaction modals ──────────── */
676
+ @media (orientation: landscape) and (max-height: 500px) {
677
+ #${te} { align-items: center !important; }
678
+ .__crossx-card--send-tx,
679
+ .__crossx-card--sign-tx,
680
+ .__crossx-card--sign-msg,
681
+ .__crossx-card--sign-typed {
682
+ width: 600px;
683
+ max-width: calc(100vw - 32px);
684
+ border-radius: 24px;
685
+ border-bottom: 4px solid var(--cx-border);
686
+ max-height: calc(100vh - 32px);
687
+ overflow-y: auto;
688
+ animation: __crossx-slide-up 0.18s ease;
689
+ }
690
+ .__crossx-card--send-tx .__crossx-header,
691
+ .__crossx-card--sign-tx .__crossx-header,
692
+ .__crossx-card--sign-msg .__crossx-header,
693
+ .__crossx-card--sign-typed .__crossx-header {
694
+ padding: 16px 24px 12px;
695
+ }
696
+ .__crossx-card--send-tx .__crossx-body,
697
+ .__crossx-card--sign-tx .__crossx-body,
698
+ .__crossx-card--sign-msg .__crossx-body,
699
+ .__crossx-card--sign-typed .__crossx-body {
700
+ padding: 16px 24px 20px;
701
+ gap: 12px;
702
+ }
703
+ .__crossx-card--send-tx .__crossx-body-cols,
704
+ .__crossx-card--sign-tx .__crossx-body-cols,
705
+ .__crossx-card--sign-msg .__crossx-body-cols,
706
+ .__crossx-card--sign-typed .__crossx-body-cols {
707
+ flex-direction: row;
708
+ gap: 24px;
709
+ align-items: flex-start;
710
+ }
711
+ .__crossx-body-cols > * { flex: 1; min-width: 0; }
712
+ .__crossx-col-left { gap: 8px; }
713
+ .__crossx-divider--cols { display: none; }
714
+ .__crossx-card--send-tx .__crossx-pill {
715
+ flex-direction: column;
716
+ align-items: flex-end;
717
+ }
718
+ .__crossx-card--sign-tx .__crossx-raw-tx { max-height: 120px; }
719
+ .__crossx-card--sign-msg .__crossx-msg-raw,
720
+ .__crossx-card--sign-msg .__crossx-msg-box { max-height: 130px; }
721
+ .__crossx-card--sign-typed .__crossx-td-rows { max-height: 130px; overflow-y: auto; }
722
+ .__crossx-col-left > .__crossx-divider { display: none; }
723
+ }
724
+ `;function Se(){let r=document.getElementById(Gt);r||(r=document.createElement("style"),r.id=Gt,document.head.appendChild(r)),r.textContent=nn}function Q(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function on(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const n=ot(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Wt={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function vs(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Wt[e]?Wt[e]:r}function ot(r,e){if(r===0n)return"0";const s=10n**BigInt(e),t=r/s,i=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function tt(r){try{const e=BigInt(r),s=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${s}.${n}`:`${s}`}catch{return r}}function an(r){try{return BigInt(r).toLocaleString()}catch{return r}}function cn(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:o="ETH",nativeDecimals:i=18}=r;if(!e)return null;try{const a=BigInt(e),c=an(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${ot(l,i)} ${o}`,maxFeeGwei:tt(t),maxPriorityFeeGwei:n?tt(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${ot(l,i)} ${o}`,gasPriceGwei:tt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Ss(r){const e=cn(r);if(!e)return G("Estimated fee","<span>—</span>");let s=G("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=G("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=G("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=G("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=G("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}const ce=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
705
725
  <rect x="9" y="9" width="13" height="13" rx="2"/>
706
726
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
707
- </svg>`,fe=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
727
+ </svg>`,de=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
708
728
  <line x1="18" y1="6" x2="6" y2="18"/>
709
729
  <line x1="6" y1="6" x2="18" y2="18"/>
710
- </svg>`;function wr(s){return`<svg width="28" height="28" viewBox="0 0 28 28" fill="none">
711
- <circle cx="14" cy="14" r="14" fill="${s}"/>
730
+ </svg>`;function ln(r){return`<svg width="28" height="28" viewBox="0 0 28 28" fill="none">
731
+ <circle cx="14" cy="14" r="14" fill="${r}"/>
712
732
  <path d="M14 7.5L19.2 10.5V16.5L14 19.5L8.8 16.5V10.5L14 7.5Z" fill="white" opacity="0.9"/>
713
- </svg>`}const et=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
733
+ </svg>`}const pt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
714
734
  <rect x="2" y="5" width="16" height="12" rx="2" stroke="currentColor" stroke-width="1.5"/>
715
735
  <path d="M2 9h16" stroke="currentColor" stroke-width="1.5"/>
716
736
  <rect x="12.5" y="11.5" width="3.5" height="2.5" rx="0.75" fill="currentColor"/>
717
- </svg>`;function ge(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-title:${s.titleColor}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-secondary:${s.secondary}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function oe(s,e){return`
737
+ </svg>`,dn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
738
+ <path d="M12 0C18.6274 0 24 5.37258 24 12C23.9999 18.6273 18.6274 24 12 24C5.37264 24 9.89594e-05 18.6273 0 12C0 5.37258 5.37258 0 12 0ZM10.875 15.127V17.377H13.125V15.127H10.875ZM10.875 6.62207V13.627H13.125V6.62207H10.875Z" fill="var(--cx-secondary)"/>
739
+ </svg>`,un=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
740
+ <circle cx="12" cy="12" r="12" fill="var(--cx-secondary)"/>
741
+ <circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
742
+ <path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
743
+ </svg>`;function ue(r){return[`--cx-bg:${r.bg}`,`--cx-border:${r.border}`,`--cx-title:${r.titleColor}`,`--cx-subtitle:${r.subtitleColor}`,`--cx-label:${r.labelColor}`,`--cx-value:${r.valueColor}`,`--cx-pill-bg:${r.pillBg}`,`--cx-pill-from:${r.pillFromColor}`,`--cx-pill-amt:${r.pillAmtColor}`,`--cx-divider:${r.divider}`,`--cx-close:${r.closeColor}`,`--cx-close-hover:${r.closeHoverBg}`,`--cx-copy:${r.copyColor}`,`--cx-input-bg:${r.inputBg}`,`--cx-input-border:${r.inputBorder}`,`--cx-hint:${r.hintColor}`,`--cx-primary:${r.primary}`,`--cx-primary-glow:${r.primaryGlow}`,`--cx-secondary:${r.secondary}`,`--cx-on-primary:${r.onPrimary}`].join(";")}function G(r,e){return`
718
744
  <div class="__crossx-row">
719
- <span class="__crossx-row-label">${s}</span>
745
+ <span class="__crossx-row-label">${r}</span>
720
746
  <div class="__crossx-row-value">${e}</div>
721
- </div>`}function yr(s,e){const r=e,t=Fe(),n=s.to?`<span class="__crossx-addr-text">${he(s.to)}</span>
722
- <button class="__crossx-copy-btn" data-copy="${s.to}" title="Copy address">${Ie}</button>`:"<span>—</span>",o=`<span>${Lt(s)}</span>`,i=s.data&&s.data!=="0x"?s.data:"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
723
- <div class="__crossx-card __crossx-card--migration" style="${ge(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
747
+ </div>`}function hn(r,e){const s=e,t=Ke(),n=r.to?`<span class="__crossx-addr-text">${Q(r.to)}</span>
748
+ <button class="__crossx-copy-btn" data-copy="${D(r.to)}" title="Copy address">${ce}</button>`:"<span>—</span>",o=Ss(r),i=r.data&&r.data!=="0x"?r.data:"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
749
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
724
750
  <div class="__crossx-header">
725
751
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
726
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${fe}</button>
752
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
727
753
  </div>
728
754
  <hr class="__crossx-divider">
729
755
  <div class="__crossx-body">
730
- <p class="__crossx-sig-subtitle">
731
- <span class="__crossx-sig-origin">${X(t)} </span>is requesting a Signature
732
- </p>
733
- <div class="__crossx-addr-pill">
734
- ${et}
735
- <span class="__crossx-addr-pill-text">${he(s.from)}</span>
756
+ <div class="__crossx-body-cols">
757
+ <div class="__crossx-col-left">
758
+ <p class="__crossx-sig-subtitle">
759
+ <span class="__crossx-sig-origin">${D(t)} </span>is requesting a Signature
760
+ </p>
761
+ <div class="__crossx-addr-pill">
762
+ ${pt}
763
+ <span class="__crossx-addr-pill-text">${Q(r.from)}</span>
764
+ </div>
765
+ <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
766
+ <hr class="__crossx-divider">
767
+ <div class="__crossx-rows">
768
+ ${G("To",n)}
769
+ ${G("Network",`<span>${vs(r.chainId)}</span>`)}
770
+ ${o}
771
+ </div>
772
+ </div>
773
+ <pre class="__crossx-raw-tx">${D(i)}</pre>
736
774
  </div>
737
- <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
738
- <hr class="__crossx-divider">
739
- <div class="__crossx-rows">
740
- ${oe("To",n)}
741
- ${oe("Network",`<span>${Qe(s.chainId)}</span>`)}
742
- ${oe("Estimated fee",o)}
743
- </div>
744
- <pre class="__crossx-raw-tx">${X(i)}</pre>
745
775
  <div class="__crossx-btn-row">
746
776
  <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">Cancel</button>
747
777
  <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">Sign</button>
748
778
  </div>
749
779
  </div>
750
780
  </div>
751
- `,a}function br(s,e){const r=e,t=s.nativeSymbol??"ETH",n=s.nativeDecimals??18,o=Fe(),i=s.to?`<span class="__crossx-addr-text">${he(s.to)}</span>
752
- <button class="__crossx-copy-btn" data-copy="${s.to}" title="Copy address">${Ie}</button>`:"<span>—</span>",a=`<span>${Lt(s)}</span>`,l=xr(s.value,t,n)??(s.data&&s.data!=="0x"?"Contract Call":`0 ${t}`),d=document.createElement("div");return d.id=te,d.innerHTML=`
753
- <div class="__crossx-card __crossx-card--migration" style="${ge(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
781
+ `,a}function fn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=Ke(),i=r.to?`<span class="__crossx-addr-text">${Q(r.to)}</span>
782
+ <button class="__crossx-copy-btn" data-copy="${D(r.to)}" title="Copy address">${ce}</button>`:"<span>—</span>",a=Ss(r),l=on(r.value,t,n)??"",d=document.createElement("div");return d.id=te,d.innerHTML=`
783
+ <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
754
784
  <div class="__crossx-header">
755
785
  <p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
756
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${fe}</button>
786
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
757
787
  </div>
758
788
  <hr class="__crossx-divider">
759
789
  <div class="__crossx-body">
760
790
  <p class="__crossx-tx-subtitle">
761
- <span class="__crossx-sig-origin">${X(o)}</span> wants your permission to approve the following transaction.
791
+ <span class="__crossx-sig-origin">${D(o)}</span> wants your permission to approve the following transaction.
762
792
  </p>
763
- <div class="__crossx-rows">
764
- ${oe("To",i)}
765
- ${oe("Network",`<span>${Qe(s.chainId)}</span>`)}
766
- ${oe("Estimated fee",a)}
767
- </div>
768
- <div class="__crossx-pill">
769
- <span class="__crossx-pill-from">${he(s.from)}</span>
770
- <span class="__crossx-pill-amount">${l}</span>
793
+ <div class="__crossx-body-cols">
794
+ <div class="__crossx-rows">
795
+ ${G("To",i)}
796
+ ${G("Network",`<span>${vs(r.chainId)}</span>`)}
797
+ ${a}
798
+ </div>
799
+ <div class="__crossx-pill">
800
+ <span class="__crossx-pill-from">${Q(r.from)}</span>
801
+ <span class="__crossx-pill-amount">${l}</span>
802
+ </div>
771
803
  </div>
772
804
  <button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
773
805
  </div>
774
806
  </div>
775
- `,d}function Fe(){var s;try{return((s=window.location)==null?void 0:s.hostname)||"This site"}catch{return"This site"}}function X(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function vr(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function Er(s){if(typeof s=="string")return X(s);if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);try{return X(JSON.stringify(s))}catch{return String(s)}}const Sr=`<svg width="36" height="36" viewBox="0 0 36 36" fill="none">
776
- <path d="M8 18L15 25L28 11" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
777
- </svg>`,Tr=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
778
- <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
779
- <polyline points="15 3 21 3 21 9"/>
780
- <line x1="10" y1="14" x2="21" y2="3"/>
781
- </svg>`;function Ir(s,e){const r=mr(s.chainId,s.txHash),t=Qe(s.chainId),n=`${s.txHash.slice(0,10)}…${s.txHash.slice(-8)}`,o=r?`<a class="__crossx-explorer-btn" id="__crossx-explorer-btn" href="${r}" target="_blank" rel="noopener noreferrer">
782
- ${Tr} View on Explorer
783
- </a>`:"",i=s.amount?`<div class="__crossx-complete-amount">${X(s.amount)}</div>`:"",a=s.to?oe("To",`<span class="__crossx-addr-text">${he(s.to)}</span>
784
- <button class="__crossx-copy-btn" data-copy="${s.to}" title="Copy address">${Ie}</button>`):"",c=document.createElement("div");return c.id=te,c.innerHTML=`
785
- <div class="__crossx-card __crossx-card--migration" style="${ge(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
807
+ `,d}function Ke(){var r;try{return((r=window.location)==null?void 0:r.hostname)||"This site"}catch{return"This site"}}function D(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function gn(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function pn(r){if(typeof r=="string")return D(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return D(JSON.stringify(r))}catch{return String(r)}}function xn(r,e){const s=G("From",`<span class="__crossx-addr-text">${Q(r.from)}</span>
808
+ <button class="__crossx-copy-btn" data-copy="${D(r.from)}" title="Copy address">${ce}</button>`),t=r.to?G("To",`<span class="__crossx-addr-text">${Q(r.to)}</span>
809
+ <button class="__crossx-copy-btn" data-copy="${D(r.to)}" title="Copy address">${ce}</button>`):"",n=r.amount?G("Transfer",`<span>${D(r.amount)}</span>`):"",o=r.fees?G("Tx Fee",`<span>${D(r.fees)}</span>`):"",i=r.txHash?G("Tx Hash",`<span class="__crossx-addr-text">${Q(r.txHash)}</span>
810
+ <button class="__crossx-copy-btn" data-copy="${D(r.txHash)}" title="Copy hash">${ce}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
811
+ <span class="__crossx-total-label">Total<br>(including fees)</span>
812
+ <span class="__crossx-total-amount">${D(r.total)}</span>
813
+ </div>`:"",c=document.createElement("div");return c.id=te,c.innerHTML=`
814
+ <div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
786
815
  <div class="__crossx-header">
787
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${fe}</button>
816
+ <p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
817
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
788
818
  </div>
789
- <div class="__crossx-complete-body">
790
- <div class="__crossx-check-wrap">${Sr}</div>
791
- <div class="__crossx-complete-texts">
792
- <p class="__crossx-complete-title" id="__crossx-ttl">Transaction Sent</p>
793
- <p class="__crossx-complete-subtitle">Your transaction has been submitted to the network.</p>
794
- </div>
795
- ${i}
796
- <div class="__crossx-complete-rows">
797
- ${a}
798
- ${oe("Network",`<span>${X(t)}</span>`)}
799
- ${oe("Tx Hash",`<span class="__crossx-addr-text">${X(n)}</span>
800
- <button class="__crossx-copy-btn" data-copy="${s.txHash}" title="Copy tx hash">${Ie}</button>`)}
801
- </div>
802
- <div class="__crossx-complete-btn-col">
819
+ <hr class="__crossx-divider">
820
+ <div class="__crossx-body">
821
+ <div class="__crossx-rows">
822
+ ${s}
823
+ ${t}
824
+ ${n}
803
825
  ${o}
804
- <button class="__crossx-done-btn" id="__crossx-done-btn">Done</button>
826
+ ${i}
805
827
  </div>
828
+ ${a}
829
+ <button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
806
830
  </div>
807
831
  </div>
808
- `,c}function Ar(s,e){const r=e,t=Fe(),n=X(s.message),o=document.createElement("div");return o.id=te,o.innerHTML=`
809
- <div class="__crossx-card __crossx-card--migration" style="${ge(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
832
+ `,c}function _n(r,e){const s=document.createElement("div");return s.id=te,s.innerHTML=`
833
+ <div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
834
+ <div class="__crossx-header">
835
+ <p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
836
+ </div>
837
+ <hr class="__crossx-divider">
838
+ <div class="__crossx-body" id="__crossx-progress-body">
839
+ <div class="__crossx-progress-center">
840
+ <div class="__crossx-spinner"></div>
841
+ <p class="__crossx-progress-text">Waiting for transaction receipt...</p>
842
+ </div>
843
+ </div>
844
+ </div>
845
+ `,s}function mn(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",o=r.querySelector("#__crossx-ttl"),i=r.querySelector(".__crossx-header");if(o){const x=n?un:t?"":dn,A=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";x?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${x}<span>${A}</span>`):o.textContent=A}if(i&&!r.querySelector("#__crossx-close-btn")){const x=document.createElement("button");x.className="__crossx-close",x.id="__crossx-close-btn",x.setAttribute("aria-label","Close"),x.innerHTML=de,i.appendChild(x)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?G("From",`<span class="__crossx-addr-text">${Q(e.from)}</span>
846
+ <button class="__crossx-copy-btn" data-copy="${D(e.from)}" title="Copy address">${ce}</button>`):"",l=e.to?G("To",`<span class="__crossx-addr-text">${Q(e.to)}</span>
847
+ <button class="__crossx-copy-btn" data-copy="${D(e.to)}" title="Copy address">${ce}</button>`):"",d=e.amount?G("Transfer",`<span>${D(e.amount)}</span>`):"",g=e.fees?G("Tx Fee",`<span>${D(e.fees)}</span>`):"",w=e.txHash?G("Tx Hash",`<span class="__crossx-addr-text">${Q(e.txHash)}</span>
848
+ <button class="__crossx-copy-btn" data-copy="${D(e.txHash)}" title="Copy hash">${ce}</button>`):"",m=e.total?`<div class="__crossx-total-pill">
849
+ <span class="__crossx-total-label">Total<br>(including fees)</span>
850
+ <span class="__crossx-total-amount">${D(e.total)}</span>
851
+ </div>`:"";a.innerHTML=`
852
+ <div class="__crossx-rows">
853
+ ${c}
854
+ ${l}
855
+ ${d}
856
+ ${g}
857
+ ${w}
858
+ </div>
859
+ ${m}
860
+ <button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
861
+ `,a.querySelectorAll(".__crossx-copy-btn").forEach(x=>{x.addEventListener("click",A=>{var C;A.stopPropagation();const E=x.dataset.copy;E&&((C=navigator.clipboard)==null||C.writeText(E).catch(()=>{}))})})}function wn(r,e){const s=e,t=Ke(),n=D(r.message),o=document.createElement("div");return o.id=te,o.innerHTML=`
862
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
810
863
  <div class="__crossx-header">
811
864
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
812
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${fe}</button>
865
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
813
866
  </div>
814
867
  <hr class="__crossx-divider">
815
868
  <div class="__crossx-body">
816
- <p class="__crossx-sig-subtitle">
817
- <span class="__crossx-sig-origin">${X(t)} </span>is requesting a Signature
818
- </p>
819
- <div class="__crossx-addr-pill">
820
- ${et}
821
- <span class="__crossx-addr-pill-text">${he(s.from)}</span>
869
+ <div class="__crossx-body-cols">
870
+ <div class="__crossx-col-left">
871
+ <p class="__crossx-sig-subtitle">
872
+ <span class="__crossx-sig-origin">${D(t)} </span>is requesting a Signature
873
+ </p>
874
+ <div class="__crossx-addr-pill">
875
+ ${pt}
876
+ <span class="__crossx-addr-pill-text">${Q(r.from)}</span>
877
+ </div>
878
+ <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
879
+ </div>
880
+ <hr class="__crossx-divider __crossx-divider--cols">
881
+ <div class="__crossx-msg-raw">${n}</div>
822
882
  </div>
823
- <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
824
- <hr class="__crossx-divider">
825
- <div class="__crossx-msg-raw">${n}</div>
826
883
  <div class="__crossx-btn-row">
827
884
  <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">Cancel</button>
828
885
  <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">Confirm</button>
829
886
  </div>
830
887
  </div>
831
888
  </div>
832
- `,o}function Rr(s,e){const r=e,t=Fe();let n={};if(typeof s.typedData=="string")try{n=JSON.parse(s.typedData)}catch{}else s.typedData&&typeof s.typedData=="object"&&(n=s.typedData);const o=n.primaryType??"—",i=n.message??{};let a=`
889
+ `,o}function yn(r,e){const s=e,t=Ke();let n={};if(typeof r.typedData=="string")try{n=JSON.parse(r.typedData)}catch{}else r.typedData&&typeof r.typedData=="object"&&(n=r.typedData);const o=n.primaryType??"—",i=n.message??{};let a=`
833
890
  <div class="__crossx-td-row">
834
891
  <span class="__crossx-td-label">Primary Type</span>
835
- <span class="__crossx-td-value">${X(o)}</span>
836
- </div>`;for(const[l,d]of Object.entries(i)){const f=Er(d),_=vr(d)?`<span class="__crossx-addr-text">${he(d)}</span>
837
- <button class="__crossx-copy-btn" data-copy="${d}" title="Copy">${Ie}</button>`:`<span>${f}</span>`;a+=`
892
+ <span class="__crossx-td-value">${D(o)}</span>
893
+ </div>`;for(const[l,d]of Object.entries(i)){const g=pn(d),m=gn(d)?`<span class="__crossx-addr-text">${Q(d)}</span>
894
+ <button class="__crossx-copy-btn" data-copy="${D(String(d))}" title="Copy">${ce}</button>`:`<span>${g}</span>`;a+=`
838
895
  <div class="__crossx-td-row">
839
- <span class="__crossx-td-label">${X(l)}</span>
840
- <div class="__crossx-td-value">${_}</div>
896
+ <span class="__crossx-td-label">${D(l)}</span>
897
+ <div class="__crossx-td-value">${m}</div>
841
898
  </div>`}const c=document.createElement("div");return c.id=te,c.innerHTML=`
842
- <div class="__crossx-card __crossx-card--migration" style="${ge(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
899
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
843
900
  <div class="__crossx-header">
844
901
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
845
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${fe}</button>
902
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
846
903
  </div>
847
904
  <hr class="__crossx-divider">
848
905
  <div class="__crossx-body">
849
- <p class="__crossx-sig-subtitle">
850
- <span class="__crossx-sig-origin">${X(t)} </span>is requesting a Signature
851
- </p>
852
- <div class="__crossx-addr-pill">
853
- ${et}
854
- <span class="__crossx-addr-pill-text">${he(s.from)}</span>
906
+ <div class="__crossx-body-cols">
907
+ <div class="__crossx-col-left">
908
+ <p class="__crossx-sig-subtitle">
909
+ <span class="__crossx-sig-origin">${D(t)} </span>is requesting a Signature
910
+ </p>
911
+ <div class="__crossx-addr-pill">
912
+ ${pt}
913
+ <span class="__crossx-addr-pill-text">${Q(r.from)}</span>
914
+ </div>
915
+ <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
916
+ </div>
917
+ <hr class="__crossx-divider __crossx-divider--cols">
918
+ <div class="__crossx-td-rows">${a}</div>
855
919
  </div>
856
- <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
857
- <hr class="__crossx-divider">
858
- <div class="__crossx-td-rows">${a}</div>
859
920
  <div class="__crossx-btn-row">
860
921
  <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">Cancel</button>
861
922
  <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">Confirm</button>
862
923
  </div>
863
924
  </div>
864
925
  </div>
865
- `,c}const Or=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
926
+ `,c}const bn=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
866
927
  <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"/>
867
928
  <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"/>
868
- </svg>`,Nr=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
929
+ </svg>`,vn=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
869
930
  <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"/>
870
931
  <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"/>
871
932
  <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"/>
872
933
  <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"/>
873
- </svg>`;function kr(s){const e=s,r=document.createElement("div");return r.id=te,r.innerHTML=`
874
- <div class="__crossx-card __crossx-card--migration" style="${ge(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
934
+ </svg>`;function Sn(r){const e=r,s=document.createElement("div");return s.id=te,s.innerHTML=`
935
+ <div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
875
936
  <div class="__crossx-header">
876
937
  <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
877
938
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">Welcome onboard</p>
878
939
  <p class="__crossx-subtitle">Creating CROSSx Embedded Wallet</p>
879
940
  </div>
880
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${fe}</button>
941
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
881
942
  </div>
882
943
  <hr class="__crossx-divider">
883
944
  <div class="__crossx-body">
884
945
  <div class="__crossx-login-btn-row">
885
946
  <button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
886
- <span class="__crossx-login-icon" style="color:var(--cx-value);">${Or}</span>
947
+ <span class="__crossx-login-icon" style="color:var(--cx-value);">${bn}</span>
887
948
  <span class="__crossx-login-btn-label">Sign in with&nbsp;&nbsp;Apple</span>
888
949
  </button>
889
950
  <button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
890
- <span class="__crossx-login-icon">${Nr}</span>
951
+ <span class="__crossx-login-icon">${vn}</span>
891
952
  <span class="__crossx-login-btn-label">Sign in with&nbsp;&nbsp;Google</span>
892
953
  </button>
893
954
  </div>
894
955
  <hr class="__crossx-divider">
895
956
  <p class="__crossx-login-terms">
896
- By continuing, you agree to NEXUS&nbsp;<a class="__crossx-login-terms-link" href="#" tabindex="-1">Terms of Service</a>&nbsp;and consent to its&nbsp;<a class="__crossx-login-terms-link" href="#" tabindex="-1">Privacy Policy.</a>
957
+ By continuing, you agree to NEXUS&nbsp;<a class="__crossx-login-terms-link" href="https://terms.crosstoken.io/docs/cross-terms-of-use" target="_blank" rel="noopener noreferrer">Terms of Service</a>&nbsp;and consent to its&nbsp;<a class="__crossx-login-terms-link" href="https://terms.crosstoken.io/docs/nexus-privacy-policy" target="_blank" rel="noopener noreferrer">Privacy Policy.</a>
897
958
  </p>
898
959
  </div>
899
960
  </div>
900
- `,r}function Cr(s){const e=s,r=document.createElement("div");return r.id=te,r.innerHTML=`
901
- <div class="__crossx-card __crossx-card--migration" style="${ge(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
961
+ `,s}function En(r){const e=r,s=document.createElement("div");return s.id=te,s.innerHTML=`
962
+ <div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
902
963
  <div class="__crossx-header">
903
964
  <p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
904
965
  <p class="__crossx-subtitle--body">We found a wallet linked to your social account. Enter your 4-digit PIN to restore your assets.</p>
905
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${fe}</button>
966
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
906
967
  </div>
907
968
  <hr class="__crossx-divider">
908
969
  <div class="__crossx-body">
@@ -911,17 +972,17 @@
911
972
  <p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
912
973
  </div>
913
974
  <button class="__crossx-recover-btn" id="__crossx-recover-btn">
914
- <span>${wr(e.primary)}</span>
975
+ <span>${ln(e.primary)}</span>
915
976
  <span class="__crossx-recover-label">Recover My Wallet</span>
916
977
  </button>
917
978
  <button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>
918
979
  </div>
919
980
  </div>
920
- `,r}function Pr(s,e){const r=s,t=e?`<p class="__crossx-pin-error-text">${e}</p>`:"",n=document.createElement("div");return n.id=te,n.innerHTML=`
921
- <div class="__crossx-card __crossx-card--migration" style="${ge(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
981
+ `,s}function Tn(r,e){const s=r,t=e?`<p class="__crossx-pin-error-text">${e}</p>`:"",n=document.createElement("div");return n.id=te,n.innerHTML=`
982
+ <div class="__crossx-card __crossx-card--migration" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
922
983
  <div class="__crossx-header">
923
984
  <p class="__crossx-title" id="__crossx-ttl">Recover My Wallet</p>
924
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${fe}</button>
985
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${de}</button>
925
986
  </div>
926
987
  <hr class="__crossx-divider">
927
988
  <div class="__crossx-pin-center">
@@ -935,5 +996,4 @@
935
996
  ${t}
936
997
  </div>
937
998
  </div>
938
- `,n}function Lr(s,e,r){var n;const t=s.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"&&r()}),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,y)=>{t[y]&&(t[y].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 Br{constructor(e="light",r){this.theme=e,this.overrides=r,this.tokens=ft(e,r)}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=ft(e,this.overrides)}getTheme(){return this.theme}showLoginSelector(){return new Promise(e=>{var a,c,l;Se();const r=kr(this.tokens);document.body.appendChild(r);const t=()=>r.remove(),n=d=>{t(),e(d)},o=()=>{t(),e(null)};(a=r.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>n("apple")),(c=r.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>n("google")),(l=r.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),r.addEventListener("click",d=>{d.target===r&&o()}),r.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",f=>f.preventDefault())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;Se();const r=Cr(this.tokens);document.body.appendChild(r);const t=()=>r.remove(),n=()=>{t(),e("recover")},o=()=>{t(),e("skip")};(a=r.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),(c=r.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",o),(l=r.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),r.addEventListener("click",d=>{d.target===r&&o()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showPinInputPrompt(e){return new Promise(r=>{var a;Se();const t=Pr(this.tokens,e);document.body.appendChild(t);const n=()=>t.remove(),o=c=>{n(),r(c)},i=()=>{n(),r(null)};Lr(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(r=>{var a,c;Se();const t=Ir(e,this.tokens);document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),r()};(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 y;d.stopPropagation();const f=l.dataset.copy;f&&((y=navigator.clipboard)==null||y.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)})}requestConfirmation(e){return new Promise(r=>{var c,l,d;Se();let t;e.type==="sign-message"?t=Ar(e,this.tokens):e.type==="sign-typed-data"?t=Rr(e,this.tokens):e.type==="sign"?t=yr(e,this.tokens):t=br(e,this.tokens),document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),r(!0)},i=()=>{n(),r(!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",y=>{var E;y.stopPropagation();const _=f.dataset.copy;_&&((E=navigator.clipboard)==null||E.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)})}}let xe=null;function xt(s){xe=s}const g={log(...s){if(xe){xe.log(...s);return}},warn(...s){if(xe){xe.warn(...s);return}},error(...s){if(xe){xe.error(...s);return}}},We="crossx_access_token",Oe="crossx_refresh_token",Ne="crossx_user_info";class $r{constructor(e,r,t,n,o,i,a){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null}async execute(e){var o,i,a,c;let r,t,n=!1;try{const l=e==null?void 0:e.provider;let d="/login";l==="google"?d="/google":l==="apple"&&(d="/apple");const f=this.config.oauthServiceUrl,y=`${f}${d}`;g.log(`[CROSSx] OAuth 팝업 열기 (${l||"일반"} 로그인):`,y);const _=await this.oauth.openAuth({authUrl:y,expectedOrigin:new URL(f).origin});g.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",_.length,")");const E=this.config.authApiUrl,{accessToken:O,refreshToken:S}=await this.exchangeFirebaseToken(_,E);g.log("[CROSSx] CROSSx access_token 교환 성공"),r=this.crypto.decodeJWT(O),g.log("[CROSSx] access_token 디코딩 — sub:",r.sub,"exp:",r.exp);const C=await this.crypto.verifyJWT(O);if(n=C.signatureVerified??!1,g.log("[CROSSx] access_token 검증 결과:",C.valid),!C.valid)throw g.error("[CROSSx] access_token 검증 실패"),new Error("Invalid access token");const U=C.payload;let F,B;try{const q=this.crypto.decodeJWT(_);B=(o=q==null?void 0:q.firebase)==null?void 0:o.sign_in_provider;const z=((i=q==null?void 0:q.firebase)==null?void 0:i.identities)??{};B==="google.com"?F=(a=z["google.com"])==null?void 0:a[0]:B==="apple.com"&&(F=(c=z["apple.com"])==null?void 0:c[0]),g.log("[CROSSx] OAuth provider sub 추출 — provider:",B,"hasProviderSub:",!!F)}catch{g.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패, fallback으로 sub 사용")}t={id:U.sub,email:U.email,...U,...B?{signInProvider:B}:{},...F?{providerSub:F}:{}},g.log("[CROSSx] 사용자 정보 — id:",t.id),this.tokenStore.set(O),await this.storage.set(We,O),S&&await this.storage.set(Oe,S),await this.storage.set(Ne,t),g.log("[CROSSx] 토큰 및 사용자 정보 저장 완료")}catch(l){return g.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",l),{success:!1,error:l instanceof Error?l.message:"Sign in failed"}}return g.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;g.log("[CROSSx] Firebase 토큰 교환 요청:",t);const n=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}});g.log("[CROSSx] 토큰 교환 응답 — status:",n.status);const o=n.data;if(o!=null&&o.code&&o.code!==200&&o.code>0)throw new m(p.AUTH_FAILED,`Token exchange failed (code ${o.code}): ${o.message}`);const i=(o==null?void 0:o.data)??o,a=i==null?void 0:i.access_token,c=i==null?void 0:i.refresh_token;if(!a)throw g.error("[CROSSx] 교환 응답에서 access_token을 찾을 수 없음:",n),new m(p.AUTH_FAILED,"access_token not found in exchange response");return{accessToken:a,refreshToken:c}}async restoreSession(){try{const e=this.tokenStore.get();if(e){const o=await this.crypto.verifyJWT(e);if(o.valid){const i=await this.storage.get(Ne);if(i)return g.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(i,o.signatureVerified)}this.tokenStore.clear()}const r=await this.storage.get(Oe);if(!r)return g.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;g.log("[CROSSx] restoreSession — refresh_token 발견, silentRefresh 시도");const t=await this.silentRefresh(r);this.tokenStore.set(t);const n=await this.storage.get(Ne);return n?(g.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",n.id),this.loadWallet(n,!1)):null}catch(e){return g.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),await this.storage.remove(Oe),await this.storage.remove(Ne),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const t=`${this.config.authApiUrl}/cross-auth/social/refresh`,n=this.tokenStore.get()??await this.storage.get(We)??"",o={refresh_token:e,access_token:n},i=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:o});g.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;if(a!=null&&a.code&&a.code!==200&&a.code>0)throw new m(p.AUTH_FAILED,`Silent refresh failed (code ${a.code}): ${a.message}`);const c=(a==null?void 0:a.data)??a,l=c==null?void 0:c.token,d=c==null?void 0:c.refresh;if(!l)throw new m(p.AUTH_FAILED,"Silent refresh failed: no token in response");return this.tokenStore.set(l),await this.storage.set(We,l),d&&await this.storage.set(Oe,d),g.log("[CROSSx] silentRefresh 성공"),l}async loadWallet(e,r){let t,n=!1;try{g.log("[CROSSx][Migration Phase 2] POST /mnemonic/create 호출 — userId:",e.id),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,g.log("[CROSSx][Migration Phase 2] 지갑 로드 완료 (기존 백업 없음) — address:",t)}catch(o){o instanceof m&&o.code===p.MIGRATION_BACKUP_EXISTS?(g.log("[CROSSx][Migration Phase 2] Gateway -10012 감지 → needsMigration = true"),n=!0):g.warn("[CROSSx][Migration Phase 2] 지갑 로드 실패 (로그인은 유지):",o)}return g.log("[CROSSx][Migration Phase 2] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}}const Mr="crossx_access_token",Dr="crossx_refresh_token",Ur="crossx_user_info";class Hr{constructor(e,r){this.storage=e,this.tokenStore=r}async execute(){this.tokenStore.clear(),await this.storage.remove(Mr),await this.storage.remove(Dr),await this.storage.remove(Ur)}}const Fr="crossx_access_token",qr="crossx_refresh_token",Gr="crossx_user_info",Wr="I agree to delete my data";class Vr{constructor(e,r,t){this.storage=e,this.walletProvider=r,this.tokenStore=t}async execute(){if(!this.tokenStore.has())throw new m(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다");if(g.log("[CROSSx] 계정 탈퇴 처리 시작"),!this.walletProvider.withdraw)throw new m(p.NOT_IMPLEMENTED,"현재 환경에서는 탈퇴 기능을 지원하지 않습니다");await this.walletProvider.withdraw(Wr),this.tokenStore.clear(),await this.storage.remove(Fr),await this.storage.remove(qr),await this.storage.remove(Gr),g.log("[CROSSx] 탈퇴 완료")}}class Kr{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new m(p.NOT_IMPLEMENTED,"Migration is not supported in the current environment");g.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return g.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}const se=class se{constructor(e,r,t,n,o,i,a){this.storage=r,this.crypto=t,this.transport=n,this.oauth=o,this.walletProvider=i,this.initialized=!1,this.authenticated=!1,this.userId=null,this.address=null,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._config=Object.freeze({...e}),e.logger&&xt(e.logger),this.confirmation=new Br(e.theme??"light",e.themeTokens),this.signInUseCase=new $r(e,r,t,o,n,i,a),this.signOutUseCase=new Hr(r,a),this.withdrawUseCase=new Vr(r,i,a),this.migrateWalletUseCase=new Kr(r,i)}get config(){return this._config}async initialize(){if(this.initialized)return this.authenticated?{success:!0,address:this.address??void 0}:null;console.log("[CROSSx SDK] v0.1.0 initializing...");try{const e=await this.signInUseCase.restoreSession();return e!=null&&e.success&&this.applyAuthResult(e),this.initialized=!0,e??null}catch(e){throw new m(p.AUTH_NOT_INITIALIZED,"SDK initialization failed",e)}}async signIn(e){this.ensureInitialized();let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector();if(t===null)return{success:!1,error:"User cancelled login"};r={...e,provider:t}}try{const t=await this.signInUseCase.execute(r);return t.success&&this.applyAuthResult(t),t}catch(t){throw new m(p.AUTH_FAILED,"Sign in failed",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new m(p.UNKNOWN_ERROR,"Sign out failed",e)}}async withdraw(){this.ensureAuthenticated(),await this.withdrawUseCase.execute(),this.clearAuthState()}isAuthenticated(){return this.authenticated}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 m(p.AUTH_NOT_AUTHENTICATED,"User ID not found");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=r.address,g.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof m?r:new m(p.MIGRATION_FAILED,"Wallet migration failed",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"User ID not found");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:0}}async getAddresses(){return this.ensureAuthenticated(),this.address?[{address:this.address,index:0}]:[]}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"User ID not found");g.log("[CROSSx] 지갑 생성 시작");try{const e=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=e.address,g.log("[CROSSx] 지갑 생성 완료:",e.address),{address:e.address}}catch(e){if(e instanceof m&&e.code===p.MIGRATION_BACKUP_EXISTS){const r=this.providerSub??this.userId;g.log("[CROSSx][Migration Phase 3] createWallet() — Gateway -10012 감지, 마이그레이션 UI 시작 — migrationSub:",r);const t=await this.handleMigrationFlow(r);if(t)return this.address=t.address,{address:t.address};throw new m(p.MIGRATION_FAILED,"Migration skipped by user")}throw e}}async signMessage(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"User ID not found");const n=t==null?void 0:t.index,o=await this.walletProvider.getAddress(this.userId,n??0);let i;if(this.walletProvider.prepare&&(i=(await this.walletProvider.prepare("sign-message",{message:r,from:o.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:o.address,message:r,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"User rejected message signing");try{const c=await this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,i,o.address);return this.verifySignatureSigner(r,c.signature,o.address),{chainId:e,signature:c.signature,message:r,address:o.address}}catch(c){throw c instanceof m?c:new m(p.SIGNATURE_FAILED,`Message signing failed (${e})`,c)}}async signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"User ID not found");if(!this.walletProvider.signTypedData)throw new m(p.NOT_IMPLEMENTED,"signTypedData is not implemented");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:r,from:n.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"User rejected typed data signing");try{const a=await this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,o,n.address);return se.validateSignatureFormat(a.signature),{chainId:e,signature:a.signature,address:n.address}}catch(a){throw a instanceof m?a:new m(p.SIGNATURE_FAILED,`Typed data signing failed (${e})`,a)}}async signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"User ID not found");let n;this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("sign",{tx:r})).uuid);const o=this.getNativeCurrency(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:r.from,to:r.to,value:r.value,data:r.data,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"User rejected transaction signing");try{const a=await this.walletProvider.signTransaction(this.userId,e,r,t==null?void 0:t.index,n);return se.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof m)throw a;const c=a instanceof Error?a.message:String(a);throw new m(p.SIGNATURE_FAILED,`Transaction signing failed (${e}): ${c}`,a)}}async sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"User ID not found");let n;this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("send",{tx:r})).uuid);const o=this.getNativeCurrency(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:r.from,to:r.to,value:r.value,data:r.data,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"User rejected transaction");try{let a;if(this.walletProvider.sendTransaction)a=(await this.walletProvider.sendTransaction(this.userId,e,r,n)).txHash;else{const l=await this.walletProvider.signTransaction(this.userId,e,r,t==null?void 0:t.index,n);a=l.txHash??l.signature}const c=se.formatTxAmount(r.value,o.symbol,o.decimals);return this.confirmation.showTransactionComplete({chainId:e,txHash:a,to:r.to,amount:c,nativeSymbol:o.symbol}).catch(()=>{}),{chainId:e,txHash:a,status:"pending"}}catch(a){const c=a instanceof Error?a.message:String(a);throw new m(p.TRANSACTION_FAILED,`Transaction failed (${e}): ${c}`,a)}}async getTransactionReceipt(e,r){if(!this.walletProvider.getTransactionReceipt)return null;try{return await this.walletProvider.getTransactionReceipt(e,r)}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??1e3,o=1e4,i=t.timeoutMs??6e4,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,o)}throw new m(p.UNKNOWN_ERROR,`Transaction receipt timeout (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var c,l;const{txHash:n}=await this.sendTransaction(e,r),o=t.intervalMs??((c=this._config.receiptPolling)==null?void 0:c.intervalMs)??2e3,i=t.timeoutMs??((l=this._config.receiptPolling)==null?void 0:l.timeoutMs)??6e4,a=await this.waitForTxAndGetReceipt(n,e,{intervalMs:o,timeoutMs:i});return{chainId:e,txHash:n,receipt:a}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;if(!this.walletProvider.getTransactionCount)throw new m(p.NOT_IMPLEMENTED,"getTransactionCount is not implemented");try{return await this.walletProvider.getTransactionCount(r,e)}catch(t){const n=t instanceof Error?t.message:String(t);throw new m(p.UNKNOWN_ERROR,`Failed to get nonce: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};if(!this.walletProvider.getBalance)throw new m(p.NOT_IMPLEMENTED,"getBalance is not implemented");try{const t=await this.walletProvider.getBalance(r,e);return{wei:t,formatted:se.formatWei(t),chainId:e}}catch(t){const n=t instanceof Error?t.message:String(t);throw new m(p.UNKNOWN_ERROR,`Failed to get balance (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const r=BigInt(e);if(r===0n)return"0";const t=BigInt("1000000000000000000"),n=r/t,i=(r%t).toString().padStart(18,"0").replace(/0+$/,"").slice(0,6);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Pt(this,e)}async walletRpc(e,r,t){if(this.ensureAuthenticated(),!this.walletProvider.rpcRequest)throw new m(p.NOT_IMPLEMENTED,"rpcRequest is not implemented");try{return await this.walletProvider.rpcRequest(e,r,t)}catch(n){const o=n instanceof Error?n.message:String(n);throw new m(p.UNKNOWN_ERROR,`rpcRequest failed [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,r,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,6).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${r}`}catch{return}}getNativeCurrency(e){const r=parseInt(e.split(":")[1]??"0",10);return se.CHAIN_NATIVE_CURRENCY[r]??{symbol:"ETH",decimals:18}}async handleMigrationFlow(e){g.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=await this.confirmation.showMigrationFoundPrompt();if(g.log("[CROSSx][Migration Phase 3] 사용자 선택:",r),r==="skip")return g.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0;for(;;){n++,g.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n})`,t?`— 이전 에러: ${t}`:"");const o=await this.confirmation.showPinInputPrompt(t);if(o===null)return g.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;g.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${o.length}자리), Gateway 마이그레이션 API 호출`);try{const i=await this.migrateWalletUseCase.execute(o,e);return g.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",i.address),i}catch(i){if(i instanceof m&&i.code===p.MIGRATION_FAILED){g.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 #${n}) — 재시도 요청`),t="Incorrect PIN. Please try again.";continue}throw g.error("[CROSSx][Migration Phase 4] 마이그레이션 실패 (복구 불가):",i),i}}}static validateSignatureFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new m(p.SIGNATURE_FAILED,"Invalid signature: not a valid hex string");if(r.length!==130)throw new m(p.SIGNATURE_FAILED,`Invalid signature length: expected 130 hex chars (65 bytes), got ${r.length}`)}static validateSignedTxFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new m(p.SIGNATURE_FAILED,"Invalid signedTx: not a valid hex string");if(r.length<2)throw new m(p.SIGNATURE_FAILED,"Invalid signedTx: too short")}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw g.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new m(p.SIGNATURE_SIGNER_MISMATCH,`Signature signer mismatch: expected ${t}, recovered ${n}`);g.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof m)throw n;g.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var r,t,n,o;this.authenticated=e.success,this.userId=((r=e.user)==null?void 0:r.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=se.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}ensureInitialized(){if(!this.initialized)throw new m(p.AUTH_NOT_INITIALIZED,"SDK is not initialized. Call initialize() first.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new m(p.AUTH_NOT_AUTHENTICATED,"Not authenticated. Call signIn() first.")}dispose(){this.clearAuthState(),this.initialized=!1,xt(null)}};se.CHAIN_NATIVE_CURRENCY={1:{symbol:"ETH",decimals:18},5:{symbol:"ETH",decimals:18},11155111:{symbol:"ETH",decimals:18},17e3:{symbol:"ETH",decimals:18},10:{symbol:"ETH",decimals:18},420:{symbol:"ETH",decimals:18},42161:{symbol:"ETH",decimals:18},421614:{symbol:"ETH",decimals:18},8453:{symbol:"ETH",decimals:18},84532:{symbol:"ETH",decimals:18},137:{symbol:"POL",decimals:18},80002:{symbol:"POL",decimals:18},56:{symbol:"BNB",decimals:18},97:{symbol:"BNB",decimals:18},43114:{symbol:"AVAX",decimals:18},43113:{symbol:"AVAX",decimals:18},250:{symbol:"FTM",decimals:18},612044:{symbol:"tCROSS",decimals:18},612055:{symbol:"CROSS",decimals:18}};let $e=se;class zr{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw g.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return g.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw g.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw g.error("Storage clear error:",e),e}}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function tt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ie(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function M(s,e,r=""){const t=tt(s),n=s==null?void 0:s.length,o=e!==void 0;if(!t||o&&n!==e){const i=r&&`"${r}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return s}function Bt(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ie(s.outputLen),ie(s.blockLen)}function be(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function $t(s,e){M(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function jr(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function ve(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Ve(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function ee(s,e){return s<<32-e|s>>>e}const Yr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Zr(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Xr(s){for(let e=0;e<s.length;e++)s[e]=Zr(s[e]);return s}const _t=Yr?s=>s:Xr,Mt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Jr=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Ae(s){if(M(s),Mt)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=Jr[s[r]];return e}const re={_0:48,_9:57,A:65,F:70,a:97,f:102};function mt(s){if(s>=re._0&&s<=re._9)return s-re._0;if(s>=re.A&&s<=re.F)return s-(re.A-10);if(s>=re.a&&s<=re.f)return s-(re.a-10)}function Me(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Mt)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,o=0;n<r;n++,o+=2){const i=mt(s.charCodeAt(o)),a=mt(s.charCodeAt(o+1));if(i===void 0||a===void 0){const c=s[o]+s[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function ue(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];M(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const o=s[t];r.set(o,n),n+=o.length}return r}function Dt(s,e={}){const r=(n,o)=>s(o).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function Ut(s=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(s))}const Qr=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function es(s,e,r){return s&e^~s&r}function ts(s,e,r){return s&e^s&r^e&r}class rs{constructor(e,r,t,n){w(this,"blockLen");w(this,"outputLen");w(this,"padOffset");w(this,"isLE");w(this,"buffer");w(this,"view");w(this,"finished",!1);w(this,"length",0);w(this,"pos",0);w(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ve(this.buffer)}update(e){be(this),M(e);const{view:r,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=Ve(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(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){be(this),$t(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;r[i++]=128,ve(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let f=i;f<n;f++)r[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=Ve(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:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,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%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=BigInt(2**32-1),wt=BigInt(32);function ss(s,e=!1){return e?{h:Number(s&ke),l:Number(s>>wt&ke)}:{h:Number(s>>wt&ke)|0,l:Number(s&ke)|0}}function ns(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let o=0;o<r;o++){const{h:i,l:a}=ss(s[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const os=(s,e,r)=>s<<r|e>>>32-r,is=(s,e,r)=>e<<r|s>>>32-r,as=(s,e,r)=>e<<r-32|s>>>64-r,cs=(s,e,r)=>s<<r-32|e>>>64-r,ls=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]),le=new Uint32Array(64);class ds extends rs{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,r,t,n,o,i,a,c]}set(e,r,t,n,o,i,a,c){this.A=e|0,this.B=r|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,r){for(let f=0;f<16;f++,r+=4)le[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const y=le[f-15],_=le[f-2],E=ee(y,7)^ee(y,18)^y>>>3,O=ee(_,17)^ee(_,19)^_>>>10;le[f]=O+le[f-7]+E+le[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 y=ee(a,6)^ee(a,11)^ee(a,25),_=d+y+es(a,c,l)+ls[f]+le[f]|0,O=(ee(t,2)^ee(t,13)^ee(t,22))+ts(t,n,o)|0;d=l,l=c,c=a,a=i+_|0,i=o,o=n,n=t,t=_+O|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(){ve(le)}destroy(){this.set(0,0,0,0,0,0,0,0),ve(this.buffer)}}class us extends ds{constructor(){super(32);w(this,"A",ce[0]|0);w(this,"B",ce[1]|0);w(this,"C",ce[2]|0);w(this,"D",ce[3]|0);w(this,"E",ce[4]|0);w(this,"F",ce[5]|0);w(this,"G",ce[6]|0);w(this,"H",ce[7]|0)}}const hs=Dt(()=>new us,Qr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rt=BigInt(0),Ze=BigInt(1);function De(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function Ht(s){if(typeof s=="bigint"){if(!Be(s))throw new Error("positive bigint expected, got "+s)}else ie(s);return s}function Ce(s){const e=Ht(s).toString(16);return e.length&1?"0"+e:e}function Ft(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?rt:BigInt("0x"+s)}function qe(s){return Ft(Ae(s))}function qt(s){return Ft(Ae(fs(M(s)).reverse()))}function st(s,e){ie(e),s=Ht(s);const r=Me(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Gt(s,e){return st(s,e).reverse()}function fs(s){return Uint8Array.from(s)}const Be=s=>typeof s=="bigint"&&rt<=s;function gs(s,e,r){return Be(s)&&Be(e)&&Be(r)&&e<=s&&s<r}function ps(s,e,r,t){if(!gs(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function xs(s){let e;for(e=0;s>rt;s>>=Ze,e+=1);return e}const nt=s=>(Ze<<BigInt(s))-Ze;function _s(s,e,r){if(ie(s,"hashLen"),ie(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=S=>new Uint8Array(S),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),d=0;const f=()=>{c.fill(1),l.fill(0),d=0},y=(...S)=>r(l,ue(c,...S)),_=(S=n)=>{l=y(o,S),c=y(),S.length!==0&&(l=y(i,S),c=y())},E=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let S=0;const C=[];for(;S<e;){c=y();const U=c.slice();C.push(U),S+=c.length}return ue(...C)};return(S,C)=>{f(),_(S);let U;for(;!(U=C(E()));)_();return f(),U}}function ot(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(o,i,a){const c=s[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(r,!0)}function yt(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const o=s(r,...t);return e.set(r,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Y=BigInt(0),K=BigInt(1),_e=BigInt(2),Wt=BigInt(3),Vt=BigInt(4),Kt=BigInt(5),ms=BigInt(7),zt=BigInt(8),ws=BigInt(9),jt=BigInt(16);function Q(s,e){const r=s%e;return r>=Y?r:e+r}function J(s,e,r){let t=s;for(;e-- >Y;)t*=t,t%=r;return t}function bt(s,e){if(s===Y)throw new Error("invert: expected non-zero number");if(e<=Y)throw new Error("invert: expected positive modulus, got "+e);let r=Q(s,e),t=e,n=Y,o=K;for(;r!==Y;){const a=t/r,c=t%r,l=n-o*a;t=r,r=c,n=o,o=l}if(t!==K)throw new Error("invert: does not exist");return Q(n,e)}function it(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function Yt(s,e){const r=(s.ORDER+K)/Vt,t=s.pow(e,r);return it(s,t,e),t}function ys(s,e){const r=(s.ORDER-Kt)/zt,t=s.mul(e,_e),n=s.pow(t,r),o=s.mul(e,n),i=s.mul(s.mul(o,_e),n),a=s.mul(o,s.sub(i,s.ONE));return it(s,a,e),a}function bs(s){const e=Ge(s),r=Zt(s),t=r(e,e.neg(e.ONE)),n=r(e,t),o=r(e,e.neg(t)),i=(s+ms)/jt;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const f=a.mul(l,n),y=a.mul(l,o),_=a.eql(a.sqr(d),c),E=a.eql(a.sqr(f),c);l=a.cmov(l,d,_),d=a.cmov(y,f,E);const O=a.eql(a.sqr(d),c),S=a.cmov(l,d,O);return it(a,S,c),S}}function Zt(s){if(s<Wt)throw new Error("sqrt is not defined for small field");let e=s-K,r=0;for(;e%_e===Y;)e/=_e,r++;let t=_e;const n=Ge(s);for(;vt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Yt;let o=n.pow(t,e);const i=(e+K)/_e;return function(c,l){if(c.is0(l))return l;if(vt(c,l)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,o),y=c.pow(l,e),_=c.pow(l,i);for(;!c.eql(y,c.ONE);){if(c.is0(y))return c.ZERO;let E=1,O=c.sqr(y);for(;!c.eql(O,c.ONE);)if(E++,O=c.sqr(O),E===d)throw new Error("Cannot find square root");const S=K<<BigInt(d-E-1),C=c.pow(f,S);d=E,f=c.sqr(C),y=c.mul(y,f),_=c.mul(_,C)}return _}}function vs(s){return s%Vt===Wt?Yt:s%zt===Kt?ys:s%jt===ws?bs(s):Zt(s)}const Es=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ss(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Es.reduce((t,n)=>(t[n]="function",t),e);return ot(s,r),s}function Ts(s,e,r){if(r<Y)throw new Error("invalid exponent, negatives unsupported");if(r===Y)return s.ONE;if(r===K)return e;let t=s.ONE,n=e;for(;r>Y;)r&K&&(t=s.mul(t,n)),n=s.sqr(n),r>>=K;return t}function Xt(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((i,a,c)=>s.is0(a)?i:(t[c]=i,s.mul(i,a)),s.ONE),o=s.inv(n);return e.reduceRight((i,a,c)=>s.is0(a)?i:(t[c]=s.mul(i,t[c]),s.mul(i,a)),o),t}function vt(s,e){const r=(s.ORDER-K)/_e,t=s.pow(e,r),n=s.eql(t,s.ONE),o=s.eql(t,s.ZERO),i=s.eql(t,s.neg(s.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function Is(s,e){e!==void 0&&ie(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class As{constructor(e,r={}){w(this,"ORDER");w(this,"BITS");w(this,"BYTES");w(this,"isLE");w(this,"ZERO",Y);w(this,"ONE",K);w(this,"_lengths");w(this,"_sqrt");w(this,"_mod");var i;if(e<=Y)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(i=r.allowedLengths)==null?void 0:i.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:o}=Is(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 Q(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Y<=e&&e<this.ORDER}is0(e){return e===Y}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&K)===K}neg(e){return Q(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return Q(e*e,this.ORDER)}add(e,r){return Q(e+r,this.ORDER)}sub(e,r){return Q(e-r,this.ORDER)}mul(e,r){return Q(e*r,this.ORDER)}pow(e,r){return Ts(this,e,r)}div(e,r){return Q(e*bt(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return bt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=vs(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Gt(e,this.BYTES):st(e,this.BYTES)}fromBytes(e,r=!1){M(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?qt(e):qe(e);if(a&&(c=Q(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Xt(this,e)}cmov(e,r,t){return t?r:e}}function Ge(s,e={}){return new As(s,e)}function Jt(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function Qt(s){const e=Jt(s);return e+Math.ceil(e/2)}function Rs(s,e,r=!1){M(s);const t=s.length,n=Jt(e),o=Qt(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=r?qt(s):qe(s),a=Q(i,e-K)+K;return r?Gt(a,n):st(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ee=BigInt(0),me=BigInt(1);function Ue(s,e){const r=e.negate();return s?r:e}function Et(s,e){const r=Xt(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function er(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Ke(s,e){er(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,o=nt(s),i=BigInt(s);return{windows:r,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function St(s,e,r){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=r;let a=Number(s&n),c=s>>i;a>t&&(a-=o,c+=me);const l=e*t,d=l+Math.abs(a)-1,f=a===0,y=a<0,_=e%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:y,isNegF:_,offsetF:l}}const ze=new WeakMap,tr=new WeakMap;function je(s){return tr.get(s)||1}function Tt(s){if(s!==Ee)throw new Error("invalid wNAF")}class Os{constructor(e,r){w(this,"BASE");w(this,"ZERO");w(this,"Fn");w(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>Ee;)r&me&&(t=t.add(n)),n=n.double(),r>>=me;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=Ke(r,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,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=Ke(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:f,isNegF:y,offsetF:_}=St(t,a,i);t=c,d?o=o.add(Ue(y,r[_])):n=n.add(Ue(f,r[l]))}return Tt(t),{p:n,f:o}}wNAFUnsafe(e,r,t,n=this.ZERO){const o=Ke(e,this.bits);for(let i=0;i<o.windows&&t!==Ee;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=St(t,i,o);if(t=a,!l){const f=r[c];n=n.add(d?f.negate():f)}}return Tt(t),n}getPrecomputes(e,r,t){let n=ze.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),ze.set(r,n))),n}cached(e,r,t){const n=je(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const o=je(e);return o===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),r,n)}createCache(e,r){er(r,this.bits),tr.set(e,r),ze.delete(e)}hasCache(e){return je(e)!==1}}function Ns(s,e,r,t){let n=e,o=s.ZERO,i=s.ZERO;for(;r>Ee||t>Ee;)r&me&&(o=o.add(n)),t&me&&(i=i.add(n)),n=n.double(),r>>=me,t>>=me;return{p1:o,p2:i}}function It(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ss(e),e}else return Ge(s,{isLE:r})}function ks(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Ee))throw new Error(`CURVE.${c} must be positive bigint`)}const n=It(e.p,r.Fp,t),o=It(e.n,r.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 Cs(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class rr{constructor(e,r){w(this,"oHash");w(this,"iHash");w(this,"blockLen");w(this,"outputLen");w(this,"finished",!1);w(this,"destroyed",!1);if(Bt(e),M(r,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(r.length>t?e.create().update(r).digest():r);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),ve(n)}update(e){return be(this),this.iHash.update(e),this}digestInto(e){be(this),M(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:r,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=r._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 sr=(s,e,r)=>new rr(s,e).update(r).digest();sr.create=(s,e)=>new rr(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const At=(s,e)=>(s+(s>=0?e:-e)/nr)/e;function Ps(s,e,r){const[[t,n],[o,i]]=e,a=At(i*s,r),c=At(-n*s,r);let l=s-a*t-c*o,d=-a*n-c*i;const f=l<ne,y=d<ne;f&&(l=-l),y&&(d=-d);const _=nt(Math.ceil(xs(r)/2))+ye;if(l<ne||l>=_||d<ne||d>=_)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:f,k1:l,k2neg:y,k2:d}}function Xe(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Ye(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return De(r.lowS,"lowS"),De(r.prehash,"prehash"),r.format!==void 0&&Xe(r.format),r}class Ls extends Error{constructor(e=""){super(e)}}const de={Err:Ls,_tlv:{encode:(s,e)=>{const{Err:r}=de;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=Ce(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const o=t>127?Ce(n.length/2|128):"";return Ce(s)+o+n+e},decode(s,e){const{Err:r}=de;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("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 r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(t+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(s){const{Err:e}=de;if(s<ne)throw new e("integer: negative integers are not allowed");let r=Ce(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=de;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return qe(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=de,n=M(s,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:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=de,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),o=t+n;return e.encode(48,o)}},ne=BigInt(0),ye=BigInt(1),nr=BigInt(2),Pe=BigInt(3),Bs=BigInt(4);function $s(s,e={}){const r=ks("weierstrass",s,e),{Fp:t,Fn:n}=r;let o=r.CURVE;const{h:i,n:a}=o;ot(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=ir(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(P,h,u){const{x,y:v}=h.toAffine(),I=t.toBytes(x);if(De(u,"isCompressed"),u){d();const T=!t.isOdd(v);return ue(or(T),I)}else return ue(Uint8Array.of(4),I,t.toBytes(v))}function y(P){M(P,void 0,"Point");const{publicKey:h,publicKeyUncompressed:u}=l,x=P.length,v=P[0],I=P.subarray(1);if(x===h&&(v===2||v===3)){const T=t.fromBytes(I);if(!t.isValid(T))throw new Error("bad point: is not on curve, wrong x");const A=O(T);let b;try{b=t.sqrt(A)}catch(H){const $=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+$)}d();const R=t.isOdd(b);return(v&1)===1!==R&&(b=t.neg(b)),{x:T,y:b}}else if(x===u&&v===4){const T=t.BYTES,A=t.fromBytes(I.subarray(0,T)),b=t.fromBytes(I.subarray(T,T*2));if(!S(A,b))throw new Error("bad point: is not on curve");return{x:A,y:b}}else throw new Error(`bad point: got length ${x}, expected compressed=${h} or uncompressed=${u}`)}const _=e.toBytes||f,E=e.fromBytes||y;function O(P){const h=t.sqr(P),u=t.mul(h,P);return t.add(t.add(u,t.mul(P,o.a)),o.b)}function S(P,h){const u=t.sqr(h),x=O(P);return t.eql(u,x)}if(!S(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const C=t.mul(t.pow(o.a,Pe),Bs),U=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(C,U)))throw new Error("bad curve params: a or b");function F(P,h,u=!1){if(!t.isValid(h)||u&&t.is0(h))throw new Error(`bad point coordinate ${P}`);return h}function B(P){if(!(P instanceof j))throw new Error("Weierstrass Point expected")}function q(P){if(!c||!c.basises)throw new Error("no endo");return Ps(P,c.basises,n.ORDER)}const z=yt((P,h)=>{const{X:u,Y:x,Z:v}=P;if(t.eql(v,t.ONE))return{x:u,y:x};const I=P.is0();h==null&&(h=I?t.ONE:t.inv(v));const T=t.mul(u,h),A=t.mul(x,h),b=t.mul(v,h);if(I)return{x:t.ZERO,y:t.ZERO};if(!t.eql(b,t.ONE))throw new Error("invZ was invalid");return{x:T,y:A}}),we=yt(P=>{if(P.is0()){if(e.allowInfinityPoint&&!t.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:h,y:u}=P.toAffine();if(!t.isValid(h)||!t.isValid(u))throw new Error("bad point: x or y not field elements");if(!S(h,u))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function ae(P,h,u,x,v){return u=new j(t.mul(u.X,P),u.Y,u.Z),h=Ue(x,h),u=Ue(v,u),h.add(u)}const L=class L{constructor(h,u,x){w(this,"X");w(this,"Y");w(this,"Z");this.X=F("x",h),this.Y=F("y",u,!0),this.Z=F("z",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(h){const{x:u,y:x}=h||{};if(!h||!t.isValid(u)||!t.isValid(x))throw new Error("invalid affine point");if(h instanceof L)throw new Error("projective point not allowed");return t.is0(u)&&t.is0(x)?L.ZERO:new L(u,x,t.ONE)}static fromBytes(h){const u=L.fromAffine(E(M(h,void 0,"point")));return u.assertValidity(),u}static fromHex(h){return L.fromBytes(Me(h))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,u=!0){return pe.createCache(this,h),u||this.multiply(Pe),this}assertValidity(){we(this)}hasEvenY(){const{y:h}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(h)}equals(h){B(h);const{X:u,Y:x,Z:v}=this,{X:I,Y:T,Z:A}=h,b=t.eql(t.mul(u,A),t.mul(I,v)),R=t.eql(t.mul(x,A),t.mul(T,v));return b&&R}negate(){return new L(this.X,t.neg(this.Y),this.Z)}double(){const{a:h,b:u}=o,x=t.mul(u,Pe),{X:v,Y:I,Z:T}=this;let A=t.ZERO,b=t.ZERO,R=t.ZERO,k=t.mul(v,v),H=t.mul(I,I),$=t.mul(T,T),N=t.mul(v,I);return N=t.add(N,N),R=t.mul(v,T),R=t.add(R,R),A=t.mul(h,R),b=t.mul(x,$),b=t.add(A,b),A=t.sub(H,b),b=t.add(H,b),b=t.mul(A,b),A=t.mul(N,A),R=t.mul(x,R),$=t.mul(h,$),N=t.sub(k,$),N=t.mul(h,N),N=t.add(N,R),R=t.add(k,k),k=t.add(R,k),k=t.add(k,$),k=t.mul(k,N),b=t.add(b,k),$=t.mul(I,T),$=t.add($,$),k=t.mul($,N),A=t.sub(A,k),R=t.mul($,H),R=t.add(R,R),R=t.add(R,R),new L(A,b,R)}add(h){B(h);const{X:u,Y:x,Z:v}=this,{X:I,Y:T,Z:A}=h;let b=t.ZERO,R=t.ZERO,k=t.ZERO;const H=o.a,$=t.mul(o.b,Pe);let N=t.mul(u,I),G=t.mul(x,T),W=t.mul(v,A),Z=t.add(u,x),D=t.add(I,T);Z=t.mul(Z,D),D=t.add(N,G),Z=t.sub(Z,D),D=t.add(u,v);let V=t.add(I,A);return D=t.mul(D,V),V=t.add(N,W),D=t.sub(D,V),V=t.add(x,v),b=t.add(T,A),V=t.mul(V,b),b=t.add(G,W),V=t.sub(V,b),k=t.mul(H,D),b=t.mul($,W),k=t.add(b,k),b=t.sub(G,k),k=t.add(G,k),R=t.mul(b,k),G=t.add(N,N),G=t.add(G,N),W=t.mul(H,W),D=t.mul($,D),G=t.add(G,W),W=t.sub(N,W),W=t.mul(H,W),D=t.add(D,W),N=t.mul(G,D),R=t.add(R,N),N=t.mul(V,D),b=t.mul(Z,b),b=t.sub(b,N),N=t.mul(Z,G),k=t.mul(V,k),k=t.add(k,N),new L(b,R,k)}subtract(h){return this.add(h.negate())}is0(){return this.equals(L.ZERO)}multiply(h){const{endo:u}=e;if(!n.isValidNot0(h))throw new Error("invalid scalar: out of range");let x,v;const I=T=>pe.cached(this,T,A=>Et(L,A));if(u){const{k1neg:T,k1:A,k2neg:b,k2:R}=q(h),{p:k,f:H}=I(A),{p:$,f:N}=I(R);v=H.add(N),x=ae(u.beta,k,$,T,b)}else{const{p:T,f:A}=I(h);x=T,v=A}return Et(L,[x,v])[0]}multiplyUnsafe(h){const{endo:u}=e,x=this;if(!n.isValid(h))throw new Error("invalid scalar: out of range");if(h===ne||x.is0())return L.ZERO;if(h===ye)return x;if(pe.hasCache(this))return this.multiply(h);if(u){const{k1neg:v,k1:I,k2neg:T,k2:A}=q(h),{p1:b,p2:R}=Ns(L,x,I,A);return ae(u.beta,b,R,v,T)}else return pe.unsafe(x,h)}toAffine(h){return z(this,h)}isTorsionFree(){const{isTorsionFree:h}=e;return i===ye?!0:h?h(L,this):pe.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:h}=e;return i===ye?this:h?h(L,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(h=!0){return De(h,"isCompressed"),this.assertValidity(),_(L,this,h)}toHex(h=!0){return Ae(this.toBytes(h))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};w(L,"BASE",new L(o.Gx,o.Gy,t.ONE)),w(L,"ZERO",new L(t.ZERO,t.ONE,t.ZERO)),w(L,"Fp",t),w(L,"Fn",n);let j=L;const Re=n.BITS,pe=new Os(j,e.endo?Math.ceil(Re/2):Re);return j.BASE.precompute(8),j}function or(s){return Uint8Array.of(s?2:3)}function ir(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Ms(s,e={}){const{Fn:r}=s,t=e.randomBytes||Ut,n=Object.assign(ir(s.Fp,r),{seed:Qt(r.ORDER)});function o(_){try{const E=r.fromBytes(_);return r.isValidNot0(E)}catch{return!1}}function i(_,E){const{publicKey:O,publicKeyUncompressed:S}=n;try{const C=_.length;return E===!0&&C!==O||E===!1&&C!==S?!1:!!s.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return Rs(M(_,n.seed,"seed"),r.ORDER)}function c(_,E=!0){return s.BASE.multiply(r.fromBytes(_)).toBytes(E)}function l(_){const{secretKey:E,publicKey:O,publicKeyUncompressed:S}=n;if(!tt(_)||"_lengths"in r&&r._lengths||E===O)return;const C=M(_,void 0,"key").length;return C===O||C===S}function d(_,E,O=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(E)===!1)throw new Error("second arg must be public key");const S=r.fromBytes(_);return s.fromBytes(E).multiply(S).toBytes(O)}const f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},y=Cs(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:y,Point:s,utils:f,lengths:n})}function Ds(s,e,r={}){Bt(e),ot(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||Ut,n=r.hmac||((h,u)=>sr(e,h,u)),{Fp:o,Fn:i}=s,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:f,utils:y,lengths:_}=Ms(s,r),E={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},O=a*nr<o.ORDER;function S(h){const u=a>>ye;return h>u}function C(h,u){if(!i.isValidNot0(u))throw new Error(`invalid signature ${h}: out of range 1..Point.Fn.ORDER`);return u}function U(){if(O)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function F(h,u){Xe(u);const x=_.signature,v=u==="compact"?x:u==="recovered"?x+1:void 0;return M(h,v)}class B{constructor(u,x,v){w(this,"r");w(this,"s");w(this,"recovery");if(this.r=C("r",u),this.s=C("s",x),v!=null){if(U(),![0,1,2,3].includes(v))throw new Error("invalid recovery id");this.recovery=v}Object.freeze(this)}static fromBytes(u,x=E.format){F(u,x);let v;if(x==="der"){const{r:b,s:R}=de.toSig(M(u));return new B(b,R)}x==="recovered"&&(v=u[0],x="compact",u=u.subarray(1));const I=_.signature/2,T=u.subarray(0,I),A=u.subarray(I,I*2);return new B(i.fromBytes(T),i.fromBytes(A),v)}static fromHex(u,x){return this.fromBytes(Me(u),x)}assertRecovery(){const{recovery:u}=this;if(u==null)throw new Error("invalid recovery id: must be present");return u}addRecoveryBit(u){return new B(this.r,this.s,u)}recoverPublicKey(u){const{r:x,s:v}=this,I=this.assertRecovery(),T=I===2||I===3?x+a:x;if(!o.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const A=o.toBytes(T),b=s.fromBytes(ue(or((I&1)===0),A)),R=i.inv(T),k=z(M(u,void 0,"msgHash")),H=i.create(-k*R),$=i.create(v*R),N=s.BASE.multiplyUnsafe(H).add(b.multiplyUnsafe($));if(N.is0())throw new Error("invalid recovery: point at infinify");return N.assertValidity(),N}hasHighS(){return S(this.s)}toBytes(u=E.format){if(Xe(u),u==="der")return Me(de.hexFromSig(this));const{r:x,s:v}=this,I=i.toBytes(x),T=i.toBytes(v);return u==="recovered"?(U(),ue(Uint8Array.of(this.assertRecovery()),I,T)):ue(I,T)}toHex(u){return Ae(this.toBytes(u))}}const q=r.bits2int||function(u){if(u.length>8192)throw new Error("input is too large");const x=qe(u),v=u.length*8-c;return v>0?x>>BigInt(v):x},z=r.bits2int_modN||function(u){return i.create(q(u))},we=nt(c);function ae(h){return ps("num < 2^"+c,h,ne,we),i.toBytes(h)}function j(h,u){return M(h,void 0,"message"),u?M(e(h),void 0,"prehashed message"):h}function Re(h,u,x){const{lowS:v,prehash:I,extraEntropy:T}=Ye(x,E);h=j(h,I);const A=z(h),b=i.fromBytes(u);if(!i.isValidNot0(b))throw new Error("invalid private key");const R=[ae(b),ae(A)];if(T!=null&&T!==!1){const N=T===!0?t(_.secretKey):T;R.push(M(N,void 0,"extraEntropy"))}const k=ue(...R),H=A;function $(N){const G=q(N);if(!i.isValidNot0(G))return;const W=i.inv(G),Z=s.BASE.multiply(G).toAffine(),D=i.create(Z.x);if(D===ne)return;const V=i.create(W*i.create(H+D*b));if(V===ne)return;let dt=(Z.x===D?0:2)|Number(Z.y&ye),ut=V;return v&&S(V)&&(ut=i.neg(V),dt^=1),new B(D,ut,O?void 0:dt)}return{seed:k,k2sig:$}}function pe(h,u,x={}){const{seed:v,k2sig:I}=Re(h,u,x);return _s(e.outputLen,i.BYTES,n)(v,I).toBytes(x.format)}function L(h,u,x,v={}){const{lowS:I,prehash:T,format:A}=Ye(v,E);if(x=M(x,void 0,"publicKey"),u=j(u,T),!tt(h)){const b=h instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+b)}F(h,A);try{const b=B.fromBytes(h,A),R=s.fromBytes(x);if(I&&b.hasHighS())return!1;const{r:k,s:H}=b,$=z(u),N=i.inv(H),G=i.create($*N),W=i.create(k*N),Z=s.BASE.multiplyUnsafe(G).add(R.multiplyUnsafe(W));return Z.is0()?!1:i.create(Z.x)===k}catch{return!1}}function P(h,u,x={}){const{prehash:v}=Ye(x,E);return u=j(u,v),B.fromBytes(h,"recovered").recoverPublicKey(u).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:f,utils:y,lengths:_,Point:s,sign:pe,verify:L,recoverPublicKey:P,Signature:B,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const at={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Us={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Rt=BigInt(2);function Hs(s){const e=at.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,d=l*l*s%e,f=J(d,r,e)*d%e,y=J(f,r,e)*d%e,_=J(y,Rt,e)*l%e,E=J(_,n,e)*_%e,O=J(E,o,e)*E%e,S=J(O,a,e)*O%e,C=J(S,c,e)*S%e,U=J(C,a,e)*O%e,F=J(U,r,e)*d%e,B=J(F,i,e)*E%e,q=J(B,t,e)*l%e,z=J(q,Rt,e);if(!Je.eql(Je.sqr(z),s))throw new Error("Cannot find square root");return z}const Je=Ge(at.p,{sqrt:Hs}),Fs=$s(at,{Fp:Je,endo:Us}),qs=Ds(Fs,hs),Gs=BigInt(0),Te=BigInt(1),Ws=BigInt(2),Vs=BigInt(7),Ks=BigInt(256),zs=BigInt(113),ar=[],cr=[],lr=[];for(let s=0,e=Te,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],ar.push(2*(5*t+r)),cr.push((s+1)*(s+2)/2%64);let n=Gs;for(let o=0;o<7;o++)e=(e<<Te^(e>>Vs)*zs)%Ks,e&Ws&&(n^=Te<<(Te<<BigInt(o))-Te);lr.push(n)}const dr=ns(lr,!0),js=dr[0],Ys=dr[1],Ot=(s,e,r)=>r>32?as(s,e,r):os(s,e,r),Nt=(s,e,r)=>r>32?cs(s,e,r):is(s,e,r);function Zs(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)r[i]=s[i]^s[i+10]^s[i+20]^s[i+30]^s[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=r[c],d=r[c+1],f=Ot(l,d,1)^r[a],y=Nt(l,d,1)^r[a+1];for(let _=0;_<50;_+=10)s[i+_]^=f,s[i+_+1]^=y}let n=s[2],o=s[3];for(let i=0;i<24;i++){const a=cr[i],c=Ot(n,o,a),l=Nt(n,o,a),d=ar[i];n=s[d],o=s[d+1],s[d]=c,s[d+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=s[i+a];for(let a=0;a<10;a++)s[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=js[t],s[1]^=Ys[t]}ve(r)}class ct{constructor(e,r,t,n=!1,o=24){w(this,"state");w(this,"pos",0);w(this,"posOut",0);w(this,"finished",!1);w(this,"state32");w(this,"destroyed",!1);w(this,"blockLen");w(this,"suffix");w(this,"outputLen");w(this,"enableXOF",!1);w(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=o,ie(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=jr(this.state)}clone(){return this._cloneInto()}keccak(){_t(this.state32),Zs(this.state32,this.rounds),_t(this.state32),this.posOut=0,this.pos=0}update(e){be(this),M(e);const{blockLen:r,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(r-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){be(this,!1),M(e),this.finish();const r=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(r.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 ie(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($t(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,ve(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new ct(r,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 Xs=(s,e,r,t={})=>Dt(()=>new ct(e,s,r),t),kt=Xs(1,136,32);class Js{async verifyJWT(e,r){try{const t=this.decodeJWT(e);g.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const n=Math.floor(Date.now()/1e3);return t.exp&&t.exp<n?(g.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(g.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(g.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw g.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return fr.decodeJwt(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
939
- ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);const i=kt(o),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`Invalid signature length: expected 130 hex chars, got ${a.length}`);const c=Qs(a),l=c.slice(0,32),d=c.slice(32,64),f=c[64],y=f>=27?f-27:f,O=new qs.Signature(Ct(l),Ct(d)).addRecoveryBit(y).recoverPublicKey(i).toBytes(!1).slice(1),S=kt(O);return"0x"+Ae(S.slice(12))}}function Qs(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function Ct(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const en=3e4;class tn{async request(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??en);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal}),o=await n.json();return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}class lt{static generateState(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}openAuth(e){return new Promise((r,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=lt.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 y=setTimeout(()=>{E(),t(new Error("Authentication timeout"))},5*60*1e3),_=setInterval(()=>{try{f.closed&&(g.log("[CROSSx] 팝업이 닫혔습니다"),E(),t(new Error("로그인이 취소되었습니다")))}catch{}},1e3),E=()=>{clearTimeout(y),clearInterval(_),window.removeEventListener("message",O)},O=S=>{var U,F,B,q,z,we,ae;if(S.origin!==e.expectedOrigin)return;E(),g.log("[CROSSx] OAuth postMessage 수신 — status:",S.data.status);const C=S.data.state??((U=S.data.data)==null?void 0:U.state);if(C&&C!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(S.data.status==="success"){const j=((F=S.data.data)==null?void 0:F.accessToken)||((B=S.data.data)==null?void 0:B.idToken);g.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!((q=S.data.data)!=null&&q.accessToken),hasIdToken:!!((z=S.data.data)!=null&&z.idToken)}),j?r(j):(g.error("[CROSSx] 토큰을 찾을 수 없음:",S.data),t(new Error("Token not found in response")))}else g.error("[CROSSx] OAuth 실패:",(we=S.data.data)==null?void 0:we.error),t(new Error(((ae=S.data.data)==null?void 0:ae.error)||"Authentication failed"))};window.addEventListener("message",O)})}}const Le="crossx_wallet_data";class rn{constructor(e){this.storage=e}async getOrCreateWallet(e){try{const r=await this.storage.get(Le);if(r)return r;const t={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};return await this.storage.set(Le,t),t}catch(r){throw new m(p.WALLET_CREATION_FAILED,"Wallet creation failed",r)}}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async getBalance(e,r){return"0x0"}async getTransactionCount(e,r){return 0}async getTransactionReceipt(e,r){return null}async rpcRequest(e,r,t){return g.log(`[Mock] rpcRequest: ${e}`),null}async prepare(e,r){const t="mock-"+crypto.randomUUID();return g.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,r,t,n=0,o,i){return g.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,o,i){return g.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${o} from=${i}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,o){g.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:i,format:"hex"}}async sendTransaction(e,r,t,n){return g.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async withdraw(e){g.log("[Mock] withdraw confirmation:",e)}async recoverWallet(e,r){g.log("[Mock] recoverWallet");const t={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};return await this.storage.set(Le,t),t}async migrateWallet(e,r){g.log(`[Mock] migrateWallet pin=${e} sub=${r}`);const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};return await this.storage.set(Le,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 He{constructor(e,r,t,n){this.baseUrl=e.gatewayUrl,this.projectId=e.projectId,this.appId=e.appId,this.appType=e.appType,this.storage=r,this.transport=t,this.tokenStore=n}getAuthToken(){const e=this.tokenStore.get();if(!e)throw new m(p.AUTH_NOT_AUTHENTICATED,"No auth token found. Please sign in first.");return e}async request(e,r,t){var a,c;const n=this.getAuthToken(),o=`${this.baseUrl}${r}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Project-Id":this.projectId};this.appId&&(i["X-App-Id"]=this.appId,i["X-App-Type"]=this.appType);try{const d=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const f=d.message||d.data||"API request failed";g.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:f,url:o,method:e,fullResponse:d});const y=He.mapGatewayError(d.code),_=He.getGatewayErrorMessage(d.code,f),E=new m(y,_);throw E.gatewayCode=d.code,E.gatewayMessage=f,E}return g.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:o,method:e}),d.data??d}return d}catch(l){if(l instanceof m)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,f=d.message||d.data||"API request failed",y=d.code||"UNKNOWN";throw g.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:y,message:f,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new m(p.UNKNOWN_ERROR,`Wallet Gateway error (${y}): ${f}`)}throw l}}async getOrCreateWallet(e){var r;g.log("[CROSSx][Migration Phase 2] GET /mnemonic/addresses — 기존 지갑 조회");try{const t=await this.request("GET","/mnemonic/addresses");if(t.addresses&&t.addresses.length>0){const{address:n}=t.addresses[0];return g.log("[CROSSx][Migration Phase 2] 기존 지갑 발견 — address:",n),{id:e,address:n,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}}catch{g.log("[CROSSx][Migration Phase 2] 기존 지갑 없음, POST /mnemonic/create 진행")}g.log("[CROSSx][Migration Phase 2] POST /mnemonic/create — ignoreBackup: false");try{const t={ignoreBackup:!1},n=await this.request("POST","/mnemonic/create",t);return g.log("[CROSSx][Migration Phase 2] /mnemonic/create 성공 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}catch(t){if((t==null?void 0:t.gatewayCode)===-10004||(r=t==null?void 0:t.message)!=null&&r.includes("-10004")){g.log("[CROSSx][Migration Phase 2] 지갑 이미 존재 (-10004), 주소 재조회");const n=await this.request("GET","/mnemonic/addresses");if(n.addresses&&n.addresses.length>0)return{id:e,address:n.addresses[0].address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}throw(t==null?void 0:t.gatewayCode)===-10012&&g.log("[CROSSx][Migration Phase 2] Gateway -10012 수신 → MIGRATION_BACKUP_EXISTS throw"),t}}async getAddress(e,r){try{return{address:(await this.request("GET",`/mnemonic/address?index=${r}`)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}catch(t){if(t instanceof m&&this.isAddressNotFoundError(t))return g.log(`[CROSSx] index ${r} 주소 없음, 파생 중...`),{address:(await this.request("GET",`/mnemonic/address?index=${r}&derive=true`)).address,derivationPath:`m/44'/60'/0'/0/${r}`};throw t}}isAddressNotFoundError(e){const r=e.message.toLowerCase();return r.includes("404")||r.includes("not found")||r.includes("찾을 수 없")||r.includes("does not exist")||r.includes("no address")}async rpcCall(e,r,t){const n={jsonrpc:"2.0",method:e,params:r,id:Date.now()},o=await this.request("POST",`/wallet/rpc/${encodeURIComponent(t)}`,n);if(o!=null&&o.error)throw new m(p.UNKNOWN_ERROR,`RPC call failed (${e}): ${o.error.message}`);return o==null?void 0:o.result}async getBalance(e,r){return await this.rpcCall("eth_getBalance",[e,"latest"],r)??"0x0"}async getTransactionCount(e,r){const t=await this.rpcCall("eth_getTransactionCount",[e,"pending"],r);return parseInt(t??"0x0",16)}async getTransactionReceipt(e,r){return await this.rpcCall("eth_getTransactionReceipt",[e],r)??null}async rpcRequest(e,r,t){return this.rpcCall(e,r,t)}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new m(p.TX_INVALID_PARAMS,"prepare: tx is required");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new m(p.TX_INVALID_PARAMS,"prepare: message is required");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new m(p.TX_INVALID_PARAMS,"prepare: typedData is required");t={typedData:r.typedData},r.from&&(t.from=r.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,r,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:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,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",a);return{chainId:r,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,r,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t)};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,i);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const o={unsignedTx:this.buildUnsignedTx(t)};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,o)).txHash}}async withdraw(e){const r={confirmation:e};if(!(await this.request("POST","/mnemonic/withdraw",r)).success)throw new m(p.UNKNOWN_ERROR,"Wallet withdrawal failed")}async recoverWallet(e,r){const t={shareC:r},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,r){g.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출 — sub:",r);const t={pin:e,sub:r},n=await this.request("POST","/mnemonic/migrate",t);return g.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}static mapGatewayError(e){switch(e){case-10002:return p.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_OR_APP_ID_MISSING;case-10025:return p.INVALID_APP_TYPE;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){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"This project or origin is not registered. Check your projectId and allowed origins in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Web requests need a valid Origin; native apps need appId and appType in SDKConfig.";case-10025:return'Invalid app type. appType must be "ios" or "android".';default:return`Request failed (${e}): ${r}`}}}class sn{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}const nn="https://cross-wallet-oauth.crosstoken.io",on="https://cross-auth.crosstoken.io",an="https://embedded-wallet-gateway.crosstoken.io/api/v1";function cn(){return nn}function ln(){return on}function dn(){return an}function un(s){s.debug;const e=cn(),r=ln(),t=dn(),n={...s,oauthServiceUrl:e,authApiUrl:r,walletGatewayUrl:t},o=new zr,i=new Js,a=new tn,c=new lt,l=new sn;let d;return s.useMockWallet?(g.log("[CROSSx] Mock Wallet Provider 사용"),d=new rn(o)):(g.log("[CROSSx] Remote Wallet Provider 사용"),d=new He({gatewayUrl:t,projectId:s.projectId,appId:s.appId,appType:s.appType},o,a,l)),new $e(n,o,i,a,c,d,l)}const hn={CROSS_MAINNET:"eip155:612055",CROSS_TESTNET:"eip155:612044",ETHEREUM_MAINNET:"eip155:1",ETHEREUM_SEPOLIA:"eip155:11155111",ETHEREUM_HOLESKY:"eip155:17000",POLYGON_MAINNET:"eip155:137",POLYGON_AMOY:"eip155:80002",BSC_MAINNET:"eip155:56",BSC_TESTNET:"eip155:97",ARBITRUM_ONE:"eip155:42161",ARBITRUM_SEPOLIA:"eip155:421614",OPTIMISM_MAINNET:"eip155:10",OPTIMISM_SEPOLIA:"eip155:11155420",BASE_MAINNET:"eip155:8453",BASE_SEPOLIA:"eip155:84532"};exports.CROSSxError=m;exports.CROSSxEthereumProvider=Pt;exports.CROSSxSDK=$e;exports.ChainId=hn;exports.ErrorCode=p;exports.createCROSSxSDK=un;
999
+ `,n}function An(r,e,s){var n;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,i)=>{o.addEventListener("input",()=>{const a=o.value.replace(/\D/g,"");o.value=a?a[0]:"",a&&i<3&&t[i+1].focus();const c=Array.from(t).map(l=>l.value).join("");c.length===4&&setTimeout(()=>e(c),200)}),o.addEventListener("keydown",a=>{a.key==="Backspace"&&!o.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&s()}),o.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),o.addEventListener("paste",a=>{var d;a.preventDefault();const c=(((d=a.clipboardData)==null?void 0:d.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!c)return;c.split("").forEach((g,w)=>{t[w]&&(t[w].value=g)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(n=t[0])==null||n.focus()}class In{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=qt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=qt(e,this.overrides)}getTheme(){return this.theme}showLoginSelector(){return new Promise(e=>{var a,c,l;Se();const s=Sn(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=d=>{t(),e(d)},o=()=>{t(),e(null)};(a=s.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>n("apple")),(c=s.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>n("google")),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()}),s.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",g=>g.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;Se();const s=En(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=()=>{t(),e("recover")},o=()=>{t(),e("skip")};(a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),(c=s.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",o),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showPinInputPrompt(e){return new Promise(s=>{var a;Se();const t=Tn(this.tokens,e);document.body.appendChild(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};An(t,o,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;Se();const t=xn(e,this.tokens);document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var w;d.stopPropagation();const g=l.dataset.copy;g&&((w=navigator.clipboard)==null||w.writeText(g).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{Se();const n=_n(e,this.tokens);document.body.appendChild(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var d,g;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(g=n.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",a),n.addEventListener("click",w=>{w.target===n&&a()});const l=w=>{w.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(mn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;Se();let t;e.type==="sign-message"?t=wn(e,this.tokens):e.type==="sign-typed-data"?t=yn(e,this.tokens):e.type==="sign"?t=hn(e,this.tokens):t=fn(e,this.tokens),document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s(!0)},i=()=>{n(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",o),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(d=t.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",w=>{var x;w.stopPropagation();const m=g.dataset.copy;m&&((x=navigator.clipboard)==null||x.writeText(m).catch(()=>{}))})}),t.addEventListener("click",g=>{g.target===t&&i()});const a=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class Rn{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}const On="https://cross-wallet-oauth.crosstoken.io",Cn="https://cross-auth.crosstoken.io",Nn="https://embedded-wallet-gateway.crosstoken.io/api/v1";function Pn(){return On}function kn(){return Cn}function Ln(){return Nn}function Dn(r){r.debug;const e=Pn(),s=kn(),t=Ln(),n={...r,oauthServiceUrl:e,authApiUrl:s,walletGatewayUrl:t},i=r.authMode==="token"&&Tt.isAvailable()?new Tt:new Ws,a=new Jr,c=new tn,l=new gt,d=new Rn;let g;r.useMockWallet?(f.log("[CROSSx] Mock Wallet Provider 사용"),g=new sn(i)):(f.log("[CROSSx] Remote Wallet Provider 사용"),g=new qe({gatewayUrl:t,projectId:r.projectId},i,c,d));const w=new Oe({gatewayUrl:t,projectId:r.projectId},c),m=new In(r.theme??"light",r.themeTokens);return new Fe(n,i,a,c,l,g,d,m,w)}exports.CROSSxError=_;exports.CROSSxEthereumProvider=jt;exports.CROSSxSDK=Fe;exports.ChainId=Is;exports.ErrorCode=p;exports.createCROSSxSDK=Dn;