@skip-go/widget-web-component 3.18.5 → 3.19.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.
@@ -1,5 +1,5 @@
1
1
  /*! For license information please see 9194.index.js.LICENSE.txt */
2
- export const __webpack_esm_id__=9194;export const __webpack_esm_ids__=[9194];export const __webpack_esm_modules__={1420:(e,t,s)=>{s.d(t,{H:()=>c});var i=s(89168),r=s(39150),n=s(3555),o=s(47436);const a=(0,i.BX)({features:n.oU.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:n.oU.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),c={state:a,subscribeKey:(e,t)=>(0,r.u$)(a,e,t),setOptions(e){Object.assign(a,e)},setRemoteFeatures(e){if(!e)return;const t={...a.remoteFeatures,...e};a.remoteFeatures=t,a.remoteFeatures?.socials&&(a.remoteFeatures.socials=o.D.filterSocialsByPlatform(a.remoteFeatures.socials))},setFeatures(e){if(!e)return;a.features||(a.features=n.oU.DEFAULT_FEATURES);const t={...a.features,...e};a.features=t},setProjectId(e){a.projectId=e},setCustomRpcUrls(e){a.customRpcUrls=e},setAllWallets(e){a.allWallets=e},setIncludeWalletIds(e){a.includeWalletIds=e},setExcludeWalletIds(e){a.excludeWalletIds=e},setFeaturedWalletIds(e){a.featuredWalletIds=e},setTokens(e){a.tokens=e},setTermsConditionsUrl(e){a.termsConditionsUrl=e},setPrivacyPolicyUrl(e){a.privacyPolicyUrl=e},setCustomWallets(e){a.customWallets=e},setIsSiweEnabled(e){a.isSiweEnabled=e},setIsUniversalProvider(e){a.isUniversalProvider=e},setSdkVersion(e){a.sdkVersion=e},setMetadata(e){a.metadata=e},setDisableAppend(e){a.disableAppend=e},setEIP6963Enabled(e){a.enableEIP6963=e},setDebug(e){a.debug=e},setEnableWalletConnect(e){a.enableWalletConnect=e},setEnableWalletGuide(e){a.enableWalletGuide=e},setEnableAuthLogger(e){a.enableAuthLogger=e},setEnableWallets(e){a.enableWallets=e},setPreferUniversalLinks(e){a.experimental_preferUniversalLinks=e},setHasMultipleAddresses(e){a.hasMultipleAddresses=e},setSIWX(e){a.siwx=e},setConnectMethodsOrder(e){a.features={...a.features,connectMethodsOrder:e}},setWalletFeaturesOrder(e){a.features={...a.features,walletFeaturesOrder:e}},setSocialsOrder(e){a.remoteFeatures={...a.remoteFeatures,socials:e}},setCollapseWallets(e){a.features={...a.features,collapseWallets:e}},setEnableEmbedded(e){a.enableEmbedded=e},setAllowUnsupportedChain(e){a.allowUnsupportedChain=e},setManualWCControl(e){a.manualWCControl=e},setEnableNetworkSwitch(e){a.enableNetworkSwitch=e},setDefaultAccountTypes(e={}){Object.entries(e).forEach(([e,t])=>{t&&(a.defaultAccountTypes[e]=t)})},setUniversalProviderConfigOverride(e){a.universalProviderConfigOverride=e},getUniversalProviderConfigOverride:()=>a.universalProviderConfigOverride,getSnapshot:()=>(0,i.P9)(a)}},1435:(e,t,s)=>{s.d(t,{E:()=>i});const i={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]}},2974:(e,t,s)=>{s.d(t,{r:()=>r});var i=s(70255);const r={createLogger(e,t="error"){const s=(0,i.iP)({level:t}),{logger:r}=(0,i.D5)({opts:s});return r.error=(...t)=>{for(const s of t)if(s instanceof Error)return void e(s,...t);e(void 0,...t)},r}}},3555:(e,t,s)=>{s.d(t,{Db:()=>o,oU:()=>a,tM:()=>n});var i=s(39907);const r=(void 0!==i&&void 0!==i.env?i.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",n=[{label:"Coinbase",name:"coinbase",feeRange:"1-2%",url:"",supportedChains:["eip155"]},{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],o="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",a={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:r,SECURE_SITE_DASHBOARD:`${r}/dashboard`,SECURE_SITE_FAVICON:`${r}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],WC_COINBASE_PAY_SDK_CHAINS:["ethereum","arbitrum","polygon","berachain","avalanche-c-chain","optimism","celo","base"],WC_COINBASE_PAY_SDK_FALLBACK_CHAIN:"ethereum",WC_COINBASE_PAY_SDK_CHAIN_NAME_MAP:{Ethereum:"ethereum","Arbitrum One":"arbitrum",Polygon:"polygon",Berachain:"berachain",Avalanche:"avalanche-c-chain","OP Mainnet":"optimism",Celo:"celo",Base:"base"},WC_COINBASE_ONRAMP_APP_ID:"bf18c88d-495a-463b-b249-0b9d3656cf5e",SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:["eip155","solana"],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:["eip155"],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:["eip155","solana"],ACTIVITY_ENABLED_CHAIN_NAMESPACES:["eip155"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:["eip155","solana"],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["coinbase","meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"}}},4159:(e,t,s)=>{s.d(t,{S:()=>r});var i=s(66857);const r={bigNumber:e=>e?new i.A(e):new i.A(0),multiply(e,t){if(void 0===e||void 0===t)return new i.A(0);const s=new i.A(e),r=new i.A(t);return s.times(r)},formatNumberToLocalString:(e,t=2)=>void 0===e?"0.00":"number"==typeof e?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t}),parseLocalStringToNumber:e=>void 0===e?0:parseFloat(e.replace(/,/gu,""))}},6262:(e,t,s)=>{s.d(t,{j:()=>c});var i=s(89168),r=s(39150),n=s(37834);const o=(0,i.BX)({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),a={state:o,subscribeNetworkImages:e=>(0,i.B1)(o.networkImages,()=>e(o.networkImages)),subscribeKey:(e,t)=>(0,r.u$)(o,e,t),subscribe:e=>(0,i.B1)(o,()=>e(o)),setWalletImage(e,t){o.walletImages[e]=t},setNetworkImage(e,t){o.networkImages[e]=t},setChainImage(e,t){o.chainImages[e]=t},setConnectorImage(e,t){o.connectorImages={...o.connectorImages,[e]:t}},setTokenImage(e,t){o.tokenImages[e]=t},setCurrencyImage(e,t){o.currencyImages[e]=t}},c=(0,n.X)(a)},9732:(e,t,s)=>{s.d(t,{O:()=>r,W:()=>n});var i=s(72269);const r={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},n={handleMobileDeeplinkRedirect(e,t){const s=window.location.href,n=encodeURIComponent(s);if(e===r.PHANTOM.id&&!("phantom"in window)){const e=s.startsWith("https")?"https":"http",t=s.split("/")[2],i=encodeURIComponent(`${e}://${t}`);window.location.href=`${r.PHANTOM.url}/ul/browse/${n}?ref=${i}`}e!==r.SOLFLARE.id||"solflare"in window||(window.location.href=`${r.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),t===i.o.CHAIN.SOLANA&&(e!==r.COINBASE.id||"coinbaseSolana"in window||(window.location.href=`${r.COINBASE.url}/dapp?cb_url=${n}`))}}},11148:(e,t,s)=>{s.d(t,{t:()=>c});var i=s(23981),r=s(16444),n=s(98299),o=s(86792),a=s(54947);const c={async getMyTokensWithBalance(e){const t=i.U.state.address,s=n.W.state.activeCaipNetwork;if(!t||!s)return[];if("eip155"===s.chainNamespace){const e=await this.getEIP155Balances(t,s);if(e)return this.filterLowQualityTokens(e)}const o=await r.T.getBalance(t,s.caipNetworkId,e);return this.filterLowQualityTokens(o.balances)},async getEIP155Balances(e,t){try{const s=a.T.getChainIdHexFromCAIP2ChainId(t.caipNetworkId),i=await o.x.getCapabilities(e);if(!i?.[s]?.assetDiscovery?.supported)return null;const r=await o.x.walletGetAssets({account:e,chainFilter:[s]});return a.T.isWalletGetAssetsResponse(r)?(r[s]||[]).map(e=>a.T.createBalance(e,t.caipNetworkId)):null}catch(e){return null}},filterLowQualityTokens:e=>e.filter(e=>"0"!==e.quantity.decimals),mapBalancesToSwapTokens:e=>e?.map(e=>({...e,address:e?.address?e.address:n.W.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]}},11628:(e,t,s)=>{s.d(t,{i:()=>i});const i="1.7.8"},11847:(e,t,s)=>{s.d(t,{i:()=>r});var i=s(80971);const r={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired:(e,t)=>Date.now()-e>t,getActiveNetworkProps(){const e=r.getActiveNamespace(),t=r.getActiveCaipNetworkId(),s=t?t.split(":")[1]:void 0;return{namespace:e,caipNetworkId:t,chainId:s?isNaN(Number(s))?s:Number(s):void 0}},setWalletConnectDeepLink({name:e,href:t}){try{i.Ud.setItem(i.Ws.DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const e=i.Ud.getItem(i.Ws.DEEPLINK_CHOICE);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{i.Ud.removeItem(i.Ws.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{i.Ud.setItem(i.Ws.ACTIVE_NAMESPACE,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{i.Ud.setItem(i.Ws.ACTIVE_CAIP_NETWORK_ID,e),r.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return i.Ud.getItem(i.Ws.ACTIVE_CAIP_NETWORK_ID)}catch{return void console.info("Unable to get active caip network id")}},deleteActiveCaipNetworkId(){try{i.Ud.removeItem(i.Ws.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{const t=(0,i.T8)(e);i.Ud.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{const t=r.getRecentWallets();t.find(t=>t.id===e.id)||(t.unshift(e),t.length>2&&t.pop(),i.Ud.setItem(i.Ws.RECENT_WALLETS,JSON.stringify(t)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const e=i.Ud.getItem(i.Ws.RECENT_WALLETS);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(e,t){try{const s=(0,i.T8)(e);i.Ud.setItem(s,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return i.Ud.getItem(i.Ws.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{const t=(0,i.T8)(e);return i.Ud.getItem(t)}catch(t){console.info("Unable to get connected connector id in namespace ",e)}},setConnectedSocialProvider(e){try{i.Ud.setItem(i.Ws.CONNECTED_SOCIAL,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return i.Ud.getItem(i.Ws.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{i.Ud.removeItem(i.Ws.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return i.Ud.getItem(i.Ws.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){const e=i.Ud.getItem(i.Ws.ACTIVE_CAIP_NETWORK_ID),t=e?.split(":")?.[1];return t},setConnectionStatus(e){try{i.Ud.setItem(i.Ws.CONNECTION_STATUS,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return i.Ud.getItem(i.Ws.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const e=i.Ud.getItem(i.Ws.CONNECTED_NAMESPACES);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));i.Ud.setItem(i.Ws.CONNECTED_NAMESPACES,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{const t=r.getConnectedNamespaces();t.includes(e)||(t.push(e),r.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{const t=r.getConnectedNamespaces(),s=t.indexOf(e);s>-1&&(t.splice(s,1),r.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return i.Ud.getItem(i.Ws.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{i.Ud.setItem(i.Ws.TELEGRAM_SOCIAL_PROVIDER,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{i.Ud.removeItem(i.Ws.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{const t=i.Ud.getItem(i.Ws.PORTFOLIO_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{const t=r.getBalanceCache();i.Ud.setItem(i.Ws.PORTFOLIO_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{const t=r.getBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;r.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{const t=r.getBalanceCache();t[e.caipAddress]=e,i.Ud.setItem(i.Ws.PORTFOLIO_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{const t=i.Ud.getItem(i.Ws.NATIVE_BALANCE_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{const t=r.getBalanceCache();i.Ud.setItem(i.Ws.NATIVE_BALANCE_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getNativeBalanceCacheForCaipAddress(e){try{const t=r.getNativeBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",e),r.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{const t=r.getNativeBalanceCache();t[e.caipAddress]=e,i.Ud.setItem(i.Ws.NATIVE_BALANCE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{const t=i.Ud.getItem(i.Ws.ENS_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{const t=r.getEnsCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;r.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{const t=r.getEnsCache();t[e.address]=e,i.Ud.setItem(i.Ws.ENS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{const t=r.getEnsCache();i.Ud.setItem(i.Ws.ENS_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove ens name from cache",e)}},getIdentityCache(){let e={};try{const t=i.Ud.getItem(i.Ws.IDENTITY_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{const t=r.getIdentityCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;r.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{const t=r.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},i.Ud.setItem(i.Ws.IDENTITY_CACHE,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{const t=r.getIdentityCache();i.Ud.setItem(i.Ws.IDENTITY_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},clearAddressCache(){try{i.Ud.removeItem(i.Ws.PORTFOLIO_CACHE),i.Ud.removeItem(i.Ws.NATIVE_BALANCE_CACHE),i.Ud.removeItem(i.Ws.ENS_CACHE),i.Ud.removeItem(i.Ws.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{i.Ud.setItem(i.Ws.PREFERRED_ACCOUNT_TYPES,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{const e=i.Ud.getItem(i.Ws.PREFERRED_ACCOUNT_TYPES);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{const s={...r.getConnections(),[t]:e};i.Ud.setItem(i.Ws.CONNECTIONS,JSON.stringify(s))}catch(e){console.error("Unable to sync connections to storage",e)}},getConnections(){try{const e=i.Ud.getItem(i.Ws.CONNECTIONS);return e?JSON.parse(e):{}}catch(e){return console.error("Unable to get connections from storage",e),{}}}}},13679:(e,t,s)=>{function i(e){return function(t){return"function"==typeof t?function(e,t){return customElements.get(e)||customElements.define(e,t),t}(e,t):function(e,t){const{kind:s,elements:i}=t;return{kind:s,elements:i,finisher(t){customElements.get(e)||customElements.define(e,t)}}}(e,t)}}s.d(t,{E:()=>i})},13766:(e,t,s)=>{s.d(t,{f:()=>f});var i=s(89168),r=s(39150),n=s(39030),o=s(11847),a=s(37834),c=s(23981),l=s(16444),d=s(98299),h=s(86792),p=s(83077),u=s(72397);const g=(0,i.BX)({suggestions:[],loading:!1}),m={state:g,subscribe:e=>(0,i.B1)(g,()=>e(g)),subscribeKey:(e,t)=>(0,r.u$)(g,e,t),async resolveName(e){try{return await l.T.lookupEnsName(e)}catch(e){const t=e;throw new Error(t?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(e){try{return await l.T.lookupEnsName(e),!0}catch{return!1}},async getSuggestions(e){try{g.loading=!0,g.suggestions=[];const t=await l.T.getEnsNameSuggestions(e);return g.suggestions=t.suggestions.map(e=>({...e,name:e.name}))||[],g.suggestions}catch(e){const t=f.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(t)}finally{g.loading=!1}},async getNamesForAddress(e){try{if(!d.W.state.activeCaipNetwork)return[];const t=o.i.getEnsFromCacheForAddress(e);if(t)return t;const s=await l.T.reverseLookupEnsName({address:e});return o.i.updateEnsCache({address:e,ens:s,timestamp:Date.now()}),s}catch(e){const t=f.parseEnsApiError(e,"Error fetching names for address");throw new Error(t)}},async registerName(e){const t=d.W.state.activeCaipNetwork;if(!t)throw new Error("Network not found");const s=c.U.state.address,i=p.a.getAuthConnector();if(!s||!i)throw new Error("Address or auth connector not found");g.loading=!0;try{const i=JSON.stringify({name:e,attributes:{},timestamp:Math.floor(Date.now()/1e3)});u.I.pushTransactionStack({onCancel(){u.I.replace("RegisterAccountName")}});const r=await h.x.signMessage(i);g.loading=!1;const o=t.id;if(!o)throw new Error("Network not found");const a=n.p.convertEVMChainIdToCoinType(Number(o));await l.T.registerEnsName({coinType:a,address:s,signature:r,message:i}),c.U.setProfileName(e,t.chainNamespace),u.I.replace("RegisterAccountNameSuccess")}catch(t){const s=f.parseEnsApiError(t,`Error registering name ${e}`);throw u.I.replace("RegisterAccountName"),new Error(s)}finally{g.loading=!1}},validateName:e=>/^[a-zA-Z0-9-]{4,}$/u.test(e),parseEnsApiError(e,t){const s=e;return s?.reasons?.[0]?.description||t}},f=(0,a.X)(m)},15179:(e,t,s)=>{s.d(t,{Z:()=>i});const i={getSpacingStyles:(e,t)=>Array.isArray(e)?e[t]?`var(--wui-spacing-${e[t]})`:void 0:"string"==typeof e?`var(--wui-spacing-${e})`:void 0,getFormattedDate:e=>new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}).format(e),getHostName(e){try{return new URL(e).hostname}catch(e){return""}},getTruncateString:({string:e,charsStart:t,charsEnd:s,truncate:i})=>e.length<=t+s?e:"end"===i?`${e.substring(0,t)}...`:"start"===i?`...${e.substring(e.length-s)}`:`${e.substring(0,Math.floor(t))}...${e.substring(e.length-Math.floor(s))}`,generateAvatarColors(e){const t=e.toLowerCase().replace(/^0x/iu,"").replace(/[^a-f0-9]/gu,"").substring(0,6).padEnd(6,"0"),s=this.hexToRgb(t),i=getComputedStyle(document.documentElement).getPropertyValue("--w3m-border-radius-master"),r=100-3*Number(i?.replace("px","")),n=`${r}% ${r}% at 65% 40%`,o=[];for(let e=0;e<5;e+=1){const t=this.tintColor(s,.15*e);o.push(`rgb(${t[0]}, ${t[1]}, ${t[2]})`)}return`\n --local-color-1: ${o[0]};\n --local-color-2: ${o[1]};\n --local-color-3: ${o[2]};\n --local-color-4: ${o[3]};\n --local-color-5: ${o[4]};\n --local-radial-circle: ${n}\n `},hexToRgb(e){const t=parseInt(e,16);return[t>>16&255,t>>8&255,255&t]},tintColor(e,t){const[s,i,r]=e;return[Math.round(s+(255-s)*t),Math.round(i+(255-i)*t),Math.round(r+(255-r)*t)]},isNumber:e=>/^[0-9]+$/u.test(e),getColorTheme:e=>e||("undefined"!=typeof window&&window.matchMedia?window.matchMedia("(prefers-color-scheme: dark)")?.matches?"dark":"light":"dark"),splitBalance(e){const t=e.split(".");return 2===t.length?[t[0],t[1]]:["0","00"]},roundNumber:(e,t,s)=>e.toString().length>=t?Number(e).toFixed(s):e,formatNumberToLocalString:(e,t=2)=>void 0===e?"0.00":"number"==typeof e?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t})}},15529:(e,t,s)=>{s.d(t,{$Bq:()=>or,$hI:()=>te,ADD:()=>z,ALl:()=>Wi,AYU:()=>xr,Alu:()=>Hr,AwN:()=>Ji,BdH:()=>x,C5G:()=>Gi,CTo:()=>Ur,Ds_:()=>L,EHS:()=>Pi,EN$:()=>Li,EWt:()=>Ii,F$L:()=>Vi,FR8:()=>Gr,FiO:()=>jr,GuA:()=>Nr,HNf:()=>kr,Hbs:()=>en,Hjj:()=>Ar,IjX:()=>et,K3g:()=>F,Lln:()=>T,Lp_:()=>Si,M8n:()=>Kr,OP1:()=>_r,PAk:()=>qe,PUk:()=>$,Pa8:()=>Ni,QJh:()=>nr,Qhg:()=>Tr,R7U:()=>D,TRk:()=>Z,TZl:()=>xi,TeY:()=>Fr,Tw2:()=>Fi,U0i:()=>Zi,V7m:()=>Xi,V9G:()=>$r,VBM:()=>dt,Van:()=>vr,WWN:()=>lt,Wx8:()=>H,X3c:()=>Vr,XEe:()=>Er,XqR:()=>Zr,Xw0:()=>J,YcA:()=>Hi,_Yb:()=>m,_dF:()=>X,aF0:()=>Sr,aRZ:()=>R,aa1:()=>tr,b07:()=>Pr,bEt:()=>Ci,c82:()=>G,e8_:()=>ot,esh:()=>Br,gOF:()=>K,gZm:()=>se,h0Y:()=>q,hEn:()=>Y,hVC:()=>at,hwK:()=>tt,iV1:()=>zr,iui:()=>Ki,jTh:()=>ee,jUZ:()=>B,kob:()=>yr,kuU:()=>qr,lFF:()=>W,lVv:()=>O,m01:()=>k,mr0:()=>Dr,n3s:()=>Q,n6V:()=>er,nWe:()=>wr,nyL:()=>on,oKp:()=>Xr,ojD:()=>M,ovp:()=>Di,ps1:()=>Yi,q_h:()=>Qe,sKr:()=>rn,sc7:()=>tn,sc_:()=>ct,tLy:()=>Jr,tk0:()=>Lr,two:()=>Ui,uym:()=>sn,w8K:()=>ie,wYp:()=>ir,wa2:()=>$i,x0t:()=>Bi,xkc:()=>Ze,yy4:()=>ne,z2N:()=>Yr});var i=s(24661),r=s(91315),n=s(20635),o=s(67822),a=s(71268),c=s(33244),l=s(97353),d=s(1030),h=s(17367),p=s(39907),u=s(48526).hp;const g=":";function m(e){const[t,s]=e.split(g);return{namespace:t,reference:s}}function f(e,t){return e.includes(":")?[e]:t.chains||[]}var w=Object.defineProperty,y=Object.defineProperties,b=Object.getOwnPropertyDescriptors,v=Object.getOwnPropertySymbols,E=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable,I=(e,t,s)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,N=(e,t)=>{for(var s in t||(t={}))E.call(t,s)&&I(e,s,t[s]);if(v)for(var s of v(t))C.call(t,s)&&I(e,s,t[s]);return e},A=(e,t)=>y(e,b(t));const _="ReactNative",S={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},P="js";function T(){return typeof p<"u"&&typeof p.versions<"u"&&typeof p.versions.node<"u"}function O(){return!(0,n.getDocument)()&&!!(0,n.getNavigator)()&&navigator.product===_}function k(){return O()&&typeof s.g<"u"&&typeof(null==s.g?void 0:s.g.Platform)<"u"&&"android"===(null==s.g?void 0:s.g.Platform.OS)}function R(){return O()&&typeof s.g<"u"&&typeof(null==s.g?void 0:s.g.Platform)<"u"&&"ios"===(null==s.g?void 0:s.g.Platform.OS)}function x(){return!T()&&!!(0,n.getNavigator)()&&!!(0,n.getDocument)()}function U(){return O()?S.reactNative:T()?S.node:x()?S.browser:S.unknown}function D(){var e;try{return O()&&typeof s.g<"u"&&typeof(null==s.g?void 0:s.g.Application)<"u"?null==(e=s.g.Application)?void 0:e.applicationId:void 0}catch{return}}function L(e){var t,s;const i=W();try{return null!=e&&e.url&&i.url&&new URL(e.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),e.url=i.url),null!=(t=e?.icons)&&t.length&&e.icons.length>0&&(e.icons=e.icons.filter(e=>""!==e)),A(N(N({},i),e),{url:e?.url||i.url,name:e?.name||i.name,description:e?.description||i.description,icons:null!=(s=e?.icons)&&s.length&&e.icons.length>0?e.icons:i.icons})}catch(t){return console.warn("Error populating app metadata",t),e||i}}function W(){return(0,o.g)()||{name:"",description:"",url:"",icons:[""]}}function M(e,t,r){const o=function(){if(U()===S.reactNative&&typeof s.g<"u"&&typeof(null==s.g?void 0:s.g.Platform)<"u"){const{OS:e,Version:t}=s.g.Platform;return[e,t].join("-")}const e=(0,i.o0)();if(null===e)return"unknown";const t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[t,e.name,e.version].join("-"):[t,e.version].join("-")}(),a=function(){var e;const t=U();return t===S.browser?[t,(null==(e=(0,n.getLocation)())?void 0:e.host)||"unknown"].join(":"):t}();return[[e,t].join("-"),[P,r].join("-"),o,a].join("/")}function B({protocol:e,version:t,relayUrl:s,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d={auth:r,ua:M(e,t,i),projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=function(e,t){const s=new URLSearchParams(e);for(const e of Object.keys(t).sort())if(t.hasOwnProperty(e)){const i=t[e];void 0!==i&&s.set(e,i)}return s.toString()}(l[1]||"",d);return l[0]+"?"+h}function j(e,t){return e.filter(e=>t.includes(e)).length===e.length}function q(e){return Object.fromEntries(e.entries())}function $(e){return new Map(Object.entries(e))}function H(e=r.FIVE_MINUTES,t){const s=(0,r.toMiliseconds)(e||r.FIVE_MINUTES);let i,n,o,a;return{resolve:e=>{o&&i&&(clearTimeout(o),i(e),a=Promise.resolve(e))},reject:e=>{o&&n&&(clearTimeout(o),n(e))},done:()=>new Promise((e,r)=>{if(a)return e(a);o=setTimeout(()=>{const e=new Error(t);a=Promise.reject(e),r(e)},s),i=e,n=r})}}function F(e,t,s){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(s)),t);try{i(await e)}catch(e){r(e)}clearTimeout(n)})}function V(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function z(e){return V("topic",e)}function K(e){return V("id",e)}function G(e){const[t,s]=e.split(":"),i={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof s)i.topic=s;else{if("id"!==t||!Number.isInteger(Number(s)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${s}`);i.id=Number(s)}return i}function J(e,t){return(0,r.fromMiliseconds)((t||Date.now())+(0,r.toMiliseconds)(e))}function X(e){return Date.now()>=(0,r.toMiliseconds)(e)}function Y(e,t){return`${e}${t?`:${t}`:""}`}function Z(e=[],t=[]){return[...new Set([...e,...t])]}async function Q({id:e,topic:t,wcDeepLink:i}){var r;try{if(!i)return;const o="string"==typeof i?JSON.parse(i):i,a=o?.href;if("string"!=typeof a)return;const c=function(e,t,s){const i=`requestId=${t}&sessionTopic=${s}`;e.endsWith("/")&&(e=e.slice(0,-1));let r=`${e}`;return r=e.startsWith("https://t.me")?`${r}${e.includes("?")?"&startapp=":"?startapp="}${function(e,t=!1){const s=u.from(e).toString("base64");return t?s.replace(/[=]/g,""):s}(i,!0)}`:`${r}/wc?${i}`,r}(a,e,t),l=U();if(l===S.browser){if(null==(r=(0,n.getDocument)())||!r.hasFocus())return void console.warn("Document does not have focus, skipping deeplink.");!function(e){let t="_self";!function(){try{return window.self!==window.top}catch{return!1}}()?(typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"):t="_top",window.open(e,t,"noreferrer noopener")}(c)}else l===S.reactNative&&typeof(null==s.g?void 0:s.g.Linking)<"u"&&await s.g.Linking.openURL(c)}catch(e){console.error(e)}}async function ee(e,t){let s="";try{if(x()&&(s=localStorage.getItem(t),s))return s;s=await e.getItem(t)}catch(e){console.error(e)}return s}function te(e,t){if(!e.includes(t))return null;const s=e.split(/([&,?,=])/),i=s.indexOf(t);return s[i+2]}function se(){return typeof crypto<"u"&&null!=crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function ie(){return typeof p<"u"&&"true"===p.env.IS_VITEST}function re(e){return u.from(e,"base64").toString("utf-8")}function ne(e){return new Promise(t=>setTimeout(t,e))}function oe(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ae(e,...t){if(!function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ce(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");oe(e.outputLen),oe(e.blockLen)}function le(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function de(e,t){ae(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const he=BigInt(2**32-1),pe=BigInt(32);function ue(e,t=!1){return t?{h:Number(e&he),l:Number(e>>pe&he)}:{h:0|Number(e>>pe&he),l:0|Number(e&he)}}const ge="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function me(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function fe(e,t){return e<<32-t|e>>>t}const we=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function ye(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function be(e){for(let t=0;t<e.length;t++)e[t]=ye(e[t])}function ve(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),ae(e),e}class Ee{clone(){return this._cloneInto()}}function Ce(e){const t=t=>e().update(ve(t)).digest(),s=e();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>e(),t}function Ie(e=32){if(ge&&"function"==typeof ge.getRandomValues)return ge.getRandomValues(new Uint8Array(e));if(ge&&"function"==typeof ge.randomBytes)return ge.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}const Ne=[],Ae=[],_e=[],Se=BigInt(0),Pe=BigInt(1),Te=BigInt(2),Oe=BigInt(7),ke=BigInt(256),Re=BigInt(113);for(let e=0,t=Pe,s=1,i=0;e<24;e++){[s,i]=[i,(2*s+3*i)%5],Ne.push(2*(5*i+s)),Ae.push((e+1)*(e+2)/2%64);let r=Se;for(let e=0;e<7;e++)t=(t<<Pe^(t>>Oe)*Re)%ke,t&Te&&(r^=Pe<<(Pe<<BigInt(e))-Pe);_e.push(r)}const[xe,Ue]=function(e,t=!1){let s=new Uint32Array(e.length),i=new Uint32Array(e.length);for(let r=0;r<e.length;r++){const{h:n,l:o}=ue(e[r],t);[s[r],i[r]]=[n,o]}return[s,i]}(_e,!0),De=(e,t,s)=>s>32?((e,t,s)=>t<<s-32|e>>>64-s)(e,t,s):((e,t,s)=>e<<s|t>>>32-s)(e,t,s),Le=(e,t,s)=>s>32?((e,t,s)=>e<<s-32|t>>>64-s)(e,t,s):((e,t,s)=>t<<s|e>>>32-s)(e,t,s);class We extends Ee{constructor(e,t,s,i=!1,r=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=i,this.rounds=r,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,oe(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");var n;this.state=new Uint8Array(200),this.state32=(n=this.state,new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4)))}keccak(){we||be(this.state32),function(e,t=24){const s=new Uint32Array(10);for(let i=24-t;i<24;i++){for(let t=0;t<10;t++)s[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const i=(t+8)%10,r=(t+2)%10,n=s[r],o=s[r+1],a=De(n,o,1)^s[i],c=Le(n,o,1)^s[i+1];for(let s=0;s<50;s+=10)e[t+s]^=a,e[t+s+1]^=c}let t=e[2],r=e[3];for(let s=0;s<24;s++){const i=Ae[s],n=De(t,r,i),o=Le(t,r,i),a=Ne[s];t=e[a],r=e[a+1],e[a]=n,e[a+1]=o}for(let t=0;t<50;t+=10){for(let i=0;i<10;i++)s[i]=e[t+i];for(let i=0;i<10;i++)e[t+i]^=~s[(i+2)%10]&s[(i+4)%10]}e[0]^=xe[i],e[1]^=Ue[i]}s.fill(0)}(this.state32,this.rounds),we||be(this.state32),this.posOut=0,this.pos=0}update(e){le(this);const{blockLen:t,state:s}=this,i=(e=ve(e)).length;for(let r=0;r<i;){const n=Math.min(t-this.pos,i-r);for(let t=0;t<n;t++)s[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:s,blockLen:i}=this;e[s]^=t,!!(128&t)&&s===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){le(this,!1),ae(e),this.finish();const t=this.state,{blockLen:s}=this;for(let i=0,r=e.length;i<r;){this.posOut>=s&&this.keccak();const n=Math.min(s-this.posOut,r-i);e.set(t.subarray(this.posOut,this.posOut+n),i),this.posOut+=n,i+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return oe(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(de(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,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:i,rounds:r,enableXOF:n}=this;return e||(e=new We(t,s,i,n,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=s,e.outputLen=i,e.enableXOF=n,e.destroyed=this.destroyed,e}}const Me=Ce(()=>new We(136,1,32)),Be="https://rpc.walletconnect.org/v1";function je(e){const t=`Ethereum Signed Message:\n${e.length}`,s=(new TextEncoder).encode(t+e);return"0x"+u.from(Me(s)).toString("hex")}function qe(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);const i=s[0];if(0===i)throw new Error("No signatures found");const r=1+64*i;if(s.length<r)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const n=u.from(e,"base64").slice(1,65);return c.A.encode(n)}var $e=Object.defineProperty,He=Object.defineProperties,Fe=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertySymbols,ze=Object.prototype.hasOwnProperty,Ke=Object.prototype.propertyIsEnumerable,Ge=(e,t,s)=>t in e?$e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Je=(e,t)=>{for(var s in t||(t={}))ze.call(t,s)&&Ge(e,s,t[s]);if(Ve)for(var s of Ve(t))Ke.call(t,s)&&Ge(e,s,t[s]);return e},Xe=(e,t)=>He(e,Fe(t));const Ye=e=>e?.split(":"),Ze=e=>{const t=e&&Ye(e);if(t)return t[2]+":"+t[3]},Qe=e=>{const t=e&&Ye(e);if(t)return t.pop()};async function et(e){const{cacao:t,projectId:s}=e,{s:i,p:r}=t,n=tt(r,r.iss),o=Qe(r.iss);return await async function(e,t,s,i,r,n){switch(s.t){case"eip191":return await async function(e,t,s){return(await(0,a.x)({hash:je(t),signature:s})).toLowerCase()===e.toLowerCase()}(e,t,s.s);case"eip1271":return await async function(e,t,s,i,r,n){const o=m(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const o="0x1626ba7e",a="0000000000000000000000000000000000000000000000000000000000000040",c="0000000000000000000000000000000000000000000000000000000000000041",l=s.substring(2),d=o+je(t).substring(2)+a+c+l,h=await fetch(`${n||Be}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:Date.now()+Math.floor(1e3*Math.random()),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:d},"latest"]})}),{result:p}=await h.json();return!!p&&p.slice(0,o.length).toLowerCase()===o.toLowerCase()}catch(e){return console.error("isValidEip1271Signature: ",e),!1}}(e,t,s.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}(o,n,i,Ze(r.iss),s)}const tt=(e,t)=>{const s=`${e.domain} wants you to sign in with your Ethereum account:`,i=Qe(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=e.statement||void 0;const n=`URI: ${e.aud||e.uri}`,o=`Version: ${e.version}`,a=`Chain ID: ${(e=>{const t=e&&Ye(e);if(t)return e.includes("did:pkh:")?t[3]:t[1]})(t)}`,c=`Nonce: ${e.nonce}`,l=`Issued At: ${e.iat}`,d=e.exp?`Expiration Time: ${e.exp}`:void 0,h=e.nbf?`Not Before: ${e.nbf}`:void 0,p=e.requestId?`Request ID: ${e.requestId}`:void 0,u=e.resources?`Resources:${e.resources.map(e=>`\n- ${e}`).join("")}`:void 0,g=dt(e.resources);return g&&(r=function(e="",t){st(t);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(s))return e;const i=[];let r=0;return Object.keys(t.att).forEach(e=>{const s=Object.keys(t.att[e]).map(e=>({ability:e.split("/")[0],action:e.split("/")[1]}));s.sort((e,t)=>e.action.localeCompare(t.action));const n={};s.forEach(e=>{n[e.ability]||(n[e.ability]=[]),n[e.ability].push(e.action)});const o=Object.keys(n).map(t=>(r++,`(${r}) '${t}': '${n[t].join("', '")}' for '${e}'.`));i.push(o.join(", ").replace(".,","."))}),`${e?e+" ":""}${s}${i.join(" ")}`}(r,nt(g))),[s,i,"",r,"",n,o,a,c,l,d,h,p,u].filter(e=>null!=e).join("\n")};function st(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");const t=Object.keys(e.att);if(null==t||!t.length)throw new Error("No resources found in `att` property");t.forEach(t=>{const s=e.att[t];if(Array.isArray(s))throw new Error(`Resource must be an object: ${t}`);if("object"!=typeof s)throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(s).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(s).forEach(e=>{const t=s[e];if(!Array.isArray(t))throw new Error(`Ability limits ${e} must be an array of objects, found: ${t}`);if(!t.length)throw new Error(`Value of ${e} is empty array, must be an array with objects`);t.forEach(t=>{if("object"!=typeof t)throw new Error(`Ability limits (${e}) must be an array of objects, found: ${t}`)})})})}function it(e,t,s={}){t=t?.sort((e,t)=>e.localeCompare(t));const i=t.map(t=>({[`${e}/${t}`]:[s]}));return Object.assign({},...i)}function rt(e){return st(e),`urn:recap:${function(e){return u.from(JSON.stringify(e)).toString("base64")}(e).replace(/=/g,"")}`}function nt(e){const t=function(e){return JSON.parse(u.from(e,"base64").toString("utf-8"))}(e.replace("urn:recap:",""));return st(t),t}function ot(e,t,s){const i=function(e,t,s,i={}){return s?.sort((e,t)=>e.localeCompare(t)),{att:{[e]:it(t,s,i)}}}(e,t,s);return rt(i)}function at(e,t){const s=function(e,t){st(e),st(t);const s=Object.keys(e.att).concat(Object.keys(t.att)).sort((e,t)=>e.localeCompare(t)),i={att:{}};return s.forEach(s=>{var r,n;Object.keys((null==(r=e.att)?void 0:r[s])||{}).concat(Object.keys((null==(n=t.att)?void 0:n[s])||{})).sort((e,t)=>e.localeCompare(t)).forEach(r=>{var n,o;i.att[s]=Xe(Je({},i.att[s]),{[r]:(null==(n=e.att[s])?void 0:n[r])||(null==(o=t.att[s])?void 0:o[r])})})}),i}(nt(e),nt(t));return rt(s)}function ct(e){var t;const s=nt(e);st(s);const i=null==(t=s.att)?void 0:t.eip155;return i?Object.keys(i).map(e=>e.split("/")[1]):[]}function lt(e){const t=nt(e);st(t);const s=[];return Object.values(t.att).forEach(e=>{Object.values(e).forEach(e=>{var t;null!=(t=e?.[0])&&t.chains&&s.push(e[0].chains)})}),[...new Set(s.flat())]}function dt(e){if(!e)return;const t=e?.[e.length-1];return function(e){return e&&e.includes("urn:recap:")}(t)?t:void 0}function ht(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function pt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ut(e,...t){if(!pt(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function gt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function mt(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}const ft=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function wt(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!pt(e))throw new Error("Uint8Array expected, got "+typeof e);e=vt(e)}return e}function yt(e,t,s=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(s&&!function(e){return e.byteOffset%4==0}(t))throw new Error("invalid output, must be aligned");return t}function bt(e,t,s,i){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,s,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(s>>r&n),a=Number(s&n),c=i?4:0,l=i?0:4;e.setUint32(t+c,o,i),e.setUint32(t+l,a,i)}function vt(e){return Uint8Array.from(e)}function Et(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Ct=e=>Uint8Array.from(e.split("").map(e=>e.charCodeAt(0))),It=Ct("expand 16-byte k"),Nt=Ct("expand 32-byte k"),At=ft(It),_t=ft(Nt);function St(e,t){return e<<t|e>>>32-t}function Pt(e){return e.byteOffset%4==0}const Tt=2**32-1,Ot=new Uint32Array,kt=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Rt{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,ut(e=wt(e),32);const t=kt(e,0),s=kt(e,2),i=kt(e,4),r=kt(e,6),n=kt(e,8),o=kt(e,10),a=kt(e,12),c=kt(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|s<<3),this.r[2]=7939&(s>>>10|i<<6),this.r[3]=8191&(i>>>7|r<<9),this.r[4]=255&(r>>>4|n<<12),this.r[5]=n>>>1&8190,this.r[6]=8191&(n>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=kt(e,16+2*t)}process(e,t,s=!1){const i=s?0:2048,{h:r,r:n}=this,o=n[0],a=n[1],c=n[2],l=n[3],d=n[4],h=n[5],p=n[6],u=n[7],g=n[8],m=n[9],f=kt(e,t+0),w=kt(e,t+2),y=kt(e,t+4),b=kt(e,t+6),v=kt(e,t+8),E=kt(e,t+10),C=kt(e,t+12),I=kt(e,t+14);let N=r[0]+(8191&f),A=r[1]+(8191&(f>>>13|w<<3)),_=r[2]+(8191&(w>>>10|y<<6)),S=r[3]+(8191&(y>>>7|b<<9)),P=r[4]+(8191&(b>>>4|v<<12)),T=r[5]+(v>>>1&8191),O=r[6]+(8191&(v>>>14|E<<2)),k=r[7]+(8191&(E>>>11|C<<5)),R=r[8]+(8191&(C>>>8|I<<8)),x=r[9]+(I>>>5|i),U=0,D=U+N*o+A*(5*m)+_*(5*g)+S*(5*u)+P*(5*p);U=D>>>13,D&=8191,D+=T*(5*h)+O*(5*d)+k*(5*l)+R*(5*c)+x*(5*a),U+=D>>>13,D&=8191;let L=U+N*a+A*o+_*(5*m)+S*(5*g)+P*(5*u);U=L>>>13,L&=8191,L+=T*(5*p)+O*(5*h)+k*(5*d)+R*(5*l)+x*(5*c),U+=L>>>13,L&=8191;let W=U+N*c+A*a+_*o+S*(5*m)+P*(5*g);U=W>>>13,W&=8191,W+=T*(5*u)+O*(5*p)+k*(5*h)+R*(5*d)+x*(5*l),U+=W>>>13,W&=8191;let M=U+N*l+A*c+_*a+S*o+P*(5*m);U=M>>>13,M&=8191,M+=T*(5*g)+O*(5*u)+k*(5*p)+R*(5*h)+x*(5*d),U+=M>>>13,M&=8191;let B=U+N*d+A*l+_*c+S*a+P*o;U=B>>>13,B&=8191,B+=T*(5*m)+O*(5*g)+k*(5*u)+R*(5*p)+x*(5*h),U+=B>>>13,B&=8191;let j=U+N*h+A*d+_*l+S*c+P*a;U=j>>>13,j&=8191,j+=T*o+O*(5*m)+k*(5*g)+R*(5*u)+x*(5*p),U+=j>>>13,j&=8191;let q=U+N*p+A*h+_*d+S*l+P*c;U=q>>>13,q&=8191,q+=T*a+O*o+k*(5*m)+R*(5*g)+x*(5*u),U+=q>>>13,q&=8191;let $=U+N*u+A*p+_*h+S*d+P*l;U=$>>>13,$&=8191,$+=T*c+O*a+k*o+R*(5*m)+x*(5*g),U+=$>>>13,$&=8191;let H=U+N*g+A*u+_*p+S*h+P*d;U=H>>>13,H&=8191,H+=T*l+O*c+k*a+R*o+x*(5*m),U+=H>>>13,H&=8191;let F=U+N*m+A*g+_*u+S*p+P*h;U=F>>>13,F&=8191,F+=T*d+O*l+k*c+R*a+x*o,U+=F>>>13,F&=8191,U=(U<<2)+U|0,U=U+D|0,D=8191&U,U>>>=13,L+=U,r[0]=D,r[1]=L,r[2]=W,r[3]=M,r[4]=B,r[5]=j,r[6]=q,r[7]=$,r[8]=H,r[9]=F}finalize(){const{h:e,pad:t}=this,s=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=i,i=e[t]>>>13,e[t]&=8191;e[0]+=5*i,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,s[0]=e[0]+5,i=s[0]>>>13,s[0]&=8191;for(let t=1;t<10;t++)s[t]=e[t]+i,i=s[t]>>>13,s[t]&=8191;s[9]-=8192;let r=(1^i)-1;for(let e=0;e<10;e++)s[e]&=r;r=~r;for(let t=0;t<10;t++)e[t]=e[t]&r|s[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let n=e[0]+t[0];e[0]=65535&n;for(let s=1;s<8;s++)n=(e[s]+t[s]|0)+(n>>>16)|0,e[s]=65535&n;Et(s)}update(e){gt(this);const{buffer:t,blockLen:s}=this,i=(e=wt(e)).length;for(let r=0;r<i;){const n=Math.min(s-this.pos,i-r);if(n!==s)t.set(e.subarray(r,r+n),this.pos),this.pos+=n,r+=n,this.pos===s&&(this.process(t,0,!1),this.pos=0);else for(;s<=i-r;r+=s)this.process(e,r)}return this}destroy(){Et(this.h,this.r,this.buffer,this.pad)}digestInto(e){gt(this),function(e,t){ut(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}(e,this),this.finished=!0;const{buffer:t,h:s}=this;let{pos:i}=this;if(i){for(t[i++]=1;i<16;i++)t[i]=0;this.process(t,0,!0)}this.finalize();let r=0;for(let t=0;t<8;t++)e[r++]=s[t]>>>0,e[r++]=s[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}}const xt=function(e){const t=(t,s)=>e(s).update(wt(t)).digest(),s=e(new Uint8Array(32));return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=t=>e(t),t}(e=>new Rt(e)),Ut=function(e){const{allowShortKeys:t,extendNonceFn:s,counterLength:i,counterRight:r,rounds:n}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,{counterRight:!1,counterLength:4,allowShortKeys:!1});return ht(i),ht(n),mt(r),mt(t),(o,a,c,l,d=0)=>{ut(o),ut(a),ut(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),ut(l),ht(d),d<0||d>=Tt)throw new Error("arx: counter overflow");if(l.length<h)throw new Error(`arx: output (${l.length}) is shorter than data (${h})`);const p=[];let u,g,m=o.length;if(32===m)p.push(u=vt(o)),g=_t;else{if(16!==m||!t)throw new Error(`arx: invalid 32-byte key, got length=${m}`);u=new Uint8Array(32),u.set(o),u.set(o,16),g=At,p.push(u)}Pt(a)||p.push(a=vt(a));const f=ft(u);if(s){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");s(g,f,ft(a.subarray(0,16)),f),a=a.subarray(16)}const w=16-i;if(w!==a.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(12!==w){const e=new Uint8Array(12);e.set(a,r?0:12-a.length),a=e,p.push(a)}const y=ft(a);return function(e,t,s,i,r,n,o,a){const c=r.length,l=new Uint8Array(64),d=ft(l),h=Pt(r)&&Pt(n),p=h?ft(r):Ot,u=h?ft(n):Ot;for(let g=0;g<c;o++){if(e(t,s,i,d,o,a),o>=Tt)throw new Error("arx: counter overflow");const m=Math.min(64,c-g);if(h&&64===m){const e=g/4;if(g%4!=0)throw new Error("arx: invalid block position");for(let t,s=0;s<16;s++)t=e+s,u[t]=p[t]^d[s];g+=64;continue}for(let e,t=0;t<m;t++)e=g+t,n[e]=r[e]^l[t];g+=m}}(e,g,f,y,c,l,d,n),Et(...p),l}}(function(e,t,s,i,r,n=20){let o=e[0],a=e[1],c=e[2],l=e[3],d=t[0],h=t[1],p=t[2],u=t[3],g=t[4],m=t[5],f=t[6],w=t[7],y=r,b=s[0],v=s[1],E=s[2],C=o,I=a,N=c,A=l,_=d,S=h,P=p,T=u,O=g,k=m,R=f,x=w,U=y,D=b,L=v,W=E;for(let e=0;e<n;e+=2)C=C+_|0,U=St(U^C,16),O=O+U|0,_=St(_^O,12),C=C+_|0,U=St(U^C,8),O=O+U|0,_=St(_^O,7),I=I+S|0,D=St(D^I,16),k=k+D|0,S=St(S^k,12),I=I+S|0,D=St(D^I,8),k=k+D|0,S=St(S^k,7),N=N+P|0,L=St(L^N,16),R=R+L|0,P=St(P^R,12),N=N+P|0,L=St(L^N,8),R=R+L|0,P=St(P^R,7),A=A+T|0,W=St(W^A,16),x=x+W|0,T=St(T^x,12),A=A+T|0,W=St(W^A,8),x=x+W|0,T=St(T^x,7),C=C+S|0,W=St(W^C,16),R=R+W|0,S=St(S^R,12),C=C+S|0,W=St(W^C,8),R=R+W|0,S=St(S^R,7),I=I+P|0,U=St(U^I,16),x=x+U|0,P=St(P^x,12),I=I+P|0,U=St(U^I,8),x=x+U|0,P=St(P^x,7),N=N+T|0,D=St(D^N,16),O=O+D|0,T=St(T^O,12),N=N+T|0,D=St(D^N,8),O=O+D|0,T=St(T^O,7),A=A+_|0,L=St(L^A,16),k=k+L|0,_=St(_^k,12),A=A+_|0,L=St(L^A,8),k=k+L|0,_=St(_^k,7);let M=0;i[M++]=o+C|0,i[M++]=a+I|0,i[M++]=c+N|0,i[M++]=l+A|0,i[M++]=d+_|0,i[M++]=h+S|0,i[M++]=p+P|0,i[M++]=u+T|0,i[M++]=g+O|0,i[M++]=m+k|0,i[M++]=f+R|0,i[M++]=w+x|0,i[M++]=y+U|0,i[M++]=b+D|0,i[M++]=v+L|0,i[M++]=E+W|0}),Dt=new Uint8Array(16),Lt=(e,t)=>{e.update(t);const s=t.length%16;s&&e.update(Dt.subarray(s))},Wt=new Uint8Array(32);function Mt(e,t,s,i,r){const n=e(t,s,Wt),o=xt.create(n);r&&Lt(o,r),Lt(o,i);const a=new Uint8Array(16),c=(e=>new DataView(e.buffer,e.byteOffset,e.byteLength))(a);bt(c,0,BigInt(r?r.length:0),!0),bt(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return Et(n,a),l}const Bt=((e,t)=>{function s(s,...i){if(ut(s),void 0!==e.nonceLength){const t=i[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?ut(t):ut(t,e.nonceLength)}const r=e.tagLength;r&&void 0!==i[1]&&ut(i[1]);const n=t(s,...i),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");ut(t)}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,ut(e),o(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(ut(e),r&&e.length<r)throw new Error("invalid ciphertext length: smaller than tagLength="+r);return o(n.decrypt.length,t),n.decrypt(e,t)}}}return Object.assign(s,e),s})({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,s,i)=>({encrypt(r,n){const o=r.length;(n=yt(o+16,n,!1)).set(r);const a=n.subarray(0,-16);e(t,s,a,a,1);const c=Mt(e,t,s,a,i);return n.set(c,o),Et(c),n},decrypt(r,n){n=yt(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Mt(e,t,s,o,i);if(!function(e,t){if(e.length!==t.length)return!1;let s=0;for(let i=0;i<e.length;i++)s|=e[i]^t[i];return 0===s}(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),e(t,s,n,n,1),Et(c),n}}))(Ut));class jt extends Ee{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ce(e);const s=ve(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,r=new Uint8Array(i);r.set(s.length>i?e.create().update(s).digest():s);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),r.fill(0)}update(e){return le(this),this.iHash.update(e),this}digestInto(e){le(this),ae(e,this.outputLen),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:t,iHash:s,finished:i,destroyed:r,blockLen:n,outputLen:o}=this;return e.finished=i,e.destroyed=r,e.blockLen=n,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const qt=(e,t,s)=>new jt(e,t).update(s).digest();qt.create=(e,t)=>new jt(e,t);const $t=new Uint8Array([0]),Ht=new Uint8Array,Ft=(e,t,s,i,r)=>function(e,t,s,i=32){if(ce(e),oe(i),i>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/e.outputLen);void 0===s&&(s=Ht);const n=new Uint8Array(r*e.outputLen),o=qt.create(e,t),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let t=0;t<r;t++)$t[0]=t+1,a.update(0===t?Ht:c).update(s).update($t).digestInto(c),n.set(c,e.outputLen*t),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),$t.fill(0),n.slice(0,i)}(e,function(e,t,s){return ce(e),void 0===s&&(s=new Uint8Array(e.outputLen)),qt(e,ve(s),ve(t))}(e,t,s),i,r);function Vt(e,t,s){return e&t^~e&s}function zt(e,t,s){return e&t^e&s^t&s}class Kt extends Ee{constructor(e,t,s,i){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=me(this.buffer)}update(e){le(this);const{view:t,buffer:s,blockLen:i}=this,r=(e=ve(e)).length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){const t=me(e);for(;i<=r-n;n+=i)this.process(t,n);continue}s.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){le(this),de(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:i,isLE:r}=this;let{pos:n}=this;t[n++]=128,this.buffer.subarray(n).fill(0),this.padOffset>i-n&&(this.process(s,0),n=0);for(let e=n;e<i;e++)t[e]=0;(function(e,t,s,i){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,s,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(s>>r&n),a=Number(s&n),c=i?4:0,l=i?0:4;e.setUint32(t+c,o,i),e.setUint32(t+l,a,i)})(s,i-8,BigInt(8*this.length),r),this.process(s,0);const o=me(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,length:i,finished:r,destroyed:n,pos:o}=this;return e.length=i,e.pos=o,e.finished=r,e.destroyed=n,i%t&&e.buffer.set(s),e}}const Gt=new Uint32Array([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]),Jt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Xt=new Uint32Array(64);class Yt extends Kt{constructor(){super(64,32,8,!1),this.A=0|Jt[0],this.B=0|Jt[1],this.C=0|Jt[2],this.D=0|Jt[3],this.E=0|Jt[4],this.F=0|Jt[5],this.G=0|Jt[6],this.H=0|Jt[7]}get(){const{A:e,B:t,C:s,D:i,E:r,F:n,G:o,H:a}=this;return[e,t,s,i,r,n,o,a]}set(e,t,s,i,r,n,o,a){this.A=0|e,this.B=0|t,this.C=0|s,this.D=0|i,this.E=0|r,this.F=0|n,this.G=0|o,this.H=0|a}process(e,t){for(let s=0;s<16;s++,t+=4)Xt[s]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Xt[e-15],s=Xt[e-2],i=fe(t,7)^fe(t,18)^t>>>3,r=fe(s,17)^fe(s,19)^s>>>10;Xt[e]=r+Xt[e-7]+i+Xt[e-16]|0}let{A:s,B:i,C:r,D:n,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(fe(o,6)^fe(o,11)^fe(o,25))+Vt(o,a,c)+Gt[e]+Xt[e]|0,d=(fe(s,2)^fe(s,13)^fe(s,22))+zt(s,i,r)|0;l=c,c=a,a=o,o=n+t|0,n=r,r=i,i=s,s=t+d|0}s=s+this.A|0,i=i+this.B|0,r=r+this.C|0,n=n+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(s,i,r,n,o,a,c,l)}roundClean(){Xt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Zt=Ce(()=>new Yt),Qt=BigInt(0),es=BigInt(1),ts=BigInt(2);function ss(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function is(e){if(!ss(e))throw new Error("Uint8Array expected")}function rs(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const ns=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function os(e){is(e);let t="";for(let s=0;s<e.length;s++)t+=ns[e[s]];return t}function as(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function cs(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Qt:BigInt("0x"+e)}function ls(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function ds(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,s=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const i=new Uint8Array(s);for(let t=0,r=0;t<s;t++,r+=2){const s=ls(e.charCodeAt(r)),n=ls(e.charCodeAt(r+1));if(void 0===s||void 0===n){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}i[t]=16*s+n}return i}function hs(e){return cs(os(e))}function ps(e){return is(e),cs(os(Uint8Array.from(e).reverse()))}function us(e,t){return ds(e.toString(16).padStart(2*t,"0"))}function gs(e,t){return us(e,t).reverse()}function ms(e,t,s){let i;if("string"==typeof t)try{i=ds(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!ss(t))throw new Error(e+" must be hex string or Uint8Array");i=Uint8Array.from(t)}const r=i.length;if("number"==typeof s&&r!==s)throw new Error(e+" of length "+s+" expected, got "+r);return i}function fs(...e){let t=0;for(let s=0;s<e.length;s++){const i=e[s];is(i),t+=i.length}const s=new Uint8Array(t);for(let t=0,i=0;t<e.length;t++){const r=e[t];s.set(r,i),i+=r.length}return s}const ws=e=>"bigint"==typeof e&&Qt<=e;function ys(e,t,s){return ws(e)&&ws(t)&&ws(s)&&t<=e&&e<s}function bs(e,t,s,i){if(!ys(t,s,i))throw new Error("expected valid "+e+": "+s+" <= n < "+i+", got "+t)}function vs(e){let t;for(t=0;e>Qt;e>>=es,t+=1);return t}const Es=e=>(ts<<BigInt(e-1))-es,Cs=e=>new Uint8Array(e),Is=e=>Uint8Array.from(e);function Ns(e,t,s){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof s)throw new Error("hmacFn must be a function");let i=Cs(e),r=Cs(e),n=0;const o=()=>{i.fill(1),r.fill(0),n=0},a=(...e)=>s(r,i,...e),c=(e=Cs())=>{r=a(Is([0]),e),i=a(),0!==e.length&&(r=a(Is([1]),e),i=a())},l=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const s=[];for(;e<t;){i=a();const t=i.slice();s.push(t),e+=i.length}return fs(...s)};return(e,t)=>{let s;for(o(),c(e);!(s=t(l()));)c();return o(),s}}const As={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||ss(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function _s(e,t,s={}){const i=(t,s,i)=>{const r=As[s];if("function"!=typeof r)throw new Error("invalid validator function");const n=e[t];if(!(i&&void 0===n||r(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+s+", got "+n)};for(const[e,s]of Object.entries(t))i(e,s,!1);for(const[e,t]of Object.entries(s))i(e,t,!0);return e}function Ss(e){const t=new WeakMap;return(s,...i)=>{const r=t.get(s);if(void 0!==r)return r;const n=e(s,...i);return t.set(s,n),n}}var Ps=Object.freeze({__proto__:null,isBytes:ss,abytes:is,abool:rs,bytesToHex:os,numberToHexUnpadded:as,hexToNumber:cs,hexToBytes:ds,bytesToNumberBE:hs,bytesToNumberLE:ps,numberToBytesBE:us,numberToBytesLE:gs,numberToVarBytesBE:function(e){return ds(as(e))},ensureBytes:ms,concatBytes:fs,equalBytes:function(e,t){if(e.length!==t.length)return!1;let s=0;for(let i=0;i<e.length;i++)s|=e[i]^t[i];return 0===s},utf8ToBytes:function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))},inRange:ys,aInRange:bs,bitLen:vs,bitGet:function(e,t){return e>>BigInt(t)&es},bitSet:function(e,t,s){return e|(s?es:Qt)<<BigInt(t)},bitMask:Es,createHmacDrbg:Ns,validateObject:_s,notImplemented:()=>{throw new Error("not implemented")},memoized:Ss});const Ts=BigInt(0),Os=BigInt(1),ks=BigInt(2),Rs=BigInt(3),xs=BigInt(4),Us=BigInt(5),Ds=BigInt(8);function Ls(e,t){const s=e%t;return s>=Ts?s:t+s}function Ws(e,t,s){if(t<Ts)throw new Error("invalid exponent, negatives unsupported");if(s<=Ts)throw new Error("invalid modulus");if(s===Os)return Ts;let i=Os;for(;t>Ts;)t&Os&&(i=i*e%s),e=e*e%s,t>>=Os;return i}function Ms(e,t,s){let i=e;for(;t-- >Ts;)i*=i,i%=s;return i}function Bs(e,t){if(e===Ts)throw new Error("invert: expected non-zero number");if(t<=Ts)throw new Error("invert: expected positive modulus, got "+t);let s=Ls(e,t),i=t,r=Ts,n=Os;for(;s!==Ts;){const e=i%s,t=r-n*(i/s);i=s,s=e,r=n,n=t}if(i!==Os)throw new Error("invert: does not exist");return Ls(r,t)}const js=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qs(e,t){const s=void 0!==t?t:e.toString(2).length;return{nBitLength:s,nByteLength:Math.ceil(s/8)}}function $s(e,t,s=!1,i={}){if(e<=Ts)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:r,nByteLength:n}=qs(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:s,BITS:r,BYTES:n,MASK:Es(r),ZERO:Ts,ONE:Os,create:t=>Ls(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Ts<=t&&t<e},is0:e=>e===Ts,isOdd:e=>(e&Os)===Os,neg:t=>Ls(-t,e),eql:(e,t)=>e===t,sqr:t=>Ls(t*t,e),add:(t,s)=>Ls(t+s,e),sub:(t,s)=>Ls(t-s,e),mul:(t,s)=>Ls(t*s,e),pow:(e,t)=>function(e,t,s){if(s<Ts)throw new Error("invalid exponent, negatives unsupported");if(s===Ts)return e.ONE;if(s===Os)return t;let i=e.ONE,r=t;for(;s>Ts;)s&Os&&(i=e.mul(i,r)),r=e.sqr(r),s>>=Os;return i}(a,e,t),div:(t,s)=>Ls(t*Bs(s,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Bs(t,e),sqrt:i.sqrt||(t=>(o||(o=function(e){if(e%xs===Rs){const t=(e+Os)/xs;return function(e,s){const i=e.pow(s,t);if(!e.eql(e.sqr(i),s))throw new Error("Cannot find square root");return i}}if(e%Ds===Us){const t=(e-Us)/Ds;return function(e,s){const i=e.mul(s,ks),r=e.pow(i,t),n=e.mul(s,r),o=e.mul(e.mul(n,ks),r),a=e.mul(n,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),s))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-Os)/ks;let s,i,r;for(s=e-Os,i=0;s%ks===Ts;s/=ks,i++);for(r=ks;r<e&&Ws(r,t,e)!==e-Os;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===i){const t=(e+Os)/xs;return function(e,s){const i=e.pow(s,t);if(!e.eql(e.sqr(i),s))throw new Error("Cannot find square root");return i}}const n=(s+Os)/ks;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=i,c=e.pow(e.mul(e.ONE,r),s),l=e.pow(o,n),d=e.pow(o,s);for(;!e.eql(d,e.ONE);){if(e.eql(d,e.ZERO))return e.ZERO;let t=1;for(let s=e.sqr(d);t<a&&!e.eql(s,e.ONE);t++)s=e.sqr(s);const s=e.pow(c,Os<<BigInt(a-t-1));c=e.sqr(s),l=e.mul(l,s),d=e.mul(d,c),a=t}return l}}(e)}(e)),o(a,t))),invertBatch:e=>function(e,t){const s=new Array(t.length),i=t.reduce((t,i,r)=>e.is0(i)?t:(s[r]=t,e.mul(t,i)),e.ONE),r=e.inv(i);return t.reduceRight((t,i,r)=>e.is0(i)?t:(s[r]=e.mul(t,s[r]),e.mul(t,i)),r),s}(a,e),cmov:(e,t,s)=>s?t:e,toBytes:e=>s?gs(e,n):us(e,n),fromBytes:e=>{if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);return s?ps(e):hs(e)}});return Object.freeze(a)}function Hs(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Fs(e){const t=Hs(e);return t+Math.ceil(t/2)}const Vs=BigInt(0),zs=BigInt(1);function Ks(e,t){const s=t.negate();return e?s:t}function Gs(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Js(e,t){return Gs(e,t),{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const Xs=new WeakMap,Ys=new WeakMap;function Zs(e){return Ys.get(e)||1}function Qs(e){return function(e){_s(e,js.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}))}(e.Fp),_s(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...qs(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const ei=BigInt(0),ti=BigInt(1),si=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const ii=BigInt(1),ri=BigInt(2),ni=BigInt(3),oi=BigInt(5);BigInt(8);const ai=function(e){const t=function(e){return _s(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})}(e),{P:s}=t,i=e=>Ls(e,s),r=t.montgomeryBits,n=Math.ceil(r/8),o=t.nByteLength,a=t.adjustScalarBytes||(e=>e),c=t.powPminus2||(e=>Ws(e,s-BigInt(2),s));function l(e,t,s){const r=i(e*(t-s));return[t=i(t-r),s=i(s+r)]}const d=(t.a-BigInt(2))/BigInt(4);function h(e){return gs(i(e),n)}function p(e,t){const p=function(e){const t=ms("u coordinate",e,n);return 32===o&&(t[31]&=127),ps(t)}(t),u=function(e){const t=ms("scalar",e),s=t.length;if(s!==n&&s!==o)throw new Error("invalid scalar, expected "+n+" or "+o+" bytes, got "+s);return ps(a(t))}(e),g=function(e,t){bs("u",e,ei,s),bs("scalar",t,ei,s);const n=t,o=e;let a,h=ti,p=ei,u=e,g=ti,m=ei;for(let e=BigInt(r-1);e>=ei;e--){const t=n>>e&ti;m^=t,a=l(m,h,u),h=a[0],u=a[1],a=l(m,p,g),p=a[0],g=a[1],m=t;const s=h+p,r=i(s*s),c=h-p,f=i(c*c),w=r-f,y=u+g,b=i((u-g)*s),v=i(y*c),E=b+v,C=b-v;u=i(E*E),g=i(o*i(C*C)),h=i(r*f),p=i(w*(r+i(d*w)))}a=l(m,h,u),h=a[0],u=a[1],a=l(m,p,g),p=a[0],g=a[1];const f=c(p);return i(h*f)}(p,u);if(g===ei)throw new Error("invalid private or public key received");return h(g)}const u=h(t.Gu);function g(e){return p(e,u)}return{scalarMult:p,scalarMultBase:g,getSharedSecret:(e,t)=>p(e,t),getPublicKey:e=>g(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:u}}({P:si,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=si,{pow_p_5_8:s,b2:i}=function(e){const t=BigInt(10),s=BigInt(20),i=BigInt(40),r=BigInt(80),n=si,o=e*e%n*e%n,a=Ms(o,ri,n)*o%n,c=Ms(a,ii,n)*e%n,l=Ms(c,oi,n)*c%n,d=Ms(l,t,n)*l%n,h=Ms(d,s,n)*d%n,p=Ms(h,i,n)*h%n,u=Ms(p,r,n)*p%n,g=Ms(u,r,n)*p%n,m=Ms(g,t,n)*l%n;return{pow_p_5_8:Ms(m,ri,n)*e%n,b2:o}}(e);return Ls(Ms(s,ni,t)*i,t)},adjustScalarBytes:function(e){return e[0]&=248,e[31]&=127,e[31]|=64,e},randomBytes:Ie});function ci(e){void 0!==e.lowS&&rs("lowS",e.lowS),void 0!==e.prehash&&rs("prehash",e.prehash)}const{bytesToNumberBE:li,hexToBytes:di}=Ps;class hi extends Error{constructor(e=""){super(e)}}const pi={Err:hi,_tlv:{encode:(e,t)=>{const{Err:s}=pi;if(e<0||e>256)throw new s("tlv.encode: wrong tag");if(1&t.length)throw new s("tlv.encode: unpadded data");const i=t.length/2,r=as(i);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const n=i>127?as(r.length/2|128):"";return as(e)+n+r+t},decode(e,t){const{Err:s}=pi;let i=0;if(e<0||e>256)throw new s("tlv.encode: wrong tag");if(t.length<2||t[i++]!==e)throw new s("tlv.decode: wrong tlv");const r=t[i++];let n=0;if(128&r){const e=127&r;if(!e)throw new s("tlv.decode(long): indefinite length not supported");if(e>4)throw new s("tlv.decode(long): byte length is too big");const o=t.subarray(i,i+e);if(o.length!==e)throw new s("tlv.decode: length bytes not complete");if(0===o[0])throw new s("tlv.decode(long): zero leftmost byte");for(const e of o)n=n<<8|e;if(i+=e,n<128)throw new s("tlv.decode(long): not minimal encoding")}else n=r;const o=t.subarray(i,i+n);if(o.length!==n)throw new s("tlv.decode: wrong value length");return{v:o,l:t.subarray(i+n)}}},_int:{encode(e){const{Err:t}=pi;if(e<ui)throw new t("integer: negative integers are not allowed");let s=as(e);if(8&Number.parseInt(s[0],16)&&(s="00"+s),1&s.length)throw new t("unexpected DER parsing assertion: unpadded hex");return s},decode(e){const{Err:t}=pi;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return li(e)}},toSig(e){const{Err:t,_int:s,_tlv:i}=pi,r="string"==typeof e?di(e):e;is(r);const{v:n,l:o}=i.decode(48,r);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:l,l:d}=i.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(e){const{_tlv:t,_int:s}=pi,i=t.encode(2,s.encode(e.r))+t.encode(2,s.encode(e.s));return t.encode(48,i)}},ui=BigInt(0),gi=BigInt(1);BigInt(2);const mi=BigInt(3);function fi(e){const t=function(e){const t=Qs(e);_s(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:s,Fp:i,a:r}=t;if(s){if(!i.eql(r,i.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if("object"!=typeof s||"bigint"!=typeof s.beta||"function"!=typeof s.splitScalar)throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:s}=t,i=$s(t.n,t.nBitLength),r=t.toBytes||((e,t,i)=>{const r=t.toAffine();return fs(Uint8Array.from([4]),s.toBytes(r.x),s.toBytes(r.y))}),n=t.fromBytes||(e=>{const t=e.subarray(1);return{x:s.fromBytes(t.subarray(0,s.BYTES)),y:s.fromBytes(t.subarray(s.BYTES,2*s.BYTES))}});function o(e){const{a:i,b:r}=t,n=s.sqr(e),o=s.mul(n,e);return s.add(s.add(o,s.mul(e,i)),r)}if(!s.eql(s.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function a(e){const{allowedPrivateKeyLengths:s,nByteLength:i,wrapPrivateKey:r,n}=t;if(s&&"bigint"!=typeof e){if(ss(e)&&(e=os(e)),"string"!=typeof e||!s.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*i,"0")}let o;try{o="bigint"==typeof e?e:hs(ms("private key",e,i))}catch{throw new Error("invalid private key, expected hex or "+i+" bytes, got "+typeof e)}return r&&(o=Ls(o,n)),bs("private key",o,gi,n),o}function c(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}const l=Ss((e,t)=>{const{px:i,py:r,pz:n}=e;if(s.eql(n,s.ONE))return{x:i,y:r};const o=e.is0();null==t&&(t=o?s.ONE:s.inv(n));const a=s.mul(i,t),c=s.mul(r,t),l=s.mul(n,t);if(o)return{x:s.ZERO,y:s.ZERO};if(!s.eql(l,s.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),d=Ss(e=>{if(e.is0()){if(t.allowInfinityPoint&&!s.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:i,y:r}=e.toAffine();if(!s.isValid(i)||!s.isValid(r))throw new Error("bad point: x or y not FE");const n=s.sqr(r),a=o(i);if(!s.eql(n,a))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(e,t,i){if(this.px=e,this.py=t,this.pz=i,null==e||!s.isValid(e))throw new Error("x required");if(null==t||!s.isValid(t))throw new Error("y required");if(null==i||!s.isValid(i))throw new Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:i}=e||{};if(!e||!s.isValid(t)||!s.isValid(i))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const r=e=>s.eql(e,s.ZERO);return r(t)&&r(i)?h.ZERO:new h(t,i,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=s.invertBatch(e.map(e=>e.pz));return e.map((e,s)=>e.toAffine(t[s])).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(n(ms("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(a(e))}static msm(e,t){return function(e,t,s,i){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,s)=>{if(!(e instanceof t))throw new Error("invalid point at index "+s)})}(s,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,s)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+s)})}(i,t),s.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const r=e.ZERO,n=vs(BigInt(s.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r);let l=r;for(let e=Math.floor((t.BITS-1)/o)*o;e>=0;e-=o){c.fill(r);for(let t=0;t<i.length;t++){const r=i[t],n=Number(r>>BigInt(e)&BigInt(a));c[n]=c[n].add(s[t])}let t=r;for(let e=c.length-1,s=r;e>0;e--)s=s.add(c[e]),t=t.add(s);if(l=l.add(t),0!==e)for(let e=0;e<o;e++)l=l.double()}return l}(h,i,e,t)}_setWindowSize(e){u.setWindowSize(this,e)}assertValidity(){d(this)}hasEvenY(){const{y:e}=this.toAffine();if(s.isOdd)return!s.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:i,pz:r}=this,{px:n,py:o,pz:a}=e,l=s.eql(s.mul(t,a),s.mul(n,r)),d=s.eql(s.mul(i,a),s.mul(o,r));return l&&d}negate(){return new h(this.px,s.neg(this.py),this.pz)}double(){const{a:e,b:i}=t,r=s.mul(i,mi),{px:n,py:o,pz:a}=this;let c=s.ZERO,l=s.ZERO,d=s.ZERO,p=s.mul(n,n),u=s.mul(o,o),g=s.mul(a,a),m=s.mul(n,o);return m=s.add(m,m),d=s.mul(n,a),d=s.add(d,d),c=s.mul(e,d),l=s.mul(r,g),l=s.add(c,l),c=s.sub(u,l),l=s.add(u,l),l=s.mul(c,l),c=s.mul(m,c),d=s.mul(r,d),g=s.mul(e,g),m=s.sub(p,g),m=s.mul(e,m),m=s.add(m,d),d=s.add(p,p),p=s.add(d,p),p=s.add(p,g),p=s.mul(p,m),l=s.add(l,p),g=s.mul(o,a),g=s.add(g,g),p=s.mul(g,m),c=s.sub(c,p),d=s.mul(g,u),d=s.add(d,d),d=s.add(d,d),new h(c,l,d)}add(e){c(e);const{px:i,py:r,pz:n}=this,{px:o,py:a,pz:l}=e;let d=s.ZERO,p=s.ZERO,u=s.ZERO;const g=t.a,m=s.mul(t.b,mi);let f=s.mul(i,o),w=s.mul(r,a),y=s.mul(n,l),b=s.add(i,r),v=s.add(o,a);b=s.mul(b,v),v=s.add(f,w),b=s.sub(b,v),v=s.add(i,n);let E=s.add(o,l);return v=s.mul(v,E),E=s.add(f,y),v=s.sub(v,E),E=s.add(r,n),d=s.add(a,l),E=s.mul(E,d),d=s.add(w,y),E=s.sub(E,d),u=s.mul(g,v),d=s.mul(m,y),u=s.add(d,u),d=s.sub(w,u),u=s.add(w,u),p=s.mul(d,u),w=s.add(f,f),w=s.add(w,f),y=s.mul(g,y),v=s.mul(m,v),w=s.add(w,y),y=s.sub(f,y),y=s.mul(g,y),v=s.add(v,y),f=s.mul(w,v),p=s.add(p,f),f=s.mul(E,v),d=s.mul(b,d),d=s.sub(d,f),f=s.mul(b,w),u=s.mul(E,u),u=s.add(u,f),new h(d,p,u)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return u.wNAFCached(this,e,h.normalizeZ)}multiplyUnsafe(e){const{endo:i,n:r}=t;bs("scalar",e,ui,r);const n=h.ZERO;if(e===ui)return n;if(this.is0()||e===gi)return this;if(!i||u.hasPrecomputes(this))return u.wNAFCachedUnsafe(this,e,h.normalizeZ);let{k1neg:o,k1:a,k2neg:c,k2:l}=i.splitScalar(e),d=n,p=n,g=this;for(;a>ui||l>ui;)a&gi&&(d=d.add(g)),l&gi&&(p=p.add(g)),g=g.double(),a>>=gi,l>>=gi;return o&&(d=d.negate()),c&&(p=p.negate()),p=new h(s.mul(p.px,i.beta),p.py,p.pz),d.add(p)}multiply(e){const{endo:i,n:r}=t;let n,o;if(bs("scalar",e,gi,r),i){const{k1neg:t,k1:r,k2neg:a,k2:c}=i.splitScalar(e);let{p:l,f:d}=this.wNAF(r),{p,f:g}=this.wNAF(c);l=u.constTimeNegate(t,l),p=u.constTimeNegate(a,p),p=new h(s.mul(p.px,i.beta),p.py,p.pz),n=l.add(p),o=d.add(g)}else{const{p:t,f:s}=this.wNAF(e);n=t,o=s}return h.normalizeZ([n,o])[0]}multiplyAndAddUnsafe(e,t,s){const i=h.BASE,r=(e,t)=>t!==ui&&t!==gi&&e.equals(i)?e.multiply(t):e.multiplyUnsafe(t),n=r(this,t).add(r(e,s));return n.is0()?void 0:n}toAffine(e){return l(this,e)}isTorsionFree(){const{h:e,isTorsionFree:s}=t;if(e===gi)return!0;if(s)return s(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:s}=t;return e===gi?this:s?s(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return rs("isCompressed",e),this.assertValidity(),r(h,this,e)}toHex(e=!0){return rs("isCompressed",e),os(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,s.ONE),h.ZERO=new h(s.ZERO,s.ONE,s.ZERO);const p=t.nBitLength,u=function(e,t){return{constTimeNegate:Ks,hasPrecomputes:e=>1!==Zs(e),unsafeLadder(t,s,i=e.ZERO){let r=t;for(;s>Vs;)s&zs&&(i=i.add(r)),r=r.double(),s>>=zs;return i},precomputeWindow(e,s){const{windows:i,windowSize:r}=Js(s,t),n=[];let o=e,a=o;for(let e=0;e<i;e++){a=o,n.push(a);for(let e=1;e<r;e++)a=a.add(o),n.push(a);o=a.double()}return n},wNAF(s,i,r){const{windows:n,windowSize:o}=Js(s,t);let a=e.ZERO,c=e.BASE;const l=BigInt(2**s-1),d=2**s,h=BigInt(s);for(let e=0;e<n;e++){const t=e*o;let s=Number(r&l);r>>=h,s>o&&(s-=d,r+=zs);const n=t,p=t+Math.abs(s)-1,u=e%2!=0,g=s<0;0===s?c=c.add(Ks(u,i[n])):a=a.add(Ks(g,i[p]))}return{p:a,f:c}},wNAFUnsafe(s,i,r,n=e.ZERO){const{windows:o,windowSize:a}=Js(s,t),c=BigInt(2**s-1),l=2**s,d=BigInt(s);for(let e=0;e<o;e++){const t=e*a;if(r===Vs)break;let s=Number(r&c);if(r>>=d,s>a&&(s-=l,r+=zs),0===s)continue;let o=i[t+Math.abs(s)-1];s<0&&(o=o.negate()),n=n.add(o)}return n},getPrecomputes(e,t,s){let i=Xs.get(t);return i||(i=this.precomputeWindow(t,e),1!==e&&Xs.set(t,s(i))),i},wNAFCached(e,t,s){const i=Zs(e);return this.wNAF(i,this.getPrecomputes(i,e,s),t)},wNAFCachedUnsafe(e,t,s,i){const r=Zs(e);return 1===r?this.unsafeLadder(e,t,i):this.wNAFUnsafe(r,this.getPrecomputes(r,e,s),t,i)},setWindowSize(e,s){Gs(s,t),Ys.set(e,s),Xs.delete(e)}}}(h,t.endo?Math.ceil(p/2):p);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:function(e){return ys(e,gi,t.n)}}}function wi(e){const t=function(e){const t=Qs(e);return _s(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:s,n:i}=t,r=s.BYTES+1,n=2*s.BYTES+1;function o(e){return Ls(e,i)}function a(e){return Bs(e,i)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:d,isWithinCurveOrder:h}=fi({...t,toBytes(e,t,i){const r=t.toAffine(),n=s.toBytes(r.x),o=fs;return rs("isCompressed",i),i?o(Uint8Array.from([t.hasEvenY()?2:3]),n):o(Uint8Array.from([4]),n,s.toBytes(r.y))},fromBytes(e){const t=e.length,i=e[0],o=e.subarray(1);if(t!==r||2!==i&&3!==i){if(t===n&&4===i)return{x:s.fromBytes(o.subarray(0,s.BYTES)),y:s.fromBytes(o.subarray(s.BYTES,2*s.BYTES))};throw new Error("invalid Point, expected length of "+r+", or uncompressed "+n+", got "+t)}{const e=hs(o);if(!ys(e,gi,s.ORDER))throw new Error("Point is not on curve");const t=d(e);let r;try{r=s.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~i)!=((r&gi)===gi)&&(r=s.neg(r)),{x:e,y:r}}}}),p=e=>os(us(e,t.nByteLength));function u(e){return e>i>>gi}const g=(e,t,s)=>hs(e.slice(t,s));class m{constructor(e,t,s){this.r=e,this.s=t,this.recovery=s,this.assertValidity()}static fromCompact(e){const s=t.nByteLength;return e=ms("compactSignature",e,2*s),new m(g(e,0,s),g(e,s,2*s))}static fromDER(e){const{r:t,s}=pi.toSig(ms("DER",e));return new m(t,s)}assertValidity(){bs("r",this.r,gi,i),bs("s",this.s,gi,i)}addRecoveryBit(e){return new m(this.r,this.s,e)}recoverPublicKey(e){const{r:i,s:r,recovery:n}=this,l=b(ms("msgHash",e));if(null==n||![0,1,2,3].includes(n))throw new Error("recovery id invalid");const d=2===n||3===n?i+t.n:i;if(d>=s.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&n?"03":"02",u=c.fromHex(h+p(d)),g=a(d),m=o(-l*g),f=o(r*g),w=c.BASE.multiplyAndAddUnsafe(u,m,f);if(!w)throw new Error("point at infinify");return w.assertValidity(),w}hasHighS(){return u(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return ds(this.toDERHex())}toDERHex(){return pi.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ds(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const f={isValidPrivateKey(e){try{return l(e),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=Fs(t.n);return function(e,t,s=!1){const i=e.length,r=Hs(t),n=Fs(t);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=Ls(s?ps(e):hs(e),t-Os)+Os;return s?gs(o,r):us(o,r)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function w(e){const t=ss(e),s="string"==typeof e,i=(t||s)&&e.length;return t?i===r||i===n:s?i===2*r||i===2*n:e instanceof c}const y=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const s=hs(e),i=8*e.length-t.nBitLength;return i>0?s>>BigInt(i):s},b=t.bits2int_modN||function(e){return o(y(e))},v=Es(t.nBitLength);function E(e){return bs("num < 2^"+t.nBitLength,e,ui,v),us(e,t.nByteLength)}const C={lowS:t.lowS,prehash:!1},I={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,s=!0){if(w(e))throw new Error("first arg must be private key");if(!w(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(s)},sign:function(e,i,r=C){const{seed:n,k2sig:d}=function(e,i,r=C){if(["recovered","canonical"].some(e=>e in r))throw new Error("sign() legacy options not supported");const{hash:n,randomBytes:d}=t;let{lowS:p,prehash:g,extraEntropy:f}=r;null==p&&(p=!0),e=ms("msgHash",e),ci(r),g&&(e=ms("prehashed msgHash",n(e)));const w=b(e),v=l(i),I=[E(v),E(w)];if(null!=f&&!1!==f){const e=!0===f?d(s.BYTES):f;I.push(ms("extraEntropy",e))}const N=fs(...I),A=w;return{seed:N,k2sig:function(e){const t=y(e);if(!h(t))return;const s=a(t),i=c.BASE.multiply(t).toAffine(),r=o(i.x);if(r===ui)return;const n=o(s*o(A+r*v));if(n===ui)return;let l=(i.x===r?0:2)|Number(i.y&gi),d=n;return p&&u(n)&&(d=function(e){return u(e)?o(-e):e}(n),l^=1),new m(r,d,l)}}}(e,i,r),p=t;return Ns(p.hash.outputLen,p.nByteLength,p.hmac)(n,d)},verify:function(e,s,i,r=I){const n=e;s=ms("msgHash",s),i=ms("publicKey",i);const{lowS:l,prehash:d,format:h}=r;if(ci(r),"strict"in r)throw new Error("options.strict was renamed to lowS");if(void 0!==h&&"compact"!==h&&"der"!==h)throw new Error("format must be compact or der");const p="string"==typeof n||ss(n),u=!p&&!h&&"object"==typeof n&&null!==n&&"bigint"==typeof n.r&&"bigint"==typeof n.s;if(!p&&!u)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let g,f;try{if(u&&(g=new m(n.r,n.s)),p){try{"compact"!==h&&(g=m.fromDER(n))}catch(e){if(!(e instanceof pi.Err))throw e}!g&&"der"!==h&&(g=m.fromCompact(n))}f=c.fromHex(i)}catch{return!1}if(!g||l&&g.hasHighS())return!1;d&&(s=t.hash(s));const{r:w,s:y}=g,v=b(s),E=a(y),C=o(v*E),N=o(w*E),A=c.BASE.multiplyAndAddUnsafe(f,C,N)?.toAffine();return!!A&&o(A.x)===w},ProjectivePoint:c,Signature:m,utils:f}}function yi(e){return{hash:e,hmac:(t,...s)=>qt(e,t,function(...e){let t=0;for(let s=0;s<e.length;s++){const i=e[s];ae(i),t+=i.length}const s=new Uint8Array(t);for(let t=0,i=0;t<e.length;t++){const r=e[t];s.set(r,i),i+=r.length}return s}(...s)),randomBytes:Ie}}BigInt(4);const bi=$s(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),vi=function(e,t){const s=t=>wi({...e,...yi(t)});return{...s(t),create:s}}({a:bi.create(BigInt("-3")),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Fp:bi,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Zt),Ei="base10",Ci="base16",Ii="base64pad",Ni="base64url",Ai="utf8",_i=0,Si=1,Pi=2,Ti=0,Oi=1,ki=12,Ri=32;function xi(){const e=ai.utils.randomPrivateKey(),t=ai.getPublicKey(e);return{privateKey:(0,d.dI)(e,Ci),publicKey:(0,d.dI)(t,Ci)}}function Ui(){const e=Ie(Ri);return(0,d.dI)(e,Ci)}function Di(e,t){const s=ai.getSharedSecret((0,d.sH)(e,Ci),(0,d.sH)(t,Ci)),i=Ft(Zt,s,void 0,void 0,Ri);return(0,d.dI)(i,Ci)}function Li(e){const t=Zt((0,d.sH)(e,Ci));return(0,d.dI)(t,Ci)}function Wi(e){const t=Zt((0,d.sH)(e,Ai));return(0,d.dI)(t,Ci)}function Mi(e){return(0,d.sH)(`${e}`,Ei)}function Bi(e){return Number((0,d.dI)(e,Ei))}function ji(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qi(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),s=(4-t.length%4)%4;return t+"=".repeat(s)}function $i(e){const t=Mi(typeof e.type<"u"?e.type:_i);if(Bi(t)===Si&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof e.senderPublicKey<"u"?(0,d.sH)(e.senderPublicKey,Ci):void 0,i=typeof e.iv<"u"?(0,d.sH)(e.iv,Ci):Ie(ki),r=(0,d.sH)(e.symKey,Ci),n=zi({type:t,sealed:Bt(r,i).encrypt((0,d.sH)(e.message,Ai)),iv:i,senderPublicKey:s});return e.encoding===Ni?ji(n):n}function Hi(e){const t=(0,d.sH)(e.symKey,Ci),{sealed:s,iv:i}=Ki({encoded:e.encoded,encoding:e.encoding}),r=Bt(t,i).decrypt(s);if(null===r)throw new Error("Failed to decrypt");return(0,d.dI)(r,Ai)}function Fi(e,t){const s=Mi(Pi),i=Ie(ki),r=zi({type:s,sealed:(0,d.sH)(e,Ai),iv:i});return t===Ni?ji(r):r}function Vi(e,t){const{sealed:s}=Ki({encoded:e,encoding:t});return(0,d.dI)(s,Ai)}function zi(e){if(Bi(e.type)===Pi)return(0,d.dI)((0,d.xW)([e.type,e.sealed]),Ii);if(Bi(e.type)===Si){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return(0,d.dI)((0,d.xW)([e.type,e.senderPublicKey,e.iv,e.sealed]),Ii)}return(0,d.dI)((0,d.xW)([e.type,e.iv,e.sealed]),Ii)}function Ki(e){const t=(e.encoding||Ii)===Ni?qi(e.encoded):e.encoded,s=(0,d.sH)(t,Ii),i=s.slice(Ti,Oi),r=Oi;if(Bi(i)===Si){const e=r+Ri,t=e+ki,n=s.slice(r,e),o=s.slice(e,t);return{type:i,sealed:s.slice(t),iv:o,senderPublicKey:n}}if(Bi(i)===Pi)return{type:i,sealed:s.slice(r),iv:Ie(ki)};const n=r+ki,o=s.slice(r,n);return{type:i,sealed:s.slice(n),iv:o}}function Gi(e,t){const s=Ki({encoded:e,encoding:t?.encoding});return Ji({type:Bi(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?(0,d.dI)(s.senderPublicKey,Ci):void 0,receiverPublicKey:t?.receiverPublicKey})}function Ji(e){const t=e?.type||_i;if(t===Si){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function Xi(e){return e.type===Si&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function Yi(e){return e.type===Pi}function Zi(e,t){const[s,i,r]=e.split("."),n=u.from(qi(r),"base64");if(64!==n.length)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=Zt(`${s}.${i}`),h=function(e){const t=u.from(e.x,"base64"),s=u.from(e.y,"base64");return(0,d.xW)([new Uint8Array([4]),t,s])}(t);if(!vi.verify((0,d.xW)([o,a]),c,h))throw new Error("Invalid signature");return(0,l.Cq)(e).payload}const Qi="irn";function er(e){return e?.relay||{protocol:Qi}}function tr(e){const t=h.CG[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function sr(e,t="-"){const s={},i="relay"+t;return Object.keys(e).forEach(t=>{if(t.startsWith(i)){const r=t.replace(i,""),n=e[t];s[r]=n}}),s}function ir(e){if(!e.includes("wc:")){const t=re(e);null!=t&&t.includes("wc:")&&(e=t)}const t=(e=(e=e.includes("wc://")?e.replace("wc://",""):e).includes("wc:")?e.replace("wc:",""):e).indexOf(":"),s=-1!==e.indexOf("?")?e.indexOf("?"):void 0,i=e.substring(0,t),r=e.substring(t+1,s).split("@"),n=typeof s<"u"?e.substring(s):"",o=new URLSearchParams(n),a={};o.forEach((e,t)=>{a[t]=e});const c="string"==typeof a.methods?a.methods.split(","):void 0;return{protocol:i,topic:rr(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:sr(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function rr(e){return e.startsWith("//")?e.substring(2):e}function nr(e){const t=new URLSearchParams,s=function(e,t="-"){const s={};return Object.keys(e).forEach(i=>{const r=i,n="relay"+t+r;e[r]&&(s[n]=e[r])}),s}(e.relay);Object.keys(s).sort().forEach(e=>{t.set(e,s[e])}),t.set("symKey",e.symKey),e.expiryTimestamp&&t.set("expiryTimestamp",e.expiryTimestamp.toString()),e.methods&&t.set("methods",e.methods.join(","));const i=t.toString();return`${e.protocol}:${e.topic}@${e.version}?${i}`}function or(e,t,s){return`${e}?wc_ev=${s}&topic=${t}`}var ar=Object.defineProperty,cr=Object.defineProperties,lr=Object.getOwnPropertyDescriptors,dr=Object.getOwnPropertySymbols,hr=Object.prototype.hasOwnProperty,pr=Object.prototype.propertyIsEnumerable,ur=(e,t,s)=>t in e?ar(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,gr=(e,t)=>{for(var s in t||(t={}))hr.call(t,s)&&ur(e,s,t[s]);if(dr)for(var s of dr(t))pr.call(t,s)&&ur(e,s,t[s]);return e},mr=(e,t)=>cr(e,lr(t));function fr(e){const t=[];return e.forEach(e=>{const[s,i]=e.split(":");t.push(`${s}:${i}`)}),t}function wr(e){return e.includes(":")}function yr(e){return wr(e)?e.split(":")[0]:e}function br(e){var t,s,i;const r={};if(!Sr(e))return r;for(const[n,o]of Object.entries(e)){const e=wr(n)?[n]:o.chains,a=o.methods||[],c=o.events||[],l=yr(n);r[l]=mr(gr({},r[l]),{chains:Z(e,null==(t=r[l])?void 0:t.chains),methods:Z(a,null==(s=r[l])?void 0:s.methods),events:Z(c,null==(i=r[l])?void 0:i.events)})}return r}function vr(e,t){const s=function(e){const t={};return e?.forEach(e=>{var s;const[i,r]=e.split(":");t[i]||(t[i]={accounts:[],chains:[],events:[],methods:[]}),t[i].accounts.push(e),null==(s=t[i].chains)||s.push(`${i}:${r}`)}),t}(t=t.map(e=>e.replace("did:pkh:","")));for(const[t,i]of Object.entries(s))i.methods?i.methods=Z(i.methods,e):i.methods=e,i.events=["chainChanged","accountsChanged"];return s}function Er(e,t){var s,i,r,n,o,a;const c=br(e),l=br(t),d={},h=Object.keys(c).concat(Object.keys(l));for(const e of h)d[e]={chains:Z(null==(s=c[e])?void 0:s.chains,null==(i=l[e])?void 0:i.chains),methods:Z(null==(r=c[e])?void 0:r.methods,null==(n=l[e])?void 0:n.methods),events:Z(null==(o=c[e])?void 0:o.events,null==(a=l[e])?void 0:a.events)};return d}const Cr={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},Ir={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Nr(e,t){const{message:s,code:i}=Ir[e];return{message:t?`${s} ${t}`:s,code:i}}function Ar(e,t){const{message:s,code:i}=Cr[e];return{message:t?`${s} ${t}`:s,code:i}}function _r(e,t){return!!Array.isArray(e)&&(!(typeof t<"u"&&e.length)||e.every(t))}function Sr(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Pr(e){return typeof e>"u"}function Tr(e,t){return!(!t||!Pr(e))||"string"==typeof e&&!!e.trim().length}function Or(e,t){return!(!t||!Pr(e))||"number"==typeof e&&!isNaN(e)}function kr(e,t){const{requiredNamespaces:s}=t,i=Object.keys(e.namespaces),r=Object.keys(s);let n=!0;return!!j(r,i)&&(i.forEach(t=>{const{accounts:i,methods:r,events:o}=e.namespaces[t],a=fr(i),c=s[t];j(f(t,c),a)&&j(c.methods,r)&&j(c.events,o)||(n=!1)}),n)}function Rr(e){return!(!Tr(e,!1)||!e.includes(":"))&&2===e.split(":").length}function xr(e){function t(e){try{return typeof new URL(e)<"u"}catch{return!1}}try{if(Tr(e,!1))return!!t(e)||t(re(e))}catch{}return!1}function Ur(e){var t;return null==(t=e?.proposer)?void 0:t.publicKey}function Dr(e){return e?.topic}function Lr(e,t){let s=null;return Tr(e?.publicKey,!1)||(s=Nr("MISSING_OR_INVALID",`${t} controller public key should be a string`)),s}function Wr(e){let t=!0;return _r(e)?e.length&&(t=e.every(e=>Tr(e,!1))):t=!1,t}function Mr(e,t){let s=null;return Object.values(e).forEach(e=>{if(s)return;const i=function(e,t){let s=null;return Wr(e?.methods)?Wr(e?.events)||(s=Ar("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):s=Ar("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),s}(e,`${t}, namespace`);i&&(s=i)}),s}function Br(e,t,s){let i=null;if(e&&Sr(e)){const r=Mr(e,t);r&&(i=r);const n=function(e,t,s){let i=null;return Object.entries(e).forEach(([e,r])=>{if(i)return;const n=function(e,t,s){let i=null;return _r(t)&&t.length?t.forEach(e=>{i||Rr(e)||(i=Ar("UNSUPPORTED_CHAINS",`${s}, chain ${e} should be a string and conform to "namespace:chainId" format`))}):Rr(e)||(i=Ar("UNSUPPORTED_CHAINS",`${s}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}(e,f(e,r),`${t} ${s}`);n&&(i=n)}),i}(e,t,s);n&&(i=n)}else i=Nr("MISSING_OR_INVALID",`${t}, ${s} should be an object with data`);return i}function jr(e,t){let s=null;if(e&&Sr(e)){const i=Mr(e,t);i&&(s=i);const r=function(e,t){let s=null;return Object.values(e).forEach(e=>{if(s)return;const i=function(e,t){let s=null;return _r(e)?e.forEach(e=>{s||function(e){if(Tr(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&Rr(e)}}return!1}(e)||(s=Ar("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))}):s=Ar("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}(e?.accounts,`${t} namespace`);i&&(s=i)}),s}(e,t);r&&(s=r)}else s=Nr("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return s}function qr(e){return Tr(e.protocol,!0)}function $r(e,t){let s=!1;return t&&!e?s=!0:e&&_r(e)&&e.length&&e.forEach(e=>{s=qr(e)}),s}function Hr(e){return"number"==typeof e}function Fr(e){return typeof e<"u"&&null!==typeof e}function Vr(e){return!!(e&&"object"==typeof e&&e.code&&Or(e.code,!1)&&e.message&&Tr(e.message,!1))}function zr(e){return!(Pr(e)||!Tr(e.method,!1))}function Kr(e){return!(Pr(e)||Pr(e.result)&&Pr(e.error)||!Or(e.id,!1)||!Tr(e.jsonrpc,!1))}function Gr(e){return!(Pr(e)||!Tr(e.name,!1))}function Jr(e,t){return!(!Rr(t)||!function(e){const t=[];return Object.values(e).forEach(e=>{t.push(...fr(e.accounts))}),t}(e).includes(t))}function Xr(e,t,s){return!!Tr(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach(e=>{fr(e.accounts).includes(t)&&s.push(...e.methods)}),s}(e,t).includes(s)}function Yr(e,t,s){return!!Tr(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach(e=>{fr(e.accounts).includes(t)&&s.push(...e.events)}),s}(e,t).includes(s)}function Zr(e,t,s){let i=null;const r=function(e){const t={};return Object.keys(e).forEach(s=>{var i;s.includes(":")?t[s]=e[s]:null==(i=e[s].chains)||i.forEach(i=>{t[i]={methods:e[s].methods,events:e[s].events}})}),t}(e),n=function(e){const t={};return Object.keys(e).forEach(s=>{if(s.includes(":"))t[s]=e[s];else{const i=fr(e[s].accounts);i?.forEach(i=>{t[i]={accounts:e[s].accounts.filter(e=>e.includes(`${i}:`)),methods:e[s].methods,events:e[s].events}})}}),t}(t),o=Object.keys(r),a=Object.keys(n),c=Qr(Object.keys(e)),l=Qr(Object.keys(t)),d=c.filter(e=>!l.includes(e));return d.length&&(i=Nr("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.\n Required: ${d.toString()}\n Received: ${Object.keys(t).toString()}`)),j(o,a)||(i=Nr("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.\n Required: ${o.toString()}\n Approved: ${a.toString()}`)),Object.keys(t).forEach(e=>{if(!e.includes(":")||i)return;const r=fr(t[e].accounts);r.includes(e)||(i=Nr("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${r.toString()}`))}),o.forEach(e=>{i||(j(r[e].methods,n[e].methods)?j(r[e].events,n[e].events)||(i=Nr("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${e}`)):i=Nr("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${e}`))}),i}function Qr(e){return[...new Set(e.map(e=>e.includes(":")?e.split(":")[0]:e))]}function en(e,t){return Or(e,!1)&&e<=t.max&&e>=t.min}function tn(){const e=U();return new Promise(t=>{switch(e){case S.browser:t(x()&&navigator?.onLine);break;case S.reactNative:t(async function(){if(O()&&typeof s.g<"u"&&null!=s.g&&s.g.NetInfo){const e=await(null==s.g?void 0:s.g.NetInfo.fetch());return e?.isConnected}return!0}());break;case S.node:default:t(!0)}})}function sn(e){switch(U()){case S.browser:!function(e){!O()&&x()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}(e);break;case S.reactNative:!function(e){O()&&typeof s.g<"u"&&null!=s.g&&s.g.NetInfo&&s.g?.NetInfo.addEventListener(t=>e(t?.isConnected))}(e);case S.node:}}function rn(){var e;return!x()||!(0,n.getDocument)()||"visible"===(null==(e=(0,n.getDocument)())?void 0:e.visibilityState)}const nn={};class on{static get(e){return nn[e]}static set(e,t){nn[e]=t}static delete(e){delete nn[e]}}},16444:(e,t,s)=>{s.d(t,{T:()=>m});var i=s(89168),r=s(3555),n=s(22143),o=s(35646),a=s(11847),c=s(23981),l=s(98299),d=s(1420),h=s(92492);const p={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},u=n.w.getBlockchainApiUrl(),g=(0,i.BX)({clientId:null,api:new o.Z({baseUrl:u,clientId:null}),supportedChains:{http:[],ws:[]}}),m={state:g,async get(e){const{st:t,sv:s}=m.getSdkProperties(),i=d.H.state.projectId,r={...e.params||{},st:t,sv:s,projectId:i};return g.api.get({...e,params:r})},getSdkProperties(){const{sdkType:e,sdkVersion:t}=d.H.state;return{st:e||"unknown",sv:t||"unknown"}},async isNetworkSupported(e){if(!e)return!1;try{g.supportedChains.http.length||await m.getSupportedNetworks()}catch(e){return!1}return g.supportedChains.http.includes(e)},async getSupportedNetworks(){try{const e=await m.get({path:"v1/supported-chains"});return g.supportedChains=e,e}catch{return g.supportedChains}},async fetchIdentity({address:e,caipNetworkId:t}){if(!await m.isNetworkSupported(t))return{avatar:"",name:""};const s=a.i.getIdentityFromCacheForAddress(e);if(s)return s;const i=await m.get({path:`/v1/identity/${e}`,params:{sender:l.W.state.activeCaipAddress?n.w.getPlainAddress(l.W.state.activeCaipAddress):void 0}});return a.i.updateIdentityCache({address:e,identity:i,timestamp:Date.now()}),i},fetchTransactions:async({account:e,cursor:t,onramp:s,signal:i,cache:r,chainId:n})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:`/v1/account/${e}/history`,params:{cursor:t,onramp:s,chainId:n},signal:i,cache:r}):{data:[],next:void 0},fetchSwapQuote:async({amount:e,userAddress:t,from:s,to:i,gasPrice:r})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:e,userAddress:t,from:s,to:i,gasPrice:r}}):{quotes:[]},fetchSwapTokens:async({chainId:e})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:"/v1/convert/tokens",params:{chainId:e}}):{tokens:[]},fetchTokenPrice:async({addresses:e})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?g.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:e,projectId:d.H.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]},fetchSwapAllowance:async({tokenAddress:e,userAddress:t})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:"/v1/convert/allowance",params:{tokenAddress:e,userAddress:t},headers:{"Content-Type":"application/json"}}):{allowance:"0"},async fetchGasPrice({chainId:e}){const{st:t,sv:s}=m.getSdkProperties();if(!await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return m.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:e,st:t,sv:s}})},async generateSwapCalldata({amount:e,from:t,to:s,userAddress:i,disableEstimate:n}){if(!await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return g.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:e,eip155:{slippage:r.oU.CONVERT_SLIPPAGE_TOLERANCE},projectId:d.H.state.projectId,from:t,to:s,userAddress:i,disableEstimate:n}})},async generateApproveCalldata({from:e,to:t,userAddress:s}){const{st:i,sv:r}=m.getSdkProperties();if(!await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return m.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:e,to:t,st:i,sv:r}})},async getBalance(e,t,s){const{st:i,sv:r}=m.getSdkProperties();if(!await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId))return h.P.showError("Token Balance Unavailable"),{balances:[]};const n=`${t}:${e}`,o=a.i.getBalanceCacheForCaipAddress(n);if(o)return o;const c=await m.get({path:`/v1/account/${e}/balance`,params:{currency:"usd",chainId:t,forceUpdate:s,st:i,sv:r}});return a.i.updateBalanceCache({caipAddress:n,balance:c,timestamp:Date.now()}),c},lookupEnsName:async e=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:`/v1/profile/account/${e}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]},reverseLookupEnsName:async({address:e})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:`/v1/profile/reverse/${e}`,params:{sender:c.U.state.address,apiVersion:"2"}}):[],getEnsNameSuggestions:async e=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:`/v1/profile/suggestions/${e}`,params:{zone:"reown.id"}}):{suggestions:[]},registerEnsName:async({coinType:e,address:t,message:s,signature:i})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?g.api.post({path:"/v1/profile/account",body:{coin_type:e,address:t,message:s,signature:i},headers:{"Content-Type":"application/json"}}):{success:!1},generateOnRampURL:async({destinationWallets:e,partnerUserId:t,defaultNetwork:s,purchaseAmount:i,paymentAmount:r})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?(await g.api.post({path:"/v1/generators/onrampurl",params:{projectId:d.H.state.projectId},body:{destinationWallets:e,defaultNetwork:s,partnerUserId:t,defaultExperience:"buy",presetCryptoAmount:i,presetFiatAmount:r}})).url:"",async getOnrampOptions(){if(!await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await m.get({path:"/v1/onramp/options"})}catch(e){return p}},async getOnrampQuote({purchaseCurrency:e,paymentCurrency:t,amount:s,network:i}){try{return await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?await g.api.post({path:"/v1/onramp/quote",params:{projectId:d.H.state.projectId},body:{purchaseCurrency:e,paymentCurrency:t,amount:s,network:i}}):null}catch(e){return{coinbaseFee:{amount:s,currency:t.id},networkFee:{amount:s,currency:t.id},paymentSubtotal:{amount:s,currency:t.id},paymentTotal:{amount:s,currency:t.id},purchaseAmount:{amount:s,currency:t.id},quoteId:"mocked-quote-id"}}},getSmartSessions:async e=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:`/v1/sessions/${e}`}):[],revokeSmartSession:async(e,t,s)=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?g.api.post({path:`/v1/sessions/${e}/revoke`,params:{projectId:d.H.state.projectId},body:{pci:t,signature:s}}):{success:!1},setClientId(e){g.clientId=e,g.api=new o.Z({baseUrl:u,clientId:e})}}},18338:(e,t,s)=>{s.d(t,{A:()=>Ze});var i=s(27811),r=s(15529),n=s(70255),o=s(64264),a=s(93786),c=s(14350),l=s(50046),d=s.n(l),h=s(48526).hp;const p="error",u="wc@2:universal_provider:",g="https://rpc.walletconnect.org/v1/",m="generic",f=`${g}bundler`,w="default_chain_changed";function y(){}function b(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function v(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function E(e){return"object"==typeof e&&null!==e}function C(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function I(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const N="[object String]",A="[object Number]",_="[object Boolean]",S="[object Arguments]";function P(e,t,s,i=new Map,r=void 0){const n=r?.(e,t,s,i);if(null!=n)return n;if(b(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){const t=new Array(e.length);i.set(e,t);for(let n=0;n<e.length;n++)t[n]=P(e[n],n,s,i,r);return Object.hasOwn(e,"index")&&(t.index=e.index),Object.hasOwn(e,"input")&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){const t=new Map;i.set(e,t);for(const[n,o]of e)t.set(n,P(o,n,s,i,r));return t}if(e instanceof Set){const t=new Set;i.set(e,t);for(const n of e)t.add(P(n,void 0,s,i,r));return t}if(typeof h<"u"&&h.isBuffer(e))return e.subarray();if(v(e)){const t=new(Object.getPrototypeOf(e).constructor)(e.length);i.set(e,t);for(let n=0;n<e.length;n++)t[n]=P(e[n],n,s,i,r);return t}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,t),T(t,e,s,i,r),t}if(typeof File<"u"&&e instanceof File){const t=new File([e],e.name,{type:e.type});return i.set(e,t),T(t,e,s,i,r),t}if(e instanceof Blob){const t=new Blob([e],{type:e.type});return i.set(e,t),T(t,e,s,i,r),t}if(e instanceof Error){const t=new e.constructor;return i.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,T(t,e,s,i,r),t}if("object"==typeof e&&function(e){switch(I(e)){case S:case"[object Array]":case"[object ArrayBuffer]":case"[object DataView]":case _:case"[object Date]":case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Map]":case A:case"[object Object]":case"[object RegExp]":case"[object Set]":case N:case"[object Symbol]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return!0;default:return!1}}(e)){const t=Object.create(Object.getPrototypeOf(e));return i.set(e,t),T(t,e,s,i,r),t}return e}function T(e,t,s=e,i,r){const n=[...Object.keys(t),...C(t)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(e,a);(null==c||c.writable)&&(e[a]=P(t[a],a,s,i,r))}}function O(e){return function(e,t){return function(e,t){return P(e,void 0,e,new Map,t)}(e,(s,i,r,n)=>{const o=t?.(s,i,r,n);if(null!=o)return o;if("object"==typeof e)switch(Object.prototype.toString.call(e)){case A:case N:case _:{const t=new e.constructor(e?.valueOf());return T(t,e),t}case S:{const t={};return T(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}})}(e)}function k(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===I(e)}function R(e){return v(e)}function x(e){if("object"!=typeof e||null==e)return!1;if(null===Object.getPrototypeOf(e))return!0;if("[object Object]"!==Object.prototype.toString.call(e)){const t=e[Symbol.toStringTag];return!(null==t||!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable)&&e.toString()===`[object ${t}]`}let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function U(e,t,s,i){if(b(e)&&(e=Object(e)),null==t||"object"!=typeof t)return e;if(i.has(t))return function(e){if(b(e))return e;if(Array.isArray(e)||v(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e),s=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new s(e);if(e instanceof RegExp){const t=new s(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new s(e.buffer.slice(0));if(e instanceof Error){const t=new s(e.message);return t.stack=e.stack,t.name=e.name,t.cause=e.cause,t}if(typeof File<"u"&&e instanceof File)return new s([e],e.name,{type:e.type,lastModified:e.lastModified});if("object"==typeof e){const s=Object.create(t);return Object.assign(s,e)}return e}(i.get(t));if(i.set(t,e),Array.isArray(t)){t=t.slice();for(let e=0;e<t.length;e++)t[e]=t[e]??void 0}const r=[...Object.keys(t),...C(t)];for(let n=0;n<r.length;n++){const o=r[n];let a=t[o],c=e[o];if(k(a)&&(a={...a}),k(c)&&(c={...c}),typeof h<"u"&&h.isBuffer(a)&&(a=O(a)),Array.isArray(a))if("object"==typeof c&&null!=c){const e=[],t=Reflect.ownKeys(c);for(let s=0;s<t.length;s++){const i=t[s];e[i]=c[i]}c=e}else c=[];const l=s(c,a,o,e,t,i);null!=l?e[o]=l:Array.isArray(a)||E(c)&&E(a)?e[o]=U(c,a,s,i):null==c&&x(a)?e[o]=U({},a,s,i):null==c&&R(a)?e[o]=O(a):(void 0===c||void 0!==a)&&(e[o]=a)}return e}var D=Object.defineProperty,L=Object.defineProperties,W=Object.getOwnPropertyDescriptors,M=Object.getOwnPropertySymbols,B=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable,q=(e,t,s)=>t in e?D(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,$=(e,t)=>{for(var s in t||(t={}))B.call(t,s)&&q(e,s,t[s]);if(M)for(var s of M(t))j.call(t,s)&&q(e,s,t[s]);return e},H=(e,t)=>L(e,W(t));function F(e,t,s){var i;const n=(0,r._Yb)(e);return(null==(i=t.rpcMap)?void 0:i[n.reference])||`${g}?chainId=${n.namespace}:${n.reference}&projectId=${s}`}function V(e){return e.includes(":")?e.split(":")[1]:e}function z(e){return e.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function K(e={},t={}){return function(e,...t){return function(e,...t){const s=t.slice(0,-1),i=t[t.length-1];let r=e;for(let e=0;e<s.length;e++)r=U(r,s[e],i,new Map);return r}(e,...t,y)}(G(e),G(t))}function G(e){var t,s,i,n,o;const a={};if(!(0,r.aF0)(e))return a;for(const[c,l]of Object.entries(e)){const e=(0,r.nWe)(c)?[c]:l.chains,d=l.methods||[],h=l.events||[],p=l.rpcMap||{},u=(0,r.kob)(c);a[u]=H($($({},a[u]),l),{chains:(0,r.TRk)(e,null==(t=a[u])?void 0:t.chains),methods:(0,r.TRk)(d,null==(s=a[u])?void 0:s.methods),events:(0,r.TRk)(h,null==(i=a[u])?void 0:i.events)}),((0,r.aF0)(p)||(0,r.aF0)((null==(n=a[u])?void 0:n.rpcMap)||{}))&&(a[u].rpcMap=$($({},p),null==(o=a[u])?void 0:o.rpcMap))}return a}function J(e){return e.includes(":")?e.split(":")[2]:e}function X(e){const t={};for(const[s,i]of Object.entries(e)){const e=i.methods||[],n=i.events||[],o=i.accounts||[],a=(0,r.nWe)(s)?[s]:i.chains?i.chains:z(i.accounts);t[s]={chains:a,methods:e,events:n,accounts:o}}return t}function Y(e){return"number"==typeof e?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}const Z={},Q=e=>Z[e],ee=(e,t)=>{Z[e]=t};var te=Object.defineProperty,se=(e,t,s)=>((e,t,s)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class ie{constructor(e){se(this,"name","polkadot"),se(this,"client"),se(this,"httpProviders"),se(this,"events"),se(this,"namespace"),se(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e&&e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=V(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var re=Object.defineProperty,ne=Object.defineProperties,oe=Object.getOwnPropertyDescriptors,ae=Object.getOwnPropertySymbols,ce=Object.prototype.hasOwnProperty,le=Object.prototype.propertyIsEnumerable,de=(e,t,s)=>t in e?re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,he=(e,t)=>{for(var s in t||(t={}))ce.call(t,s)&&de(e,s,t[s]);if(ae)for(var s of ae(t))le.call(t,s)&&de(e,s,t[s]);return e},pe=(e,t)=>ne(e,oe(t)),ue=(e,t,s)=>de(e,"symbol"!=typeof t?t+"":t,s);class ge{constructor(e){ue(this,"name","eip155"),ue(this,"client"),ue(this,"chainId"),ue(this,"namespace"),ue(this,"httpProviders"),ue(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(w,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const s=t||F(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.V(s,Q("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=parseInt(V(t));e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,s;let i=e.request.params?null==(t=e.request.params[0])?void 0:t.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const r=parseInt(i,16);if(this.isChainApproved(r))this.setDefaultChain(`${r}`);else{if(!this.namespace.methods.includes("wallet_switchEthereumChain"))throw new Error(`Failed to switch to chain 'eip155:${r}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:null==(s=this.namespace.chains)?void 0:s[0]}),this.setDefaultChain(`${r}`)}return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,s,i,r,n;const o=null==(s=null==(t=e.request)?void 0:t.params)?void 0:s[0],a=`${o}${((null==(r=null==(i=e.request)?void 0:i.params)?void 0:r[1])||[]).join(",")}`;if(!o)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const c=this.client.session.get(e.topic),l=(null==(n=c?.sessionProperties)?void 0:n.capabilities)||{};if(null!=l&&l[a])return l?.[a];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:pe(he({},c.sessionProperties||{}),{capabilities:pe(he({},l||{}),{[a]:d})})})}catch(e){console.warn("Failed to update session with capabilities",e)}return d}async getCallStatus(e){var t,s;const i=this.client.session.get(e.topic),r=null==(t=i.sessionProperties)?void 0:t.bundler_name;if(r){const t=this.getBundlerUrl(e.chainId,r);try{return await this.getUserOperationReceipt(t,e)}catch(e){console.warn("Failed to fetch call status from bundler",e,t)}}const n=null==(s=i.sessionProperties)?void 0:s.bundler_url;if(n)try{return await this.getUserOperationReceipt(n,e)}catch(e){console.warn("Failed to fetch call status from custom bundler",e,n)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var s;const i=new URL(e),r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify((0,c.formatJsonRpcRequest)("eth_getUserOperationReceipt",[null==(s=t.request.params)?void 0:s[0]]))});if(!r.ok)throw new Error(`Failed to fetch user operation receipt - ${r.status}`);return await r.json()}getBundlerUrl(e,t){return`${f}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var me=Object.defineProperty,fe=(e,t,s)=>((e,t,s)=>t in e?me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class we{constructor(e){fe(this,"name","solana"),fe(this,"client"),fe(this,"httpProviders"),fe(this,"events"),fe(this,"namespace"),fe(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=V(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var ye=Object.defineProperty,be=(e,t,s)=>((e,t,s)=>t in e?ye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class ve{constructor(e){be(this,"name","cosmos"),be(this,"client"),be(this,"httpProviders"),be(this,"events"),be(this,"namespace"),be(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=V(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var Ee=Object.defineProperty,Ce=(e,t,s)=>((e,t,s)=>t in e?Ee(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ie{constructor(e){Ce(this,"name","algorand"),Ce(this,"client"),Ce(this,"httpProviders"),Ce(this,"events"),Ce(this,"namespace"),Ce(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const s=t||F(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.chainId=e,this.events.emit(w,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;e[t]=this.createHttpProvider(t,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new a.F(new o.A(s,Q("disableProviderPing")))}}var Ne=Object.defineProperty,Ae=(e,t,s)=>((e,t,s)=>t in e?Ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class _e{constructor(e){Ae(this,"name","cip34"),Ae(this,"client"),Ae(this,"httpProviders"),Ae(this,"events"),Ae(this,"namespace"),Ae(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const s=this.getCardanoRPCUrl(t),i=V(t);e[i]=this.createHttpProvider(i,s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||this.getCardanoRPCUrl(e);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var Se=Object.defineProperty,Pe=(e,t,s)=>((e,t,s)=>t in e?Se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Te{constructor(e){Pe(this,"name","elrond"),Pe(this,"client"),Pe(this,"httpProviders"),Pe(this,"events"),Pe(this,"namespace"),Pe(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=V(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var Oe=Object.defineProperty,ke=(e,t,s)=>((e,t,s)=>t in e?Oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Re{constructor(e){ke(this,"name","multiversx"),ke(this,"client"),ke(this,"httpProviders"),ke(this,"events"),ke(this,"namespace"),ke(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=V(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var xe=Object.defineProperty,Ue=(e,t,s)=>((e,t,s)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class De{constructor(e){Ue(this,"name","near"),Ue(this,"client"),Ue(this,"httpProviders"),Ue(this,"events"),Ue(this,"namespace"),Ue(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||F(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(w,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e&&e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;e[t]=this.createHttpProvider(t,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace);return typeof s>"u"?void 0:new a.F(new o.A(s,Q("disableProviderPing")))}}var Le=Object.defineProperty,We=(e,t,s)=>((e,t,s)=>t in e?Le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Me{constructor(e){We(this,"name","tezos"),We(this,"client"),We(this,"httpProviders"),We(this,"events"),We(this,"namespace"),We(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||F(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(w,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e&&e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace);return typeof s>"u"?void 0:new a.F(new o.A(s))}}var Be=Object.defineProperty,je=(e,t,s)=>((e,t,s)=>t in e?Be(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class qe{constructor(e){je(this,"name",m),je(this,"client"),je(this,"httpProviders"),je(this,"events"),je(this,"namespace"),je(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){var e,t;const s={};return null==(t=null==(e=this.namespace)?void 0:e.accounts)||t.forEach(e=>{const t=(0,r._Yb)(e);s[`${t.namespace}:${t.reference}`]=this.createHttpProvider(e)}),s}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var $e=Object.defineProperty,He=Object.defineProperties,Fe=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertySymbols,ze=Object.prototype.hasOwnProperty,Ke=Object.prototype.propertyIsEnumerable,Ge=(e,t,s)=>t in e?$e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Je=(e,t)=>{for(var s in t||(t={}))ze.call(t,s)&&Ge(e,s,t[s]);if(Ve)for(var s of Ve(t))Ke.call(t,s)&&Ge(e,s,t[s]);return e},Xe=(e,t)=>He(e,Fe(t)),Ye=(e,t,s)=>Ge(e,"symbol"!=typeof t?t+"":t,s);class Ze{constructor(e){Ye(this,"client"),Ye(this,"namespaces"),Ye(this,"optionalNamespaces"),Ye(this,"sessionProperties"),Ye(this,"scopedProperties"),Ye(this,"events",new(d())),Ye(this,"rpcProviders",{}),Ye(this,"session"),Ye(this,"providerOpts"),Ye(this,"logger"),Ye(this,"uri"),Ye(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&"string"!=typeof e?.logger?e.logger:(0,n.h6)((0,n.iP)({level:e?.logger||p})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new Ze(e);return await t.initialize(),t}async request(e,t,s){const[i,r]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:Je({},e),chainId:`${i}:${r}`,topic:this.session.topic,expiry:s})}sendAsync(e,t,s,i){const r=(new Date).getTime();this.request(e,s,i).then(e=>t(null,(0,c.formatJsonRpcResult)(r,e))).catch(e=>t(e,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:null==(e=this.session)?void 0:e.topic,reason:(0,r.Hjj)("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:s,response:i}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const r=await i();if(this.session=r.session,this.session){const e=X(this.session.namespaces);this.namespaces=K(this.namespaces,e),await this.persist("namespaces",this.namespaces),this.onConnect()}return r}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const i=await s();this.session=i;const r=X(i.namespaces);return this.namespaces=K(this.namespaces,r),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[s,i]=this.validateChain(e),r=this.getProvider(s);r.name===m?r.setDefaultChain(`${s}:${i}`,t):r.setDefaultChain(i,t)}catch(e){if(!/Please call connect/.test(e.message))throw e}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if((0,r.OP1)(t)){for(const s of t)e.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,t;if(this.client=this.providerOpts.client||await i.Ay.init({core:this.providerOpts.core,logger:this.providerOpts.logger||p,relayUrl:this.providerOpts.relayUrl||"wss://relay.walletconnect.org",projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(s){throw this.logger.error("Failed to get session",s),new Error(`The provided session: ${null==(t=null==(e=this.providerOpts)?void 0:e.session)?void 0:t.topic} doesn't exist in the Sign client`)}else{const e=this.client.session.getAll();this.session=e[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(e=>(0,r.kob)(e)))];ee("client",this.client),ee("events",this.events),ee("disableProviderPing",this.disableProviderPing),e.forEach(e=>{if(!this.session)return;const t=function(e,t){const s=Object.keys(t.namespaces).filter(t=>t.includes(e));if(!s.length)return[];const i=[];return s.forEach(e=>{const s=t.namespaces[e].accounts;i.push(...s)}),i}(e,this.session),s=z(t),i=K(this.namespaces,this.optionalNamespaces),r=Xe(Je({},i[e]),{accounts:t,chains:s});switch(e){case"eip155":this.rpcProviders[e]=new ge({namespace:r});break;case"algorand":this.rpcProviders[e]=new Ie({namespace:r});break;case"solana":this.rpcProviders[e]=new we({namespace:r});break;case"cosmos":this.rpcProviders[e]=new ve({namespace:r});break;case"polkadot":this.rpcProviders[e]=new ie({namespace:r});break;case"cip34":this.rpcProviders[e]=new _e({namespace:r});break;case"elrond":this.rpcProviders[e]=new Te({namespace:r});break;case"multiversx":this.rpcProviders[e]=new Re({namespace:r});break;case"near":this.rpcProviders[e]=new De({namespace:r});break;case"tezos":this.rpcProviders[e]=new Me({namespace:r});break;default:this.rpcProviders[m]?this.rpcProviders[m].updateNamespace(r):this.rpcProviders[m]=new qe({namespace:r})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:s}=e;s===(null==(t=this.session)?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:s,topic:i}=e;if(i!==(null==(t=this.session)?void 0:t.topic))return;const{event:n}=s;if("accountsChanged"===n.name){const e=n.data;e&&(0,r.OP1)(e)&&this.events.emit("accountsChanged",e.map(J))}else if("chainChanged"===n.name){const e=s.chainId,t=s.event.data,i=(0,r.kob)(e),n=Y(e)!==Y(t)?`${i}:${Y(t)}`:e;this.onChainChanged(n)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var s,i;if(e!==(null==(s=this.session)?void 0:s.topic))return;const{namespaces:r}=t,n=null==(i=this.client)?void 0:i.session.get(e);this.session=Xe(Je({},n),{namespaces:r}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===(null==(t=this.session)?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Xe(Je({},(0,r.Hjj)("USER_DISCONNECTED")),{data:e.topic})))}),this.on(w,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[m]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace(null==(t=this.session)?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:s={},sessionProperties:i,scopedProperties:r}=e;this.optionalNamespaces=K(t,s),this.sessionProperties=i,this.scopedProperties=r}validateChain(e){const[t,s]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(e=>(0,r.kob)(e)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&s)return[t,s];const i=(0,r.kob)(Object.keys(this.namespaces)[0]);return[i,this.rpcProviders[i].getDefaultChain()]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[s,i]=this.validateChain(e);if(!i)return;this.updateNamespaceChain(s,i),this.events.emit("chainChanged",i);const r=this.getProvider(s).getDefaultChain();t||this.getProvider(s).setDefaultChain(i),this.emitAccountsChangedOnChainChange({namespace:s,previousChainId:r,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:s}){var i,n;try{if(t===s)return;const o=null==(n=null==(i=this.session)?void 0:i.namespaces[e])?void 0:n.accounts;if(!o)return;const a=o.filter(e=>e.includes(`${s}:`)).map(J);if(!(0,r.OP1)(a))return;this.events.emit("accountsChanged",a)}catch(e){this.logger.warn("Failed to emit accountsChanged on chain change",e)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const s=this.namespaces[e]?e:`${e}:${t}`,i={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[s]?this.namespaces[s]&&(this.namespaces[s].defaultChain=t):this.namespaces[s]=i}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var s;const i=(null==(s=this.session)?void 0:s.topic)||"";await this.client.core.storage.setItem(`${u}/${e}${i}`,t)}async getFromStore(e){var t;const s=(null==(t=this.session)?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${u}/${e}${s}`)}async deleteFromStore(e){var t;const s=(null==(t=this.session)?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${u}/${e}${s}`)}async cleanupStorage(){var e;try{if((null==(e=this.client)?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const e of t)e.startsWith(u)&&await this.client.core.storage.removeItem(e)}catch(e){this.logger.warn("Failed to cleanup storage",e)}}}},18496:(e,t,s)=>{s.d(t,{v:()=>a});var i=s(29972),r=s(34311),n=s(89604),o=s(72269);const a={getERC20Abi:e=>o.o.USDT_CONTRACT_ADDRESSES.includes(e)?n.r:i.F,getSwapAbi:()=>r.Q}},18898:(e,t,s)=>{s.d(t,{$Q:()=>b,GF:()=>y,S9:()=>C,Vx:()=>f,ZP:()=>c,dQ:()=>h,lZ:()=>d,m5:()=>u,mF:()=>m,pi:()=>g,qE:()=>p,yJ:()=>I,zl:()=>w});var i=s(94549),r=s(50046),n=s.n(r),o=Object.defineProperty,a=(e,t,s)=>((e,t,s)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class c extends i.H{constructor(e){super(),this.opts=e,a(this,"protocol","wc"),a(this,"version",2)}}var l=Object.defineProperty;class d extends i.H{constructor(e,t){super(),this.core=e,this.logger=t,((e,t,s)=>{((e,t,s)=>{t in e?l(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s})(e,"symbol"!=typeof t?t+"":t,s)})(this,"records",new Map)}}class h{constructor(e,t){this.logger=e,this.core=t}}class p extends i.H{constructor(e,t){super(),this.relayer=e,this.logger=t}}class u extends i.H{constructor(e){super()}}class g{constructor(e,t,s,i){this.core=e,this.logger=t,this.name=s}}Object.defineProperty;class m extends i.H{constructor(e,t){super(),this.relayer=e,this.logger=t}}class f extends i.H{constructor(e,t){super(),this.core=e,this.logger=t}}class w{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}}class y{constructor(e,t){this.projectId=e,this.logger=t}}class b{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}}var v=Object.defineProperty,E=(e,t,s)=>((e,t,s)=>t in e?v(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);n();class C{constructor(e){this.opts=e,E(this,"protocol","wc"),E(this,"version",2)}}r.EventEmitter;class I{constructor(e){this.client=e}}},20475:(e,t,s)=>{s.d(t,{_:()=>q});var i=s(18338),r=s(67902),n=s(72269),o=s(55611),a=s(88759),c=s(72397),l=s(23981),d=s(98299),h=s(89305),p=s(86792),u=s(83077),g=s(92492),m=s(93474),f=s(49951),w=s(1420),y=s(16444),b=s(68251),v=s(47981),E=s(37686),C=s(13766),I=s(31100),N=s(86454),A=s(3555),_=s(22143),S=s(11847),P=s(36507),T=s(41607),O=s(44242),k=s(69658),R=s(83229),x=s(51765),U=s(20602),D=s(2974),L=s(38097),W=s(36347),M=s(28873),B=s(62410),j=s(25598);class q{constructor(e){this.chainNamespaces=[],this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(e,t)=>{if(e){const s=d.W.getNetworkData(e)?.requestedCaipNetworks?.find(e=>e.id===t);if(s)return s;const i=d.W.getNetworkData(e)?.caipNetwork;if(i)return i;const r=d.W.getRequestedCaipNetworks(e);return r.filter(t=>t.chainNamespace===e)?.[0]}return d.W.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const e=this.getCaipNetwork();if(e)return e.id},this.getCaipNetworks=e=>d.W.getCaipNetworks(e),this.getActiveChainNamespace=()=>d.W.state.activeChain,this.setRequestedCaipNetworks=(e,t)=>{d.W.setRequestedCaipNetworks(e,t)},this.getApprovedCaipNetworkIds=()=>d.W.getAllApprovedCaipNetworkIds(),this.getCaipAddress=e=>d.W.state.activeChain!==e&&e?d.W.getAccountProp("caipAddress",e):d.W.state.activeCaipAddress,this.setClientId=e=>{y.T.setClientId(e)},this.getProvider=e=>W.A.getProvider(e),this.getProviderType=e=>W.A.getProviderId(e),this.getPreferredAccountType=e=>l.U.state.preferredAccountTypes?.[e],this.setCaipAddress=(e,t)=>{l.U.setCaipAddress(e,t),e&&w.H.state.enableEmbedded&&this.close()},this.setBalance=(e,t,s)=>{l.U.setBalance(e,t,s)},this.setProfileName=(e,t)=>{l.U.setProfileName(e,t)},this.setProfileImage=(e,t)=>{l.U.setProfileImage(e,t)},this.setUser=(e,t)=>{l.U.setUser(e,t)},this.resetAccount=e=>{l.U.resetAccount(e)},this.setCaipNetwork=e=>{d.W.setActiveCaipNetwork(e)},this.setCaipNetworkOfNamespace=(e,t)=>{d.W.setChainNetworkData(t,{caipNetwork:e})},this.setAllAccounts=(e,t)=>{l.U.setAllAccounts(e,t),w.H.setHasMultipleAddresses(e?.length>1)},this.setStatus=(e,t)=>{l.U.setStatus(e,t),u.a.isConnected()?S.i.setConnectionStatus("connected"):S.i.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=e=>d.W.getAccountProp("address",e),this.setConnectors=e=>{const t=[...u.a.state.allConnectors,...e];u.a.setConnectors(t)},this.setConnections=(e,t)=>{p.x.setConnections(e,t)},this.fetchIdentity=e=>y.T.fetchIdentity(e),this.getReownName=e=>C.f.getNamesForAddress(e),this.getConnectors=()=>u.a.getConnectors(),this.getConnectorImage=e=>N.$.getConnectorImage(e),this.setConnectedWalletInfo=(e,t)=>{const s=W.A.getProviderId(t),i=e?{...e,type:s}:void 0;l.U.setConnectedWalletInfo(i,t)},this.getIsConnectedState=()=>Boolean(d.W.state.activeCaipAddress),this.addAddressLabel=(e,t,s)=>{l.U.addAddressLabel(e,t,s)},this.removeAddressLabel=(e,t)=>{l.U.removeAddressLabel(e,t)},this.getAddress=e=>d.W.state.activeChain!==e&&e?d.W.getAccountProp("address",e):l.U.state.address,this.setApprovedCaipNetworksData=e=>d.W.setApprovedCaipNetworksData(e),this.resetNetwork=e=>{d.W.resetNetwork(e)},this.addConnector=e=>{u.a.addConnector(e)},this.resetWcConnection=()=>{p.x.resetWcConnection()},this.setAddressExplorerUrl=(e,t)=>{l.U.setAddressExplorerUrl(e,t)},this.setSmartAccountDeployed=(e,t)=>{l.U.setSmartAccountDeployed(e,t)},this.setSmartAccountEnabledNetworks=(e,t)=>{d.W.setSmartAccountEnabledNetworks(e,t)},this.setPreferredAccountType=(e,t)=>{l.U.setPreferredAccountType(e,t)},this.setEIP6963Enabled=e=>{w.H.setEIP6963Enabled(e)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,t){const s=e?.map(e=>e.namespace).filter(e=>Boolean(e));if(s?.length)return[...new Set(s)];const i=t?.map(e=>e.chainNamespace);return[...new Set(i)]}async initialize(e){this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),await this.syncExistingConnection(),this.remoteFeatures=await B.x.fetchRemoteFeatures(e),w.H.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&h.aG.setOnrampProviders(this.remoteFeatures.onramp),(w.H.state.remoteFeatures?.email||Array.isArray(w.H.state.remoteFeatures?.socials)&&w.H.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){const e=await m.N.fetchAllowedOrigins();if(e&&_.w.isClient()){const t=window.location.origin;j.kl.isOriginAllowed(t,e,j.E1.DEFAULT_ALLOWED_ANCESTORS)||I.h.open(U.R.ALERT_ERRORS.INVALID_APP_CONFIGURATION,"error")}else I.h.open(U.R.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}sendInitializeEvent(e){const{...t}=e;delete t.adapters,delete t.universalProvider,v.E.sendEvent({type:"track",event:"INITIALIZE",properties:{...t,networks:e.networks.map(e=>e.id),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&f.W.setThemeMode(e.themeMode),e.themeVariables&&f.W.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");d.W.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&d.W.setActiveCaipNetwork(t)}initializeConnectionController(e){p.x.setWcBasic(e.basic??!1)}initializeConnectorController(){u.a.initialize(this.chainNamespaces)}initializeProjectSettings(e){w.H.setProjectId(e.projectId),w.H.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){w.H.setDebug(!1!==e.debug),w.H.setEnableWalletConnect(!1!==e.enableWalletConnect),w.H.setEnableWalletGuide(!1!==e.enableWalletGuide),w.H.setEnableWallets(!1!==e.enableWallets),w.H.setEIP6963Enabled(!1!==e.enableEIP6963),w.H.setEnableNetworkSwitch(!1!==e.enableNetworkSwitch),w.H.setEnableAuthLogger(!1!==e.enableAuthLogger),w.H.setCustomRpcUrls(e.customRpcUrls),w.H.setEnableEmbedded(e.enableEmbedded),w.H.setAllWallets(e.allWallets),w.H.setIncludeWalletIds(e.includeWalletIds),w.H.setExcludeWalletIds(e.excludeWalletIds),w.H.setFeaturedWalletIds(e.featuredWalletIds),w.H.setTokens(e.tokens),w.H.setTermsConditionsUrl(e.termsConditionsUrl),w.H.setPrivacyPolicyUrl(e.privacyPolicyUrl),w.H.setCustomWallets(e.customWallets),w.H.setFeatures(e.features),w.H.setAllowUnsupportedChain(e.allowUnsupportedChain),w.H.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),w.H.setPreferUniversalLinks(e.experimental_preferUniversalLinks),w.H.setDefaultAccountTypes(e.defaultAccountTypes);const t=S.i.getPreferredAccountTypes()||{},s={...w.H.state.defaultAccountTypes,...t};l.U.setPreferredAccountTypes(s);const i=this.getDefaultMetaData();if(!e.metadata&&i&&(e.metadata=i),w.H.setMetadata(e.metadata),w.H.setDisableAppend(e.disableAppend),w.H.setEnableEmbedded(e.enableEmbedded),w.H.setSIWX(e.siwx),!e.projectId)return void I.h.open(U.R.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");const r=e.adapters?.find(e=>e.namespace===n.o.CHAIN.EVM);if(r&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");w.H.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return _.w.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const t=this.getActiveChainNamespace();if(t){const s=L.R.getUnsupportedNetwork(`${t}:${e}`);d.W.setActiveCaipNetwork(s)}}getDefaultNetwork(){return L.R.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return L.R.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return L.R.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const t=e.networks.find(t=>t.id===e.defaultNetwork?.id);return t?L.R.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectNamespace(e){try{const t=this.getAdapter(e),s=W.A.getProvider(e),i=W.A.getProviderId(e),{caipAddress:r}=d.W.getAccountData(e)||{};this.setLoading(!0,e),r&&t?.disconnect&&await t.disconnect({provider:s,providerType:i}),S.i.removeConnectedNamespace(e),W.A.resetChain(e),this.setUser(void 0,e),this.setStatus("disconnected",e),this.setConnectedWalletInfo(void 0,e),u.a.removeConnectorId(e),d.W.resetAccount(e),d.W.resetNetwork(e),this.setLoading(!1,e)}catch(t){throw this.setLoading(!1,e),new Error(`Failed to disconnect chain ${e}: ${t.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const e=d.W.state.activeChain,t=this.getAdapter(e),s=this.getCaipNetwork(e)?.id;if(!t)throw new Error("Adapter not found");const i=await t.connectWalletConnect(s);this.close(),this.setClientId(i?.clientId||null),S.i.setConnectedNamespaces([...d.W.state.chains.keys()]),this.chainNamespaces.forEach(e=>{u.a.setConnectorId(R.o.CONNECTOR_TYPE_WALLET_CONNECT,e)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:t,type:s,provider:i,chain:r,caipNetwork:n,socialUri:o})=>{const a=d.W.state.activeChain,c=r||a,h=this.getAdapter(c);if(r&&r!==a&&!n){const e=this.getCaipNetworks().find(e=>e.chainNamespace===r);e&&this.setCaipNetwork(e)}if(!h)throw new Error("Adapter not found");const p=this.getCaipNetwork(c),u=await h.connect({id:e,info:t,type:s,provider:i,socialUri:o,chainId:n?.id||p?.id,rpcUrl:n?.rpcUrls?.default?.http?.[0]||p?.rpcUrls?.default?.http?.[0]});if(!u)return;S.i.addConnectedNamespace(c),this.syncProvider({...u,chainNamespace:c});const g=l.U.state.allAccounts,{accounts:m}=g?.length>0?{accounts:[...g]}:await h.getAccounts({namespace:c,id:e});this.setAllAccounts(m,c),this.setStatus("connected",c),this.syncConnectedWalletInfo(c)},reconnectExternal:async({id:e,info:t,type:s,provider:i})=>{const r=d.W.state.activeChain,n=this.getAdapter(r);n?.reconnect&&(await(n?.reconnect({id:e,info:t,type:s,provider:i,chainId:this.getCaipNetwork()?.id})),S.i.addConnectedNamespace(r),this.syncConnectedWalletInfo(r))},disconnect:async e=>{const t=(0,T.g)(e);try{const s=await Promise.allSettled(t.map(async([e])=>this.disconnectNamespace(e)));E.R.resetSend(),p.x.resetWcConnection(),await P.U.clearSessions(),u.a.setFilterByNamespace(void 0);const i=s.filter(e=>"rejected"===e.status);if(i.length>0)throw new Error(i.map(e=>e.reason.message).join(", "));S.i.deleteConnectedSocialProvider(),v.E.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:e||"all"}})}catch(e){throw new Error(`Failed to disconnect chains: ${e.message}`)}},checkInstalled:e=>e?e.some(e=>Boolean(window.ethereum?.[String(e)])):Boolean(window.ethereum),signMessage:async e=>{const t=this.getAdapter(d.W.state.activeChain),s=await(t?.signMessage({message:e,address:l.U.state.address,provider:W.A.getProvider(d.W.state.activeChain)}));return s?.signature||""},sendTransaction:async e=>{const t=e.chainNamespace;if(A.oU.SEND_SUPPORTED_NAMESPACES.includes(t)){const s=this.getAdapter(d.W.state.activeChain),i=W.A.getProvider(t),r=await(s?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}));return r?.hash||""}return""},estimateGas:async e=>{if(e.chainNamespace===n.o.CHAIN.EVM){const t=this.getAdapter(d.W.state.activeChain),s=W.A.getProvider(d.W.state.activeChain),i=this.getCaipNetwork();if(!i)throw new Error("CaipNetwork is undefined");const r=await(t?.estimateGas({...e,provider:s,caipNetwork:i}));return r?.gas||0n}return 0n},getEnsAvatar:async()=>(await this.syncIdentity({address:l.U.state.address,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:d.W.state.activeChain}),l.U.state.profileImage||!1),getEnsAddress:async e=>await j.kl.resolveReownName(e),writeContract:async e=>{const t=this.getAdapter(d.W.state.activeChain),s=this.getCaipNetwork(),i=this.getCaipAddress(),r=W.A.getProvider(d.W.state.activeChain);if(!s||!i)throw new Error("CaipNetwork or CaipAddress is undefined");const n=await(t?.writeContract({...e,caipNetwork:s,provider:r,caipAddress:i}));return n?.hash},parseUnits:(e,t)=>{const s=this.getAdapter(d.W.state.activeChain);return s?.parseUnits({value:e,decimals:t})??0n},formatUnits:(e,t)=>{const s=this.getAdapter(d.W.state.activeChain);return s?.formatUnits({value:e,decimals:t})??"0"},getCapabilities:async e=>{const t=this.getAdapter(d.W.state.activeChain);return await(t?.getCapabilities(e))},grantPermissions:async e=>{const t=this.getAdapter(d.W.state.activeChain);return await(t?.grantPermissions(e))},revokePermissions:async e=>{const t=this.getAdapter(d.W.state.activeChain);return t?.revokePermissions?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>{const t=this.getAdapter(d.W.state.activeChain);return await(t?.walletGetAssets(e))??{}},updateBalance:e=>{const t=this.getCaipNetwork(e);t&&l.U.state.address&&this.updateNativeBalance(l.U.state.address,t?.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},p.x.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){if(W.A.getProviderId(d.W.state.activeChain)===R.o.CONNECTOR_TYPE_WALLET_CONNECT){const e=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:"MetaMask Wallet"===this.universalProvider?.session?.peer?.metadata.name,approvedCaipNetworkIds:this.getChainsFromNamespaces(e)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const t=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const s=W.A.getProvider(t),i=W.A.getProviderId(t);if(e.chainNamespace===d.W.state.activeChain){const r=this.getAdapter(t);await(r?.switchNetwork({caipNetwork:e,provider:s,providerType:i}))}else if(this.setCaipNetwork(e),i===R.o.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const s=this.getAddressByChainNamespace(t);s&&this.syncAccount({address:s,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(e=>{const t=e.chains||[],s=e.accounts.map(e=>{const{chainId:t,chainNamespace:s}=o.C.parseCaipAddress(e);return`${s}:${t}`});return Array.from(new Set([...t,...s]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((t,s)=>{const i=e?.find(e=>e.namespace===s);return i?(i.construct({namespace:s,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),t[s]=i):t[s]=new M.n({namespace:s,networks:this.getCaipNetworks()}),t},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e),await(this.chainAdapters?.[e].syncConnectors(this.options,this)),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){const t=this.getAdapter(e);t?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const t=this.getAdapter(e);if(!t)return;const s=S.i.getConnectionStatus();"connected"===s?this.setStatus("connecting",e):"disconnected"===s?(S.i.clearAddressCache(),this.setStatus(s,e)):this.setStatus(s,e),t.on("switchNetwork",({address:t,chainId:s})=>{const i=this.getCaipNetworks().find(e=>e.id===s||e.caipNetworkId===s),r=d.W.state.activeChain===e,n=d.W.getAccountProp("address",e);if(i){const s=r&&t?t:n;s&&this.syncAccount({address:s,chainId:i.id,chainNamespace:e})}else this.setUnsupportedNetwork(s)}),t.on("disconnect",this.disconnect.bind(this,e)),t.on("connections",t=>{this.setConnections(t,e)}),t.on("pendingTransactions",()=>{const e=l.U.state.address,t=d.W.state.activeCaipNetwork;e&&t?.id&&this.updateNativeBalance(e,t.id,t.chainNamespace)}),t.on("accountChanged",({address:t,chainId:s})=>{const i=d.W.state.activeChain===e;i&&s?this.syncAccount({address:t,chainId:s,chainNamespace:e}):i&&d.W.state.activeCaipNetwork?.id?this.syncAccount({address:t,chainId:d.W.state.activeCaipNetwork?.id,chainNamespace:e}):this.syncAccountInfo(t,s,e),this.syncAllAccounts(e)})}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{e===n.o.CHAIN.EVM&&_.w.isSafeApp()&&u.a.setConnectorId(n.o.CONNECTOR_ID.SAFE,e);const t=u.a.getConnectorId(e);switch(this.setStatus("connecting",e),t){case n.o.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case n.o.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(t){console.warn("AppKit couldn't sync existing connection",t),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){const t=this.getAdapter(e),s=u.a.getConnectorId(e),i=this.getCaipNetwork(e),r=u.a.getConnectors(e).find(e=>e.id===s);try{if(!t||!r)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!i?.id)throw new Error("CaipNetwork not found");const s=await(t?.syncConnection({namespace:e,id:r.id,chainId:i.id,rpcUrl:i?.rpcUrls?.default?.http?.[0]}));if(s){const i=await(t?.getAccounts({namespace:e,id:r.id}));i&&i.accounts.length>0?this.setAllAccounts(i.accounts,e):this.setAllAccounts([_.w.createAccount(e,s.address,"eoa")],e),this.syncProvider({...s,chainNamespace:e}),await this.syncAccount({...s,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch(t){this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async e=>{const t=this.getAdapter(e),s=this.universalProvider?.session?.namespaces?.[e]?.accounts||[],i=d.W.state.activeCaipNetwork?.id,r=s.find(e=>{const{chainId:t}=o.C.parseCaipAddress(e);return t===i?.toString()})||s[0];if(r){const s=o.C.validateCaipAddress(r),{chainId:i,address:a}=o.C.parseCaipAddress(s);if(W.A.setProviderId(e,R.o.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&d.W.state.activeCaipNetwork&&t?.namespace!==n.o.CHAIN.EVM){const s=t?.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:d.W.state.activeCaipNetwork});W.A.setProvider(e,s)}else W.A.setProvider(e,this.universalProvider);u.a.setConnectorId(n.o.CONNECTOR_ID.WALLET_CONNECT,e),S.i.addConnectedNamespace(e),this.syncWalletConnectAccounts(e),await this.syncAccount({address:a,chainId:i,chainNamespace:e})}else this.setStatus("disconnected",e);this.syncConnectedWalletInfo(e),await d.W.setApprovedCaipNetworksData(e)});await Promise.all(e)}syncWalletConnectAccounts(e){const t=this.universalProvider?.session?.namespaces?.[e]?.accounts?.map(e=>{const{address:t}=o.C.parseCaipAddress(e);return t}).filter((e,t,s)=>s.indexOf(e)===t);t&&this.setAllAccounts(t.map(t=>_.w.createAccount(e,t,"bip122"===e?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:s,chainNamespace:i}){W.A.setProviderId(i,e),W.A.setProvider(i,t),u.a.setConnectorId(s,i)}async syncAllAccounts(e){const t=u.a.getConnectorId(e);if(!t)return;const s=this.getAdapter(e),i=await(s?.getAccounts({namespace:e,id:t}));i&&i.accounts.length>0&&this.setAllAccounts(i.accounts,e)}async syncAccount(e){const t=e.chainNamespace===d.W.state.activeChain,s=d.W.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:i,chainId:r,chainNamespace:a}=e,{chainId:c}=S.i.getActiveNetworkProps(),h=r||c,p=d.W.state.activeCaipNetwork?.name===n.o.UNSUPPORTED_NETWORK_NAME,u=d.W.getNetworkProp("supportsAllNetworks",a);if(this.setStatus("connected",a),(!p||u)&&h){let e=this.getCaipNetworks().find(e=>e.id.toString()===h.toString()),r=this.getCaipNetworks().find(e=>e.chainNamespace===a);if(!u&&!e&&!r){const t=this.getApprovedCaipNetworkIds()||[],s=t.find(e=>o.C.parseCaipNetworkId(e)?.chainId===h.toString()),i=t.find(e=>o.C.parseCaipNetworkId(e)?.chainNamespace===a);e=this.getCaipNetworks().find(e=>e.caipNetworkId===s),r=this.getCaipNetworks().find(e=>e.caipNetworkId===i||"deprecatedCaipNetworkId"in e&&e.deprecatedCaipNetworkId===i)}const c=e||r;c?.chainNamespace===d.W.state.activeChain?w.H.state.enableNetworkSwitch&&!w.H.state.allowUnsupportedChain&&d.W.state.activeCaipNetwork?.name===n.o.UNSUPPORTED_NETWORK_NAME?d.W.showUnsupportedChainUI():this.setCaipNetwork(c):t||s&&this.setCaipNetworkOfNamespace(s,a),this.syncConnectedWalletInfo(a),x.y.isLowerCaseMatch(i,l.U.state.address)||this.syncAccountInfo(i,c?.id,a),t?await this.syncBalance({address:i,chainId:c?.id,chainNamespace:a}):await this.syncBalance({address:i,chainId:s?.id,chainNamespace:a})}}async syncAccountInfo(e,t,s){const i=this.getCaipAddress(s),r=t||i?.split(":")[1];if(!r)return;const n=`${s}:${r}:${e}`;this.setCaipAddress(n,s),await this.syncIdentity({address:e,chainId:r,chainNamespace:s})}async syncReownName(e,t){try{const s=await this.getReownName(e);if(s[0]){const e=s[0];this.setProfileName(e.name,t)}else this.setProfileName(null,t)}catch{this.setProfileName(null,t)}}syncConnectedWalletInfo(e){const t=u.a.getConnectorId(e),s=W.A.getProviderId(e);if(s===R.o.CONNECTOR_TYPE_ANNOUNCED||s===R.o.CONNECTOR_TYPE_INJECTED){if(t){const s=this.getConnectors().find(e=>e.id===t);if(s){const{info:t,name:i,imageUrl:r}=s,n=r||this.getConnectorImage(s);this.setConnectedWalletInfo({name:i,icon:n,...t},e)}}}else if(s===R.o.CONNECTOR_TYPE_WALLET_CONNECT){const t=W.A.getProvider(e);t?.session&&this.setConnectedWalletInfo({...t.session.peer.metadata,name:t.session.peer.metadata.name,icon:t.session.peer.metadata.icons?.[0]},e)}else if(t&&t===n.o.CONNECTOR_ID.COINBASE){const t=this.getConnectors().find(e=>e.id===n.o.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(t)},e)}}async syncBalance(e){r.L.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(t=>t.id.toString()===e.chainId?.toString())&&e.chainId&&await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,t,s){const i=this.getAdapter(s),r=d.W.getCaipNetworkByNamespace(s,t);if(i){const n=await i.getBalance({address:e,chainId:t,caipNetwork:r,tokens:this.options.tokens});return this.setBalance(n.balance,n.symbol,s),n}}async initializeUniversalAdapter(){const e=D.r.createLogger((e,...t)=>{e&&this.handleAlertError(e),console.error(...t)}),t={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};w.H.setManualWCControl(Boolean(this.options?.manualWCControl)),this.universalProvider=this.options.universalProvider??await i.A.init(t),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{p.x.setUri(e)}),this.universalProvider.on("connect",p.x.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),p.x.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{const t=this.getCaipNetworks().find(t=>t.id==e),s=this.getCaipNetwork();t?s?.id!==t?.id&&this.setCaipNetwork(t):this.setUnsupportedNetwork(e)}),this.universalProvider.on("session_event",e=>{if(j.kl.isSessionEventData(e)){const{name:t,data:s}=e.params.event;"accountsChanged"===t&&Array.isArray(s)&&_.w.isCaipAddress(s[0])&&this.syncAccount(o.C.parseCaipAddress(s[0]))}}))}createUniversalProvider(){return!this.universalProviderInitPromise&&_.w.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){v.E.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const t=Object.entries(U.R.UniversalProviderErrors).find(([,{message:t}])=>e.message.includes(t)),[s,i]=t??[],{message:r,alertErrorKey:n}=i??{};if(s&&r&&!this.reportedAlertErrors[s]){const e=U.R.ALERT_ERRORS[n];e&&(I.h.open(e,"error"),this.reportedAlertErrors[s]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const t=e.namespace;if(!t)return;this.createClients();const s=e;s.namespace=t,s.construct({namespace:t,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),this.chainNamespaces.includes(t)||this.chainNamespaces.push(t),this.chainAdapters&&(this.chainAdapters[t]=s)}async open(e){return await this.injectModalUi(),e?.uri&&p.x.setUri(e.uri),e?.arguments&&"Swap"===e?.view?a.W.open({...e,data:{swap:e.arguments}}):a.W.open(e)}async close(){await this.injectModalUi(),a.W.close()}setLoading(e,t){a.W.setLoading(e,t)}async disconnect(e){await p.x.disconnect(e)}getSIWX(){return w.H.state.siwx}getError(){return""}getChainId(){return d.W.state.activeCaipNetwork?.id}async switchNetwork(e){const t=this.getCaipNetworks().find(t=>t.id===e.id);t?await d.W.switchActiveNetwork(t):I.h.open(U.R.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error")}getWalletProvider(){return d.W.state.activeChain?W.A.state.providers[d.W.state.activeChain]:null}getWalletProviderType(){return W.A.getProviderId(d.W.state.activeChain)}subscribeProviders(e){return W.A.subscribeProviders(e)}getThemeMode(){return f.W.state.themeMode}getThemeVariables(){return f.W.state.themeVariables}setThemeMode(e){f.W.setThemeMode(e),(0,k.JX)(f.W.state.themeMode)}setTermsConditionsUrl(e){w.H.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){w.H.setPrivacyPolicyUrl(e)}setThemeVariables(e){f.W.setThemeVariables(e),(0,k.ds)(f.W.state.themeVariables)}subscribeTheme(e){return f.W.subscribe(e)}getWalletInfo(){return l.U.state.connectedWalletInfo}getAccount(e){const t=u.a.getAuthConnector(e),s=d.W.getAccountData(e),i=d.W.state.activeChain,r=S.i.getConnectedConnectorId(e||i);if(s)return{allAccounts:s.allAccounts,caipAddress:s.caipAddress,address:_.w.getPlainAddress(s.caipAddress),isConnected:Boolean(s.caipAddress),status:s.status,embeddedWalletInfo:t&&r===n.o.CONNECTOR_ID.AUTH?{user:s.user?{...s.user,username:S.i.getConnectedSocialUsername()}:void 0,authProvider:s.socialProvider||"email",accountType:s.preferredAccountTypes?.[e||i],isSmartAccountDeployed:Boolean(s.smartAccountDeployed)}:void 0}}subscribeAccount(e,t){const s=()=>{const s=this.getAccount(t);s&&e(s)};t?d.W.subscribeChainProp("accountState",s,t):d.W.subscribe(s),u.a.subscribe(s)}subscribeNetwork(e){return d.W.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t?.id,caipNetworkId:t?.caipNetworkId})})}subscribeWalletInfo(e){return l.U.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){l.U.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){d.W.subscribeKey("activeCaipNetwork",e)}getState(){return b.z.state}subscribeState(e){return b.z.subscribe(e)}showErrorMessage(e){g.P.showError(e)}showSuccessMessage(e){g.P.showSuccess(e)}getEvent(){return{...v.E.state}}subscribeEvents(e){return v.E.subscribe(e)}replace(e){c.I.replace(e)}redirect(e){c.I.push(e)}popTransactionStack(e){c.I.popTransactionStack(e)}isOpen(){return a.W.state.open}isTransactionStackEmpty(){return 0===c.I.state.transactionStack.length}static getInstance(){return this.instance}updateFeatures(e){w.H.setFeatures(e)}updateRemoteFeatures(e){w.H.setRemoteFeatures(e)}updateOptions(e){const t={...w.H.state||{},...e};w.H.setOptions(t)}setConnectMethodsOrder(e){w.H.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){w.H.setWalletFeaturesOrder(e)}setCollapseWallets(e){w.H.setCollapseWallets(e)}setSocialsOrder(e){w.H.setSocialsOrder(e)}getConnectMethodsOrder(){return O.Aj.getConnectOrderMethod(w.H.state.features,u.a.getConnectors())}addNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const s=this.extendCaipNetwork(t,this.options);this.getCaipNetworks().find(e=>e.id===s.id)||d.W.addNetwork(s)}removeNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(e=>e.id===t)&&d.W.removeNetwork(e,t)}}},20602:(e,t,s)=>{s.d(t,{R:()=>i});const i={EmbeddedWalletAbortController:new AbortController,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"INVALID_APP_CONFIGURATION"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{shortMessage:"Network Not Found",longMessage:"Network not found - please make sure it is included in 'networks' array in createAppKit function"},INVALID_APP_CONFIGURATION:{shortMessage:"Invalid App Configuration",longMessage:()=>`Origin ${"undefined"!=typeof window?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},IFRAME_LOAD_FAILED:{shortMessage:"Network Error - Could not load embedded wallet",longMessage:()=>"There was an issue loading the embedded wallet. Please try again later."},IFRAME_REQUEST_TIMEOUT:{shortMessage:"Embedded Wallet Request Timed Out",longMessage:()=>"There was an issue doing the request to the embedded wallet. Please try again later."},UNVERIFIED_DOMAIN:{shortMessage:"Invalid App Configuration",longMessage:()=>"There was an issue loading the embedded wallet. Please verify that your domain is allowed at cloud.reown.com"},JWT_TOKEN_NOT_VALID:{shortMessage:"Session Expired",longMessage:"Invalid session found on UniversalProvider - please check your time settings and connect again"},INVALID_PROJECT_ID:{shortMessage:"Invalid App Configuration",longMessage:"Invalid Project ID - update configuration"},PROJECT_ID_NOT_CONFIGURED:{shortMessage:"Project ID Not Configured",longMessage:"Project ID Not Configured - update configuration on cloud.reown.com"}}}},22129:(e,t,s)=>{s.d(t,{F:()=>l}),s(18338);var i=s(72269),r=s(98299),n=s(1420),o=s(36507),a=s(82868),c=s(25598);class l{constructor({provider:e,namespace:t}){this.id=i.o.CONNECTOR_ID.WALLET_CONNECT,this.name=a.L.ConnectorNamesMap[i.o.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=a.L.ConnectorImageIds[i.o.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=r.W.getCaipNetworks.bind(r.W),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=t}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const e=this.getCaipNetworks(),t=n.H.state.universalProviderConfigOverride,s=c.kl.createNamespaces(e,t);await this.provider.connect({optionalNamespaces:s})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(e=>e.caipNetworkId);return o.U.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:d})}}const d=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"]},22143:(e,t,s)=>{s.d(t,{w:()=>o});var i=s(72269),r=s(3555),n=s(11847);const o={isMobile(){return!!this.isClient()&&Boolean("function"==typeof window?.matchMedia&&window?.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent))},checkCaipNetwork:(e,t="")=>e?.caipNetworkId.toLocaleLowerCase().includes(t.toLowerCase()),isAndroid(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return o.isMobile()&&e.includes("android")},isIos(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")},isSafari(){if(!this.isClient())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("safari")},isClient:()=>"undefined"!=typeof window,isPairingExpired:e=>!e||e-Date.now()<=r.oU.TEN_SEC_MS,isAllowedRetry:(e,t=r.oU.ONE_SEC_MS)=>Date.now()-e>=t,copyToClopboard(e){navigator.clipboard.writeText(e)},isIframe(){try{return window?.self!==window?.top}catch(e){return!1}},isSafeApp(){if(o.isClient()&&window.self!==window.top)try{const e=window?.location?.ancestorOrigins?.[0],t="https://app.safe.global";if(e){const s=new URL(e),i=new URL(t);return s.hostname===i.hostname}}catch{return!1}return!1},getPairingExpiry:()=>Date.now()+r.oU.FOUR_MINUTES_MS,getNetworkId:e=>e?.split(":")[1],getPlainAddress:e=>e?.split(":")[2],wait:async e=>new Promise(t=>{setTimeout(t,e)}),debounce(e,t=500){let s;return(...i)=>{s&&clearTimeout(s),s=setTimeout(function(){e(...i)},t)}},isHttpUrl:e=>e.startsWith("http://")||e.startsWith("https://"),formatNativeUrl(e,t,s=null){if(o.isHttpUrl(e))return this.formatUniversalUrl(e,t);let i=e,r=s;i.includes("://")||(i=e.replaceAll("/","").replaceAll(":",""),i=`${i}://`),i.endsWith("/")||(i=`${i}/`),r&&!r?.endsWith("/")&&(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));const n=encodeURIComponent(t);return{redirect:`${i}wc?uri=${n}`,redirectUniversalLink:r?`${r}wc?uri=${n}`:void 0,href:i}},formatUniversalUrl(e,t){if(!o.isHttpUrl(e))return this.formatNativeUrl(e,t);let s=e;return s.endsWith("/")||(s=`${s}/`),{redirect:`${s}wc?uri=${encodeURIComponent(t)}`,href:s}},getOpenTargetForPlatform(e){return"popupWindow"===e?e:this.isTelegram()?n.i.getTelegramSocialProvider()?"_top":"_blank":e},openHref(e,t,s){window?.open(e,this.getOpenTargetForPlatform(t),s||"noreferrer noopener")},returnOpenHref(e,t,s){return window?.open(e,this.getOpenTargetForPlatform(t),s||"noreferrer noopener")},isTelegram:()=>"undefined"!=typeof window&&(Boolean(window.TelegramWebviewProxy)||Boolean(window.Telegram)||Boolean(window.TelegramWebviewProxyProto)),isPWA(){if("undefined"==typeof window)return!1;const e=window.matchMedia?.("(display-mode: standalone)")?.matches,t=window?.navigator?.standalone;return Boolean(e||t)},async preloadImage(e){const t=new Promise((t,s)=>{const i=new Image;i.onload=t,i.onerror=s,i.crossOrigin="anonymous",i.src=e});return Promise.race([t,o.wait(2e3)])},formatBalance(e,t){let s="0.000";if("string"==typeof e){const t=Number(e);if(t){const e=Math.floor(1e3*t)/1e3;e&&(s=e.toString())}}return`${s}${t?` ${t}`:""}`},formatBalance2(e,t){let s;if("0"===e)s="0";else if("string"==typeof e){const t=Number(e);t&&(s=t.toString().match(/^-?\d+(?:\.\d{0,3})?/u)?.[0])}return{value:s??"0",rest:"0"===s?"000":"",symbol:t}},getApiUrl:()=>i.o.W3M_API_URL,getBlockchainApiUrl:()=>i.o.BLOCKCHAIN_API_RPC_URL,getAnalyticsUrl:()=>i.o.PULSE_API_URL,getUUID:()=>crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),parseError:e=>"string"==typeof e?e:"string"==typeof e?.issues?.[0]?.message?e.issues[0].message:e instanceof Error?e.message:"Unknown error",sortRequestedNetworks(e,t=[]){const s={};return t&&e&&(e.forEach((e,t)=>{s[e]=t}),t.sort((e,t)=>{const i=s[e.id],r=s[t.id];return void 0!==i&&void 0!==r?i-r:void 0!==i?-1:void 0!==r?1:0})),t},calculateBalance(e){let t=0;for(const s of e)t+=s.value??0;return t},formatTokenBalance(e){const t=e.toFixed(2),[s,i]=t.split(".");return{dollars:s,pennies:i}},isAddress(e,t="eip155"){switch(t){case"eip155":return!(!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)||!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)&&!/^(?:0x)?[0-9A-F]{40}$/iu.test(e));case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(e);default:return!1}},uniqueBy(e,t){const s=new Set;return e.filter(e=>{const i=e[t];return!s.has(i)&&(s.add(i),!0)})},generateSdkVersion:(e,t,s)=>`${t}-${0===e.length?r.oU.ADAPTER_TYPES.UNIVERSAL:e.map(e=>e.adapterType).join(",")}-${s}`,createAccount:(e,t,s,i,r)=>({namespace:e,address:t,type:s,publicKey:i,path:r}),isCaipAddress(e){if("string"!=typeof e)return!1;const t=e.split(":"),s=t[0];return 3===t.filter(Boolean).length&&s in i.o.CHAIN_NAME_MAP},isMac(){const e=window?.navigator.userAgent.toLowerCase();return e.includes("macintosh")&&!e.includes("safari")},formatTelegramSocialLoginUrl(e){const t=`--${encodeURIComponent(window?.location.href)}`,s="state=";if("auth.magic.link"===new URL(e).host){const i="provider_authorization_url=",r=e.substring(e.indexOf(i)+i.length),n=this.injectIntoUrl(decodeURIComponent(r),s,t);return e.replace(r,encodeURIComponent(n))}return this.injectIntoUrl(e,s,t)},injectIntoUrl(e,t,s){const i=e.indexOf(t);if(-1===i)throw new Error(`${t} parameter not found in the URL: ${e}`);const r=e.indexOf("&",i),n=t.length,o=-1!==r?r:e.length;return e.substring(0,i+n)+(e.substring(i+n,o)+s)+e.substring(r)}}},23981:(e,t,s)=>{s.d(t,{U:()=>p});var i=s(89168),r=s(3555),n=s(22143),o=s(37834),a=s(16444),c=s(98299),l=s(92492);const d=(0,i.BX)({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),h={state:d,replaceState(e){e&&Object.assign(d,(0,i.KR)(e))},subscribe:e=>c.W.subscribeChainProp("accountState",t=>{if(t)return e(t)}),subscribeKey(e,t,s){let i;return c.W.subscribeChainProp("accountState",s=>{if(s){const r=s[e];i!==r&&(i=r,t(r))}},s)},setStatus(e,t){c.W.setAccountProp("status",e,t)},getCaipAddress:e=>c.W.getAccountProp("caipAddress",e),setCaipAddress(e,t){const s=e?n.w.getPlainAddress(e):void 0;t===c.W.state.activeChain&&(c.W.state.activeCaipAddress=e),c.W.setAccountProp("caipAddress",e,t),c.W.setAccountProp("address",s,t)},setBalance(e,t,s){c.W.setAccountProp("balance",e,s),c.W.setAccountProp("balanceSymbol",t,s)},setProfileName(e,t){c.W.setAccountProp("profileName",e,t)},setProfileImage(e,t){c.W.setAccountProp("profileImage",e,t)},setUser(e,t){c.W.setAccountProp("user",e,t)},setAddressExplorerUrl(e,t){c.W.setAccountProp("addressExplorerUrl",e,t)},setSmartAccountDeployed(e,t){c.W.setAccountProp("smartAccountDeployed",e,t)},setCurrentTab(e){c.W.setAccountProp("currentTab",e,c.W.state.activeChain)},setTokenBalance(e,t){e&&c.W.setAccountProp("tokenBalance",e,t)},setShouldUpdateToAddress(e,t){c.W.setAccountProp("shouldUpdateToAddress",e,t)},setAllAccounts(e,t){c.W.setAccountProp("allAccounts",e,t)},addAddressLabel(e,t,s){const i=c.W.getAccountProp("addressLabels",s)||new Map;i.set(e,t),c.W.setAccountProp("addressLabels",i,s)},removeAddressLabel(e,t){const s=c.W.getAccountProp("addressLabels",t)||new Map;s.delete(e),c.W.setAccountProp("addressLabels",s,t)},setConnectedWalletInfo(e,t){c.W.setAccountProp("connectedWalletInfo",e,t,!1)},setPreferredAccountType(e,t){c.W.setAccountProp("preferredAccountTypes",{...d.preferredAccountTypes,[t]:e},t)},setPreferredAccountTypes(e){d.preferredAccountTypes=e},setSocialProvider(e,t){e&&c.W.setAccountProp("socialProvider",e,t)},setSocialWindow(e,t){c.W.setAccountProp("socialWindow",e?(0,i.KR)(e):void 0,t)},setFarcasterUrl(e,t){c.W.setAccountProp("farcasterUrl",e,t)},async fetchTokenBalance(e){d.balanceLoading=!0;const t=c.W.state.activeCaipNetwork?.caipNetworkId,s=c.W.state.activeCaipNetwork?.chainNamespace,i=c.W.state.activeCaipAddress,o=i?n.w.getPlainAddress(i):void 0;if(d.lastRetry&&!n.w.isAllowedRetry(d.lastRetry,30*r.oU.ONE_SEC_MS))return d.balanceLoading=!1,[];try{if(o&&t&&s){const e=(await a.T.getBalance(o,t)).balances.filter(e=>"0"!==e.quantity.decimals);return p.setTokenBalance(e,s),d.lastRetry=void 0,d.balanceLoading=!1,e}}catch(t){d.lastRetry=Date.now(),e?.(t),l.P.showError("Token Balance Unavailable")}finally{d.balanceLoading=!1}return[]},resetAccount(e){c.W.resetAccount(e)}},p=(0,o.X)(h)},25598:(e,t,s)=>{s.d(t,{E1:()=>i.E,kl:()=>r.k});var i=s(1435),r=s(61387)},27811:(e,t,s)=>{s.d(t,{Ay:()=>K});var i=s(90169),r=s(70255),n=s(18898),o=s(91315),a=s(15529),c=s(50046),l=s.n(c),d=s(14350);const h="client",p=`wc@2:${h}:`,u=h,g="WALLETCONNECT_DEEPLINK_CHOICE",m="Proposal expired",f=o.SEVEN_DAYS,w={wc_sessionPropose:{req:{ttl:o.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:o.ONE_DAY,prompt:!1,tag:1104},res:{ttl:o.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:o.ONE_DAY,prompt:!1,tag:1106},res:{ttl:o.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:o.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:o.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:o.ONE_DAY,prompt:!1,tag:1112},res:{ttl:o.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:o.ONE_DAY,prompt:!1,tag:1114},res:{ttl:o.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:o.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:o.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1119}}},y={min:o.FIVE_MINUTES,max:o.SEVEN_DAYS},b="IDLE",v="ACTIVE",E={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},C=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],I="wc@1.5:auth:",N=`${I}:PUB_KEY`;var A=Object.defineProperty,_=Object.defineProperties,S=Object.getOwnPropertyDescriptors,P=Object.getOwnPropertySymbols,T=Object.prototype.hasOwnProperty,O=Object.prototype.propertyIsEnumerable,k=(e,t,s)=>t in e?A(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,R=(e,t)=>{for(var s in t||(t={}))T.call(t,s)&&k(e,s,t[s]);if(P)for(var s of P(t))O.call(t,s)&&k(e,s,t[s]);return e},x=(e,t)=>_(e,S(t)),U=(e,t,s)=>k(e,"symbol"!=typeof t?t+"":t,s);class D extends n.yJ{constructor(e){super(e),U(this,"name","engine"),U(this,"events",new(l())),U(this,"initialized",!1),U(this,"requestQueue",{state:b,queue:[]}),U(this,"sessionRequestQueue",{state:b,queue:[]}),U(this,"requestQueueDelay",o.ONE_SECOND),U(this,"expectedPairingMethodMap",new Map),U(this,"recentlyDeletedMap",new Map),U(this,"recentlyDeletedLimit",200),U(this,"relayMessageCache",[]),U(this,"pendingSessions",new Map),U(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(w)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,o.toMiliseconds)(this.requestQueueDelay)))}),U(this,"connect",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t=x(R({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(t),t.optionalNamespaces=(0,a.XEe)(t.requiredNamespaces,t.optionalNamespaces),t.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:c,scopedProperties:l,relays:h}=t;let p,u=s,g=!1;try{if(u){const e=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),g=e.active}}catch(e){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),e}if(!u||!g){const{topic:e,uri:t}=await this.client.core.pairing.create();u=e,p=t}if(!u){const{message:e}=(0,a.GuA)("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(e)}const f=await this.client.core.crypto.generateKeyPair(),y=w.wc_sessionPropose.req.ttl||o.FIVE_MINUTES,b=(0,a.Xw0)(y),v=x(R(R({requiredNamespaces:r,optionalNamespaces:n,relays:h??[{protocol:i.sD}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:b,pairingTopic:u},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:(0,d.payloadId)()}),E=(0,a.hEn)("session_connect",v.id),{reject:C,resolve:I,done:N}=(0,a.Wx8)(y,m),A=({id:e})=>{e===v.id&&(this.client.events.off("proposal_expire",A),this.pendingSessions.delete(v.id),this.events.emit(E,{error:{message:m,code:0}}))};return this.client.events.on("proposal_expire",A),this.events.once(E,({error:e,session:t})=>{this.client.events.off("proposal_expire",A),e?C(e):t&&I(t)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:v,throwOnFailedPublish:!0,clientRpcId:v.id}),await this.setProposal(v.id,v),{uri:p,approval:N}}),U(this,"pair",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(e){throw this.client.logger.error("pair() failed"),e}}),U(this,"approve",async e=>{var t,s,r;const n=this.client.core.eventClient.createEvent({properties:{topic:null==(t=e?.id)?void 0:t.toString(),trace:[i.$I.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(e){throw n.setError(i.U.no_internet_connection),e}try{await this.isValidProposalId(e?.id)}catch(t){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),n.setError(i.U.proposal_not_found),t}try{await this.isValidApprove(e)}catch(e){throw this.client.logger.error("approve() -> isValidApprove() failed"),n.setError(i.U.session_approve_namespace_validation_failure),e}const{id:o,relayProtocol:c,namespaces:l,sessionProperties:d,scopedProperties:h,sessionConfig:p}=e,u=this.client.proposal.get(o);this.client.core.eventClient.deleteEvent({eventId:n.eventId});const{pairingTopic:g,proposer:m,requiredNamespaces:w,optionalNamespaces:y}=u;let b=null==(s=this.client.core.eventClient)?void 0:s.getEvent({topic:g});b||(b=null==(r=this.client.core.eventClient)?void 0:r.createEvent({type:i.$I.session_approve_started,properties:{topic:g,trace:[i.$I.session_approve_started,i.$I.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),E=m.publicKey,C=await this.client.core.crypto.generateSharedKey(v,E),I=R(R(R({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:(0,a.Xw0)(f)},d&&{sessionProperties:d}),h&&{scopedProperties:h}),p&&{sessionConfig:p}),N=i.cV.relay;b.addTrace(i.$I.subscribing_session_topic);try{await this.client.core.relayer.subscribe(C,{transportType:N})}catch(e){throw b.setError(i.U.subscribe_session_topic_failure),e}b.addTrace(i.$I.subscribe_session_topic_success);const A=x(R({},I),{topic:C,requiredNamespaces:w,optionalNamespaces:y,pairingTopic:g,acknowledged:!1,self:I.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:v,transportType:i.cV.relay});await this.client.session.set(C,A),b.addTrace(i.$I.store_session);try{b.addTrace(i.$I.publishing_session_settle),await this.sendRequest({topic:C,method:"wc_sessionSettle",params:I,throwOnFailedPublish:!0}).catch(e=>{throw b?.setError(i.U.session_settle_publish_failure),e}),b.addTrace(i.$I.session_settle_publish_success),b.addTrace(i.$I.publishing_session_approve),await this.sendResult({id:o,topic:g,result:{relay:{protocol:c??"irn"},responderPublicKey:v},throwOnFailedPublish:!0}).catch(e=>{throw b?.setError(i.U.session_approve_publish_failure),e}),b.addTrace(i.$I.session_approve_publish_success)}catch(e){throw this.client.logger.error(e),this.client.session.delete(C,(0,a.Hjj)("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(C),e}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:m.metadata}),await this.client.proposal.delete(o,(0,a.Hjj)("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(C,(0,a.Xw0)(f)),{topic:C,acknowledged:()=>Promise.resolve(this.client.session.get(C))}}),U(this,"reject",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(e){throw this.client.logger.error("reject() -> isValidReject() failed"),e}const{id:t,reason:s}=e;let i;try{i=this.client.proposal.get(t).pairingTopic}catch(e){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),e}i&&(await this.sendError({id:t,topic:i,error:s,rpcOpts:w.wc_sessionPropose.reject}),await this.client.proposal.delete(t,(0,a.Hjj)("USER_DISCONNECTED")))}),U(this,"update",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(e){throw this.client.logger.error("update() -> isValidUpdate() failed"),e}const{topic:t,namespaces:s}=e,{done:i,resolve:r,reject:n}=(0,a.Wx8)(),o=(0,d.payloadId)(),c=(0,d.getBigIntRpcId)().toString(),l=this.client.session.get(t).namespaces;return this.events.once((0,a.hEn)("session_update",o),({error:e})=>{e?n(e):r()}),await this.client.session.update(t,{namespaces:s}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:c}).catch(e=>{this.client.logger.error(e),this.client.session.update(t,{namespaces:l}),n(e)}),{acknowledged:i}}),U(this,"extend",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(e){throw this.client.logger.error("extend() -> isValidExtend() failed"),e}const{topic:t}=e,s=(0,d.payloadId)(),{done:i,resolve:r,reject:n}=(0,a.Wx8)();return this.events.once((0,a.hEn)("session_extend",s),({error:e})=>{e?n(e):r()}),await this.setExpiry(t,(0,a.Xw0)(f)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(e=>{n(e)}),{acknowledged:i}}),U(this,"request",async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(e){throw this.client.logger.error("request() -> isValidRequest() failed"),e}const{chainId:t,request:s,topic:r,expiry:n=w.wc_sessionRequest.req.ttl}=e,o=this.client.session.get(r);o?.transportType===i.cV.relay&&await this.confirmOnlineStateOrThrow();const c=(0,d.payloadId)(),l=(0,d.getBigIntRpcId)().toString(),{done:h,resolve:p,reject:u}=(0,a.Wx8)(n,"Request expired. Please try again.");this.events.once((0,a.hEn)("session_request",c),({error:e,result:t})=>{e?u(e):p(t)});const m="wc_sessionRequest",f=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:r,method:m,params:{request:x(R({},s),{expiryTimestamp:(0,a.Xw0)(n)}),chainId:t},expiry:n,throwOnFailedPublish:!0,appLink:f}).catch(e=>u(e)),this.client.events.emit("session_request_sent",{topic:r,request:s,chainId:t,id:c}),await h();const y={request:x(R({},s),{expiryTimestamp:(0,a.Xw0)(n)}),chainId:t},b=this.shouldSetTVF(m,y);return await Promise.all([new Promise(async e=>{await this.sendRequest(R({clientRpcId:c,relayRpcId:l,topic:r,method:m,params:y,expiry:n,throwOnFailedPublish:!0},b&&{tvf:this.getTVFParams(c,y)})).catch(e=>u(e)),this.client.events.emit("session_request_sent",{topic:r,request:s,chainId:t,id:c}),e()}),new Promise(async e=>{var t;if(null==(t=o.sessionConfig)||!t.disableDeepLink){const e=await(0,a.jTh)(this.client.core.storage,g);await(0,a.n3s)({id:c,topic:r,wcDeepLink:e})}e()}),h()]).then(e=>e[2])}),U(this,"respond",async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:s}=e,{id:r}=s,n=this.client.session.get(t);n.transportType===i.cV.relay&&await this.confirmOnlineStateOrThrow();const o=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);(0,d.isJsonRpcResult)(s)?await this.sendResult({id:r,topic:t,result:s.result,throwOnFailedPublish:!0,appLink:o}):(0,d.isJsonRpcError)(s)&&await this.sendError({id:r,topic:t,error:s.error,appLink:o}),this.cleanupAfterResponse(e)}),U(this,"ping",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(e){throw this.client.logger.error("ping() -> isValidPing() failed"),e}const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=(0,d.payloadId)(),s=(0,d.getBigIntRpcId)().toString(),{done:i,resolve:r,reject:n}=(0,a.Wx8)();this.events.once((0,a.hEn)("session_ping",e),({error:e})=>{e?n(e):r()}),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:e,relayRpcId:s}),i()])}else this.client.core.pairing.pairings.keys.includes(t)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:t}))}),U(this,"emit",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:s,chainId:i}=e,r=(0,d.getBigIntRpcId)().toString(),n=(0,d.payloadId)();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:r,clientRpcId:n})}),U(this,"disconnect",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:(0,a.Hjj)("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else{if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:e}=(0,a.GuA)("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(e)}await this.client.core.pairing.disconnect({topic:t})}}),U(this,"find",e=>(this.isInitialized(),this.client.session.getAll().filter(t=>(0,a.HNf)(t,e)))),U(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),U(this,"authenticate",async(e,t)=>{var s;this.isInitialized(),this.isValidAuthenticate(e);const r=t&&this.client.core.linkModeSupportedApps.includes(t)&&(null==(s=this.client.metadata.redirect)?void 0:s.linkMode),n=r?i.cV.link_mode:i.cV.relay;n===i.cV.relay&&await this.confirmOnlineStateOrThrow();const{chains:o,statement:c="",uri:l,domain:h,nonce:p,type:u,exp:g,nbf:m,methods:y=[],expiry:b}=e,v=[...e.resources||[]],{topic:E,uri:C}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:n});this.client.logger.info({message:"Generated new pairing",pairing:{topic:E,uri:C}});const I=await this.client.core.crypto.generateKeyPair(),A=(0,a.EN$)(I);if(await Promise.all([this.client.auth.authKeys.set(N,{responseTopic:A,publicKey:I}),this.client.auth.pairingTopics.set(A,{topic:A,pairingTopic:E})]),await this.client.core.relayer.subscribe(A,{transportType:n}),this.client.logger.info(`sending request to new pairing topic: ${E}`),y.length>0){const{namespace:e}=(0,a._Yb)(o[0]);let t=(0,a.e8_)(e,"request",y);(0,a.VBM)(v)&&(t=(0,a.hVC)(t,v.pop())),v.push(t)}const _=b&&b>w.wc_sessionAuthenticate.req.ttl?b:w.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:u??"caip122",chains:o,statement:c,aud:l,domain:h,version:"1",nonce:p,iat:(new Date).toISOString(),exp:g,nbf:m,resources:v},requester:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:(0,a.Xw0)(_)},P={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:o,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:E,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:(0,a.Xw0)(w.wc_sessionPropose.req.ttl),id:(0,d.payloadId)()},{done:T,resolve:O,reject:k}=(0,a.Wx8)(_,"Request expired"),U=(0,d.payloadId)(),D=(0,a.hEn)("session_connect",P.id),L=(0,a.hEn)("session_request",U),W=async({error:e,session:t})=>{this.events.off(L,M),e?k(e):t&&O({session:t})},M=async e=>{var s,r,o;if(await this.deletePendingAuthRequest(U,{message:"fulfilled",code:0}),e.error){const t=(0,a.Hjj)("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(D,W),k(e.error.message))}await this.deleteProposal(P.id),this.events.off(D,W);const{cacaos:c,responder:l}=e.result,d=[],h=[];for(const e of c){await(0,a.IjX)({cacao:e,projectId:this.client.core.projectId})||(this.client.logger.error(e,"Signature verification failed"),k((0,a.Hjj)("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:t}=e,s=(0,a.VBM)(t.resources),i=[(0,a.xkc)(t.iss)],r=(0,a.q_h)(t.iss);if(s){const e=(0,a.sc_)(s),t=(0,a.WWN)(s);d.push(...e),i.push(...t)}for(const e of i)h.push(`${e}:${r}`)}const p=await this.client.core.crypto.generateSharedKey(I,l.publicKey);let u;d.length>0&&(u={topic:p,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:l,controller:l.publicKey,expiry:(0,a.Xw0)(f),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:E,namespaces:(0,a.Van)([...new Set(d)],[...new Set(h)]),transportType:n},await this.client.core.relayer.subscribe(p,{transportType:n}),await this.client.session.set(p,u),E&&await this.client.core.pairing.updateMetadata({topic:E,metadata:l.metadata}),u=this.client.session.get(p)),null!=(s=this.client.metadata.redirect)&&s.linkMode&&null!=(r=l.metadata.redirect)&&r.linkMode&&null!=(o=l.metadata.redirect)&&o.universal&&t&&(this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.session.update(p,{transportType:i.cV.link_mode})),O({auths:c,session:u})};let B;this.events.once(D,W),this.events.once(L,M);try{if(r){const e=(0,d.formatJsonRpcRequest)("wc_sessionAuthenticate",S,U);this.client.core.history.set(E,e);const s=await this.client.core.crypto.encode("",e,{type:a.EHS,encoding:a.Pa8});B=(0,a.$Bq)(t,E,s)}else await Promise.all([this.sendRequest({topic:E,method:"wc_sessionAuthenticate",params:S,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:U}),this.sendRequest({topic:E,method:"wc_sessionPropose",params:P,expiry:w.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:P.id})])}catch(e){throw this.events.off(D,W),this.events.off(L,M),e}return await this.setProposal(P.id,P),await this.setAuthRequest(U,{request:x(R({},S),{verifyContext:{}}),pairingTopic:E,transportType:n}),{uri:B??C,response:T}}),U(this,"approveSessionAuthenticate",async e=>{const{id:t,auths:s}=e,r=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[i.U$.authenticated_session_approve_started]}});try{this.isInitialized()}catch(e){throw r.setError(i.Tn.no_internet_connection),e}const n=this.getPendingAuthRequest(t);if(!n)throw r.setError(i.Tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${t}`);const o=n.transportType||i.cV.relay;o===i.cV.relay&&await this.confirmOnlineStateOrThrow();const c=n.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=(0,a.EN$)(c),h={type:a.Lp_,receiverPublicKey:c,senderPublicKey:l},p=[],u=[];for(const e of s){if(!await(0,a.IjX)({cacao:e,projectId:this.client.core.projectId})){r.setError(i.Tn.invalid_cacao);const e=(0,a.Hjj)("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:d,error:e,encodeOpts:h}),new Error(e.message)}r.addTrace(i.U$.cacaos_verified);const{p:s}=e,n=(0,a.VBM)(s.resources),o=[(0,a.xkc)(s.iss)],c=(0,a.q_h)(s.iss);if(n){const e=(0,a.sc_)(n),t=(0,a.WWN)(n);p.push(...e),o.push(...t)}for(const e of o)u.push(`${e}:${c}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);let m;if(r.addTrace(i.U$.create_authenticated_session_topic),p?.length>0){m={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:n.requester.metadata},controller:c,expiry:(0,a.Xw0)(f),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:n.pairingTopic,namespaces:(0,a.Van)([...new Set(p)],[...new Set(u)]),transportType:o},r.addTrace(i.U$.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:o})}catch(e){throw r.setError(i.Tn.subscribe_authenticated_session_topic_failure),e}r.addTrace(i.U$.subscribe_authenticated_session_topic_success),await this.client.session.set(g,m),r.addTrace(i.U$.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:n.pairingTopic,metadata:n.requester.metadata})}r.addTrace(i.U$.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:t,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(n.requester.metadata,o)})}catch(e){throw r.setError(i.Tn.authenticated_session_approve_publish_failure),e}return await this.client.auth.requests.delete(t,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:n.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:r.eventId}),{session:m}}),U(this,"rejectSessionAuthenticate",async e=>{this.isInitialized();const{id:t,reason:s}=e,r=this.getPendingAuthRequest(t);if(!r)throw new Error(`Could not find pending auth request with id ${t}`);r.transportType===i.cV.relay&&await this.confirmOnlineStateOrThrow();const n=r.requester.publicKey,o=await this.client.core.crypto.generateKeyPair(),c=(0,a.EN$)(n),l={type:a.Lp_,receiverPublicKey:n,senderPublicKey:o};await this.sendError({id:t,topic:c,error:s,encodeOpts:l,rpcOpts:w.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(r.requester.metadata,r.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.client.proposal.delete(t,(0,a.Hjj)("USER_DISCONNECTED"))}),U(this,"formatAuthMessage",e=>{this.isInitialized();const{request:t,iss:s}=e;return(0,a.hwK)(t,s)}),U(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(0!==this.relayMessageCache.length)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}},50)}),U(this,"cleanupDuplicatePairings",async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(s=>{var i,r;return(null==(i=s.peerMetadata)?void 0:i.url)&&(null==(r=s.peerMetadata)?void 0:r.url)===e.peer.metadata.url&&s.topic&&s.topic!==t.topic});if(0===s.length)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(e=>this.client.core.pairing.disconnect({topic:e.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}}),U(this,"deleteSession",async e=>{var t;const{topic:s,expirerHasDeleted:i=!1,emitEvent:r=!0,id:n=0}=e,{self:o}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,(0,a.Hjj)("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(o.publicKey)&&await this.client.core.crypto.deleteKeyPair(o.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),i||this.client.core.expirer.del(s),this.client.core.storage.removeItem(g).catch(e=>this.client.logger.warn(e)),this.getPendingSessionRequests().forEach(e=>{e.topic===s&&this.deletePendingSessionRequest(e.id,(0,a.Hjj)("USER_DISCONNECTED"))}),s===(null==(t=this.sessionRequestQueue.queue[0])?void 0:t.topic)&&(this.sessionRequestQueue.state=b),r&&this.client.events.emit("session_delete",{id:n,topic:s})}),U(this,"deleteProposal",async(e,t)=>{if(t)try{const t=this.client.proposal.get(e),s=this.client.core.eventClient.getEvent({topic:t.pairingTopic});s?.setError(i.U.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(e,(0,a.Hjj)("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")}),U(this,"deletePendingSessionRequest",async(e,t,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(t=>t.id!==e),s&&(this.sessionRequestQueue.state=b,this.client.events.emit("session_request_expire",{id:e}))}),U(this,"deletePendingAuthRequest",async(e,t,s=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)])}),U(this,"setExpiry",async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))}),U(this,"setProposal",async(e,t)=>{this.client.core.expirer.set(e,(0,a.Xw0)(w.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)}),U(this,"setAuthRequest",async(e,t)=>{const{request:s,pairingTopic:r,transportType:n=i.cV.relay}=t;this.client.core.expirer.set(e,s.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:e,pairingTopic:r,verifyContext:s.verifyContext,transportType:n})}),U(this,"setPendingSessionRequest",async e=>{const{id:t,topic:s,params:i,verifyContext:r}=e,n=i.request.expiryTimestamp||(0,a.Xw0)(w.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,n),await this.client.pendingRequest.set(t,{id:t,topic:s,params:i,verifyContext:r})}),U(this,"sendRequest",async e=>{const{topic:t,method:i,params:r,expiry:n,relayRpcId:o,clientRpcId:c,throwOnFailedPublish:l,appLink:h,tvf:p}=e,u=(0,d.formatJsonRpcRequest)(i,r,c);let g;const m=!!h;try{const e=m?a.Pa8:a.EWt;g=await this.client.core.crypto.encode(t,u,{encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`),e}let f;if(C.includes(i)){const e=(0,a.ALl)(JSON.stringify(u)),t=(0,a.ALl)(g);f=await this.client.core.verify.register({id:t,decryptedId:e})}const y=w[i].req;if(y.attestation=f,n&&(y.ttl=n),o&&(y.id=o),this.client.core.history.set(t,u),m){const e=(0,a.$Bq)(h,t,g);await s.g.Linking.openURL(e,this.client.name)}else{const e=w[i].req;n&&(e.ttl=n),o&&(e.id=o),e.tvf=x(R({},p),{correlationId:u.id}),l?(e.internal=x(R({},e.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(t,g,e)):this.client.core.relayer.publish(t,g,e).catch(e=>this.client.logger.error(e))}return u.id}),U(this,"sendResult",async e=>{const{id:t,topic:i,result:r,throwOnFailedPublish:n,encodeOpts:o,appLink:c}=e,l=(0,d.formatJsonRpcResult)(t,r);let h;const p=c&&typeof(null==s.g?void 0:s.g.Linking)<"u";try{const e=p?a.Pa8:a.EWt;h=await this.client.core.crypto.encode(i,l,x(R({},o||{}),{encoding:e}))}catch(e){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),e}let u,g;try{u=await this.client.core.history.get(i,t);const e=u.request;try{this.shouldSetTVF(e.method,e.params)&&(g=this.getTVFParams(t,e.params,r))}catch(e){this.client.logger.warn("sendResult() -> getTVFParams() failed",e)}}catch(e){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${t}) failed`),e}if(p){const e=(0,a.$Bq)(c,i,h);await s.g.Linking.openURL(e,this.client.name)}else{const e=u.request.method,s=w[e].res;s.tvf=x(R({},g),{correlationId:t}),n?(s.internal=x(R({},s.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,h,s)):this.client.core.relayer.publish(i,h,s).catch(e=>this.client.logger.error(e))}await this.client.core.history.resolve(l)}),U(this,"sendError",async e=>{const{id:t,topic:i,error:r,encodeOpts:n,rpcOpts:o,appLink:c}=e,l=(0,d.formatJsonRpcError)(t,r);let h;const p=c&&typeof(null==s.g?void 0:s.g.Linking)<"u";try{const e=p?a.Pa8:a.EWt;h=await this.client.core.crypto.encode(i,l,x(R({},n||{}),{encoding:e}))}catch(e){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),e}let u;try{u=await this.client.core.history.get(i,t)}catch(e){throw this.client.logger.error(`sendError() -> history.get(${i}, ${t}) failed`),e}if(p){const e=(0,a.$Bq)(c,i,h);await s.g.Linking.openURL(e,this.client.name)}else{const e=u.request.method,t=o||w[e].res;this.client.core.relayer.publish(i,h,t)}await this.client.core.history.resolve(l)}),U(this,"cleanup",async()=>{const e=[],t=[];this.client.session.getAll().forEach(t=>{let s=!1;(0,a._dF)(t.expiry)&&(s=!0),this.client.core.crypto.keychain.has(t.topic)||(s=!0),s&&e.push(t.topic)}),this.client.proposal.getAll().forEach(e=>{(0,a._dF)(e.expiryTimestamp)&&t.push(e.id)}),await Promise.all([...e.map(e=>this.deleteSession({topic:e})),...t.map(e=>this.deleteProposal(e))])}),U(this,"onProviderMessageEvent",async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)}),U(this,"onRelayEventRequest",async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()}),U(this,"processRequestsQueue",async()=>{if(this.requestQueue.state!==v){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=v;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=b}else this.client.logger.info("Request queue already active, skipping...")}),U(this,"processRequest",async e=>{const{topic:t,payload:s,attestation:i,transportType:r,encryptedId:n}=e,o=s.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:o}))switch(o){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:t,payload:s,attestation:i,encryptedId:n});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,s);case"wc_sessionPing":return await this.onSessionPingRequest(t,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});case"wc_sessionEvent":return await this.onSessionEventRequest(t,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});default:return this.client.logger.info(`Unsupported request method ${o}`)}}),U(this,"onRelayEventResponse",async e=>{const{topic:t,payload:s,transportType:i}=e,r=(await this.client.core.history.get(t,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(t,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,s);case"wc_sessionExtend":return this.onSessionExtendResponse(t,s);case"wc_sessionPing":return this.onSessionPingResponse(t,s);case"wc_sessionRequest":return this.onSessionRequestResponse(t,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}}),U(this,"onRelayEventUnknownPayload",e=>{const{topic:t}=e,{message:s}=(0,a.GuA)("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),U(this,"shouldIgnorePairingRequest",e=>{const{topic:t,requestMethod:s}=e,i=this.expectedPairingMethodMap.get(t);return!(!i||i.includes(s)||!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0))}),U(this,"onSessionProposeRequest",async e=>{const{topic:t,payload:s,attestation:r,encryptedId:n}=e,{params:o,id:c}=s;try{const e=this.client.core.eventClient.getEvent({topic:t});0===this.client.events.listenerCount("session_proposal")&&(console.warn("No listener for session_proposal event"),e?.setError(i.S$.proposal_listener_not_found)),this.isValidConnect(R({},s.params));const l=o.expiryTimestamp||(0,a.Xw0)(w.wc_sessionPropose.req.ttl),d=R({id:c,pairingTopic:t,expiryTimestamp:l},o);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:r,hash:(0,a.ALl)(JSON.stringify(s)),encryptedId:n,metadata:d.proposer.metadata});e?.addTrace(i.$w.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(e){await this.sendError({id:c,topic:t,error:e,rpcOpts:w.wc_sessionPropose.autoReject}),this.client.logger.error(e)}}),U(this,"onSessionProposeResponse",async(e,t,s)=>{const{id:i}=t;if((0,d.isJsonRpcResult)(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const n=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const o=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:o});const a=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});const c=await this.client.core.crypto.generateSharedKey(o,a);this.pendingSessions.set(i,{sessionTopic:c,pairingTopic:e,proposalId:i,publicKey:o});const l=await this.client.core.relayer.subscribe(c,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:e})}else if((0,d.isJsonRpcError)(t)){await this.client.proposal.delete(i,(0,a.Hjj)("USER_DISCONNECTED"));const e=(0,a.hEn)("session_connect",i);if(0===this.events.listenerCount(e))throw new Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:t.error})}}),U(this,"onSessionSettleRequest",async(e,t)=>{const{id:s,params:r}=t;try{this.isValidSessionSettleRequest(r);const{relay:s,controller:n,expiry:o,namespaces:c,sessionProperties:l,scopedProperties:d,sessionConfig:h}=t.params,p=[...this.pendingSessions.values()].find(t=>t.sessionTopic===e);if(!p)return this.client.logger.error(`Pending session not found for topic ${e}`);const u=this.client.proposal.get(p.proposalId),g=x(R(R(R({topic:e,relay:s,expiry:o,namespaces:c,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:u.requiredNamespaces,optionalNamespaces:u.optionalNamespaces,controller:n.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:n.publicKey,metadata:n.metadata}},l&&{sessionProperties:l}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:i.cV.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit((0,a.hEn)("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:t.id,topic:e,result:!0,throwOnFailedPublish:!0})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}}),U(this,"onSessionSettleResponse",async(e,t)=>{const{id:s}=t;(0,d.isJsonRpcResult)(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit((0,a.hEn)("session_approve",s),{})):(0,d.isJsonRpcError)(t)&&(await this.client.session.delete(e,(0,a.Hjj)("USER_DISCONNECTED")),this.events.emit((0,a.hEn)("session_approve",s),{error:t.error}))}),U(this,"onSessionUpdateRequest",async(e,t)=>{const{params:s,id:i}=t;try{const t=`${e}_session_update`,r=a.nyL.get(t);if(r&&this.isRequestOutOfSync(r,i))return this.client.logger.warn(`Discarding out of sync request - ${i}`),void this.sendError({id:i,topic:e,error:(0,a.Hjj)("INVALID_UPDATE_REQUEST")});this.isValidUpdate(R({topic:e},s));try{a.nyL.set(t,i),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:e,result:!0,throwOnFailedPublish:!0})}catch(e){throw a.nyL.delete(t),e}this.client.events.emit("session_update",{id:i,topic:e,params:s})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}}),U(this,"isRequestOutOfSync",(e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3)),U(this,"onSessionUpdateResponse",(e,t)=>{const{id:s}=t,i=(0,a.hEn)("session_update",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);(0,d.isJsonRpcResult)(t)?this.events.emit((0,a.hEn)("session_update",s),{}):(0,d.isJsonRpcError)(t)&&this.events.emit((0,a.hEn)("session_update",s),{error:t.error})}),U(this,"onSessionExtendRequest",async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,(0,a.Xw0)(f)),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:s,topic:e})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}}),U(this,"onSessionExtendResponse",(e,t)=>{const{id:s}=t,i=(0,a.hEn)("session_extend",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);(0,d.isJsonRpcResult)(t)?this.events.emit((0,a.hEn)("session_extend",s),{}):(0,d.isJsonRpcError)(t)&&this.events.emit((0,a.hEn)("session_extend",s),{error:t.error})}),U(this,"onSessionPingRequest",async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:e})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}}),U(this,"onSessionPingResponse",(e,t)=>{const{id:s}=t,i=(0,a.hEn)("session_ping",s);setTimeout(()=>{if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners 2176`);(0,d.isJsonRpcResult)(t)?this.events.emit((0,a.hEn)("session_ping",s),{}):(0,d.isJsonRpcError)(t)&&this.events.emit((0,a.hEn)("session_ping",s),{error:t.error})},500)}),U(this,"onSessionDeleteRequest",async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),Promise.all([new Promise(t=>{this.client.core.relayer.once(i.Jf.publish,async()=>{t(await this.deleteSession({topic:e,id:s}))})}),this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:e,error:(0,a.Hjj)("USER_DISCONNECTED")})]).catch(e=>this.client.logger.error(e))}catch(e){this.client.logger.error(e)}}),U(this,"onSessionRequest",async e=>{var t,s,r;const{topic:n,payload:o,attestation:c,encryptedId:l,transportType:h}=e,{id:p,params:u}=o;try{await this.isValidRequest(R({topic:n},u));const e=this.client.session.get(n),o={id:p,topic:n,params:u,verifyContext:await this.getVerifyContext({attestationId:c,hash:(0,a.ALl)(JSON.stringify((0,d.formatJsonRpcRequest)("wc_sessionRequest",u,p))),encryptedId:l,metadata:e.peer.metadata,transportType:h})};await this.setPendingSessionRequest(o),h===i.cV.link_mode&&null!=(t=e.peer.metadata.redirect)&&t.universal&&this.client.core.addLinkModeSupportedApp(null==(s=e.peer.metadata.redirect)?void 0:s.universal),null!=(r=this.client.signConfig)&&r.disableRequestQueue?this.emitSessionRequest(o):(this.addSessionRequestToSessionRequestQueue(o),this.processSessionRequestQueue())}catch(e){await this.sendError({id:p,topic:n,error:e}),this.client.logger.error(e)}}),U(this,"onSessionRequestResponse",(e,t)=>{const{id:s}=t,i=(0,a.hEn)("session_request",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);(0,d.isJsonRpcResult)(t)?this.events.emit((0,a.hEn)("session_request",s),{result:t.result}):(0,d.isJsonRpcError)(t)&&this.events.emit((0,a.hEn)("session_request",s),{error:t.error})}),U(this,"onSessionEventRequest",async(e,t)=>{const{id:s,params:i}=t;try{const t=`${e}_session_event_${i.event.name}`,r=a.nyL.get(t);if(r&&this.isRequestOutOfSync(r,s))return void this.client.logger.info(`Discarding out of sync request - ${s}`);this.isValidEmit(R({topic:e},i)),this.client.events.emit("session_event",{id:s,topic:e,params:i}),a.nyL.set(t,s)}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}}),U(this,"onSessionAuthenticateResponse",(e,t)=>{const{id:s}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),(0,d.isJsonRpcResult)(t)?this.events.emit((0,a.hEn)("session_request",s),{result:t.result}):(0,d.isJsonRpcError)(t)&&this.events.emit((0,a.hEn)("session_request",s),{error:t.error})}),U(this,"onSessionAuthenticateRequest",async e=>{var t;const{topic:s,payload:r,attestation:n,encryptedId:o,transportType:c}=e;try{const{requester:e,authPayload:l,expiryTimestamp:d}=r.params,h=await this.getVerifyContext({attestationId:n,hash:(0,a.ALl)(JSON.stringify(r)),encryptedId:o,metadata:e.metadata,transportType:c}),p={requester:e,pairingTopic:s,id:r.id,authPayload:l,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(r.id,{request:p,pairingTopic:s,transportType:c}),c===i.cV.link_mode&&null!=(t=e.metadata.redirect)&&t.universal&&this.client.core.addLinkModeSupportedApp(e.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:r.params,id:r.id,verifyContext:h})}catch(e){this.client.logger.error(e);const t=r.params.requester.publicKey,i=await this.client.core.crypto.generateKeyPair(),n=this.getAppLinkIfEnabled(r.params.requester.metadata,c),o={type:a.Lp_,receiverPublicKey:t,senderPublicKey:i};await this.sendError({id:r.id,topic:s,error:e,encodeOpts:o,rpcOpts:w.wc_sessionAuthenticate.autoReject,appLink:n})}}),U(this,"addSessionRequestToSessionRequestQueue",e=>{this.sessionRequestQueue.queue.push(e)}),U(this,"cleanupAfterResponse",e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=b,this.processSessionRequestQueue()},(0,o.toMiliseconds)(this.requestQueueDelay))}),U(this,"cleanupPendingSentRequestsForTopic",({topic:e,error:t})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(t=>t.topic===e&&"wc_sessionRequest"===t.request.method).forEach(e=>{const s=e.request.id,i=(0,a.hEn)("session_request",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);this.events.emit((0,a.hEn)("session_request",e.request.id),{error:t})})}),U(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===v)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.sessionRequestQueue.state=v,this.emitSessionRequest(e)}catch(e){this.client.logger.error(e)}else this.client.logger.info("session request queue is empty.")}),U(this,"emitSessionRequest",e=>{this.client.events.emit("session_request",e)}),U(this,"onPairingCreated",e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find(t=>t.pairingTopic===e.topic);t&&this.onSessionProposeRequest({topic:e.topic,payload:(0,d.formatJsonRpcRequest)("wc_sessionPropose",x(R({},t),{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties,scopedProperties:t.scopedProperties}),t.id)})}),U(this,"isValidConnect",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:r,scopedProperties:n,relays:o}=e;if((0,a.b07)(t)||await this.isValidPairingTopic(t),!(0,a.V9G)(o,!0)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`connect() relays: ${o}`);throw new Error(e)}if(!(0,a.b07)(s)&&0!==(0,a.aF0)(s)){const e="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(e):this.client.logger.warn(e),this.validateNamespaces(s,"requiredNamespaces")}if(!(0,a.b07)(i)&&0!==(0,a.aF0)(i)&&this.validateNamespaces(i,"optionalNamespaces"),(0,a.b07)(r)||this.validateSessionProps(r,"sessionProperties"),!(0,a.b07)(n)){this.validateSessionProps(n,"scopedProperties");const e=Object.keys(s||{}).concat(Object.keys(i||{}));if(!Object.keys(n).every(t=>e.includes(t)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(n)}, required/optional namespaces: ${JSON.stringify(e)}`)}}),U(this,"validateNamespaces",(e,t)=>{const s=(0,a.esh)(e,"connect()",t);if(s)throw new Error(s.message)}),U(this,"isValidApprove",async e=>{if(!(0,a.TeY)(e))throw new Error((0,a.GuA)("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:i,sessionProperties:r,scopedProperties:n}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const o=this.client.proposal.get(t),c=(0,a.FiO)(s,"approve()");if(c)throw new Error(c.message);const l=(0,a.XqR)(o.requiredNamespaces,s,"approve()");if(l)throw new Error(l.message);if(!(0,a.Qhg)(i,!0)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(e)}if((0,a.b07)(r)||this.validateSessionProps(r,"sessionProperties"),!(0,a.b07)(n)){this.validateSessionProps(n,"scopedProperties");const e=new Set(Object.keys(s));if(!Object.keys(n).every(t=>e.has(t)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(n)}, approved namespaces: ${Array.from(e).join(", ")}`)}}),U(this,"isValidReject",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:s}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!(0,a.X3c)(s)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(e)}}),U(this,"isValidSessionSettleRequest",e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:s,namespaces:i,expiry:r}=e;if(!(0,a.kuU)(t)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const n=(0,a.tk0)(s,"onSessionSettleRequest()");if(n)throw new Error(n.message);const o=(0,a.FiO)(i,"onSessionSettleRequest()");if(o)throw new Error(o.message);if((0,a._dF)(r)){const{message:e}=(0,a.GuA)("EXPIRED","onSessionSettleRequest()");throw new Error(e)}}),U(this,"isValidUpdate",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:s}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const i=this.client.session.get(t),r=(0,a.FiO)(s,"update()");if(r)throw new Error(r.message);const n=(0,a.XqR)(i.requiredNamespaces,s,"update()");if(n)throw new Error(n.message)}),U(this,"isValidExtend",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)}),U(this,"isValidRequest",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:s,chainId:i,expiry:r}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!(0,a.tLy)(n,i)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(e)}if(!(0,a.iV1)(s)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(e)}if(!(0,a.oKp)(n,i,s.method)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(e)}if(r&&!(0,a.Hbs)(r,y)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`request() expiry: ${r}. Expiry must be a number (in seconds) between ${y.min} and ${y.max}`);throw new Error(e)}}),U(this,"isValidRespond",async e=>{var t;if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:s,response:i}=e;try{await this.isValidSessionTopic(s)}catch(s){throw null!=(t=e?.response)&&t.id&&this.cleanupAfterResponse(e),s}if(!(0,a.M8n)(i)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(e)}}),U(this,"isValidPing",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),U(this,"isValidEmit",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:s,chainId:i}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!(0,a.tLy)(r,i)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(e)}if(!(0,a.FR8)(s)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}if(!(0,a.z2N)(r,i,s.name)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}}),U(this,"isValidDisconnect",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),U(this,"isValidAuthenticate",e=>{const{chains:t,uri:s,domain:i,nonce:r}=e;if(!Array.isArray(t)||0===t.length)throw new Error("chains is required and must be a non-empty array");if(!(0,a.Qhg)(s,!1))throw new Error("uri is required parameter");if(!(0,a.Qhg)(i,!1))throw new Error("domain is required parameter");if(!(0,a.Qhg)(r,!1))throw new Error("nonce is required parameter");if([...new Set(t.map(e=>(0,a._Yb)(e).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:n}=(0,a._Yb)(t[0]);if("eip155"!==n)throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),U(this,"getVerifyContext",async e=>{const{attestationId:t,hash:s,encryptedId:r,metadata:n,transportType:o}=e,a={verified:{verifyUrl:n.verifyUrl||i.WB,validation:"UNKNOWN",origin:n.url||""}};try{if(o===i.cV.link_mode){const e=this.getAppLinkIfEnabled(n,o);return a.verified.validation=e&&new URL(e).origin===new URL(n.url).origin?"VALID":"INVALID",a}const e=await this.client.core.verify.resolve({attestationId:t,hash:s,encryptedId:r,verifyUrl:n.verifyUrl});e&&(a.verified.origin=e.origin,a.verified.isScam=e.isScam,a.verified.validation=e.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.warn(e)}return this.client.logger.debug(`Verify context: ${JSON.stringify(a)}`),a}),U(this,"validateSessionProps",(e,t)=>{Object.values(e).forEach((s,i)=>{if(null==s){const{message:r}=(0,a.GuA)("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${s} for key ${Object.keys(e)[i]}`);throw new Error(r)}})}),U(this,"getPendingAuthRequest",e=>{const t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0}),U(this,"addToRecentlyDeleted",(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0;const t=this.recentlyDeletedLimit/2;for(const s of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(s)}}}),U(this,"checkRecentlyDeleted",e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:s}=(0,a.GuA)("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(s)}}),U(this,"isLinkModeEnabled",(e,t)=>{var r,n,o,a,c,l,d,h,p;return!(!e||t!==i.cV.link_mode)&&!0===(null==(n=null==(r=this.client.metadata)?void 0:r.redirect)?void 0:n.linkMode)&&void 0!==(null==(a=null==(o=this.client.metadata)?void 0:o.redirect)?void 0:a.universal)&&""!==(null==(l=null==(c=this.client.metadata)?void 0:c.redirect)?void 0:l.universal)&&void 0!==(null==(d=e?.redirect)?void 0:d.universal)&&""!==(null==(h=e?.redirect)?void 0:h.universal)&&!0===(null==(p=e?.redirect)?void 0:p.linkMode)&&this.client.core.linkModeSupportedApps.includes(e.redirect.universal)&&typeof(null==s.g?void 0:s.g.Linking)<"u"}),U(this,"getAppLinkIfEnabled",(e,t)=>{var s;return this.isLinkModeEnabled(e,t)?null==(s=e?.redirect)?void 0:s.universal:void 0}),U(this,"handleLinkModeMessage",({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=(0,a.$hI)(e,"topic")||"",s=decodeURIComponent((0,a.$hI)(e,"wc_ev")||""),r=this.client.session.keys.includes(t);r&&this.client.session.update(t,{transportType:i.cV.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:s,sessionExists:r})}),U(this,"registerLinkModeListeners",async()=>{var e;if((0,a.w8K)()||(0,a.lVv)()&&null!=(e=this.client.metadata.redirect)&&e.linkMode){const e=null==s.g?void 0:s.g.Linking;if(typeof e<"u"){e.addEventListener("url",this.handleLinkModeMessage,this.client.name);const t=await e.getInitialURL();t&&setTimeout(()=>{this.handleLinkModeMessage({url:t})},50)}}}),U(this,"shouldSetTVF",(e,t)=>{if(!t||"wc_sessionRequest"!==e)return!1;const{request:s}=t;return Object.keys(E).includes(s.method)}),U(this,"getTVFParams",(e,t,s)=>{var i,r;try{const n=t.request.method,o=this.extractTxHashesFromResult(n,s);return x(R({correlationId:e,rpcMethods:[n],chainId:t.chainId},this.isValidContractData(t.request.params)&&{contractAddresses:[null==(r=null==(i=t.request.params)?void 0:i[0])?void 0:r.to]}),{txHashes:o})}catch(e){this.client.logger.warn("Error getting TVF params",e)}return{}}),U(this,"isValidContractData",e=>{var t;if(!e)return!1;try{const s=e?.data||(null==(t=e?.[0])?void 0:t.data);if(!s.startsWith("0x"))return!1;const i=s.slice(2);return!!/^[0-9a-fA-F]*$/.test(i)&&i.length%2==0}catch{}return!1}),U(this,"extractTxHashesFromResult",(e,t)=>{try{if("string"==typeof t)return[t];const s=t[E[e].key];if((0,a.OP1)(s))return"solana_signAllTransactions"===e?s.map(e=>(0,a.PAk)(e)):s;if("string"==typeof s)return[s]}catch(e){this.client.logger.warn("Error extracting tx hashes from result",e)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[e,s]of Object.entries(t))for(const t of s)try{await this.onProviderMessageEvent({topic:e,message:t,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${e}, message: ${t}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=(0,a.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(i.Jf.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(N)?this.client.auth.authKeys.get(N):{responseTopic:void 0,publicKey:void 0};try{const e=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===i.cV.link_mode?a.Pa8:a.EWt});(0,d.isJsonRpcRequest)(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:r,transportType:n,encryptedId:(0,a.ALl)(s)})):(0,d.isJsonRpcResponse)(e)?(await this.client.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e,transportType:n}),this.client.core.history.delete(t,e.id)):await this.onRelayEventUnknownPayload({topic:t,payload:e,transportType:n}),await this.client.core.relayer.messages.ack(t,s)}catch(e){this.client.logger.error(e)}}registerExpirerEvents(){this.client.core.expirer.on(i.wn.expired,async e=>{const{topic:t,id:s}=(0,a.c82)(e.target);return s&&this.client.pendingRequest.keys.includes(s)?await this.deletePendingSessionRequest(s,(0,a.GuA)("EXPIRED"),!0):s&&this.client.auth.requests.keys.includes(s)?await this.deletePendingAuthRequest(s,(0,a.GuA)("EXPIRED"),!0):void(t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):s&&(await this.deleteProposal(s,!0),this.client.events.emit("proposal_expire",{id:s})))})}registerPairingEvents(){this.client.core.pairing.events.on(i.zN.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(i.zN.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!(0,a.Qhg)(e,!1)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=(0,a.GuA)("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if((0,a._dF)(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=(0,a.GuA)("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!(0,a.Qhg)(e,!1)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=(0,a.GuA)("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if((0,a._dF)(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=(0,a.GuA)("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else{if(!this.client.core.pairing.pairings.keys.includes(e)){if((0,a.Qhg)(e,!1)){const{message:t}=(0,a.GuA)("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if(!(0,a.Alu)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=(0,a.GuA)("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if((0,a._dF)(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=(0,a.GuA)("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class L extends i.il{constructor(e,t){super(e,t,"proposal",p),this.core=e,this.logger=t}}class W extends i.il{constructor(e,t){super(e,t,"session",p),this.core=e,this.logger=t}}class M extends i.il{constructor(e,t){super(e,t,"request",p,e=>e.id),this.core=e,this.logger=t}}class B extends i.il{constructor(e,t){super(e,t,"authKeys",I,()=>N),this.core=e,this.logger=t}}class j extends i.il{constructor(e,t){super(e,t,"pairingTopics",I),this.core=e,this.logger=t}}class q extends i.il{constructor(e,t){super(e,t,"requests",I,e=>e.id),this.core=e,this.logger=t}}var $=Object.defineProperty,H=(e,t,s)=>((e,t,s)=>t in e?$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class F{constructor(e,t){this.core=e,this.logger=t,H(this,"authKeys"),H(this,"pairingTopics"),H(this,"requests"),this.authKeys=new B(this.core,this.logger),this.pairingTopics=new j(this.core,this.logger),this.requests=new q(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var V=Object.defineProperty,z=(e,t,s)=>((e,t,s)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class K extends n.S9{constructor(e){super(e),z(this,"protocol","wc"),z(this,"version",2),z(this,"name",u),z(this,"metadata"),z(this,"core"),z(this,"logger"),z(this,"events",new c.EventEmitter),z(this,"engine"),z(this,"session"),z(this,"proposal"),z(this,"pendingRequest"),z(this,"auth"),z(this,"signConfig"),z(this,"on",(e,t)=>this.events.on(e,t)),z(this,"once",(e,t)=>this.events.once(e,t)),z(this,"off",(e,t)=>this.events.off(e,t)),z(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),z(this,"removeAllListeners",e=>this.events.removeAllListeners(e)),z(this,"connect",async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"pair",async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"approve",async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"reject",async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"update",async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"extend",async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"request",async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"respond",async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"ping",async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"emit",async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"disconnect",async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"find",e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}}),z(this,"authenticate",async(e,t)=>{try{return await this.engine.authenticate(e,t)}catch(e){throw this.logger.error(e.message),e}}),z(this,"formatAuthMessage",e=>{try{return this.engine.formatAuthMessage(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"approveSessionAuthenticate",async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"rejectSessionAuthenticate",async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}}),this.name=e?.name||u,this.metadata=(0,a.Ds_)(e?.metadata),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&"string"!=typeof e?.logger?e.logger:(0,r.h6)((0,r.iP)({level:e?.logger||"error"}));this.core=e?.core||new i.iJ(e),this.logger=(0,r.U5)(t,this.name),this.session=new W(this.core,this.logger),this.proposal=new L(this.core,this.logger),this.pendingRequest=new M(this.core,this.logger),this.engine=new D(this),this.auth=new F(this.core,this.logger)}static async init(e){const t=new K(e);return await t.initialize(),t}get context(){return(0,r.oI)(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},(0,o.toMiliseconds)(o.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}},28873:(e,t,s)=>{s.d(t,{n:()=>u});var i=s(33244),r=s(38903),n=s(72269),o=s(23981),a=s(98299),c=s(3555),l=s(22143),d=s(96517),h=s(22129),p=s(1435);class u extends d.X{setUniversalProvider(e){this.addConnector(new h.F({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace}))}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{const e=this.getWalletConnectConnector();await e.disconnect()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){const t=this.provider,s=t?.session?.namespaces?.[e]?.accounts?.map(e=>{const[,,t]=e.split(":");return t}).filter((e,t,s)=>s.indexOf(e)===t)||[];return Promise.resolve({accounts:s.map(t=>l.w.createAccount(e,t,"bip122"===e?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!e.caipNetwork||!c.oU.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace)||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};if(o.U.state.balanceLoading&&e.chainId===a.W.state.activeCaipNetwork?.id)return{balance:o.U.state.balance||"0.00",symbol:o.U.state.balanceSymbol||""};const t=(await o.U.fetchTokenBalance()).find(t=>t.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&t.symbol===e.caipNetwork?.nativeCurrency.symbol);return{balance:t?.quantity.numeric||"0.00",symbol:t?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:t,message:s,address:r}=e;if(!t)throw new Error("UniversalAdapter:signMessage - provider is undefined");let o="";return o=a.W.state.activeCaipNetwork?.chainNamespace===n.o.CHAIN.SOLANA?(await t.request({method:"solana_signMessage",params:{message:i.A.encode((new TextEncoder).encode(s)),pubkey:r}},a.W.state.activeCaipNetwork?.caipNetworkId)).signature:await t.request({method:"personal_sign",params:[s,r]},a.W.state.activeCaipNetwork?.caipNetworkId),{signature:o}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){const{caipNetwork:t}=e,s=this.getWalletConnectConnector();if(t.chainNamespace===n.o.CHAIN.EVM)try{await(s.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:(0,r.nj)(t.id)}]}))}catch(e){if(e.code===p.E.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||e.code===p.E.ERROR_INVALID_CHAIN_ID||e.code===p.E.ERROR_CODE_DEFAULT||e?.data?.originalError?.code===p.E.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await(s.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:(0,r.nj)(t.id),rpcUrls:[t?.rpcUrls.chainDefault?.http],chainName:t.name,nativeCurrency:t.nativeCurrency,blockExplorerUrls:[t.blockExplorers?.default.url]}]}))}catch(e){throw new Error("Chain is not supported")}}s.provider.setDefaultChain(t.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(e=>"WALLET_CONNECT"===e.type),t=e?.provider;return t}}},29972:(e,t,s)=>{s.d(t,{F:()=>i});const i=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}]},31100:(e,t,s)=>{s.d(t,{h:()=>l});var i=s(89168),r=s(39150),n=s(37834),o=s(1420);const a=(0,i.BX)({message:"",variant:"info",open:!1}),c={state:a,subscribeKey:(e,t)=>(0,r.u$)(a,e,t),open(e,t){const{debug:s}=o.H.state,{shortMessage:i,longMessage:r}=e;s&&(a.message=i,a.variant=t,a.open=!0),r&&console.error("function"==typeof r?r():r)},close(){a.open=!1,a.message="",a.variant="info"}},l=(0,n.X)(c)},32523:(e,t,s)=>{s.d(t,{g:()=>u});var i=s(72269),r=s(98299),n=s(86792),o=s(83077),a=s(93474),c=s(1420),l=s(22143),d=s(11847),h=s(51765),p=s(84279);const u={getConnectorsByType(e,t,s){const{customWallets:i}=c.H.state,r=d.i.getRecentWallets(),n=p.A.filterOutDuplicateWallets(t),o=p.A.filterOutDuplicateWallets(s),a=e.filter(e=>"MULTI_CHAIN"===e.type),l=e.filter(e=>"ANNOUNCED"===e.type),h=e.filter(e=>"INJECTED"===e.type);return{custom:i,recent:r,external:e.filter(e=>"EXTERNAL"===e.type),multiChain:a,announced:l,injected:h,recommended:n,featured:o}},showConnector(e){const t=e.info?.rdns,s=Boolean(t)&&a.N.state.excludedWallets.some(e=>Boolean(e.rdns)&&e.rdns===t),i=Boolean(e.name)&&a.N.state.excludedWallets.some(t=>h.y.isLowerCaseMatch(t.name,e.name));if("INJECTED"===e.type){if("Browser Wallet"===e.name){if(!l.w.isMobile())return!1;if(l.w.isMobile()&&!t&&!n.x.checkInstalled())return!1}if(s||i)return!1}return"ANNOUNCED"!==e.type&&"EXTERNAL"!==e.type||!s&&!i},getIsConnectedWithWC:()=>Array.from(r.W.state.chains.values()).some(e=>o.a.getConnectorId(e.namespace)===i.o.CONNECTOR_ID.WALLET_CONNECT),getConnectorTypeOrder({recommended:e,featured:t,custom:s,recent:i,announced:r,injected:n,multiChain:o,external:a,overriddenConnectors:l=c.H.state.features?.connectorTypeOrder??[]}){const d=u.getIsConnectedWithWC(),h=[{type:"walletConnect",isEnabled:c.H.state.enableWalletConnect&&!d},{type:"recent",isEnabled:i.length>0},{type:"injected",isEnabled:[...n,...r,...o].length>0},{type:"featured",isEnabled:t.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:e.length>0}].filter(e=>e.isEnabled),p=new Set(h.map(e=>e.type)),g=l.filter(e=>p.has(e)).map(e=>({type:e,isEnabled:!0})),m=h.filter(({type:e})=>!g.some(({type:t})=>t===e));return Array.from(new Set([...g,...m].map(({type:e})=>e)))}}},33868:(e,t,s)=>{var i=s(39275);(0,i.x)({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}}),(0,i.x)({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0})},34311:(e,t,s)=>{s.d(t,{Q:()=>i});const i=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}]},34631:(e,t,s)=>{},35646:(e,t,s)=>{async function i(...e){const t=await fetch(...e);if(!t.ok)throw new Error(`HTTP status code: ${t.status}`,{cause:t});return t}s.d(t,{Z:()=>r});class r{constructor({baseUrl:e,clientId:t}){this.baseUrl=e,this.clientId=t}async get({headers:e,signal:t,cache:s,...r}){const n=this.createUrl(r);return(await i(n,{method:"GET",headers:e,signal:t,cache:s})).json()}async getBlob({headers:e,signal:t,...s}){const r=this.createUrl(s);return(await i(r,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:s,...r}){const n=this.createUrl(r);return(await i(n,{method:"POST",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}async put({body:e,headers:t,signal:s,...r}){const n=this.createUrl(r);return(await i(n,{method:"PUT",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}async delete({body:e,headers:t,signal:s,...r}){const n=this.createUrl(r);return(await i(n,{method:"DELETE",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}createUrl({path:e,params:t}){const s=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([e,t])=>{t&&s.searchParams.append(e,t)}),this.clientId&&s.searchParams.append("clientId",this.clientId),s}}},36347:(e,t,s)=>{s.d(t,{A:()=>a});var i=s(89168),r=s(39150);const n={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},o=(0,i.BX)({providers:{...n},providerIds:{...n}}),a={state:o,subscribeKey:(e,t)=>(0,r.u$)(o,e,t),subscribe:e=>(0,i.B1)(o,()=>{e(o)}),subscribeProviders:e=>(0,i.B1)(o.providers,()=>e(o.providers)),setProvider(e,t){t&&(o.providers[e]=(0,i.KR)(t))},getProvider:e=>o.providers[e],setProviderId(e,t){t&&(o.providerIds[e]=t)},getProviderId(e){if(e)return o.providerIds[e]},reset(){o.providers={...n},o.providerIds={...n}},resetChain(e){o.providers[e]=void 0,o.providerIds[e]=void 0}}},36507:(e,t,s)=>{s.d(t,{U:()=>m}),s(18338);var i=s(72269),r=s(88889),n=s(23981),o=s(98299),a=s(86792),c=s(83077),l=s(47981),d=s(88759),h=s(1420),p=s(72397),u=s(92492),g=s(22143);const m={getSIWX:()=>h.H.state.siwx,async initializeIfEnabled(){const e=h.H.state.siwx,t=o.W.getActiveCaipAddress();if(!e||!t)return;const[s,i,r]=t.split(":");if(o.W.checkIfSupportedNetwork(s))try{if((await e.getSessions(`${s}:${i}`,r)).length)return;await d.W.open({view:"SIWXSignMessage"})}catch(e){console.error("SIWXUtil:initializeIfEnabled",e),l.E.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await(a.x._getClient()?.disconnect().catch(console.error)),p.I.reset("Connect"),u.P.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const e=h.H.state.siwx,t=g.w.getPlainAddress(o.W.getActiveCaipAddress()),s=o.W.getActiveCaipNetwork(),r=a.x._getClient();if(!e)throw new Error("SIWX is not enabled");if(!t)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");if(!r)throw new Error("No ConnectionController client found");try{const n=await e.createMessage({chainId:s.caipNetworkId,accountAddress:t}),o=n.toString();c.a.getConnectorId(s.chainNamespace)===i.o.CONNECTOR_ID.AUTH&&p.I.pushTransactionStack({});const a=await r.signMessage(o);await e.addSession({data:n,message:o,signature:a}),d.W.close(),l.E.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(e){const t=this.getSIWXEventProperties();d.W.state.open&&"ApproveTransaction"!==p.I.state.view||await d.W.open({view:"SIWXSignMessage"}),t.isSmartAccount?u.P.showError("This application might not support Smart Accounts"):u.P.showError("Signature declined"),l.E.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:t}),console.error("SWIXUtil:requestSignMessage",e)}},async cancelSignMessage(){try{const e=this.getSIWX(),t=e?.getRequired?.();t?await a.x.disconnect():d.W.close(),p.I.reset("Connect"),l.E.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getSessions(){const e=h.H.state.siwx,t=g.w.getPlainAddress(o.W.getActiveCaipAddress()),s=o.W.getActiveCaipNetwork();return e&&t&&s?e.getSessions(s.caipNetworkId,t):[]},async isSIWXCloseDisabled(){const e=this.getSIWX();if(e){const t="ApproveTransaction"===p.I.state.view,s="SIWXSignMessage"===p.I.state.view;if(t||s)return e.getRequired?.()&&0===(await this.getSessions()).length}return!1},async universalProviderAuthenticate({universalProvider:e,chains:t,methods:s}){const i=m.getSIWX(),r=new Set(t.map(e=>e.split(":")[0]));if(!i||1!==r.size||!r.has("eip155"))return!1;const a=await i.createMessage({chainId:o.W.getActiveCaipNetwork()?.caipNetworkId||"",accountAddress:""}),c=await e.authenticate({nonce:a.nonce,domain:a.domain,uri:a.uri,exp:a.expirationTime,iat:a.issuedAt,nbf:a.notBefore,requestId:a.requestId,version:a.version,resources:a.resources,statement:a.statement,chainId:a.chainId,methods:s,chains:[a.chainId,...t.filter(e=>e!==a.chainId)]});if(u.P.showLoading("Authenticating...",{autoClose:!1}),n.U.setConnectedWalletInfo({...c.session.peer.metadata,name:c.session.peer.metadata.name,icon:c.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"},Array.from(r)[0]),c?.auths?.length){const t=c.auths.map(t=>{const s=e.client.formatAuthMessage({request:t.p,iss:t.p.iss});return{data:{...t.p,accountAddress:t.p.iss.split(":").slice(-1).join(""),chainId:t.p.iss.split(":").slice(2,4).join(":"),uri:t.p.aud,version:t.p.version||a.version,expirationTime:t.p.exp,issuedAt:t.p.iat,notBefore:t.p.nbf},message:s,signature:t.s.s,cacao:t}});try{await i.setSessions(t),l.E.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:m.getSIWXEventProperties()})}catch(t){throw console.error("SIWX:universalProviderAuth - failed to set sessions",t),l.E.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:m.getSIWXEventProperties()}),await e.disconnect().catch(console.error),t}finally{u.P.hide()}}return!0},getSIWXEventProperties(){const e=o.W.state.activeChain;return{network:o.W.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:n.U.state.preferredAccountTypes?.[e]===r.Vl.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const e=this.getSIWX();e&&await e.setSessions([])}}},37686:(e,t,s)=>{s.d(t,{R:()=>v});var i=s(89168),r=s(39150),n=s(4159),o=s(18496),a=s(88889),c=s(3555),l=s(22143),d=s(11148),h=s(37834),p=s(23981),u=s(98299),g=s(86792),m=s(47981),f=s(72397),w=s(92492);const y=(0,i.BX)({tokenBalances:[],loading:!1}),b={state:y,subscribe:e=>(0,i.B1)(y,()=>e(y)),subscribeKey:(e,t)=>(0,r.u$)(y,e,t),setToken(e){e&&(y.token=(0,i.KR)(e))},setTokenAmount(e){y.sendTokenAmount=e},setReceiverAddress(e){y.receiverAddress=e},setReceiverProfileImageUrl(e){y.receiverProfileImageUrl=e},setReceiverProfileName(e){y.receiverProfileName=e},setNetworkBalanceInUsd(e){y.networkBalanceInUSD=e},setLoading(e){y.loading=e},async sendToken(){try{switch(v.setLoading(!0),u.W.state.activeCaipNetwork?.chainNamespace){case"eip155":return void await v.sendEvmToken();case"solana":return void await v.sendSolanaToken();default:throw new Error("Unsupported chain")}}finally{v.setLoading(!1)}},async sendEvmToken(){const e=u.W.state.activeChain,t=p.U.state.preferredAccountTypes?.[e];if(!v.state.sendTokenAmount||!v.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!v.state.token)throw new Error("A token is required");v.state.token?.address?(m.E.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===a.Vl.ACCOUNT_TYPES.SMART_ACCOUNT,token:v.state.token.address,amount:v.state.sendTokenAmount,network:u.W.state.activeCaipNetwork?.caipNetworkId||""}}),await v.sendERC20Token({receiverAddress:v.state.receiverAddress,tokenAddress:v.state.token.address,sendTokenAmount:v.state.sendTokenAmount,decimals:v.state.token.quantity.decimals})):(m.E.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===a.Vl.ACCOUNT_TYPES.SMART_ACCOUNT,token:v.state.token.symbol||"",amount:v.state.sendTokenAmount,network:u.W.state.activeCaipNetwork?.caipNetworkId||""}}),await v.sendNativeToken({receiverAddress:v.state.receiverAddress,sendTokenAmount:v.state.sendTokenAmount,decimals:v.state.token.quantity.decimals}))},async fetchTokenBalance(e){y.loading=!0;const t=u.W.state.activeCaipNetwork?.caipNetworkId,s=u.W.state.activeCaipNetwork?.chainNamespace,i=u.W.state.activeCaipAddress,r=i?l.w.getPlainAddress(i):void 0;if(y.lastRetry&&!l.w.isAllowedRetry(y.lastRetry,30*c.oU.ONE_SEC_MS))return y.loading=!1,[];try{if(r&&t&&s){const e=await d.t.getMyTokensWithBalance();return y.tokenBalances=e,y.lastRetry=void 0,e}}catch(t){y.lastRetry=Date.now(),e?.(t),w.P.showError("Token Balance Unavailable")}finally{y.loading=!1}return[]},fetchNetworkBalance(){if(0===y.tokenBalances.length)return;const e=d.t.mapBalancesToSwapTokens(y.tokenBalances);if(!e)return;const t=e.find(e=>e.address===u.W.getActiveNetworkTokenAddress());t&&(y.networkBalanceInUSD=t?n.S.multiply(t.quantity.numeric,t.price).toString():"0")},async sendNativeToken(e){f.I.pushTransactionStack({});const t=e.receiverAddress,s=p.U.state.address,i=g.x.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals));await g.x.sendTransaction({chainNamespace:"eip155",to:t,address:s,data:"0x",value:i??BigInt(0)}),m.E.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:p.U.state.preferredAccountTypes?.eip155===a.Vl.ACCOUNT_TYPES.SMART_ACCOUNT,token:v.state.token?.symbol||"",amount:e.sendTokenAmount,network:u.W.state.activeCaipNetwork?.caipNetworkId||""}}),g.x._getClient()?.updateBalance("eip155"),v.resetSend()},async sendERC20Token(e){f.I.pushTransactionStack({onSuccess(){f.I.replace("Account")}});const t=g.x.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals));if(p.U.state.address&&e.sendTokenAmount&&e.receiverAddress&&e.tokenAddress){const s=l.w.getPlainAddress(e.tokenAddress);await g.x.writeContract({fromAddress:p.U.state.address,tokenAddress:s,args:[e.receiverAddress,t??BigInt(0)],method:"transfer",abi:o.v.getERC20Abi(s),chainNamespace:"eip155"}),v.resetSend()}},async sendSolanaToken(){if(!v.state.sendTokenAmount||!v.state.receiverAddress)throw new Error("An amount and receiver address are required");f.I.pushTransactionStack({onSuccess(){f.I.replace("Account")}}),await g.x.sendTransaction({chainNamespace:"solana",to:v.state.receiverAddress,value:v.state.sendTokenAmount}),g.x._getClient()?.updateBalance("solana"),v.resetSend()},resetSend(){y.token=void 0,y.sendTokenAmount=void 0,y.receiverAddress=void 0,y.receiverProfileImageUrl=void 0,y.receiverProfileName=void 0,y.loading=!1,y.tokenBalances=[]}},v=(0,h.X)(b)},37834:(e,t,s)=>{s.d(t,{A:()=>r,X:()=>o});var i=s(63917);class r extends Error{constructor(e,t,s){super(e),this.name="AppKitError",this.category=t,this.originalError=s,Object.setPrototypeOf(this,r.prototype);let i=!1;if(s instanceof Error&&"string"==typeof s.stack&&s.stack){const e=s.stack,t=e.indexOf("\n");if(t>-1){const s=e.substring(t+1);this.stack=`${this.name}: ${this.message}\n${s}`,i=!0}}i||(Error.captureStackTrace?Error.captureStackTrace(this,r):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function n(e,t){const s=e instanceof r?e:new r(e instanceof Error?e.message:String(e),t,e);throw i.s.sendError(s,s.category),s}function o(e,t="INTERNAL_SDK_ERROR"){const s={};return Object.keys(e).forEach(i=>{const r=e[i];if("function"==typeof r){let e=r;e="AsyncFunction"===r.constructor.name?async(...e)=>{try{return await r(...e)}catch(e){return n(e,t)}}:(...e)=>{try{return r(...e)}catch(e){return n(e,t)}},s[i]=e}else s[i]=r}),s}},38097:(e,t,s)=>{s.d(t,{R:()=>h});var i=s(4443),r=s(30393),n=s(72269),o=s(98299),a=s(11847),c=s(82868);function l(e,t){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",e),s.searchParams.set("projectId",t),s.toString()}const d=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],h={extendRpcUrlWithProjectId(e,t){let s=!1;try{s="rpc.walletconnect.org"===new URL(e).host}catch(e){s=!1}if(s){const s=new URL(e);return s.searchParams.has("projectId")||s.searchParams.set("projectId",t),s.toString()}return e},isCaipNetwork:e=>"chainNamespace"in e&&"caipNetworkId"in e,getChainNamespace(e){return this.isCaipNetwork(e)?e.chainNamespace:n.o.CHAIN.EVM},getCaipNetworkId(e){return this.isCaipNetwork(e)?e.caipNetworkId:`${n.o.CHAIN.EVM}:${e.id}`},getDefaultRpcUrl(e,t,s){const i=e.rpcUrls?.default?.http?.[0];return d.includes(t)?l(t,s):i||""},extendCaipNetwork(e,{customNetworkImageUrls:t,projectId:s,customRpcUrls:i}){const r=this.getChainNamespace(e),n=this.getCaipNetworkId(e),o=e.rpcUrls.default.http?.[0],a=this.getDefaultRpcUrl(e,n,s),l=e?.rpcUrls?.chainDefault?.http?.[0]||o,d=i?.[n]?.map(e=>e.url)||[],h=[...d,a],p=[...d];return l&&!p.includes(l)&&p.push(l),{...e,chainNamespace:r,caipNetworkId:n,assets:{imageId:c.L.NetworkImageIds[e.id],imageUrl:t?.[e.id]},rpcUrls:{...e.rpcUrls,default:{http:h},chainDefault:{http:p}}}},extendCaipNetworks:(e,{customNetworkImageUrls:t,projectId:s,customRpcUrls:i})=>e.map(e=>h.extendCaipNetwork(e,{customNetworkImageUrls:t,customRpcUrls:i,projectId:s})),getViemTransport(e,t,s){const n=[];return s?.forEach(e=>{n.push((0,r.L)(e.url,e.config))}),d.includes(e.caipNetworkId)&&n.push((0,r.L)(l(e.caipNetworkId,t),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),e?.rpcUrls?.default?.http?.forEach(e=>{n.push((0,r.L)(e))}),(0,i.Np)(n)},extendWagmiTransports(e,t,s){if(d.includes(e.caipNetworkId)){const n=this.getDefaultRpcUrl(e,e.caipNetworkId,t);return(0,i.Np)([s,(0,r.L)(n)])}return s},getUnsupportedNetwork:e=>({id:e.split(":")[1],caipNetworkId:e,name:n.o.UNSUPPORTED_NETWORK_NAME,chainNamespace:e.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}),getCaipNetworkFromStorage(e){const t=a.i.getActiveCaipNetworkId(),s=o.W.getAllRequestedCaipNetworks(),i=Array.from(o.W.state.chains?.keys()||[]),r=t?.split(":")[0],n=!!r&&i.includes(r),c=s?.find(e=>e.caipNetworkId===t);return n&&!c&&t?this.getUnsupportedNetwork(t):c||e||s?.[0]}}},39030:(e,t,s)=>{s.d(t,{p:()=>r});const i=2147483648,r={convertEVMChainIdToCoinType(e){if(e>=i)throw new Error("Invalid chainId");return(i|e)>>>0}}},39194:(e,t,s)=>{s.d(t,{createAppKit:()=>n});var i=s(42594),r=s(11628);function n(e){return new i._({...e,basic:!0,sdkVersion:`html-core-${r.i}`})}},39275:(e,t,s)=>{function i(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}s.d(t,{x:()=>i})},41607:(e,t,s)=>{s.d(t,{g:()=>o});var i=s(72269),r=s(98299),n=s(79217);function o(e){const t=Array.from(r.W.state.chains.keys());let s=[];return e?(s.push([e,r.W.state.chains.get(e)]),(0,n.Q)(e,i.o.CONNECTOR_ID.WALLET_CONNECT)?t.forEach(t=>{t!==e&&(0,n.Q)(t,i.o.CONNECTOR_ID.WALLET_CONNECT)&&s.push([t,r.W.state.chains.get(t)])}):(0,n.Q)(e,i.o.CONNECTOR_ID.AUTH)&&t.forEach(t=>{t!==e&&(0,n.Q)(t,i.o.CONNECTOR_ID.AUTH)&&s.push([t,r.W.state.chains.get(t)])})):s=Array.from(r.W.state.chains.entries()),s}},42177:(e,t,s)=>{s.d(t,{o:()=>r});var i=s(39907);const r={ACCOUNT_TABS:[{label:"Tokens"},{label:"NFTs"},{label:"Activity"}],SECURE_SITE_ORIGIN:(void 0!==i&&void 0!==i.env?i.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}}},42594:(e,t,s)=>{s.d(t,{_:()=>l});var i=s(86792),r=s(83077),n=s(1420),o=s(22143),a=s(20475);let c=!1;class l extends a._{async open(e){r.a.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&i.x.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!c&&o.w.isClient()){if(await Promise.all([s.e(6484),s.e(674),s.e(8373)]).then(s.bind(s,58373)),await Promise.all([s.e(674),s.e(4150)]).then(s.bind(s,54150)),!document.querySelector("w3m-modal")){const e=document.createElement("w3m-modal");n.H.state.disableAppend||n.H.state.enableEmbedded||document.body.insertAdjacentElement("beforeend",e)}c=!0}}}},44242:(e,t,s)=>{s.d(t,{Aj:()=>i.A}),s(32523),s(42177);var i=s(84279)},47436:(e,t,s)=>{s.d(t,{D:()=>n});var i=s(3555),r=s(22143);const n={getFeatureValue(e,t){const s=t?.[e];return void 0===s?i.oU.DEFAULT_FEATURES[e]:s},filterSocialsByPlatform(e){if(!e||!e.length)return e;if(r.w.isTelegram()){if(r.w.isIos())return e.filter(e=>"google"!==e);if(r.w.isMac())return e.filter(e=>"x"!==e);if(r.w.isAndroid())return e.filter(e=>!["facebook","x"].includes(e))}return e}}},47981:(e,t,s)=>{s.d(t,{E:()=>m});var i=s(89168),r=s(72269),n=s(80971),o=s(22143),a=s(35646),c=s(23981),l=s(31100),d=s(1420);const h=o.w.getAnalyticsUrl(),p=new a.Z({baseUrl:h,clientId:null}),u=["MODAL_CREATED"],g=(0,i.BX)({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),m={state:g,subscribe:e=>(0,i.B1)(g,()=>e(g)),getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=d.H.state;return{projectId:e,st:t,sv:s||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(e){try{const t=c.U.state.address;if(u.includes(e.data.event)||"undefined"==typeof window)return;await p.post({path:"/e",params:m.getSdkProperties(),body:{eventId:o.w.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:e.timestamp,props:{...e.data,address:t}}}),g.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===r.o.HTTP_STATUS_CODES.FORBIDDEN&&!g.reportedErrors.FORBIDDEN&&(l.h.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${(0,n.IP)()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),g.reportedErrors.FORBIDDEN=!0)}},sendEvent(e){g.timestamp=Date.now(),g.data=e,d.H.state.features?.analytics&&m._sendAnalyticsEvent(g)}}},49402:(e,t,s)=>{s.d(t,{Rn0:()=>i.Rn,tWt:()=>i.tW});var i=s(94311);s(33868)},49951:(e,t,s)=>{s.d(t,{W:()=>l});var i=s(89168),r=s(80989),n=s(37834),o=s(83077);const a=(0,i.BX)({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),c={state:a,subscribe:e=>(0,i.B1)(a,()=>e(a)),setThemeMode(e){a.themeMode=e;try{const t=o.a.getAuthConnector();if(t){const s=c.getSnapshot().themeVariables;t.provider.syncTheme({themeMode:e,themeVariables:s,w3mThemeVariables:(0,r.o)(s,e)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(e){a.themeVariables={...a.themeVariables,...e};try{const e=o.a.getAuthConnector();if(e){const t=c.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:(0,r.o)(a.themeVariables,a.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot:()=>(0,i.P9)(a)},l=(0,n.X)(c)},51765:(e,t,s)=>{s.d(t,{y:()=>r});var i=s(83229);const r={getCaipTokens(e){if(!e)return;const t={};return Object.entries(e).forEach(([e,s])=>{t[`${i.o.EIP155}:${e}`]=s}),t},isLowerCaseMatch:(e,t)=>e?.toLowerCase()===t?.toLowerCase()}},52788:(e,t,s)=>{s.d(t,{AH:()=>i.AH,JW:()=>i.JW,WF:()=>i.WF,iz:()=>i.iz,qy:()=>i.qy}),s(58207),s(80181);var i=s(46477)},53561:(e,t,s)=>{s(93797),s(15179)},54947:(e,t,s)=>{s.d(t,{T:()=>r});var i=s(88612);const r={createBalance(e,t){const s={name:e.metadata.name||"",symbol:e.metadata.symbol||"",decimals:e.metadata.decimals||0,value:e.metadata.value||0,price:e.metadata.price||0,iconUrl:e.metadata.iconUrl||""};return{name:s.name,symbol:s.symbol,chainId:t,address:"native"===e.address?void 0:this.convertAddressToCAIP10Address(e.address,t),value:s.value,price:s.price,quantity:{decimals:s.decimals.toString(),numeric:this.convertHexToBalance({hex:e.balance,decimals:s.decimals})},iconUrl:s.iconUrl}},convertHexToBalance:({hex:e,decimals:t})=>(0,i.J)(BigInt(e),t),convertAddressToCAIP10Address:(e,t)=>`${t}:${e}`,createCAIP2ChainId:(e,t)=>`${t}:${parseInt(e,16)}`,getChainIdHexFromCAIP2ChainId(e){const t=e.split(":");if(t.length<2||!t[1])return"0x0";const s=t[1],i=parseInt(s,10);return isNaN(i)?"0x0":`0x${i.toString(16)}`},isWalletGetAssetsResponse(e){return"object"==typeof e&&null!==e&&Object.values(e).every(e=>Array.isArray(e)&&e.every(e=>this.isValidAsset(e)))},isValidAsset:e=>"object"==typeof e&&null!==e&&"string"==typeof e.address&&"string"==typeof e.balance&&("ERC20"===e.type||"NATIVE"===e.type)&&"object"==typeof e.metadata&&null!==e.metadata&&"string"==typeof e.metadata.name&&"string"==typeof e.metadata.symbol&&"number"==typeof e.metadata.decimals&&"number"==typeof e.metadata.price&&"string"==typeof e.metadata.iconUrl}},55611:(e,t,s)=>{s.d(t,{C:()=>i});const i={validateCaipAddress(e){if(3!==e.split(":")?.length)throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){const t=e.split(":");if(3!==t.length)throw new Error(`Invalid CAIP-10 address: ${e}`);const[s,i,r]=t;if(!s||!i||!r)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:s,chainId:i,address:r}},parseCaipNetworkId(e){const t=e.split(":");if(2!==t.length)throw new Error(`Invalid CAIP-2 network id: ${e}`);const[s,i]=t;if(!s||!i)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:s,chainId:i}}}},56335:(e,t,s)=>{s.d(t,{t:()=>i});const i=(0,s(39275).x)({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"})},60032:(e,t,s)=>{s.d(t,{L:()=>c});var i=s(72269),r=s(23981),n=s(98299),o=s(83077),a=s(72397);const c={onSwitchNetwork({network:e,ignoreSwitchConfirmation:t=!1}){const s=n.W.state.activeCaipNetwork,c=a.I.state.data;if(e.id===s?.id)return;const l=r.U.getCaipAddress(n.W.state.activeChain),d=e.chainNamespace!==n.W.state.activeChain,h=r.U.getCaipAddress(e.chainNamespace),p=o.a.getConnectorId(n.W.state.activeChain)===i.o.CONNECTOR_ID.AUTH,u=i.o.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(t=>t===e.chainNamespace);t||p&&u?a.I.push("SwitchNetwork",{...c,network:e}):l&&d&&!h?a.I.push("SwitchActiveChain",{switchToChain:e.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:e}):a.I.push("SwitchNetwork",{...c,network:e})}}},61387:(e,t,s)=>{s.d(t,{k:()=>o});var i=s(13766),r=s(49402);const n={solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"]},o={getMethodsByChainNamespace:e=>n[e]||[],createDefaultNamespace(e){return{methods:this.getMethodsByChainNamespace(e),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(e,t){if(!t)return{...e};const s={...e},i=new Set;if(t.methods&&Object.keys(t.methods).forEach(e=>i.add(e)),t.chains&&Object.keys(t.chains).forEach(e=>i.add(e)),t.events&&Object.keys(t.events).forEach(e=>i.add(e)),t.rpcMap&&Object.keys(t.rpcMap).forEach(e=>{const[t]=e.split(":");t&&i.add(t)}),i.forEach(e=>{s[e]||(s[e]=this.createDefaultNamespace(e))}),t.methods&&Object.entries(t.methods).forEach(([e,t])=>{s[e]&&(s[e].methods=t)}),t.chains&&Object.entries(t.chains).forEach(([e,t])=>{s[e]&&(s[e].chains=t)}),t.events&&Object.entries(t.events).forEach(([e,t])=>{s[e]&&(s[e].events=t)}),t.rpcMap){const e=new Set;Object.entries(t.rpcMap).forEach(([t,i])=>{const[r,n]=t.split(":");r&&n&&s[r]&&(s[r].rpcMap||(s[r].rpcMap={}),e.has(r)||(s[r].rpcMap={},e.add(r)),s[r].rpcMap[n]=i)})}return s},createNamespaces(e,t){const s=e.reduce((e,t)=>{const{id:s,chainNamespace:i,rpcUrls:n}=t,o=n.default.http[0];e[i]||(e[i]=this.createDefaultNamespace(i));const a=`${i}:${s}`,c=e[i];switch(c.chains.push(a),a){case r.tWt.caipNetworkId:c.chains.push(r.tWt.deprecatedCaipNetworkId);break;case r.Rn0.caipNetworkId:c.chains.push(r.Rn0.deprecatedCaipNetworkId)}return c?.rpcMap&&o&&(c.rpcMap[s]=o),e},{});return this.applyNamespaceOverrides(s,t)},resolveReownName:async e=>{const t=await i.f.resolveName(e),s=Object.values(t?.addresses)||[];return s[0]?.address||!1},getChainsFromNamespaces:(e={})=>Object.values(e).flatMap(e=>{const t=e.chains||[],s=e.accounts.map(e=>{const[t,s]=e.split(":");return`${t}:${s}`});return Array.from(new Set([...t,...s]))}),isSessionEventData:e=>"object"==typeof e&&null!==e&&"id"in e&&"topic"in e&&"params"in e&&"object"==typeof e.params&&null!==e.params&&"chainId"in e.params&&"event"in e.params&&"object"==typeof e.params.event&&null!==e.params.event,isOriginAllowed(e,t,s){for(const i of[...t,...s])if(i.includes("*")){const t=`^${i.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(t,"u").test(e))return!0}else try{if(new URL(i).origin===e)return!0}catch(t){if(i===e)return!0}return!1}}},62410:(e,t,s)=>{s.d(t,{x:()=>c});var i=s(93474),r=s(31100),n=s(3555);const o=["email","socials","swaps","onramp","activity","reownBranding"],a={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return Boolean(e.isEnabled)&&t.includes("email")},processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.email:Boolean(e)},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t.filter(e=>"email"!==e)},processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.socials:"boolean"==typeof e?!!e&&n.oU.DEFAULT_REMOTE_FEATURES.socials:e},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t},processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.swaps:"boolean"==typeof e?!!e&&n.oU.DEFAULT_REMOTE_FEATURES.swaps:e},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t},processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.onramp:"boolean"==typeof e?!!e&&n.oU.DEFAULT_REMOTE_FEATURES.onramp:e},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.activity:Boolean(e)},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.reownBranding:Boolean(e)}},c={localSettingsOverridden:new Set,getApiConfig:(e,t)=>t?.find(t=>t.id===e),addWarning(e,t){if(void 0!==e){const e=a[t],s=e.isLegacy?`"features.${e.localFeatureName}" (now "${t}")`:`"features.${t}"`;this.localSettingsOverridden.add(s)}},processFeature(e,t,s,i,r){const n=a[e],o=t[n.localFeatureName];if(r&&!n.isAvailableOnBasic)return!1;if(i){const t=this.getApiConfig(n.apiFeatureName,s);return null===t?.config?this.processFallbackFeature(e,o):!!t?.config&&(void 0!==o&&this.addWarning(o,e),this.processApiFeature(e,t))}return this.processFallbackFeature(e,o)},processApiFeature:(e,t)=>a[e].processApi(t),processFallbackFeature:(e,t)=>a[e].processFallback(t),async fetchRemoteFeatures(e){const t=e.basic??!1,s=e.features||{};this.localSettingsOverridden.clear();let a=null,c=!1;try{a=await i.N.fetchProjectConfig(),c=null!=a}catch(e){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",e)}const l=c&&!t?n.oU.DEFAULT_REMOTE_FEATURES:n.oU.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const e of o){const i=this.processFeature(e,s,a,c,t);Object.assign(l,{[e]:i})}}catch(e){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",e),n.oU.DEFAULT_REMOTE_FEATURES}if(c&&this.localSettingsOverridden.size>0){const e=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;r.h.open({shortMessage:"Local configuration ignored",longMessage:`[Reown Config Notice] ${e}`},"warning")}return l}}},63917:(e,t,s)=>{s.d(t,{s:()=>h});var i=s(89168),r=s(39150),n=s(22143),o=s(35646),a=s(1420);const c=Object.freeze({enabled:!0,events:[]}),l=new o.Z({baseUrl:n.w.getAnalyticsUrl(),clientId:null}),d=(0,i.BX)({...c}),h={state:d,subscribeKey:(e,t)=>(0,r.u$)(d,e,t),async sendError(e,t){if(!d.enabled)return;const s=Date.now();if(d.events.filter(e=>{const t=new Date(e.properties.timestamp||"").getTime();return s-t<6e4}).length>=5)return;const i={type:"error",event:t,properties:{errorType:e.name,errorMessage:e.message,stackTrace:e.stack,timestamp:(new Date).toISOString()}};d.events.push(i);try{if("undefined"==typeof window)return;const{projectId:s,sdkType:i,sdkVersion:r}=a.H.state;await l.post({path:"/e",params:{projectId:s,st:i,sv:r||"html-wagmi-4.2.2"},body:{eventId:n.w.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:(new Date).toISOString(),props:{type:"error",event:t,errorType:e.name,errorMessage:e.message,stackTrace:e.stack}}})}catch{}},enable(){d.enabled=!0},disable(){d.enabled=!1},clearEvents(){d.events=[]}}},64525:(e,t,s)=>{s.d(t,{R:()=>i});const i=(0,s(39275).x)({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"})},65508:(e,t,s)=>{(0,s(39275).x)({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"})},67232:(e,t,s)=>{s.d(t,{JX:()=>l,RF:()=>c,W5:()=>p,ck:()=>g,ds:()=>d,fD:()=>u});var i=s(52788),r=s(80989);let n,o,a;function c(e,t){n=document.createElement("style"),o=document.createElement("style"),a=document.createElement("style"),n.textContent=h(e).core.cssText,o.textContent=h(e).dark.cssText,a.textContent=h(e).light.cssText,document.head.appendChild(n),document.head.appendChild(o),document.head.appendChild(a),l(t)}function l(e){o&&a&&("light"===e?(o.removeAttribute("media"),a.media="enabled"):(a.removeAttribute("media"),o.media="enabled"))}function d(e){n&&o&&a&&(n.textContent=h(e).core.cssText,o.textContent=h(e).dark.cssText,a.textContent=h(e).light.cssText)}function h(e){return{core:i.AH`
2
+ export const __webpack_esm_id__=9194;export const __webpack_esm_ids__=[9194];export const __webpack_esm_modules__={1420:(e,t,s)=>{s.d(t,{H:()=>c});var i=s(89168),r=s(39150),n=s(3555),o=s(47436);const a=(0,i.BX)({features:n.oU.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:n.oU.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),c={state:a,subscribeKey:(e,t)=>(0,r.u$)(a,e,t),setOptions(e){Object.assign(a,e)},setRemoteFeatures(e){if(!e)return;const t={...a.remoteFeatures,...e};a.remoteFeatures=t,a.remoteFeatures?.socials&&(a.remoteFeatures.socials=o.D.filterSocialsByPlatform(a.remoteFeatures.socials))},setFeatures(e){if(!e)return;a.features||(a.features=n.oU.DEFAULT_FEATURES);const t={...a.features,...e};a.features=t},setProjectId(e){a.projectId=e},setCustomRpcUrls(e){a.customRpcUrls=e},setAllWallets(e){a.allWallets=e},setIncludeWalletIds(e){a.includeWalletIds=e},setExcludeWalletIds(e){a.excludeWalletIds=e},setFeaturedWalletIds(e){a.featuredWalletIds=e},setTokens(e){a.tokens=e},setTermsConditionsUrl(e){a.termsConditionsUrl=e},setPrivacyPolicyUrl(e){a.privacyPolicyUrl=e},setCustomWallets(e){a.customWallets=e},setIsSiweEnabled(e){a.isSiweEnabled=e},setIsUniversalProvider(e){a.isUniversalProvider=e},setSdkVersion(e){a.sdkVersion=e},setMetadata(e){a.metadata=e},setDisableAppend(e){a.disableAppend=e},setEIP6963Enabled(e){a.enableEIP6963=e},setDebug(e){a.debug=e},setEnableWalletConnect(e){a.enableWalletConnect=e},setEnableWalletGuide(e){a.enableWalletGuide=e},setEnableAuthLogger(e){a.enableAuthLogger=e},setEnableWallets(e){a.enableWallets=e},setPreferUniversalLinks(e){a.experimental_preferUniversalLinks=e},setHasMultipleAddresses(e){a.hasMultipleAddresses=e},setSIWX(e){a.siwx=e},setConnectMethodsOrder(e){a.features={...a.features,connectMethodsOrder:e}},setWalletFeaturesOrder(e){a.features={...a.features,walletFeaturesOrder:e}},setSocialsOrder(e){a.remoteFeatures={...a.remoteFeatures,socials:e}},setCollapseWallets(e){a.features={...a.features,collapseWallets:e}},setEnableEmbedded(e){a.enableEmbedded=e},setAllowUnsupportedChain(e){a.allowUnsupportedChain=e},setManualWCControl(e){a.manualWCControl=e},setEnableNetworkSwitch(e){a.enableNetworkSwitch=e},setDefaultAccountTypes(e={}){Object.entries(e).forEach(([e,t])=>{t&&(a.defaultAccountTypes[e]=t)})},setUniversalProviderConfigOverride(e){a.universalProviderConfigOverride=e},getUniversalProviderConfigOverride:()=>a.universalProviderConfigOverride,getSnapshot:()=>(0,i.P9)(a)}},1435:(e,t,s)=>{s.d(t,{E:()=>i});const i={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]}},2974:(e,t,s)=>{s.d(t,{r:()=>r});var i=s(70255);const r={createLogger(e,t="error"){const s=(0,i.iP)({level:t}),{logger:r}=(0,i.D5)({opts:s});return r.error=(...t)=>{for(const s of t)if(s instanceof Error)return void e(s,...t);e(void 0,...t)},r}}},3555:(e,t,s)=>{s.d(t,{Db:()=>o,oU:()=>a,tM:()=>n});var i=s(39907);const r=(void 0!==i&&void 0!==i.env?i.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",n=[{label:"Coinbase",name:"coinbase",feeRange:"1-2%",url:"",supportedChains:["eip155"]},{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],o="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",a={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:r,SECURE_SITE_DASHBOARD:`${r}/dashboard`,SECURE_SITE_FAVICON:`${r}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],WC_COINBASE_PAY_SDK_CHAINS:["ethereum","arbitrum","polygon","berachain","avalanche-c-chain","optimism","celo","base"],WC_COINBASE_PAY_SDK_FALLBACK_CHAIN:"ethereum",WC_COINBASE_PAY_SDK_CHAIN_NAME_MAP:{Ethereum:"ethereum","Arbitrum One":"arbitrum",Polygon:"polygon",Berachain:"berachain",Avalanche:"avalanche-c-chain","OP Mainnet":"optimism",Celo:"celo",Base:"base"},WC_COINBASE_ONRAMP_APP_ID:"bf18c88d-495a-463b-b249-0b9d3656cf5e",SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:["eip155","solana"],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:["eip155"],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:["eip155","solana"],ACTIVITY_ENABLED_CHAIN_NAMESPACES:["eip155"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:["eip155","solana"],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["coinbase","meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"}}},4159:(e,t,s)=>{s.d(t,{S:()=>r});var i=s(66857);const r={bigNumber:e=>e?new i.A(e):new i.A(0),multiply(e,t){if(void 0===e||void 0===t)return new i.A(0);const s=new i.A(e),r=new i.A(t);return s.times(r)},formatNumberToLocalString:(e,t=2)=>void 0===e?"0.00":"number"==typeof e?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t}),parseLocalStringToNumber:e=>void 0===e?0:parseFloat(e.replace(/,/gu,""))}},6262:(e,t,s)=>{s.d(t,{j:()=>c});var i=s(89168),r=s(39150),n=s(37834);const o=(0,i.BX)({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),a={state:o,subscribeNetworkImages:e=>(0,i.B1)(o.networkImages,()=>e(o.networkImages)),subscribeKey:(e,t)=>(0,r.u$)(o,e,t),subscribe:e=>(0,i.B1)(o,()=>e(o)),setWalletImage(e,t){o.walletImages[e]=t},setNetworkImage(e,t){o.networkImages[e]=t},setChainImage(e,t){o.chainImages[e]=t},setConnectorImage(e,t){o.connectorImages={...o.connectorImages,[e]:t}},setTokenImage(e,t){o.tokenImages[e]=t},setCurrencyImage(e,t){o.currencyImages[e]=t}},c=(0,n.X)(a)},9732:(e,t,s)=>{s.d(t,{O:()=>r,W:()=>n});var i=s(72269);const r={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},n={handleMobileDeeplinkRedirect(e,t){const s=window.location.href,n=encodeURIComponent(s);if(e===r.PHANTOM.id&&!("phantom"in window)){const e=s.startsWith("https")?"https":"http",t=s.split("/")[2],i=encodeURIComponent(`${e}://${t}`);window.location.href=`${r.PHANTOM.url}/ul/browse/${n}?ref=${i}`}e!==r.SOLFLARE.id||"solflare"in window||(window.location.href=`${r.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),t===i.o.CHAIN.SOLANA&&(e!==r.COINBASE.id||"coinbaseSolana"in window||(window.location.href=`${r.COINBASE.url}/dapp?cb_url=${n}`))}}},11148:(e,t,s)=>{s.d(t,{t:()=>c});var i=s(46362),r=s(16444),n=s(98299),o=s(86792),a=s(54947);const c={async getMyTokensWithBalance(e){const t=i.U.state.address,s=n.W.state.activeCaipNetwork;if(!t||!s)return[];if("eip155"===s.chainNamespace){const e=await this.getEIP155Balances(t,s);if(e)return this.filterLowQualityTokens(e)}const o=await r.T.getBalance(t,s.caipNetworkId,e);return this.filterLowQualityTokens(o.balances)},async getEIP155Balances(e,t){try{const s=a.T.getChainIdHexFromCAIP2ChainId(t.caipNetworkId),i=await o.x.getCapabilities(e);if(!i?.[s]?.assetDiscovery?.supported)return null;const r=await o.x.walletGetAssets({account:e,chainFilter:[s]});return a.T.isWalletGetAssetsResponse(r)?(r[s]||[]).map(e=>a.T.createBalance(e,t.caipNetworkId)):null}catch(e){return null}},filterLowQualityTokens:e=>e.filter(e=>"0"!==e.quantity.decimals),mapBalancesToSwapTokens:e=>e?.map(e=>({...e,address:e?.address?e.address:n.W.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]}},11628:(e,t,s)=>{s.d(t,{i:()=>i});const i="1.7.8"},11847:(e,t,s)=>{s.d(t,{i:()=>r});var i=s(80971);const r={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired:(e,t)=>Date.now()-e>t,getActiveNetworkProps(){const e=r.getActiveNamespace(),t=r.getActiveCaipNetworkId(),s=t?t.split(":")[1]:void 0;return{namespace:e,caipNetworkId:t,chainId:s?isNaN(Number(s))?s:Number(s):void 0}},setWalletConnectDeepLink({name:e,href:t}){try{i.Ud.setItem(i.Ws.DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const e=i.Ud.getItem(i.Ws.DEEPLINK_CHOICE);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{i.Ud.removeItem(i.Ws.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{i.Ud.setItem(i.Ws.ACTIVE_NAMESPACE,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{i.Ud.setItem(i.Ws.ACTIVE_CAIP_NETWORK_ID,e),r.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return i.Ud.getItem(i.Ws.ACTIVE_CAIP_NETWORK_ID)}catch{return void console.info("Unable to get active caip network id")}},deleteActiveCaipNetworkId(){try{i.Ud.removeItem(i.Ws.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{const t=(0,i.T8)(e);i.Ud.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{const t=r.getRecentWallets();t.find(t=>t.id===e.id)||(t.unshift(e),t.length>2&&t.pop(),i.Ud.setItem(i.Ws.RECENT_WALLETS,JSON.stringify(t)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const e=i.Ud.getItem(i.Ws.RECENT_WALLETS);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(e,t){try{const s=(0,i.T8)(e);i.Ud.setItem(s,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return i.Ud.getItem(i.Ws.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{const t=(0,i.T8)(e);return i.Ud.getItem(t)}catch(t){console.info("Unable to get connected connector id in namespace ",e)}},setConnectedSocialProvider(e){try{i.Ud.setItem(i.Ws.CONNECTED_SOCIAL,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return i.Ud.getItem(i.Ws.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{i.Ud.removeItem(i.Ws.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return i.Ud.getItem(i.Ws.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){const e=i.Ud.getItem(i.Ws.ACTIVE_CAIP_NETWORK_ID),t=e?.split(":")?.[1];return t},setConnectionStatus(e){try{i.Ud.setItem(i.Ws.CONNECTION_STATUS,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return i.Ud.getItem(i.Ws.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const e=i.Ud.getItem(i.Ws.CONNECTED_NAMESPACES);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));i.Ud.setItem(i.Ws.CONNECTED_NAMESPACES,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{const t=r.getConnectedNamespaces();t.includes(e)||(t.push(e),r.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{const t=r.getConnectedNamespaces(),s=t.indexOf(e);s>-1&&(t.splice(s,1),r.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return i.Ud.getItem(i.Ws.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{i.Ud.setItem(i.Ws.TELEGRAM_SOCIAL_PROVIDER,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{i.Ud.removeItem(i.Ws.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{const t=i.Ud.getItem(i.Ws.PORTFOLIO_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{const t=r.getBalanceCache();i.Ud.setItem(i.Ws.PORTFOLIO_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{const t=r.getBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;r.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{const t=r.getBalanceCache();t[e.caipAddress]=e,i.Ud.setItem(i.Ws.PORTFOLIO_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{const t=i.Ud.getItem(i.Ws.NATIVE_BALANCE_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{const t=r.getBalanceCache();i.Ud.setItem(i.Ws.NATIVE_BALANCE_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getNativeBalanceCacheForCaipAddress(e){try{const t=r.getNativeBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",e),r.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{const t=r.getNativeBalanceCache();t[e.caipAddress]=e,i.Ud.setItem(i.Ws.NATIVE_BALANCE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{const t=i.Ud.getItem(i.Ws.ENS_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{const t=r.getEnsCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;r.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{const t=r.getEnsCache();t[e.address]=e,i.Ud.setItem(i.Ws.ENS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{const t=r.getEnsCache();i.Ud.setItem(i.Ws.ENS_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove ens name from cache",e)}},getIdentityCache(){let e={};try{const t=i.Ud.getItem(i.Ws.IDENTITY_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{const t=r.getIdentityCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;r.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{const t=r.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},i.Ud.setItem(i.Ws.IDENTITY_CACHE,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{const t=r.getIdentityCache();i.Ud.setItem(i.Ws.IDENTITY_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},clearAddressCache(){try{i.Ud.removeItem(i.Ws.PORTFOLIO_CACHE),i.Ud.removeItem(i.Ws.NATIVE_BALANCE_CACHE),i.Ud.removeItem(i.Ws.ENS_CACHE),i.Ud.removeItem(i.Ws.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{i.Ud.setItem(i.Ws.PREFERRED_ACCOUNT_TYPES,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{const e=i.Ud.getItem(i.Ws.PREFERRED_ACCOUNT_TYPES);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{const s={...r.getConnections(),[t]:e};i.Ud.setItem(i.Ws.CONNECTIONS,JSON.stringify(s))}catch(e){console.error("Unable to sync connections to storage",e)}},getConnections(){try{const e=i.Ud.getItem(i.Ws.CONNECTIONS);return e?JSON.parse(e):{}}catch(e){return console.error("Unable to get connections from storage",e),{}}}}},13679:(e,t,s)=>{function i(e){return function(t){return"function"==typeof t?function(e,t){return customElements.get(e)||customElements.define(e,t),t}(e,t):function(e,t){const{kind:s,elements:i}=t;return{kind:s,elements:i,finisher(t){customElements.get(e)||customElements.define(e,t)}}}(e,t)}}s.d(t,{E:()=>i})},13766:(e,t,s)=>{s.d(t,{f:()=>f});var i=s(89168),r=s(39150),n=s(39030),o=s(11847),a=s(37834),c=s(46362),l=s(16444),d=s(98299),h=s(86792),p=s(83077),u=s(72397);const g=(0,i.BX)({suggestions:[],loading:!1}),m={state:g,subscribe:e=>(0,i.B1)(g,()=>e(g)),subscribeKey:(e,t)=>(0,r.u$)(g,e,t),async resolveName(e){try{return await l.T.lookupEnsName(e)}catch(e){const t=e;throw new Error(t?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(e){try{return await l.T.lookupEnsName(e),!0}catch{return!1}},async getSuggestions(e){try{g.loading=!0,g.suggestions=[];const t=await l.T.getEnsNameSuggestions(e);return g.suggestions=t.suggestions.map(e=>({...e,name:e.name}))||[],g.suggestions}catch(e){const t=f.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(t)}finally{g.loading=!1}},async getNamesForAddress(e){try{if(!d.W.state.activeCaipNetwork)return[];const t=o.i.getEnsFromCacheForAddress(e);if(t)return t;const s=await l.T.reverseLookupEnsName({address:e});return o.i.updateEnsCache({address:e,ens:s,timestamp:Date.now()}),s}catch(e){const t=f.parseEnsApiError(e,"Error fetching names for address");throw new Error(t)}},async registerName(e){const t=d.W.state.activeCaipNetwork;if(!t)throw new Error("Network not found");const s=c.U.state.address,i=p.a.getAuthConnector();if(!s||!i)throw new Error("Address or auth connector not found");g.loading=!0;try{const i=JSON.stringify({name:e,attributes:{},timestamp:Math.floor(Date.now()/1e3)});u.I.pushTransactionStack({onCancel(){u.I.replace("RegisterAccountName")}});const r=await h.x.signMessage(i);g.loading=!1;const o=t.id;if(!o)throw new Error("Network not found");const a=n.p.convertEVMChainIdToCoinType(Number(o));await l.T.registerEnsName({coinType:a,address:s,signature:r,message:i}),c.U.setProfileName(e,t.chainNamespace),u.I.replace("RegisterAccountNameSuccess")}catch(t){const s=f.parseEnsApiError(t,`Error registering name ${e}`);throw u.I.replace("RegisterAccountName"),new Error(s)}finally{g.loading=!1}},validateName:e=>/^[a-zA-Z0-9-]{4,}$/u.test(e),parseEnsApiError(e,t){const s=e;return s?.reasons?.[0]?.description||t}},f=(0,a.X)(m)},15179:(e,t,s)=>{s.d(t,{Z:()=>i});const i={getSpacingStyles:(e,t)=>Array.isArray(e)?e[t]?`var(--wui-spacing-${e[t]})`:void 0:"string"==typeof e?`var(--wui-spacing-${e})`:void 0,getFormattedDate:e=>new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}).format(e),getHostName(e){try{return new URL(e).hostname}catch(e){return""}},getTruncateString:({string:e,charsStart:t,charsEnd:s,truncate:i})=>e.length<=t+s?e:"end"===i?`${e.substring(0,t)}...`:"start"===i?`...${e.substring(e.length-s)}`:`${e.substring(0,Math.floor(t))}...${e.substring(e.length-Math.floor(s))}`,generateAvatarColors(e){const t=e.toLowerCase().replace(/^0x/iu,"").replace(/[^a-f0-9]/gu,"").substring(0,6).padEnd(6,"0"),s=this.hexToRgb(t),i=getComputedStyle(document.documentElement).getPropertyValue("--w3m-border-radius-master"),r=100-3*Number(i?.replace("px","")),n=`${r}% ${r}% at 65% 40%`,o=[];for(let e=0;e<5;e+=1){const t=this.tintColor(s,.15*e);o.push(`rgb(${t[0]}, ${t[1]}, ${t[2]})`)}return`\n --local-color-1: ${o[0]};\n --local-color-2: ${o[1]};\n --local-color-3: ${o[2]};\n --local-color-4: ${o[3]};\n --local-color-5: ${o[4]};\n --local-radial-circle: ${n}\n `},hexToRgb(e){const t=parseInt(e,16);return[t>>16&255,t>>8&255,255&t]},tintColor(e,t){const[s,i,r]=e;return[Math.round(s+(255-s)*t),Math.round(i+(255-i)*t),Math.round(r+(255-r)*t)]},isNumber:e=>/^[0-9]+$/u.test(e),getColorTheme:e=>e||("undefined"!=typeof window&&window.matchMedia?window.matchMedia("(prefers-color-scheme: dark)")?.matches?"dark":"light":"dark"),splitBalance(e){const t=e.split(".");return 2===t.length?[t[0],t[1]]:["0","00"]},roundNumber:(e,t,s)=>e.toString().length>=t?Number(e).toFixed(s):e,formatNumberToLocalString:(e,t=2)=>void 0===e?"0.00":"number"==typeof e?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t})}},15529:(e,t,s)=>{s.d(t,{$Bq:()=>or,$hI:()=>te,ADD:()=>z,ALl:()=>Wi,AYU:()=>xr,Alu:()=>Hr,AwN:()=>Ji,BdH:()=>x,C5G:()=>Gi,CTo:()=>Ur,Ds_:()=>L,EHS:()=>Pi,EN$:()=>Li,EWt:()=>Ii,F$L:()=>Vi,FR8:()=>Gr,FiO:()=>jr,GuA:()=>Nr,HNf:()=>kr,Hbs:()=>en,Hjj:()=>Ar,IjX:()=>et,K3g:()=>F,Lln:()=>T,Lp_:()=>Si,M8n:()=>Kr,OP1:()=>_r,PAk:()=>qe,PUk:()=>$,Pa8:()=>Ni,QJh:()=>nr,Qhg:()=>Tr,R7U:()=>D,TRk:()=>Z,TZl:()=>xi,TeY:()=>Fr,Tw2:()=>Fi,U0i:()=>Zi,V7m:()=>Xi,V9G:()=>$r,VBM:()=>dt,Van:()=>vr,WWN:()=>lt,Wx8:()=>H,X3c:()=>Vr,XEe:()=>Er,XqR:()=>Zr,Xw0:()=>J,YcA:()=>Hi,_Yb:()=>m,_dF:()=>X,aF0:()=>Sr,aRZ:()=>R,aa1:()=>tr,b07:()=>Pr,bEt:()=>Ci,c82:()=>G,e8_:()=>ot,esh:()=>Br,gOF:()=>K,gZm:()=>se,h0Y:()=>q,hEn:()=>Y,hVC:()=>at,hwK:()=>tt,iV1:()=>zr,iui:()=>Ki,jTh:()=>ee,jUZ:()=>B,kob:()=>yr,kuU:()=>qr,lFF:()=>W,lVv:()=>O,m01:()=>k,mr0:()=>Dr,n3s:()=>Q,n6V:()=>er,nWe:()=>wr,nyL:()=>on,oKp:()=>Xr,ojD:()=>M,ovp:()=>Di,ps1:()=>Yi,q_h:()=>Qe,sKr:()=>rn,sc7:()=>tn,sc_:()=>ct,tLy:()=>Jr,tk0:()=>Lr,two:()=>Ui,uym:()=>sn,w8K:()=>ie,wYp:()=>ir,wa2:()=>$i,x0t:()=>Bi,xkc:()=>Ze,yy4:()=>ne,z2N:()=>Yr});var i=s(24661),r=s(91315),n=s(20635),o=s(67822),a=s(71268),c=s(33244),l=s(97353),d=s(1030),h=s(17367),p=s(39907),u=s(48526).hp;const g=":";function m(e){const[t,s]=e.split(g);return{namespace:t,reference:s}}function f(e,t){return e.includes(":")?[e]:t.chains||[]}var w=Object.defineProperty,y=Object.defineProperties,b=Object.getOwnPropertyDescriptors,v=Object.getOwnPropertySymbols,E=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable,I=(e,t,s)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,N=(e,t)=>{for(var s in t||(t={}))E.call(t,s)&&I(e,s,t[s]);if(v)for(var s of v(t))C.call(t,s)&&I(e,s,t[s]);return e},A=(e,t)=>y(e,b(t));const _="ReactNative",S={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},P="js";function T(){return typeof p<"u"&&typeof p.versions<"u"&&typeof p.versions.node<"u"}function O(){return!(0,n.getDocument)()&&!!(0,n.getNavigator)()&&navigator.product===_}function k(){return O()&&typeof s.g<"u"&&typeof(null==s.g?void 0:s.g.Platform)<"u"&&"android"===(null==s.g?void 0:s.g.Platform.OS)}function R(){return O()&&typeof s.g<"u"&&typeof(null==s.g?void 0:s.g.Platform)<"u"&&"ios"===(null==s.g?void 0:s.g.Platform.OS)}function x(){return!T()&&!!(0,n.getNavigator)()&&!!(0,n.getDocument)()}function U(){return O()?S.reactNative:T()?S.node:x()?S.browser:S.unknown}function D(){var e;try{return O()&&typeof s.g<"u"&&typeof(null==s.g?void 0:s.g.Application)<"u"?null==(e=s.g.Application)?void 0:e.applicationId:void 0}catch{return}}function L(e){var t,s;const i=W();try{return null!=e&&e.url&&i.url&&new URL(e.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),e.url=i.url),null!=(t=e?.icons)&&t.length&&e.icons.length>0&&(e.icons=e.icons.filter(e=>""!==e)),A(N(N({},i),e),{url:e?.url||i.url,name:e?.name||i.name,description:e?.description||i.description,icons:null!=(s=e?.icons)&&s.length&&e.icons.length>0?e.icons:i.icons})}catch(t){return console.warn("Error populating app metadata",t),e||i}}function W(){return(0,o.g)()||{name:"",description:"",url:"",icons:[""]}}function M(e,t,r){const o=function(){if(U()===S.reactNative&&typeof s.g<"u"&&typeof(null==s.g?void 0:s.g.Platform)<"u"){const{OS:e,Version:t}=s.g.Platform;return[e,t].join("-")}const e=(0,i.o0)();if(null===e)return"unknown";const t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[t,e.name,e.version].join("-"):[t,e.version].join("-")}(),a=function(){var e;const t=U();return t===S.browser?[t,(null==(e=(0,n.getLocation)())?void 0:e.host)||"unknown"].join(":"):t}();return[[e,t].join("-"),[P,r].join("-"),o,a].join("/")}function B({protocol:e,version:t,relayUrl:s,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d={auth:r,ua:M(e,t,i),projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=function(e,t){const s=new URLSearchParams(e);for(const e of Object.keys(t).sort())if(t.hasOwnProperty(e)){const i=t[e];void 0!==i&&s.set(e,i)}return s.toString()}(l[1]||"",d);return l[0]+"?"+h}function j(e,t){return e.filter(e=>t.includes(e)).length===e.length}function q(e){return Object.fromEntries(e.entries())}function $(e){return new Map(Object.entries(e))}function H(e=r.FIVE_MINUTES,t){const s=(0,r.toMiliseconds)(e||r.FIVE_MINUTES);let i,n,o,a;return{resolve:e=>{o&&i&&(clearTimeout(o),i(e),a=Promise.resolve(e))},reject:e=>{o&&n&&(clearTimeout(o),n(e))},done:()=>new Promise((e,r)=>{if(a)return e(a);o=setTimeout(()=>{const e=new Error(t);a=Promise.reject(e),r(e)},s),i=e,n=r})}}function F(e,t,s){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(s)),t);try{i(await e)}catch(e){r(e)}clearTimeout(n)})}function V(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function z(e){return V("topic",e)}function K(e){return V("id",e)}function G(e){const[t,s]=e.split(":"),i={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof s)i.topic=s;else{if("id"!==t||!Number.isInteger(Number(s)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${s}`);i.id=Number(s)}return i}function J(e,t){return(0,r.fromMiliseconds)((t||Date.now())+(0,r.toMiliseconds)(e))}function X(e){return Date.now()>=(0,r.toMiliseconds)(e)}function Y(e,t){return`${e}${t?`:${t}`:""}`}function Z(e=[],t=[]){return[...new Set([...e,...t])]}async function Q({id:e,topic:t,wcDeepLink:i}){var r;try{if(!i)return;const o="string"==typeof i?JSON.parse(i):i,a=o?.href;if("string"!=typeof a)return;const c=function(e,t,s){const i=`requestId=${t}&sessionTopic=${s}`;e.endsWith("/")&&(e=e.slice(0,-1));let r=`${e}`;return r=e.startsWith("https://t.me")?`${r}${e.includes("?")?"&startapp=":"?startapp="}${function(e,t=!1){const s=u.from(e).toString("base64");return t?s.replace(/[=]/g,""):s}(i,!0)}`:`${r}/wc?${i}`,r}(a,e,t),l=U();if(l===S.browser){if(null==(r=(0,n.getDocument)())||!r.hasFocus())return void console.warn("Document does not have focus, skipping deeplink.");!function(e){let t="_self";!function(){try{return window.self!==window.top}catch{return!1}}()?(typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"):t="_top",window.open(e,t,"noreferrer noopener")}(c)}else l===S.reactNative&&typeof(null==s.g?void 0:s.g.Linking)<"u"&&await s.g.Linking.openURL(c)}catch(e){console.error(e)}}async function ee(e,t){let s="";try{if(x()&&(s=localStorage.getItem(t),s))return s;s=await e.getItem(t)}catch(e){console.error(e)}return s}function te(e,t){if(!e.includes(t))return null;const s=e.split(/([&,?,=])/),i=s.indexOf(t);return s[i+2]}function se(){return typeof crypto<"u"&&null!=crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function ie(){return typeof p<"u"&&"true"===p.env.IS_VITEST}function re(e){return u.from(e,"base64").toString("utf-8")}function ne(e){return new Promise(t=>setTimeout(t,e))}function oe(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ae(e,...t){if(!function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ce(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");oe(e.outputLen),oe(e.blockLen)}function le(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function de(e,t){ae(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const he=BigInt(2**32-1),pe=BigInt(32);function ue(e,t=!1){return t?{h:Number(e&he),l:Number(e>>pe&he)}:{h:0|Number(e>>pe&he),l:0|Number(e&he)}}const ge="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function me(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function fe(e,t){return e<<32-t|e>>>t}const we=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function ye(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function be(e){for(let t=0;t<e.length;t++)e[t]=ye(e[t])}function ve(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),ae(e),e}class Ee{clone(){return this._cloneInto()}}function Ce(e){const t=t=>e().update(ve(t)).digest(),s=e();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>e(),t}function Ie(e=32){if(ge&&"function"==typeof ge.getRandomValues)return ge.getRandomValues(new Uint8Array(e));if(ge&&"function"==typeof ge.randomBytes)return ge.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}const Ne=[],Ae=[],_e=[],Se=BigInt(0),Pe=BigInt(1),Te=BigInt(2),Oe=BigInt(7),ke=BigInt(256),Re=BigInt(113);for(let e=0,t=Pe,s=1,i=0;e<24;e++){[s,i]=[i,(2*s+3*i)%5],Ne.push(2*(5*i+s)),Ae.push((e+1)*(e+2)/2%64);let r=Se;for(let e=0;e<7;e++)t=(t<<Pe^(t>>Oe)*Re)%ke,t&Te&&(r^=Pe<<(Pe<<BigInt(e))-Pe);_e.push(r)}const[xe,Ue]=function(e,t=!1){let s=new Uint32Array(e.length),i=new Uint32Array(e.length);for(let r=0;r<e.length;r++){const{h:n,l:o}=ue(e[r],t);[s[r],i[r]]=[n,o]}return[s,i]}(_e,!0),De=(e,t,s)=>s>32?((e,t,s)=>t<<s-32|e>>>64-s)(e,t,s):((e,t,s)=>e<<s|t>>>32-s)(e,t,s),Le=(e,t,s)=>s>32?((e,t,s)=>e<<s-32|t>>>64-s)(e,t,s):((e,t,s)=>t<<s|e>>>32-s)(e,t,s);class We extends Ee{constructor(e,t,s,i=!1,r=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=i,this.rounds=r,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,oe(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");var n;this.state=new Uint8Array(200),this.state32=(n=this.state,new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4)))}keccak(){we||be(this.state32),function(e,t=24){const s=new Uint32Array(10);for(let i=24-t;i<24;i++){for(let t=0;t<10;t++)s[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const i=(t+8)%10,r=(t+2)%10,n=s[r],o=s[r+1],a=De(n,o,1)^s[i],c=Le(n,o,1)^s[i+1];for(let s=0;s<50;s+=10)e[t+s]^=a,e[t+s+1]^=c}let t=e[2],r=e[3];for(let s=0;s<24;s++){const i=Ae[s],n=De(t,r,i),o=Le(t,r,i),a=Ne[s];t=e[a],r=e[a+1],e[a]=n,e[a+1]=o}for(let t=0;t<50;t+=10){for(let i=0;i<10;i++)s[i]=e[t+i];for(let i=0;i<10;i++)e[t+i]^=~s[(i+2)%10]&s[(i+4)%10]}e[0]^=xe[i],e[1]^=Ue[i]}s.fill(0)}(this.state32,this.rounds),we||be(this.state32),this.posOut=0,this.pos=0}update(e){le(this);const{blockLen:t,state:s}=this,i=(e=ve(e)).length;for(let r=0;r<i;){const n=Math.min(t-this.pos,i-r);for(let t=0;t<n;t++)s[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:s,blockLen:i}=this;e[s]^=t,!!(128&t)&&s===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){le(this,!1),ae(e),this.finish();const t=this.state,{blockLen:s}=this;for(let i=0,r=e.length;i<r;){this.posOut>=s&&this.keccak();const n=Math.min(s-this.posOut,r-i);e.set(t.subarray(this.posOut,this.posOut+n),i),this.posOut+=n,i+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return oe(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(de(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,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:i,rounds:r,enableXOF:n}=this;return e||(e=new We(t,s,i,n,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=s,e.outputLen=i,e.enableXOF=n,e.destroyed=this.destroyed,e}}const Me=Ce(()=>new We(136,1,32)),Be="https://rpc.walletconnect.org/v1";function je(e){const t=`Ethereum Signed Message:\n${e.length}`,s=(new TextEncoder).encode(t+e);return"0x"+u.from(Me(s)).toString("hex")}function qe(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);const i=s[0];if(0===i)throw new Error("No signatures found");const r=1+64*i;if(s.length<r)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const n=u.from(e,"base64").slice(1,65);return c.A.encode(n)}var $e=Object.defineProperty,He=Object.defineProperties,Fe=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertySymbols,ze=Object.prototype.hasOwnProperty,Ke=Object.prototype.propertyIsEnumerable,Ge=(e,t,s)=>t in e?$e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Je=(e,t)=>{for(var s in t||(t={}))ze.call(t,s)&&Ge(e,s,t[s]);if(Ve)for(var s of Ve(t))Ke.call(t,s)&&Ge(e,s,t[s]);return e},Xe=(e,t)=>He(e,Fe(t));const Ye=e=>e?.split(":"),Ze=e=>{const t=e&&Ye(e);if(t)return t[2]+":"+t[3]},Qe=e=>{const t=e&&Ye(e);if(t)return t.pop()};async function et(e){const{cacao:t,projectId:s}=e,{s:i,p:r}=t,n=tt(r,r.iss),o=Qe(r.iss);return await async function(e,t,s,i,r,n){switch(s.t){case"eip191":return await async function(e,t,s){return(await(0,a.x)({hash:je(t),signature:s})).toLowerCase()===e.toLowerCase()}(e,t,s.s);case"eip1271":return await async function(e,t,s,i,r,n){const o=m(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const o="0x1626ba7e",a="0000000000000000000000000000000000000000000000000000000000000040",c="0000000000000000000000000000000000000000000000000000000000000041",l=s.substring(2),d=o+je(t).substring(2)+a+c+l,h=await fetch(`${n||Be}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:Date.now()+Math.floor(1e3*Math.random()),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:d},"latest"]})}),{result:p}=await h.json();return!!p&&p.slice(0,o.length).toLowerCase()===o.toLowerCase()}catch(e){return console.error("isValidEip1271Signature: ",e),!1}}(e,t,s.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}(o,n,i,Ze(r.iss),s)}const tt=(e,t)=>{const s=`${e.domain} wants you to sign in with your Ethereum account:`,i=Qe(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=e.statement||void 0;const n=`URI: ${e.aud||e.uri}`,o=`Version: ${e.version}`,a=`Chain ID: ${(e=>{const t=e&&Ye(e);if(t)return e.includes("did:pkh:")?t[3]:t[1]})(t)}`,c=`Nonce: ${e.nonce}`,l=`Issued At: ${e.iat}`,d=e.exp?`Expiration Time: ${e.exp}`:void 0,h=e.nbf?`Not Before: ${e.nbf}`:void 0,p=e.requestId?`Request ID: ${e.requestId}`:void 0,u=e.resources?`Resources:${e.resources.map(e=>`\n- ${e}`).join("")}`:void 0,g=dt(e.resources);return g&&(r=function(e="",t){st(t);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(s))return e;const i=[];let r=0;return Object.keys(t.att).forEach(e=>{const s=Object.keys(t.att[e]).map(e=>({ability:e.split("/")[0],action:e.split("/")[1]}));s.sort((e,t)=>e.action.localeCompare(t.action));const n={};s.forEach(e=>{n[e.ability]||(n[e.ability]=[]),n[e.ability].push(e.action)});const o=Object.keys(n).map(t=>(r++,`(${r}) '${t}': '${n[t].join("', '")}' for '${e}'.`));i.push(o.join(", ").replace(".,","."))}),`${e?e+" ":""}${s}${i.join(" ")}`}(r,nt(g))),[s,i,"",r,"",n,o,a,c,l,d,h,p,u].filter(e=>null!=e).join("\n")};function st(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");const t=Object.keys(e.att);if(null==t||!t.length)throw new Error("No resources found in `att` property");t.forEach(t=>{const s=e.att[t];if(Array.isArray(s))throw new Error(`Resource must be an object: ${t}`);if("object"!=typeof s)throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(s).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(s).forEach(e=>{const t=s[e];if(!Array.isArray(t))throw new Error(`Ability limits ${e} must be an array of objects, found: ${t}`);if(!t.length)throw new Error(`Value of ${e} is empty array, must be an array with objects`);t.forEach(t=>{if("object"!=typeof t)throw new Error(`Ability limits (${e}) must be an array of objects, found: ${t}`)})})})}function it(e,t,s={}){t=t?.sort((e,t)=>e.localeCompare(t));const i=t.map(t=>({[`${e}/${t}`]:[s]}));return Object.assign({},...i)}function rt(e){return st(e),`urn:recap:${function(e){return u.from(JSON.stringify(e)).toString("base64")}(e).replace(/=/g,"")}`}function nt(e){const t=function(e){return JSON.parse(u.from(e,"base64").toString("utf-8"))}(e.replace("urn:recap:",""));return st(t),t}function ot(e,t,s){const i=function(e,t,s,i={}){return s?.sort((e,t)=>e.localeCompare(t)),{att:{[e]:it(t,s,i)}}}(e,t,s);return rt(i)}function at(e,t){const s=function(e,t){st(e),st(t);const s=Object.keys(e.att).concat(Object.keys(t.att)).sort((e,t)=>e.localeCompare(t)),i={att:{}};return s.forEach(s=>{var r,n;Object.keys((null==(r=e.att)?void 0:r[s])||{}).concat(Object.keys((null==(n=t.att)?void 0:n[s])||{})).sort((e,t)=>e.localeCompare(t)).forEach(r=>{var n,o;i.att[s]=Xe(Je({},i.att[s]),{[r]:(null==(n=e.att[s])?void 0:n[r])||(null==(o=t.att[s])?void 0:o[r])})})}),i}(nt(e),nt(t));return rt(s)}function ct(e){var t;const s=nt(e);st(s);const i=null==(t=s.att)?void 0:t.eip155;return i?Object.keys(i).map(e=>e.split("/")[1]):[]}function lt(e){const t=nt(e);st(t);const s=[];return Object.values(t.att).forEach(e=>{Object.values(e).forEach(e=>{var t;null!=(t=e?.[0])&&t.chains&&s.push(e[0].chains)})}),[...new Set(s.flat())]}function dt(e){if(!e)return;const t=e?.[e.length-1];return function(e){return e&&e.includes("urn:recap:")}(t)?t:void 0}function ht(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function pt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ut(e,...t){if(!pt(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function gt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function mt(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}const ft=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function wt(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!pt(e))throw new Error("Uint8Array expected, got "+typeof e);e=vt(e)}return e}function yt(e,t,s=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(s&&!function(e){return e.byteOffset%4==0}(t))throw new Error("invalid output, must be aligned");return t}function bt(e,t,s,i){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,s,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(s>>r&n),a=Number(s&n),c=i?4:0,l=i?0:4;e.setUint32(t+c,o,i),e.setUint32(t+l,a,i)}function vt(e){return Uint8Array.from(e)}function Et(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Ct=e=>Uint8Array.from(e.split("").map(e=>e.charCodeAt(0))),It=Ct("expand 16-byte k"),Nt=Ct("expand 32-byte k"),At=ft(It),_t=ft(Nt);function St(e,t){return e<<t|e>>>32-t}function Pt(e){return e.byteOffset%4==0}const Tt=2**32-1,Ot=new Uint32Array,kt=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Rt{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,ut(e=wt(e),32);const t=kt(e,0),s=kt(e,2),i=kt(e,4),r=kt(e,6),n=kt(e,8),o=kt(e,10),a=kt(e,12),c=kt(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|s<<3),this.r[2]=7939&(s>>>10|i<<6),this.r[3]=8191&(i>>>7|r<<9),this.r[4]=255&(r>>>4|n<<12),this.r[5]=n>>>1&8190,this.r[6]=8191&(n>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=kt(e,16+2*t)}process(e,t,s=!1){const i=s?0:2048,{h:r,r:n}=this,o=n[0],a=n[1],c=n[2],l=n[3],d=n[4],h=n[5],p=n[6],u=n[7],g=n[8],m=n[9],f=kt(e,t+0),w=kt(e,t+2),y=kt(e,t+4),b=kt(e,t+6),v=kt(e,t+8),E=kt(e,t+10),C=kt(e,t+12),I=kt(e,t+14);let N=r[0]+(8191&f),A=r[1]+(8191&(f>>>13|w<<3)),_=r[2]+(8191&(w>>>10|y<<6)),S=r[3]+(8191&(y>>>7|b<<9)),P=r[4]+(8191&(b>>>4|v<<12)),T=r[5]+(v>>>1&8191),O=r[6]+(8191&(v>>>14|E<<2)),k=r[7]+(8191&(E>>>11|C<<5)),R=r[8]+(8191&(C>>>8|I<<8)),x=r[9]+(I>>>5|i),U=0,D=U+N*o+A*(5*m)+_*(5*g)+S*(5*u)+P*(5*p);U=D>>>13,D&=8191,D+=T*(5*h)+O*(5*d)+k*(5*l)+R*(5*c)+x*(5*a),U+=D>>>13,D&=8191;let L=U+N*a+A*o+_*(5*m)+S*(5*g)+P*(5*u);U=L>>>13,L&=8191,L+=T*(5*p)+O*(5*h)+k*(5*d)+R*(5*l)+x*(5*c),U+=L>>>13,L&=8191;let W=U+N*c+A*a+_*o+S*(5*m)+P*(5*g);U=W>>>13,W&=8191,W+=T*(5*u)+O*(5*p)+k*(5*h)+R*(5*d)+x*(5*l),U+=W>>>13,W&=8191;let M=U+N*l+A*c+_*a+S*o+P*(5*m);U=M>>>13,M&=8191,M+=T*(5*g)+O*(5*u)+k*(5*p)+R*(5*h)+x*(5*d),U+=M>>>13,M&=8191;let B=U+N*d+A*l+_*c+S*a+P*o;U=B>>>13,B&=8191,B+=T*(5*m)+O*(5*g)+k*(5*u)+R*(5*p)+x*(5*h),U+=B>>>13,B&=8191;let j=U+N*h+A*d+_*l+S*c+P*a;U=j>>>13,j&=8191,j+=T*o+O*(5*m)+k*(5*g)+R*(5*u)+x*(5*p),U+=j>>>13,j&=8191;let q=U+N*p+A*h+_*d+S*l+P*c;U=q>>>13,q&=8191,q+=T*a+O*o+k*(5*m)+R*(5*g)+x*(5*u),U+=q>>>13,q&=8191;let $=U+N*u+A*p+_*h+S*d+P*l;U=$>>>13,$&=8191,$+=T*c+O*a+k*o+R*(5*m)+x*(5*g),U+=$>>>13,$&=8191;let H=U+N*g+A*u+_*p+S*h+P*d;U=H>>>13,H&=8191,H+=T*l+O*c+k*a+R*o+x*(5*m),U+=H>>>13,H&=8191;let F=U+N*m+A*g+_*u+S*p+P*h;U=F>>>13,F&=8191,F+=T*d+O*l+k*c+R*a+x*o,U+=F>>>13,F&=8191,U=(U<<2)+U|0,U=U+D|0,D=8191&U,U>>>=13,L+=U,r[0]=D,r[1]=L,r[2]=W,r[3]=M,r[4]=B,r[5]=j,r[6]=q,r[7]=$,r[8]=H,r[9]=F}finalize(){const{h:e,pad:t}=this,s=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=i,i=e[t]>>>13,e[t]&=8191;e[0]+=5*i,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,s[0]=e[0]+5,i=s[0]>>>13,s[0]&=8191;for(let t=1;t<10;t++)s[t]=e[t]+i,i=s[t]>>>13,s[t]&=8191;s[9]-=8192;let r=(1^i)-1;for(let e=0;e<10;e++)s[e]&=r;r=~r;for(let t=0;t<10;t++)e[t]=e[t]&r|s[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let n=e[0]+t[0];e[0]=65535&n;for(let s=1;s<8;s++)n=(e[s]+t[s]|0)+(n>>>16)|0,e[s]=65535&n;Et(s)}update(e){gt(this);const{buffer:t,blockLen:s}=this,i=(e=wt(e)).length;for(let r=0;r<i;){const n=Math.min(s-this.pos,i-r);if(n!==s)t.set(e.subarray(r,r+n),this.pos),this.pos+=n,r+=n,this.pos===s&&(this.process(t,0,!1),this.pos=0);else for(;s<=i-r;r+=s)this.process(e,r)}return this}destroy(){Et(this.h,this.r,this.buffer,this.pad)}digestInto(e){gt(this),function(e,t){ut(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}(e,this),this.finished=!0;const{buffer:t,h:s}=this;let{pos:i}=this;if(i){for(t[i++]=1;i<16;i++)t[i]=0;this.process(t,0,!0)}this.finalize();let r=0;for(let t=0;t<8;t++)e[r++]=s[t]>>>0,e[r++]=s[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}}const xt=function(e){const t=(t,s)=>e(s).update(wt(t)).digest(),s=e(new Uint8Array(32));return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=t=>e(t),t}(e=>new Rt(e)),Ut=function(e){const{allowShortKeys:t,extendNonceFn:s,counterLength:i,counterRight:r,rounds:n}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,{counterRight:!1,counterLength:4,allowShortKeys:!1});return ht(i),ht(n),mt(r),mt(t),(o,a,c,l,d=0)=>{ut(o),ut(a),ut(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),ut(l),ht(d),d<0||d>=Tt)throw new Error("arx: counter overflow");if(l.length<h)throw new Error(`arx: output (${l.length}) is shorter than data (${h})`);const p=[];let u,g,m=o.length;if(32===m)p.push(u=vt(o)),g=_t;else{if(16!==m||!t)throw new Error(`arx: invalid 32-byte key, got length=${m}`);u=new Uint8Array(32),u.set(o),u.set(o,16),g=At,p.push(u)}Pt(a)||p.push(a=vt(a));const f=ft(u);if(s){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");s(g,f,ft(a.subarray(0,16)),f),a=a.subarray(16)}const w=16-i;if(w!==a.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(12!==w){const e=new Uint8Array(12);e.set(a,r?0:12-a.length),a=e,p.push(a)}const y=ft(a);return function(e,t,s,i,r,n,o,a){const c=r.length,l=new Uint8Array(64),d=ft(l),h=Pt(r)&&Pt(n),p=h?ft(r):Ot,u=h?ft(n):Ot;for(let g=0;g<c;o++){if(e(t,s,i,d,o,a),o>=Tt)throw new Error("arx: counter overflow");const m=Math.min(64,c-g);if(h&&64===m){const e=g/4;if(g%4!=0)throw new Error("arx: invalid block position");for(let t,s=0;s<16;s++)t=e+s,u[t]=p[t]^d[s];g+=64;continue}for(let e,t=0;t<m;t++)e=g+t,n[e]=r[e]^l[t];g+=m}}(e,g,f,y,c,l,d,n),Et(...p),l}}(function(e,t,s,i,r,n=20){let o=e[0],a=e[1],c=e[2],l=e[3],d=t[0],h=t[1],p=t[2],u=t[3],g=t[4],m=t[5],f=t[6],w=t[7],y=r,b=s[0],v=s[1],E=s[2],C=o,I=a,N=c,A=l,_=d,S=h,P=p,T=u,O=g,k=m,R=f,x=w,U=y,D=b,L=v,W=E;for(let e=0;e<n;e+=2)C=C+_|0,U=St(U^C,16),O=O+U|0,_=St(_^O,12),C=C+_|0,U=St(U^C,8),O=O+U|0,_=St(_^O,7),I=I+S|0,D=St(D^I,16),k=k+D|0,S=St(S^k,12),I=I+S|0,D=St(D^I,8),k=k+D|0,S=St(S^k,7),N=N+P|0,L=St(L^N,16),R=R+L|0,P=St(P^R,12),N=N+P|0,L=St(L^N,8),R=R+L|0,P=St(P^R,7),A=A+T|0,W=St(W^A,16),x=x+W|0,T=St(T^x,12),A=A+T|0,W=St(W^A,8),x=x+W|0,T=St(T^x,7),C=C+S|0,W=St(W^C,16),R=R+W|0,S=St(S^R,12),C=C+S|0,W=St(W^C,8),R=R+W|0,S=St(S^R,7),I=I+P|0,U=St(U^I,16),x=x+U|0,P=St(P^x,12),I=I+P|0,U=St(U^I,8),x=x+U|0,P=St(P^x,7),N=N+T|0,D=St(D^N,16),O=O+D|0,T=St(T^O,12),N=N+T|0,D=St(D^N,8),O=O+D|0,T=St(T^O,7),A=A+_|0,L=St(L^A,16),k=k+L|0,_=St(_^k,12),A=A+_|0,L=St(L^A,8),k=k+L|0,_=St(_^k,7);let M=0;i[M++]=o+C|0,i[M++]=a+I|0,i[M++]=c+N|0,i[M++]=l+A|0,i[M++]=d+_|0,i[M++]=h+S|0,i[M++]=p+P|0,i[M++]=u+T|0,i[M++]=g+O|0,i[M++]=m+k|0,i[M++]=f+R|0,i[M++]=w+x|0,i[M++]=y+U|0,i[M++]=b+D|0,i[M++]=v+L|0,i[M++]=E+W|0}),Dt=new Uint8Array(16),Lt=(e,t)=>{e.update(t);const s=t.length%16;s&&e.update(Dt.subarray(s))},Wt=new Uint8Array(32);function Mt(e,t,s,i,r){const n=e(t,s,Wt),o=xt.create(n);r&&Lt(o,r),Lt(o,i);const a=new Uint8Array(16),c=(e=>new DataView(e.buffer,e.byteOffset,e.byteLength))(a);bt(c,0,BigInt(r?r.length:0),!0),bt(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return Et(n,a),l}const Bt=((e,t)=>{function s(s,...i){if(ut(s),void 0!==e.nonceLength){const t=i[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?ut(t):ut(t,e.nonceLength)}const r=e.tagLength;r&&void 0!==i[1]&&ut(i[1]);const n=t(s,...i),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");ut(t)}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,ut(e),o(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(ut(e),r&&e.length<r)throw new Error("invalid ciphertext length: smaller than tagLength="+r);return o(n.decrypt.length,t),n.decrypt(e,t)}}}return Object.assign(s,e),s})({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,s,i)=>({encrypt(r,n){const o=r.length;(n=yt(o+16,n,!1)).set(r);const a=n.subarray(0,-16);e(t,s,a,a,1);const c=Mt(e,t,s,a,i);return n.set(c,o),Et(c),n},decrypt(r,n){n=yt(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Mt(e,t,s,o,i);if(!function(e,t){if(e.length!==t.length)return!1;let s=0;for(let i=0;i<e.length;i++)s|=e[i]^t[i];return 0===s}(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),e(t,s,n,n,1),Et(c),n}}))(Ut));class jt extends Ee{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ce(e);const s=ve(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,r=new Uint8Array(i);r.set(s.length>i?e.create().update(s).digest():s);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),r.fill(0)}update(e){return le(this),this.iHash.update(e),this}digestInto(e){le(this),ae(e,this.outputLen),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:t,iHash:s,finished:i,destroyed:r,blockLen:n,outputLen:o}=this;return e.finished=i,e.destroyed=r,e.blockLen=n,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const qt=(e,t,s)=>new jt(e,t).update(s).digest();qt.create=(e,t)=>new jt(e,t);const $t=new Uint8Array([0]),Ht=new Uint8Array,Ft=(e,t,s,i,r)=>function(e,t,s,i=32){if(ce(e),oe(i),i>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/e.outputLen);void 0===s&&(s=Ht);const n=new Uint8Array(r*e.outputLen),o=qt.create(e,t),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let t=0;t<r;t++)$t[0]=t+1,a.update(0===t?Ht:c).update(s).update($t).digestInto(c),n.set(c,e.outputLen*t),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),$t.fill(0),n.slice(0,i)}(e,function(e,t,s){return ce(e),void 0===s&&(s=new Uint8Array(e.outputLen)),qt(e,ve(s),ve(t))}(e,t,s),i,r);function Vt(e,t,s){return e&t^~e&s}function zt(e,t,s){return e&t^e&s^t&s}class Kt extends Ee{constructor(e,t,s,i){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=me(this.buffer)}update(e){le(this);const{view:t,buffer:s,blockLen:i}=this,r=(e=ve(e)).length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){const t=me(e);for(;i<=r-n;n+=i)this.process(t,n);continue}s.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){le(this),de(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:i,isLE:r}=this;let{pos:n}=this;t[n++]=128,this.buffer.subarray(n).fill(0),this.padOffset>i-n&&(this.process(s,0),n=0);for(let e=n;e<i;e++)t[e]=0;(function(e,t,s,i){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,s,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(s>>r&n),a=Number(s&n),c=i?4:0,l=i?0:4;e.setUint32(t+c,o,i),e.setUint32(t+l,a,i)})(s,i-8,BigInt(8*this.length),r),this.process(s,0);const o=me(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,length:i,finished:r,destroyed:n,pos:o}=this;return e.length=i,e.pos=o,e.finished=r,e.destroyed=n,i%t&&e.buffer.set(s),e}}const Gt=new Uint32Array([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]),Jt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Xt=new Uint32Array(64);class Yt extends Kt{constructor(){super(64,32,8,!1),this.A=0|Jt[0],this.B=0|Jt[1],this.C=0|Jt[2],this.D=0|Jt[3],this.E=0|Jt[4],this.F=0|Jt[5],this.G=0|Jt[6],this.H=0|Jt[7]}get(){const{A:e,B:t,C:s,D:i,E:r,F:n,G:o,H:a}=this;return[e,t,s,i,r,n,o,a]}set(e,t,s,i,r,n,o,a){this.A=0|e,this.B=0|t,this.C=0|s,this.D=0|i,this.E=0|r,this.F=0|n,this.G=0|o,this.H=0|a}process(e,t){for(let s=0;s<16;s++,t+=4)Xt[s]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Xt[e-15],s=Xt[e-2],i=fe(t,7)^fe(t,18)^t>>>3,r=fe(s,17)^fe(s,19)^s>>>10;Xt[e]=r+Xt[e-7]+i+Xt[e-16]|0}let{A:s,B:i,C:r,D:n,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(fe(o,6)^fe(o,11)^fe(o,25))+Vt(o,a,c)+Gt[e]+Xt[e]|0,d=(fe(s,2)^fe(s,13)^fe(s,22))+zt(s,i,r)|0;l=c,c=a,a=o,o=n+t|0,n=r,r=i,i=s,s=t+d|0}s=s+this.A|0,i=i+this.B|0,r=r+this.C|0,n=n+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(s,i,r,n,o,a,c,l)}roundClean(){Xt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Zt=Ce(()=>new Yt),Qt=BigInt(0),es=BigInt(1),ts=BigInt(2);function ss(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function is(e){if(!ss(e))throw new Error("Uint8Array expected")}function rs(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const ns=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function os(e){is(e);let t="";for(let s=0;s<e.length;s++)t+=ns[e[s]];return t}function as(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function cs(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Qt:BigInt("0x"+e)}function ls(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function ds(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,s=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const i=new Uint8Array(s);for(let t=0,r=0;t<s;t++,r+=2){const s=ls(e.charCodeAt(r)),n=ls(e.charCodeAt(r+1));if(void 0===s||void 0===n){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}i[t]=16*s+n}return i}function hs(e){return cs(os(e))}function ps(e){return is(e),cs(os(Uint8Array.from(e).reverse()))}function us(e,t){return ds(e.toString(16).padStart(2*t,"0"))}function gs(e,t){return us(e,t).reverse()}function ms(e,t,s){let i;if("string"==typeof t)try{i=ds(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!ss(t))throw new Error(e+" must be hex string or Uint8Array");i=Uint8Array.from(t)}const r=i.length;if("number"==typeof s&&r!==s)throw new Error(e+" of length "+s+" expected, got "+r);return i}function fs(...e){let t=0;for(let s=0;s<e.length;s++){const i=e[s];is(i),t+=i.length}const s=new Uint8Array(t);for(let t=0,i=0;t<e.length;t++){const r=e[t];s.set(r,i),i+=r.length}return s}const ws=e=>"bigint"==typeof e&&Qt<=e;function ys(e,t,s){return ws(e)&&ws(t)&&ws(s)&&t<=e&&e<s}function bs(e,t,s,i){if(!ys(t,s,i))throw new Error("expected valid "+e+": "+s+" <= n < "+i+", got "+t)}function vs(e){let t;for(t=0;e>Qt;e>>=es,t+=1);return t}const Es=e=>(ts<<BigInt(e-1))-es,Cs=e=>new Uint8Array(e),Is=e=>Uint8Array.from(e);function Ns(e,t,s){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof s)throw new Error("hmacFn must be a function");let i=Cs(e),r=Cs(e),n=0;const o=()=>{i.fill(1),r.fill(0),n=0},a=(...e)=>s(r,i,...e),c=(e=Cs())=>{r=a(Is([0]),e),i=a(),0!==e.length&&(r=a(Is([1]),e),i=a())},l=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const s=[];for(;e<t;){i=a();const t=i.slice();s.push(t),e+=i.length}return fs(...s)};return(e,t)=>{let s;for(o(),c(e);!(s=t(l()));)c();return o(),s}}const As={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||ss(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function _s(e,t,s={}){const i=(t,s,i)=>{const r=As[s];if("function"!=typeof r)throw new Error("invalid validator function");const n=e[t];if(!(i&&void 0===n||r(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+s+", got "+n)};for(const[e,s]of Object.entries(t))i(e,s,!1);for(const[e,t]of Object.entries(s))i(e,t,!0);return e}function Ss(e){const t=new WeakMap;return(s,...i)=>{const r=t.get(s);if(void 0!==r)return r;const n=e(s,...i);return t.set(s,n),n}}var Ps=Object.freeze({__proto__:null,isBytes:ss,abytes:is,abool:rs,bytesToHex:os,numberToHexUnpadded:as,hexToNumber:cs,hexToBytes:ds,bytesToNumberBE:hs,bytesToNumberLE:ps,numberToBytesBE:us,numberToBytesLE:gs,numberToVarBytesBE:function(e){return ds(as(e))},ensureBytes:ms,concatBytes:fs,equalBytes:function(e,t){if(e.length!==t.length)return!1;let s=0;for(let i=0;i<e.length;i++)s|=e[i]^t[i];return 0===s},utf8ToBytes:function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))},inRange:ys,aInRange:bs,bitLen:vs,bitGet:function(e,t){return e>>BigInt(t)&es},bitSet:function(e,t,s){return e|(s?es:Qt)<<BigInt(t)},bitMask:Es,createHmacDrbg:Ns,validateObject:_s,notImplemented:()=>{throw new Error("not implemented")},memoized:Ss});const Ts=BigInt(0),Os=BigInt(1),ks=BigInt(2),Rs=BigInt(3),xs=BigInt(4),Us=BigInt(5),Ds=BigInt(8);function Ls(e,t){const s=e%t;return s>=Ts?s:t+s}function Ws(e,t,s){if(t<Ts)throw new Error("invalid exponent, negatives unsupported");if(s<=Ts)throw new Error("invalid modulus");if(s===Os)return Ts;let i=Os;for(;t>Ts;)t&Os&&(i=i*e%s),e=e*e%s,t>>=Os;return i}function Ms(e,t,s){let i=e;for(;t-- >Ts;)i*=i,i%=s;return i}function Bs(e,t){if(e===Ts)throw new Error("invert: expected non-zero number");if(t<=Ts)throw new Error("invert: expected positive modulus, got "+t);let s=Ls(e,t),i=t,r=Ts,n=Os;for(;s!==Ts;){const e=i%s,t=r-n*(i/s);i=s,s=e,r=n,n=t}if(i!==Os)throw new Error("invert: does not exist");return Ls(r,t)}const js=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qs(e,t){const s=void 0!==t?t:e.toString(2).length;return{nBitLength:s,nByteLength:Math.ceil(s/8)}}function $s(e,t,s=!1,i={}){if(e<=Ts)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:r,nByteLength:n}=qs(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:s,BITS:r,BYTES:n,MASK:Es(r),ZERO:Ts,ONE:Os,create:t=>Ls(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Ts<=t&&t<e},is0:e=>e===Ts,isOdd:e=>(e&Os)===Os,neg:t=>Ls(-t,e),eql:(e,t)=>e===t,sqr:t=>Ls(t*t,e),add:(t,s)=>Ls(t+s,e),sub:(t,s)=>Ls(t-s,e),mul:(t,s)=>Ls(t*s,e),pow:(e,t)=>function(e,t,s){if(s<Ts)throw new Error("invalid exponent, negatives unsupported");if(s===Ts)return e.ONE;if(s===Os)return t;let i=e.ONE,r=t;for(;s>Ts;)s&Os&&(i=e.mul(i,r)),r=e.sqr(r),s>>=Os;return i}(a,e,t),div:(t,s)=>Ls(t*Bs(s,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Bs(t,e),sqrt:i.sqrt||(t=>(o||(o=function(e){if(e%xs===Rs){const t=(e+Os)/xs;return function(e,s){const i=e.pow(s,t);if(!e.eql(e.sqr(i),s))throw new Error("Cannot find square root");return i}}if(e%Ds===Us){const t=(e-Us)/Ds;return function(e,s){const i=e.mul(s,ks),r=e.pow(i,t),n=e.mul(s,r),o=e.mul(e.mul(n,ks),r),a=e.mul(n,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),s))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-Os)/ks;let s,i,r;for(s=e-Os,i=0;s%ks===Ts;s/=ks,i++);for(r=ks;r<e&&Ws(r,t,e)!==e-Os;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===i){const t=(e+Os)/xs;return function(e,s){const i=e.pow(s,t);if(!e.eql(e.sqr(i),s))throw new Error("Cannot find square root");return i}}const n=(s+Os)/ks;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=i,c=e.pow(e.mul(e.ONE,r),s),l=e.pow(o,n),d=e.pow(o,s);for(;!e.eql(d,e.ONE);){if(e.eql(d,e.ZERO))return e.ZERO;let t=1;for(let s=e.sqr(d);t<a&&!e.eql(s,e.ONE);t++)s=e.sqr(s);const s=e.pow(c,Os<<BigInt(a-t-1));c=e.sqr(s),l=e.mul(l,s),d=e.mul(d,c),a=t}return l}}(e)}(e)),o(a,t))),invertBatch:e=>function(e,t){const s=new Array(t.length),i=t.reduce((t,i,r)=>e.is0(i)?t:(s[r]=t,e.mul(t,i)),e.ONE),r=e.inv(i);return t.reduceRight((t,i,r)=>e.is0(i)?t:(s[r]=e.mul(t,s[r]),e.mul(t,i)),r),s}(a,e),cmov:(e,t,s)=>s?t:e,toBytes:e=>s?gs(e,n):us(e,n),fromBytes:e=>{if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);return s?ps(e):hs(e)}});return Object.freeze(a)}function Hs(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Fs(e){const t=Hs(e);return t+Math.ceil(t/2)}const Vs=BigInt(0),zs=BigInt(1);function Ks(e,t){const s=t.negate();return e?s:t}function Gs(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Js(e,t){return Gs(e,t),{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const Xs=new WeakMap,Ys=new WeakMap;function Zs(e){return Ys.get(e)||1}function Qs(e){return function(e){_s(e,js.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}))}(e.Fp),_s(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...qs(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const ei=BigInt(0),ti=BigInt(1),si=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const ii=BigInt(1),ri=BigInt(2),ni=BigInt(3),oi=BigInt(5);BigInt(8);const ai=function(e){const t=function(e){return _s(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})}(e),{P:s}=t,i=e=>Ls(e,s),r=t.montgomeryBits,n=Math.ceil(r/8),o=t.nByteLength,a=t.adjustScalarBytes||(e=>e),c=t.powPminus2||(e=>Ws(e,s-BigInt(2),s));function l(e,t,s){const r=i(e*(t-s));return[t=i(t-r),s=i(s+r)]}const d=(t.a-BigInt(2))/BigInt(4);function h(e){return gs(i(e),n)}function p(e,t){const p=function(e){const t=ms("u coordinate",e,n);return 32===o&&(t[31]&=127),ps(t)}(t),u=function(e){const t=ms("scalar",e),s=t.length;if(s!==n&&s!==o)throw new Error("invalid scalar, expected "+n+" or "+o+" bytes, got "+s);return ps(a(t))}(e),g=function(e,t){bs("u",e,ei,s),bs("scalar",t,ei,s);const n=t,o=e;let a,h=ti,p=ei,u=e,g=ti,m=ei;for(let e=BigInt(r-1);e>=ei;e--){const t=n>>e&ti;m^=t,a=l(m,h,u),h=a[0],u=a[1],a=l(m,p,g),p=a[0],g=a[1],m=t;const s=h+p,r=i(s*s),c=h-p,f=i(c*c),w=r-f,y=u+g,b=i((u-g)*s),v=i(y*c),E=b+v,C=b-v;u=i(E*E),g=i(o*i(C*C)),h=i(r*f),p=i(w*(r+i(d*w)))}a=l(m,h,u),h=a[0],u=a[1],a=l(m,p,g),p=a[0],g=a[1];const f=c(p);return i(h*f)}(p,u);if(g===ei)throw new Error("invalid private or public key received");return h(g)}const u=h(t.Gu);function g(e){return p(e,u)}return{scalarMult:p,scalarMultBase:g,getSharedSecret:(e,t)=>p(e,t),getPublicKey:e=>g(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:u}}({P:si,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=si,{pow_p_5_8:s,b2:i}=function(e){const t=BigInt(10),s=BigInt(20),i=BigInt(40),r=BigInt(80),n=si,o=e*e%n*e%n,a=Ms(o,ri,n)*o%n,c=Ms(a,ii,n)*e%n,l=Ms(c,oi,n)*c%n,d=Ms(l,t,n)*l%n,h=Ms(d,s,n)*d%n,p=Ms(h,i,n)*h%n,u=Ms(p,r,n)*p%n,g=Ms(u,r,n)*p%n,m=Ms(g,t,n)*l%n;return{pow_p_5_8:Ms(m,ri,n)*e%n,b2:o}}(e);return Ls(Ms(s,ni,t)*i,t)},adjustScalarBytes:function(e){return e[0]&=248,e[31]&=127,e[31]|=64,e},randomBytes:Ie});function ci(e){void 0!==e.lowS&&rs("lowS",e.lowS),void 0!==e.prehash&&rs("prehash",e.prehash)}const{bytesToNumberBE:li,hexToBytes:di}=Ps;class hi extends Error{constructor(e=""){super(e)}}const pi={Err:hi,_tlv:{encode:(e,t)=>{const{Err:s}=pi;if(e<0||e>256)throw new s("tlv.encode: wrong tag");if(1&t.length)throw new s("tlv.encode: unpadded data");const i=t.length/2,r=as(i);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const n=i>127?as(r.length/2|128):"";return as(e)+n+r+t},decode(e,t){const{Err:s}=pi;let i=0;if(e<0||e>256)throw new s("tlv.encode: wrong tag");if(t.length<2||t[i++]!==e)throw new s("tlv.decode: wrong tlv");const r=t[i++];let n=0;if(128&r){const e=127&r;if(!e)throw new s("tlv.decode(long): indefinite length not supported");if(e>4)throw new s("tlv.decode(long): byte length is too big");const o=t.subarray(i,i+e);if(o.length!==e)throw new s("tlv.decode: length bytes not complete");if(0===o[0])throw new s("tlv.decode(long): zero leftmost byte");for(const e of o)n=n<<8|e;if(i+=e,n<128)throw new s("tlv.decode(long): not minimal encoding")}else n=r;const o=t.subarray(i,i+n);if(o.length!==n)throw new s("tlv.decode: wrong value length");return{v:o,l:t.subarray(i+n)}}},_int:{encode(e){const{Err:t}=pi;if(e<ui)throw new t("integer: negative integers are not allowed");let s=as(e);if(8&Number.parseInt(s[0],16)&&(s="00"+s),1&s.length)throw new t("unexpected DER parsing assertion: unpadded hex");return s},decode(e){const{Err:t}=pi;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return li(e)}},toSig(e){const{Err:t,_int:s,_tlv:i}=pi,r="string"==typeof e?di(e):e;is(r);const{v:n,l:o}=i.decode(48,r);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:l,l:d}=i.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(e){const{_tlv:t,_int:s}=pi,i=t.encode(2,s.encode(e.r))+t.encode(2,s.encode(e.s));return t.encode(48,i)}},ui=BigInt(0),gi=BigInt(1);BigInt(2);const mi=BigInt(3);function fi(e){const t=function(e){const t=Qs(e);_s(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:s,Fp:i,a:r}=t;if(s){if(!i.eql(r,i.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if("object"!=typeof s||"bigint"!=typeof s.beta||"function"!=typeof s.splitScalar)throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:s}=t,i=$s(t.n,t.nBitLength),r=t.toBytes||((e,t,i)=>{const r=t.toAffine();return fs(Uint8Array.from([4]),s.toBytes(r.x),s.toBytes(r.y))}),n=t.fromBytes||(e=>{const t=e.subarray(1);return{x:s.fromBytes(t.subarray(0,s.BYTES)),y:s.fromBytes(t.subarray(s.BYTES,2*s.BYTES))}});function o(e){const{a:i,b:r}=t,n=s.sqr(e),o=s.mul(n,e);return s.add(s.add(o,s.mul(e,i)),r)}if(!s.eql(s.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function a(e){const{allowedPrivateKeyLengths:s,nByteLength:i,wrapPrivateKey:r,n}=t;if(s&&"bigint"!=typeof e){if(ss(e)&&(e=os(e)),"string"!=typeof e||!s.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*i,"0")}let o;try{o="bigint"==typeof e?e:hs(ms("private key",e,i))}catch{throw new Error("invalid private key, expected hex or "+i+" bytes, got "+typeof e)}return r&&(o=Ls(o,n)),bs("private key",o,gi,n),o}function c(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}const l=Ss((e,t)=>{const{px:i,py:r,pz:n}=e;if(s.eql(n,s.ONE))return{x:i,y:r};const o=e.is0();null==t&&(t=o?s.ONE:s.inv(n));const a=s.mul(i,t),c=s.mul(r,t),l=s.mul(n,t);if(o)return{x:s.ZERO,y:s.ZERO};if(!s.eql(l,s.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),d=Ss(e=>{if(e.is0()){if(t.allowInfinityPoint&&!s.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:i,y:r}=e.toAffine();if(!s.isValid(i)||!s.isValid(r))throw new Error("bad point: x or y not FE");const n=s.sqr(r),a=o(i);if(!s.eql(n,a))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(e,t,i){if(this.px=e,this.py=t,this.pz=i,null==e||!s.isValid(e))throw new Error("x required");if(null==t||!s.isValid(t))throw new Error("y required");if(null==i||!s.isValid(i))throw new Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:i}=e||{};if(!e||!s.isValid(t)||!s.isValid(i))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const r=e=>s.eql(e,s.ZERO);return r(t)&&r(i)?h.ZERO:new h(t,i,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=s.invertBatch(e.map(e=>e.pz));return e.map((e,s)=>e.toAffine(t[s])).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(n(ms("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(a(e))}static msm(e,t){return function(e,t,s,i){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,s)=>{if(!(e instanceof t))throw new Error("invalid point at index "+s)})}(s,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,s)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+s)})}(i,t),s.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const r=e.ZERO,n=vs(BigInt(s.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r);let l=r;for(let e=Math.floor((t.BITS-1)/o)*o;e>=0;e-=o){c.fill(r);for(let t=0;t<i.length;t++){const r=i[t],n=Number(r>>BigInt(e)&BigInt(a));c[n]=c[n].add(s[t])}let t=r;for(let e=c.length-1,s=r;e>0;e--)s=s.add(c[e]),t=t.add(s);if(l=l.add(t),0!==e)for(let e=0;e<o;e++)l=l.double()}return l}(h,i,e,t)}_setWindowSize(e){u.setWindowSize(this,e)}assertValidity(){d(this)}hasEvenY(){const{y:e}=this.toAffine();if(s.isOdd)return!s.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:i,pz:r}=this,{px:n,py:o,pz:a}=e,l=s.eql(s.mul(t,a),s.mul(n,r)),d=s.eql(s.mul(i,a),s.mul(o,r));return l&&d}negate(){return new h(this.px,s.neg(this.py),this.pz)}double(){const{a:e,b:i}=t,r=s.mul(i,mi),{px:n,py:o,pz:a}=this;let c=s.ZERO,l=s.ZERO,d=s.ZERO,p=s.mul(n,n),u=s.mul(o,o),g=s.mul(a,a),m=s.mul(n,o);return m=s.add(m,m),d=s.mul(n,a),d=s.add(d,d),c=s.mul(e,d),l=s.mul(r,g),l=s.add(c,l),c=s.sub(u,l),l=s.add(u,l),l=s.mul(c,l),c=s.mul(m,c),d=s.mul(r,d),g=s.mul(e,g),m=s.sub(p,g),m=s.mul(e,m),m=s.add(m,d),d=s.add(p,p),p=s.add(d,p),p=s.add(p,g),p=s.mul(p,m),l=s.add(l,p),g=s.mul(o,a),g=s.add(g,g),p=s.mul(g,m),c=s.sub(c,p),d=s.mul(g,u),d=s.add(d,d),d=s.add(d,d),new h(c,l,d)}add(e){c(e);const{px:i,py:r,pz:n}=this,{px:o,py:a,pz:l}=e;let d=s.ZERO,p=s.ZERO,u=s.ZERO;const g=t.a,m=s.mul(t.b,mi);let f=s.mul(i,o),w=s.mul(r,a),y=s.mul(n,l),b=s.add(i,r),v=s.add(o,a);b=s.mul(b,v),v=s.add(f,w),b=s.sub(b,v),v=s.add(i,n);let E=s.add(o,l);return v=s.mul(v,E),E=s.add(f,y),v=s.sub(v,E),E=s.add(r,n),d=s.add(a,l),E=s.mul(E,d),d=s.add(w,y),E=s.sub(E,d),u=s.mul(g,v),d=s.mul(m,y),u=s.add(d,u),d=s.sub(w,u),u=s.add(w,u),p=s.mul(d,u),w=s.add(f,f),w=s.add(w,f),y=s.mul(g,y),v=s.mul(m,v),w=s.add(w,y),y=s.sub(f,y),y=s.mul(g,y),v=s.add(v,y),f=s.mul(w,v),p=s.add(p,f),f=s.mul(E,v),d=s.mul(b,d),d=s.sub(d,f),f=s.mul(b,w),u=s.mul(E,u),u=s.add(u,f),new h(d,p,u)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return u.wNAFCached(this,e,h.normalizeZ)}multiplyUnsafe(e){const{endo:i,n:r}=t;bs("scalar",e,ui,r);const n=h.ZERO;if(e===ui)return n;if(this.is0()||e===gi)return this;if(!i||u.hasPrecomputes(this))return u.wNAFCachedUnsafe(this,e,h.normalizeZ);let{k1neg:o,k1:a,k2neg:c,k2:l}=i.splitScalar(e),d=n,p=n,g=this;for(;a>ui||l>ui;)a&gi&&(d=d.add(g)),l&gi&&(p=p.add(g)),g=g.double(),a>>=gi,l>>=gi;return o&&(d=d.negate()),c&&(p=p.negate()),p=new h(s.mul(p.px,i.beta),p.py,p.pz),d.add(p)}multiply(e){const{endo:i,n:r}=t;let n,o;if(bs("scalar",e,gi,r),i){const{k1neg:t,k1:r,k2neg:a,k2:c}=i.splitScalar(e);let{p:l,f:d}=this.wNAF(r),{p,f:g}=this.wNAF(c);l=u.constTimeNegate(t,l),p=u.constTimeNegate(a,p),p=new h(s.mul(p.px,i.beta),p.py,p.pz),n=l.add(p),o=d.add(g)}else{const{p:t,f:s}=this.wNAF(e);n=t,o=s}return h.normalizeZ([n,o])[0]}multiplyAndAddUnsafe(e,t,s){const i=h.BASE,r=(e,t)=>t!==ui&&t!==gi&&e.equals(i)?e.multiply(t):e.multiplyUnsafe(t),n=r(this,t).add(r(e,s));return n.is0()?void 0:n}toAffine(e){return l(this,e)}isTorsionFree(){const{h:e,isTorsionFree:s}=t;if(e===gi)return!0;if(s)return s(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:s}=t;return e===gi?this:s?s(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return rs("isCompressed",e),this.assertValidity(),r(h,this,e)}toHex(e=!0){return rs("isCompressed",e),os(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,s.ONE),h.ZERO=new h(s.ZERO,s.ONE,s.ZERO);const p=t.nBitLength,u=function(e,t){return{constTimeNegate:Ks,hasPrecomputes:e=>1!==Zs(e),unsafeLadder(t,s,i=e.ZERO){let r=t;for(;s>Vs;)s&zs&&(i=i.add(r)),r=r.double(),s>>=zs;return i},precomputeWindow(e,s){const{windows:i,windowSize:r}=Js(s,t),n=[];let o=e,a=o;for(let e=0;e<i;e++){a=o,n.push(a);for(let e=1;e<r;e++)a=a.add(o),n.push(a);o=a.double()}return n},wNAF(s,i,r){const{windows:n,windowSize:o}=Js(s,t);let a=e.ZERO,c=e.BASE;const l=BigInt(2**s-1),d=2**s,h=BigInt(s);for(let e=0;e<n;e++){const t=e*o;let s=Number(r&l);r>>=h,s>o&&(s-=d,r+=zs);const n=t,p=t+Math.abs(s)-1,u=e%2!=0,g=s<0;0===s?c=c.add(Ks(u,i[n])):a=a.add(Ks(g,i[p]))}return{p:a,f:c}},wNAFUnsafe(s,i,r,n=e.ZERO){const{windows:o,windowSize:a}=Js(s,t),c=BigInt(2**s-1),l=2**s,d=BigInt(s);for(let e=0;e<o;e++){const t=e*a;if(r===Vs)break;let s=Number(r&c);if(r>>=d,s>a&&(s-=l,r+=zs),0===s)continue;let o=i[t+Math.abs(s)-1];s<0&&(o=o.negate()),n=n.add(o)}return n},getPrecomputes(e,t,s){let i=Xs.get(t);return i||(i=this.precomputeWindow(t,e),1!==e&&Xs.set(t,s(i))),i},wNAFCached(e,t,s){const i=Zs(e);return this.wNAF(i,this.getPrecomputes(i,e,s),t)},wNAFCachedUnsafe(e,t,s,i){const r=Zs(e);return 1===r?this.unsafeLadder(e,t,i):this.wNAFUnsafe(r,this.getPrecomputes(r,e,s),t,i)},setWindowSize(e,s){Gs(s,t),Ys.set(e,s),Xs.delete(e)}}}(h,t.endo?Math.ceil(p/2):p);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:function(e){return ys(e,gi,t.n)}}}function wi(e){const t=function(e){const t=Qs(e);return _s(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:s,n:i}=t,r=s.BYTES+1,n=2*s.BYTES+1;function o(e){return Ls(e,i)}function a(e){return Bs(e,i)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:d,isWithinCurveOrder:h}=fi({...t,toBytes(e,t,i){const r=t.toAffine(),n=s.toBytes(r.x),o=fs;return rs("isCompressed",i),i?o(Uint8Array.from([t.hasEvenY()?2:3]),n):o(Uint8Array.from([4]),n,s.toBytes(r.y))},fromBytes(e){const t=e.length,i=e[0],o=e.subarray(1);if(t!==r||2!==i&&3!==i){if(t===n&&4===i)return{x:s.fromBytes(o.subarray(0,s.BYTES)),y:s.fromBytes(o.subarray(s.BYTES,2*s.BYTES))};throw new Error("invalid Point, expected length of "+r+", or uncompressed "+n+", got "+t)}{const e=hs(o);if(!ys(e,gi,s.ORDER))throw new Error("Point is not on curve");const t=d(e);let r;try{r=s.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~i)!=((r&gi)===gi)&&(r=s.neg(r)),{x:e,y:r}}}}),p=e=>os(us(e,t.nByteLength));function u(e){return e>i>>gi}const g=(e,t,s)=>hs(e.slice(t,s));class m{constructor(e,t,s){this.r=e,this.s=t,this.recovery=s,this.assertValidity()}static fromCompact(e){const s=t.nByteLength;return e=ms("compactSignature",e,2*s),new m(g(e,0,s),g(e,s,2*s))}static fromDER(e){const{r:t,s}=pi.toSig(ms("DER",e));return new m(t,s)}assertValidity(){bs("r",this.r,gi,i),bs("s",this.s,gi,i)}addRecoveryBit(e){return new m(this.r,this.s,e)}recoverPublicKey(e){const{r:i,s:r,recovery:n}=this,l=b(ms("msgHash",e));if(null==n||![0,1,2,3].includes(n))throw new Error("recovery id invalid");const d=2===n||3===n?i+t.n:i;if(d>=s.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&n?"03":"02",u=c.fromHex(h+p(d)),g=a(d),m=o(-l*g),f=o(r*g),w=c.BASE.multiplyAndAddUnsafe(u,m,f);if(!w)throw new Error("point at infinify");return w.assertValidity(),w}hasHighS(){return u(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return ds(this.toDERHex())}toDERHex(){return pi.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ds(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const f={isValidPrivateKey(e){try{return l(e),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=Fs(t.n);return function(e,t,s=!1){const i=e.length,r=Hs(t),n=Fs(t);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=Ls(s?ps(e):hs(e),t-Os)+Os;return s?gs(o,r):us(o,r)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function w(e){const t=ss(e),s="string"==typeof e,i=(t||s)&&e.length;return t?i===r||i===n:s?i===2*r||i===2*n:e instanceof c}const y=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const s=hs(e),i=8*e.length-t.nBitLength;return i>0?s>>BigInt(i):s},b=t.bits2int_modN||function(e){return o(y(e))},v=Es(t.nBitLength);function E(e){return bs("num < 2^"+t.nBitLength,e,ui,v),us(e,t.nByteLength)}const C={lowS:t.lowS,prehash:!1},I={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,s=!0){if(w(e))throw new Error("first arg must be private key");if(!w(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(s)},sign:function(e,i,r=C){const{seed:n,k2sig:d}=function(e,i,r=C){if(["recovered","canonical"].some(e=>e in r))throw new Error("sign() legacy options not supported");const{hash:n,randomBytes:d}=t;let{lowS:p,prehash:g,extraEntropy:f}=r;null==p&&(p=!0),e=ms("msgHash",e),ci(r),g&&(e=ms("prehashed msgHash",n(e)));const w=b(e),v=l(i),I=[E(v),E(w)];if(null!=f&&!1!==f){const e=!0===f?d(s.BYTES):f;I.push(ms("extraEntropy",e))}const N=fs(...I),A=w;return{seed:N,k2sig:function(e){const t=y(e);if(!h(t))return;const s=a(t),i=c.BASE.multiply(t).toAffine(),r=o(i.x);if(r===ui)return;const n=o(s*o(A+r*v));if(n===ui)return;let l=(i.x===r?0:2)|Number(i.y&gi),d=n;return p&&u(n)&&(d=function(e){return u(e)?o(-e):e}(n),l^=1),new m(r,d,l)}}}(e,i,r),p=t;return Ns(p.hash.outputLen,p.nByteLength,p.hmac)(n,d)},verify:function(e,s,i,r=I){const n=e;s=ms("msgHash",s),i=ms("publicKey",i);const{lowS:l,prehash:d,format:h}=r;if(ci(r),"strict"in r)throw new Error("options.strict was renamed to lowS");if(void 0!==h&&"compact"!==h&&"der"!==h)throw new Error("format must be compact or der");const p="string"==typeof n||ss(n),u=!p&&!h&&"object"==typeof n&&null!==n&&"bigint"==typeof n.r&&"bigint"==typeof n.s;if(!p&&!u)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let g,f;try{if(u&&(g=new m(n.r,n.s)),p){try{"compact"!==h&&(g=m.fromDER(n))}catch(e){if(!(e instanceof pi.Err))throw e}!g&&"der"!==h&&(g=m.fromCompact(n))}f=c.fromHex(i)}catch{return!1}if(!g||l&&g.hasHighS())return!1;d&&(s=t.hash(s));const{r:w,s:y}=g,v=b(s),E=a(y),C=o(v*E),N=o(w*E),A=c.BASE.multiplyAndAddUnsafe(f,C,N)?.toAffine();return!!A&&o(A.x)===w},ProjectivePoint:c,Signature:m,utils:f}}function yi(e){return{hash:e,hmac:(t,...s)=>qt(e,t,function(...e){let t=0;for(let s=0;s<e.length;s++){const i=e[s];ae(i),t+=i.length}const s=new Uint8Array(t);for(let t=0,i=0;t<e.length;t++){const r=e[t];s.set(r,i),i+=r.length}return s}(...s)),randomBytes:Ie}}BigInt(4);const bi=$s(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),vi=function(e,t){const s=t=>wi({...e,...yi(t)});return{...s(t),create:s}}({a:bi.create(BigInt("-3")),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Fp:bi,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Zt),Ei="base10",Ci="base16",Ii="base64pad",Ni="base64url",Ai="utf8",_i=0,Si=1,Pi=2,Ti=0,Oi=1,ki=12,Ri=32;function xi(){const e=ai.utils.randomPrivateKey(),t=ai.getPublicKey(e);return{privateKey:(0,d.dI)(e,Ci),publicKey:(0,d.dI)(t,Ci)}}function Ui(){const e=Ie(Ri);return(0,d.dI)(e,Ci)}function Di(e,t){const s=ai.getSharedSecret((0,d.sH)(e,Ci),(0,d.sH)(t,Ci)),i=Ft(Zt,s,void 0,void 0,Ri);return(0,d.dI)(i,Ci)}function Li(e){const t=Zt((0,d.sH)(e,Ci));return(0,d.dI)(t,Ci)}function Wi(e){const t=Zt((0,d.sH)(e,Ai));return(0,d.dI)(t,Ci)}function Mi(e){return(0,d.sH)(`${e}`,Ei)}function Bi(e){return Number((0,d.dI)(e,Ei))}function ji(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qi(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),s=(4-t.length%4)%4;return t+"=".repeat(s)}function $i(e){const t=Mi(typeof e.type<"u"?e.type:_i);if(Bi(t)===Si&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof e.senderPublicKey<"u"?(0,d.sH)(e.senderPublicKey,Ci):void 0,i=typeof e.iv<"u"?(0,d.sH)(e.iv,Ci):Ie(ki),r=(0,d.sH)(e.symKey,Ci),n=zi({type:t,sealed:Bt(r,i).encrypt((0,d.sH)(e.message,Ai)),iv:i,senderPublicKey:s});return e.encoding===Ni?ji(n):n}function Hi(e){const t=(0,d.sH)(e.symKey,Ci),{sealed:s,iv:i}=Ki({encoded:e.encoded,encoding:e.encoding}),r=Bt(t,i).decrypt(s);if(null===r)throw new Error("Failed to decrypt");return(0,d.dI)(r,Ai)}function Fi(e,t){const s=Mi(Pi),i=Ie(ki),r=zi({type:s,sealed:(0,d.sH)(e,Ai),iv:i});return t===Ni?ji(r):r}function Vi(e,t){const{sealed:s}=Ki({encoded:e,encoding:t});return(0,d.dI)(s,Ai)}function zi(e){if(Bi(e.type)===Pi)return(0,d.dI)((0,d.xW)([e.type,e.sealed]),Ii);if(Bi(e.type)===Si){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return(0,d.dI)((0,d.xW)([e.type,e.senderPublicKey,e.iv,e.sealed]),Ii)}return(0,d.dI)((0,d.xW)([e.type,e.iv,e.sealed]),Ii)}function Ki(e){const t=(e.encoding||Ii)===Ni?qi(e.encoded):e.encoded,s=(0,d.sH)(t,Ii),i=s.slice(Ti,Oi),r=Oi;if(Bi(i)===Si){const e=r+Ri,t=e+ki,n=s.slice(r,e),o=s.slice(e,t);return{type:i,sealed:s.slice(t),iv:o,senderPublicKey:n}}if(Bi(i)===Pi)return{type:i,sealed:s.slice(r),iv:Ie(ki)};const n=r+ki,o=s.slice(r,n);return{type:i,sealed:s.slice(n),iv:o}}function Gi(e,t){const s=Ki({encoded:e,encoding:t?.encoding});return Ji({type:Bi(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?(0,d.dI)(s.senderPublicKey,Ci):void 0,receiverPublicKey:t?.receiverPublicKey})}function Ji(e){const t=e?.type||_i;if(t===Si){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function Xi(e){return e.type===Si&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function Yi(e){return e.type===Pi}function Zi(e,t){const[s,i,r]=e.split("."),n=u.from(qi(r),"base64");if(64!==n.length)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=Zt(`${s}.${i}`),h=function(e){const t=u.from(e.x,"base64"),s=u.from(e.y,"base64");return(0,d.xW)([new Uint8Array([4]),t,s])}(t);if(!vi.verify((0,d.xW)([o,a]),c,h))throw new Error("Invalid signature");return(0,l.Cq)(e).payload}const Qi="irn";function er(e){return e?.relay||{protocol:Qi}}function tr(e){const t=h.CG[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function sr(e,t="-"){const s={},i="relay"+t;return Object.keys(e).forEach(t=>{if(t.startsWith(i)){const r=t.replace(i,""),n=e[t];s[r]=n}}),s}function ir(e){if(!e.includes("wc:")){const t=re(e);null!=t&&t.includes("wc:")&&(e=t)}const t=(e=(e=e.includes("wc://")?e.replace("wc://",""):e).includes("wc:")?e.replace("wc:",""):e).indexOf(":"),s=-1!==e.indexOf("?")?e.indexOf("?"):void 0,i=e.substring(0,t),r=e.substring(t+1,s).split("@"),n=typeof s<"u"?e.substring(s):"",o=new URLSearchParams(n),a={};o.forEach((e,t)=>{a[t]=e});const c="string"==typeof a.methods?a.methods.split(","):void 0;return{protocol:i,topic:rr(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:sr(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function rr(e){return e.startsWith("//")?e.substring(2):e}function nr(e){const t=new URLSearchParams,s=function(e,t="-"){const s={};return Object.keys(e).forEach(i=>{const r=i,n="relay"+t+r;e[r]&&(s[n]=e[r])}),s}(e.relay);Object.keys(s).sort().forEach(e=>{t.set(e,s[e])}),t.set("symKey",e.symKey),e.expiryTimestamp&&t.set("expiryTimestamp",e.expiryTimestamp.toString()),e.methods&&t.set("methods",e.methods.join(","));const i=t.toString();return`${e.protocol}:${e.topic}@${e.version}?${i}`}function or(e,t,s){return`${e}?wc_ev=${s}&topic=${t}`}var ar=Object.defineProperty,cr=Object.defineProperties,lr=Object.getOwnPropertyDescriptors,dr=Object.getOwnPropertySymbols,hr=Object.prototype.hasOwnProperty,pr=Object.prototype.propertyIsEnumerable,ur=(e,t,s)=>t in e?ar(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,gr=(e,t)=>{for(var s in t||(t={}))hr.call(t,s)&&ur(e,s,t[s]);if(dr)for(var s of dr(t))pr.call(t,s)&&ur(e,s,t[s]);return e},mr=(e,t)=>cr(e,lr(t));function fr(e){const t=[];return e.forEach(e=>{const[s,i]=e.split(":");t.push(`${s}:${i}`)}),t}function wr(e){return e.includes(":")}function yr(e){return wr(e)?e.split(":")[0]:e}function br(e){var t,s,i;const r={};if(!Sr(e))return r;for(const[n,o]of Object.entries(e)){const e=wr(n)?[n]:o.chains,a=o.methods||[],c=o.events||[],l=yr(n);r[l]=mr(gr({},r[l]),{chains:Z(e,null==(t=r[l])?void 0:t.chains),methods:Z(a,null==(s=r[l])?void 0:s.methods),events:Z(c,null==(i=r[l])?void 0:i.events)})}return r}function vr(e,t){const s=function(e){const t={};return e?.forEach(e=>{var s;const[i,r]=e.split(":");t[i]||(t[i]={accounts:[],chains:[],events:[],methods:[]}),t[i].accounts.push(e),null==(s=t[i].chains)||s.push(`${i}:${r}`)}),t}(t=t.map(e=>e.replace("did:pkh:","")));for(const[t,i]of Object.entries(s))i.methods?i.methods=Z(i.methods,e):i.methods=e,i.events=["chainChanged","accountsChanged"];return s}function Er(e,t){var s,i,r,n,o,a;const c=br(e),l=br(t),d={},h=Object.keys(c).concat(Object.keys(l));for(const e of h)d[e]={chains:Z(null==(s=c[e])?void 0:s.chains,null==(i=l[e])?void 0:i.chains),methods:Z(null==(r=c[e])?void 0:r.methods,null==(n=l[e])?void 0:n.methods),events:Z(null==(o=c[e])?void 0:o.events,null==(a=l[e])?void 0:a.events)};return d}const Cr={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},Ir={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Nr(e,t){const{message:s,code:i}=Ir[e];return{message:t?`${s} ${t}`:s,code:i}}function Ar(e,t){const{message:s,code:i}=Cr[e];return{message:t?`${s} ${t}`:s,code:i}}function _r(e,t){return!!Array.isArray(e)&&(!(typeof t<"u"&&e.length)||e.every(t))}function Sr(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Pr(e){return typeof e>"u"}function Tr(e,t){return!(!t||!Pr(e))||"string"==typeof e&&!!e.trim().length}function Or(e,t){return!(!t||!Pr(e))||"number"==typeof e&&!isNaN(e)}function kr(e,t){const{requiredNamespaces:s}=t,i=Object.keys(e.namespaces),r=Object.keys(s);let n=!0;return!!j(r,i)&&(i.forEach(t=>{const{accounts:i,methods:r,events:o}=e.namespaces[t],a=fr(i),c=s[t];j(f(t,c),a)&&j(c.methods,r)&&j(c.events,o)||(n=!1)}),n)}function Rr(e){return!(!Tr(e,!1)||!e.includes(":"))&&2===e.split(":").length}function xr(e){function t(e){try{return typeof new URL(e)<"u"}catch{return!1}}try{if(Tr(e,!1))return!!t(e)||t(re(e))}catch{}return!1}function Ur(e){var t;return null==(t=e?.proposer)?void 0:t.publicKey}function Dr(e){return e?.topic}function Lr(e,t){let s=null;return Tr(e?.publicKey,!1)||(s=Nr("MISSING_OR_INVALID",`${t} controller public key should be a string`)),s}function Wr(e){let t=!0;return _r(e)?e.length&&(t=e.every(e=>Tr(e,!1))):t=!1,t}function Mr(e,t){let s=null;return Object.values(e).forEach(e=>{if(s)return;const i=function(e,t){let s=null;return Wr(e?.methods)?Wr(e?.events)||(s=Ar("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):s=Ar("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),s}(e,`${t}, namespace`);i&&(s=i)}),s}function Br(e,t,s){let i=null;if(e&&Sr(e)){const r=Mr(e,t);r&&(i=r);const n=function(e,t,s){let i=null;return Object.entries(e).forEach(([e,r])=>{if(i)return;const n=function(e,t,s){let i=null;return _r(t)&&t.length?t.forEach(e=>{i||Rr(e)||(i=Ar("UNSUPPORTED_CHAINS",`${s}, chain ${e} should be a string and conform to "namespace:chainId" format`))}):Rr(e)||(i=Ar("UNSUPPORTED_CHAINS",`${s}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}(e,f(e,r),`${t} ${s}`);n&&(i=n)}),i}(e,t,s);n&&(i=n)}else i=Nr("MISSING_OR_INVALID",`${t}, ${s} should be an object with data`);return i}function jr(e,t){let s=null;if(e&&Sr(e)){const i=Mr(e,t);i&&(s=i);const r=function(e,t){let s=null;return Object.values(e).forEach(e=>{if(s)return;const i=function(e,t){let s=null;return _r(e)?e.forEach(e=>{s||function(e){if(Tr(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&Rr(e)}}return!1}(e)||(s=Ar("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))}):s=Ar("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}(e?.accounts,`${t} namespace`);i&&(s=i)}),s}(e,t);r&&(s=r)}else s=Nr("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return s}function qr(e){return Tr(e.protocol,!0)}function $r(e,t){let s=!1;return t&&!e?s=!0:e&&_r(e)&&e.length&&e.forEach(e=>{s=qr(e)}),s}function Hr(e){return"number"==typeof e}function Fr(e){return typeof e<"u"&&null!==typeof e}function Vr(e){return!!(e&&"object"==typeof e&&e.code&&Or(e.code,!1)&&e.message&&Tr(e.message,!1))}function zr(e){return!(Pr(e)||!Tr(e.method,!1))}function Kr(e){return!(Pr(e)||Pr(e.result)&&Pr(e.error)||!Or(e.id,!1)||!Tr(e.jsonrpc,!1))}function Gr(e){return!(Pr(e)||!Tr(e.name,!1))}function Jr(e,t){return!(!Rr(t)||!function(e){const t=[];return Object.values(e).forEach(e=>{t.push(...fr(e.accounts))}),t}(e).includes(t))}function Xr(e,t,s){return!!Tr(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach(e=>{fr(e.accounts).includes(t)&&s.push(...e.methods)}),s}(e,t).includes(s)}function Yr(e,t,s){return!!Tr(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach(e=>{fr(e.accounts).includes(t)&&s.push(...e.events)}),s}(e,t).includes(s)}function Zr(e,t,s){let i=null;const r=function(e){const t={};return Object.keys(e).forEach(s=>{var i;s.includes(":")?t[s]=e[s]:null==(i=e[s].chains)||i.forEach(i=>{t[i]={methods:e[s].methods,events:e[s].events}})}),t}(e),n=function(e){const t={};return Object.keys(e).forEach(s=>{if(s.includes(":"))t[s]=e[s];else{const i=fr(e[s].accounts);i?.forEach(i=>{t[i]={accounts:e[s].accounts.filter(e=>e.includes(`${i}:`)),methods:e[s].methods,events:e[s].events}})}}),t}(t),o=Object.keys(r),a=Object.keys(n),c=Qr(Object.keys(e)),l=Qr(Object.keys(t)),d=c.filter(e=>!l.includes(e));return d.length&&(i=Nr("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.\n Required: ${d.toString()}\n Received: ${Object.keys(t).toString()}`)),j(o,a)||(i=Nr("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.\n Required: ${o.toString()}\n Approved: ${a.toString()}`)),Object.keys(t).forEach(e=>{if(!e.includes(":")||i)return;const r=fr(t[e].accounts);r.includes(e)||(i=Nr("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${r.toString()}`))}),o.forEach(e=>{i||(j(r[e].methods,n[e].methods)?j(r[e].events,n[e].events)||(i=Nr("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${e}`)):i=Nr("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${e}`))}),i}function Qr(e){return[...new Set(e.map(e=>e.includes(":")?e.split(":")[0]:e))]}function en(e,t){return Or(e,!1)&&e<=t.max&&e>=t.min}function tn(){const e=U();return new Promise(t=>{switch(e){case S.browser:t(x()&&navigator?.onLine);break;case S.reactNative:t(async function(){if(O()&&typeof s.g<"u"&&null!=s.g&&s.g.NetInfo){const e=await(null==s.g?void 0:s.g.NetInfo.fetch());return e?.isConnected}return!0}());break;case S.node:default:t(!0)}})}function sn(e){switch(U()){case S.browser:!function(e){!O()&&x()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}(e);break;case S.reactNative:!function(e){O()&&typeof s.g<"u"&&null!=s.g&&s.g.NetInfo&&s.g?.NetInfo.addEventListener(t=>e(t?.isConnected))}(e);case S.node:}}function rn(){var e;return!x()||!(0,n.getDocument)()||"visible"===(null==(e=(0,n.getDocument)())?void 0:e.visibilityState)}const nn={};class on{static get(e){return nn[e]}static set(e,t){nn[e]=t}static delete(e){delete nn[e]}}},16444:(e,t,s)=>{s.d(t,{T:()=>m});var i=s(89168),r=s(3555),n=s(22143),o=s(35646),a=s(11847),c=s(46362),l=s(98299),d=s(1420),h=s(92492);const p={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},u=n.w.getBlockchainApiUrl(),g=(0,i.BX)({clientId:null,api:new o.Z({baseUrl:u,clientId:null}),supportedChains:{http:[],ws:[]}}),m={state:g,async get(e){const{st:t,sv:s}=m.getSdkProperties(),i=d.H.state.projectId,r={...e.params||{},st:t,sv:s,projectId:i};return g.api.get({...e,params:r})},getSdkProperties(){const{sdkType:e,sdkVersion:t}=d.H.state;return{st:e||"unknown",sv:t||"unknown"}},async isNetworkSupported(e){if(!e)return!1;try{g.supportedChains.http.length||await m.getSupportedNetworks()}catch(e){return!1}return g.supportedChains.http.includes(e)},async getSupportedNetworks(){try{const e=await m.get({path:"v1/supported-chains"});return g.supportedChains=e,e}catch{return g.supportedChains}},async fetchIdentity({address:e,caipNetworkId:t}){if(!await m.isNetworkSupported(t))return{avatar:"",name:""};const s=a.i.getIdentityFromCacheForAddress(e);if(s)return s;const i=await m.get({path:`/v1/identity/${e}`,params:{sender:l.W.state.activeCaipAddress?n.w.getPlainAddress(l.W.state.activeCaipAddress):void 0}});return a.i.updateIdentityCache({address:e,identity:i,timestamp:Date.now()}),i},fetchTransactions:async({account:e,cursor:t,onramp:s,signal:i,cache:r,chainId:n})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:`/v1/account/${e}/history`,params:{cursor:t,onramp:s,chainId:n},signal:i,cache:r}):{data:[],next:void 0},fetchSwapQuote:async({amount:e,userAddress:t,from:s,to:i,gasPrice:r})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:e,userAddress:t,from:s,to:i,gasPrice:r}}):{quotes:[]},fetchSwapTokens:async({chainId:e})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:"/v1/convert/tokens",params:{chainId:e}}):{tokens:[]},fetchTokenPrice:async({addresses:e})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?g.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:e,projectId:d.H.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]},fetchSwapAllowance:async({tokenAddress:e,userAddress:t})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:"/v1/convert/allowance",params:{tokenAddress:e,userAddress:t},headers:{"Content-Type":"application/json"}}):{allowance:"0"},async fetchGasPrice({chainId:e}){const{st:t,sv:s}=m.getSdkProperties();if(!await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return m.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:e,st:t,sv:s}})},async generateSwapCalldata({amount:e,from:t,to:s,userAddress:i,disableEstimate:n}){if(!await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return g.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:e,eip155:{slippage:r.oU.CONVERT_SLIPPAGE_TOLERANCE},projectId:d.H.state.projectId,from:t,to:s,userAddress:i,disableEstimate:n}})},async generateApproveCalldata({from:e,to:t,userAddress:s}){const{st:i,sv:r}=m.getSdkProperties();if(!await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return m.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:e,to:t,st:i,sv:r}})},async getBalance(e,t,s){const{st:i,sv:r}=m.getSdkProperties();if(!await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId))return h.P.showError("Token Balance Unavailable"),{balances:[]};const n=`${t}:${e}`,o=a.i.getBalanceCacheForCaipAddress(n);if(o)return o;const c=await m.get({path:`/v1/account/${e}/balance`,params:{currency:"usd",chainId:t,forceUpdate:s,st:i,sv:r}});return a.i.updateBalanceCache({caipAddress:n,balance:c,timestamp:Date.now()}),c},lookupEnsName:async e=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:`/v1/profile/account/${e}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]},reverseLookupEnsName:async({address:e})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:`/v1/profile/reverse/${e}`,params:{sender:c.U.state.address,apiVersion:"2"}}):[],getEnsNameSuggestions:async e=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:`/v1/profile/suggestions/${e}`,params:{zone:"reown.id"}}):{suggestions:[]},registerEnsName:async({coinType:e,address:t,message:s,signature:i})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?g.api.post({path:"/v1/profile/account",body:{coin_type:e,address:t,message:s,signature:i},headers:{"Content-Type":"application/json"}}):{success:!1},generateOnRampURL:async({destinationWallets:e,partnerUserId:t,defaultNetwork:s,purchaseAmount:i,paymentAmount:r})=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?(await g.api.post({path:"/v1/generators/onrampurl",params:{projectId:d.H.state.projectId},body:{destinationWallets:e,defaultNetwork:s,partnerUserId:t,defaultExperience:"buy",presetCryptoAmount:i,presetFiatAmount:r}})).url:"",async getOnrampOptions(){if(!await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await m.get({path:"/v1/onramp/options"})}catch(e){return p}},async getOnrampQuote({purchaseCurrency:e,paymentCurrency:t,amount:s,network:i}){try{return await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?await g.api.post({path:"/v1/onramp/quote",params:{projectId:d.H.state.projectId},body:{purchaseCurrency:e,paymentCurrency:t,amount:s,network:i}}):null}catch(e){return{coinbaseFee:{amount:s,currency:t.id},networkFee:{amount:s,currency:t.id},paymentSubtotal:{amount:s,currency:t.id},paymentTotal:{amount:s,currency:t.id},purchaseAmount:{amount:s,currency:t.id},quoteId:"mocked-quote-id"}}},getSmartSessions:async e=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?m.get({path:`/v1/sessions/${e}`}):[],revokeSmartSession:async(e,t,s)=>await m.isNetworkSupported(l.W.state.activeCaipNetwork?.caipNetworkId)?g.api.post({path:`/v1/sessions/${e}/revoke`,params:{projectId:d.H.state.projectId},body:{pci:t,signature:s}}):{success:!1},setClientId(e){g.clientId=e,g.api=new o.Z({baseUrl:u,clientId:e})}}},18338:(e,t,s)=>{s.d(t,{A:()=>Ze});var i=s(27811),r=s(15529),n=s(70255),o=s(64264),a=s(93786),c=s(14350),l=s(50046),d=s.n(l),h=s(48526).hp;const p="error",u="wc@2:universal_provider:",g="https://rpc.walletconnect.org/v1/",m="generic",f=`${g}bundler`,w="default_chain_changed";function y(){}function b(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function v(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function E(e){return"object"==typeof e&&null!==e}function C(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function I(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const N="[object String]",A="[object Number]",_="[object Boolean]",S="[object Arguments]";function P(e,t,s,i=new Map,r=void 0){const n=r?.(e,t,s,i);if(null!=n)return n;if(b(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){const t=new Array(e.length);i.set(e,t);for(let n=0;n<e.length;n++)t[n]=P(e[n],n,s,i,r);return Object.hasOwn(e,"index")&&(t.index=e.index),Object.hasOwn(e,"input")&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){const t=new Map;i.set(e,t);for(const[n,o]of e)t.set(n,P(o,n,s,i,r));return t}if(e instanceof Set){const t=new Set;i.set(e,t);for(const n of e)t.add(P(n,void 0,s,i,r));return t}if(typeof h<"u"&&h.isBuffer(e))return e.subarray();if(v(e)){const t=new(Object.getPrototypeOf(e).constructor)(e.length);i.set(e,t);for(let n=0;n<e.length;n++)t[n]=P(e[n],n,s,i,r);return t}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,t),T(t,e,s,i,r),t}if(typeof File<"u"&&e instanceof File){const t=new File([e],e.name,{type:e.type});return i.set(e,t),T(t,e,s,i,r),t}if(e instanceof Blob){const t=new Blob([e],{type:e.type});return i.set(e,t),T(t,e,s,i,r),t}if(e instanceof Error){const t=new e.constructor;return i.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,T(t,e,s,i,r),t}if("object"==typeof e&&function(e){switch(I(e)){case S:case"[object Array]":case"[object ArrayBuffer]":case"[object DataView]":case _:case"[object Date]":case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Map]":case A:case"[object Object]":case"[object RegExp]":case"[object Set]":case N:case"[object Symbol]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return!0;default:return!1}}(e)){const t=Object.create(Object.getPrototypeOf(e));return i.set(e,t),T(t,e,s,i,r),t}return e}function T(e,t,s=e,i,r){const n=[...Object.keys(t),...C(t)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(e,a);(null==c||c.writable)&&(e[a]=P(t[a],a,s,i,r))}}function O(e){return function(e,t){return function(e,t){return P(e,void 0,e,new Map,t)}(e,(s,i,r,n)=>{const o=t?.(s,i,r,n);if(null!=o)return o;if("object"==typeof e)switch(Object.prototype.toString.call(e)){case A:case N:case _:{const t=new e.constructor(e?.valueOf());return T(t,e),t}case S:{const t={};return T(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}})}(e)}function k(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===I(e)}function R(e){return v(e)}function x(e){if("object"!=typeof e||null==e)return!1;if(null===Object.getPrototypeOf(e))return!0;if("[object Object]"!==Object.prototype.toString.call(e)){const t=e[Symbol.toStringTag];return!(null==t||!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable)&&e.toString()===`[object ${t}]`}let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function U(e,t,s,i){if(b(e)&&(e=Object(e)),null==t||"object"!=typeof t)return e;if(i.has(t))return function(e){if(b(e))return e;if(Array.isArray(e)||v(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e),s=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new s(e);if(e instanceof RegExp){const t=new s(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new s(e.buffer.slice(0));if(e instanceof Error){const t=new s(e.message);return t.stack=e.stack,t.name=e.name,t.cause=e.cause,t}if(typeof File<"u"&&e instanceof File)return new s([e],e.name,{type:e.type,lastModified:e.lastModified});if("object"==typeof e){const s=Object.create(t);return Object.assign(s,e)}return e}(i.get(t));if(i.set(t,e),Array.isArray(t)){t=t.slice();for(let e=0;e<t.length;e++)t[e]=t[e]??void 0}const r=[...Object.keys(t),...C(t)];for(let n=0;n<r.length;n++){const o=r[n];let a=t[o],c=e[o];if(k(a)&&(a={...a}),k(c)&&(c={...c}),typeof h<"u"&&h.isBuffer(a)&&(a=O(a)),Array.isArray(a))if("object"==typeof c&&null!=c){const e=[],t=Reflect.ownKeys(c);for(let s=0;s<t.length;s++){const i=t[s];e[i]=c[i]}c=e}else c=[];const l=s(c,a,o,e,t,i);null!=l?e[o]=l:Array.isArray(a)||E(c)&&E(a)?e[o]=U(c,a,s,i):null==c&&x(a)?e[o]=U({},a,s,i):null==c&&R(a)?e[o]=O(a):(void 0===c||void 0!==a)&&(e[o]=a)}return e}var D=Object.defineProperty,L=Object.defineProperties,W=Object.getOwnPropertyDescriptors,M=Object.getOwnPropertySymbols,B=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable,q=(e,t,s)=>t in e?D(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,$=(e,t)=>{for(var s in t||(t={}))B.call(t,s)&&q(e,s,t[s]);if(M)for(var s of M(t))j.call(t,s)&&q(e,s,t[s]);return e},H=(e,t)=>L(e,W(t));function F(e,t,s){var i;const n=(0,r._Yb)(e);return(null==(i=t.rpcMap)?void 0:i[n.reference])||`${g}?chainId=${n.namespace}:${n.reference}&projectId=${s}`}function V(e){return e.includes(":")?e.split(":")[1]:e}function z(e){return e.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function K(e={},t={}){return function(e,...t){return function(e,...t){const s=t.slice(0,-1),i=t[t.length-1];let r=e;for(let e=0;e<s.length;e++)r=U(r,s[e],i,new Map);return r}(e,...t,y)}(G(e),G(t))}function G(e){var t,s,i,n,o;const a={};if(!(0,r.aF0)(e))return a;for(const[c,l]of Object.entries(e)){const e=(0,r.nWe)(c)?[c]:l.chains,d=l.methods||[],h=l.events||[],p=l.rpcMap||{},u=(0,r.kob)(c);a[u]=H($($({},a[u]),l),{chains:(0,r.TRk)(e,null==(t=a[u])?void 0:t.chains),methods:(0,r.TRk)(d,null==(s=a[u])?void 0:s.methods),events:(0,r.TRk)(h,null==(i=a[u])?void 0:i.events)}),((0,r.aF0)(p)||(0,r.aF0)((null==(n=a[u])?void 0:n.rpcMap)||{}))&&(a[u].rpcMap=$($({},p),null==(o=a[u])?void 0:o.rpcMap))}return a}function J(e){return e.includes(":")?e.split(":")[2]:e}function X(e){const t={};for(const[s,i]of Object.entries(e)){const e=i.methods||[],n=i.events||[],o=i.accounts||[],a=(0,r.nWe)(s)?[s]:i.chains?i.chains:z(i.accounts);t[s]={chains:a,methods:e,events:n,accounts:o}}return t}function Y(e){return"number"==typeof e?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}const Z={},Q=e=>Z[e],ee=(e,t)=>{Z[e]=t};var te=Object.defineProperty,se=(e,t,s)=>((e,t,s)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class ie{constructor(e){se(this,"name","polkadot"),se(this,"client"),se(this,"httpProviders"),se(this,"events"),se(this,"namespace"),se(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e&&e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=V(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var re=Object.defineProperty,ne=Object.defineProperties,oe=Object.getOwnPropertyDescriptors,ae=Object.getOwnPropertySymbols,ce=Object.prototype.hasOwnProperty,le=Object.prototype.propertyIsEnumerable,de=(e,t,s)=>t in e?re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,he=(e,t)=>{for(var s in t||(t={}))ce.call(t,s)&&de(e,s,t[s]);if(ae)for(var s of ae(t))le.call(t,s)&&de(e,s,t[s]);return e},pe=(e,t)=>ne(e,oe(t)),ue=(e,t,s)=>de(e,"symbol"!=typeof t?t+"":t,s);class ge{constructor(e){ue(this,"name","eip155"),ue(this,"client"),ue(this,"chainId"),ue(this,"namespace"),ue(this,"httpProviders"),ue(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(w,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const s=t||F(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.V(s,Q("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=parseInt(V(t));e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,s;let i=e.request.params?null==(t=e.request.params[0])?void 0:t.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const r=parseInt(i,16);if(this.isChainApproved(r))this.setDefaultChain(`${r}`);else{if(!this.namespace.methods.includes("wallet_switchEthereumChain"))throw new Error(`Failed to switch to chain 'eip155:${r}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:null==(s=this.namespace.chains)?void 0:s[0]}),this.setDefaultChain(`${r}`)}return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,s,i,r,n;const o=null==(s=null==(t=e.request)?void 0:t.params)?void 0:s[0],a=`${o}${((null==(r=null==(i=e.request)?void 0:i.params)?void 0:r[1])||[]).join(",")}`;if(!o)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const c=this.client.session.get(e.topic),l=(null==(n=c?.sessionProperties)?void 0:n.capabilities)||{};if(null!=l&&l[a])return l?.[a];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:pe(he({},c.sessionProperties||{}),{capabilities:pe(he({},l||{}),{[a]:d})})})}catch(e){console.warn("Failed to update session with capabilities",e)}return d}async getCallStatus(e){var t,s;const i=this.client.session.get(e.topic),r=null==(t=i.sessionProperties)?void 0:t.bundler_name;if(r){const t=this.getBundlerUrl(e.chainId,r);try{return await this.getUserOperationReceipt(t,e)}catch(e){console.warn("Failed to fetch call status from bundler",e,t)}}const n=null==(s=i.sessionProperties)?void 0:s.bundler_url;if(n)try{return await this.getUserOperationReceipt(n,e)}catch(e){console.warn("Failed to fetch call status from custom bundler",e,n)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var s;const i=new URL(e),r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify((0,c.formatJsonRpcRequest)("eth_getUserOperationReceipt",[null==(s=t.request.params)?void 0:s[0]]))});if(!r.ok)throw new Error(`Failed to fetch user operation receipt - ${r.status}`);return await r.json()}getBundlerUrl(e,t){return`${f}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var me=Object.defineProperty,fe=(e,t,s)=>((e,t,s)=>t in e?me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class we{constructor(e){fe(this,"name","solana"),fe(this,"client"),fe(this,"httpProviders"),fe(this,"events"),fe(this,"namespace"),fe(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=V(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var ye=Object.defineProperty,be=(e,t,s)=>((e,t,s)=>t in e?ye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class ve{constructor(e){be(this,"name","cosmos"),be(this,"client"),be(this,"httpProviders"),be(this,"events"),be(this,"namespace"),be(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=V(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var Ee=Object.defineProperty,Ce=(e,t,s)=>((e,t,s)=>t in e?Ee(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ie{constructor(e){Ce(this,"name","algorand"),Ce(this,"client"),Ce(this,"httpProviders"),Ce(this,"events"),Ce(this,"namespace"),Ce(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const s=t||F(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.chainId=e,this.events.emit(w,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;e[t]=this.createHttpProvider(t,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new a.F(new o.A(s,Q("disableProviderPing")))}}var Ne=Object.defineProperty,Ae=(e,t,s)=>((e,t,s)=>t in e?Ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class _e{constructor(e){Ae(this,"name","cip34"),Ae(this,"client"),Ae(this,"httpProviders"),Ae(this,"events"),Ae(this,"namespace"),Ae(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const s=this.getCardanoRPCUrl(t),i=V(t);e[i]=this.createHttpProvider(i,s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||this.getCardanoRPCUrl(e);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var Se=Object.defineProperty,Pe=(e,t,s)=>((e,t,s)=>t in e?Se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Te{constructor(e){Pe(this,"name","elrond"),Pe(this,"client"),Pe(this,"httpProviders"),Pe(this,"events"),Pe(this,"namespace"),Pe(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=V(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var Oe=Object.defineProperty,ke=(e,t,s)=>((e,t,s)=>t in e?Oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Re{constructor(e){ke(this,"name","multiversx"),ke(this,"client"),ke(this,"httpProviders"),ke(this,"events"),ke(this,"namespace"),ke(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=V(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var xe=Object.defineProperty,Ue=(e,t,s)=>((e,t,s)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class De{constructor(e){Ue(this,"name","near"),Ue(this,"client"),Ue(this,"httpProviders"),Ue(this,"events"),Ue(this,"namespace"),Ue(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||F(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(w,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e&&e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;e[t]=this.createHttpProvider(t,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace);return typeof s>"u"?void 0:new a.F(new o.A(s,Q("disableProviderPing")))}}var Le=Object.defineProperty,We=(e,t,s)=>((e,t,s)=>t in e?Le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Me{constructor(e){We(this,"name","tezos"),We(this,"client"),We(this,"httpProviders"),We(this,"events"),We(this,"namespace"),We(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||F(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(w,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e&&e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace);return typeof s>"u"?void 0:new a.F(new o.A(s))}}var Be=Object.defineProperty,je=(e,t,s)=>((e,t,s)=>t in e?Be(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class qe{constructor(e){je(this,"name",m),je(this,"client"),je(this,"httpProviders"),je(this,"events"),je(this,"namespace"),je(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(w,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){var e,t;const s={};return null==(t=null==(e=this.namespace)?void 0:e.accounts)||t.forEach(e=>{const t=(0,r._Yb)(e);s[`${t.namespace}:${t.reference}`]=this.createHttpProvider(e)}),s}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||F(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new a.F(new o.A(s,Q("disableProviderPing")))}}var $e=Object.defineProperty,He=Object.defineProperties,Fe=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertySymbols,ze=Object.prototype.hasOwnProperty,Ke=Object.prototype.propertyIsEnumerable,Ge=(e,t,s)=>t in e?$e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Je=(e,t)=>{for(var s in t||(t={}))ze.call(t,s)&&Ge(e,s,t[s]);if(Ve)for(var s of Ve(t))Ke.call(t,s)&&Ge(e,s,t[s]);return e},Xe=(e,t)=>He(e,Fe(t)),Ye=(e,t,s)=>Ge(e,"symbol"!=typeof t?t+"":t,s);class Ze{constructor(e){Ye(this,"client"),Ye(this,"namespaces"),Ye(this,"optionalNamespaces"),Ye(this,"sessionProperties"),Ye(this,"scopedProperties"),Ye(this,"events",new(d())),Ye(this,"rpcProviders",{}),Ye(this,"session"),Ye(this,"providerOpts"),Ye(this,"logger"),Ye(this,"uri"),Ye(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&"string"!=typeof e?.logger?e.logger:(0,n.h6)((0,n.iP)({level:e?.logger||p})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new Ze(e);return await t.initialize(),t}async request(e,t,s){const[i,r]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:Je({},e),chainId:`${i}:${r}`,topic:this.session.topic,expiry:s})}sendAsync(e,t,s,i){const r=(new Date).getTime();this.request(e,s,i).then(e=>t(null,(0,c.formatJsonRpcResult)(r,e))).catch(e=>t(e,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:null==(e=this.session)?void 0:e.topic,reason:(0,r.Hjj)("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:s,response:i}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const r=await i();if(this.session=r.session,this.session){const e=X(this.session.namespaces);this.namespaces=K(this.namespaces,e),await this.persist("namespaces",this.namespaces),this.onConnect()}return r}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const i=await s();this.session=i;const r=X(i.namespaces);return this.namespaces=K(this.namespaces,r),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[s,i]=this.validateChain(e),r=this.getProvider(s);r.name===m?r.setDefaultChain(`${s}:${i}`,t):r.setDefaultChain(i,t)}catch(e){if(!/Please call connect/.test(e.message))throw e}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if((0,r.OP1)(t)){for(const s of t)e.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,t;if(this.client=this.providerOpts.client||await i.Ay.init({core:this.providerOpts.core,logger:this.providerOpts.logger||p,relayUrl:this.providerOpts.relayUrl||"wss://relay.walletconnect.org",projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(s){throw this.logger.error("Failed to get session",s),new Error(`The provided session: ${null==(t=null==(e=this.providerOpts)?void 0:e.session)?void 0:t.topic} doesn't exist in the Sign client`)}else{const e=this.client.session.getAll();this.session=e[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(e=>(0,r.kob)(e)))];ee("client",this.client),ee("events",this.events),ee("disableProviderPing",this.disableProviderPing),e.forEach(e=>{if(!this.session)return;const t=function(e,t){const s=Object.keys(t.namespaces).filter(t=>t.includes(e));if(!s.length)return[];const i=[];return s.forEach(e=>{const s=t.namespaces[e].accounts;i.push(...s)}),i}(e,this.session),s=z(t),i=K(this.namespaces,this.optionalNamespaces),r=Xe(Je({},i[e]),{accounts:t,chains:s});switch(e){case"eip155":this.rpcProviders[e]=new ge({namespace:r});break;case"algorand":this.rpcProviders[e]=new Ie({namespace:r});break;case"solana":this.rpcProviders[e]=new we({namespace:r});break;case"cosmos":this.rpcProviders[e]=new ve({namespace:r});break;case"polkadot":this.rpcProviders[e]=new ie({namespace:r});break;case"cip34":this.rpcProviders[e]=new _e({namespace:r});break;case"elrond":this.rpcProviders[e]=new Te({namespace:r});break;case"multiversx":this.rpcProviders[e]=new Re({namespace:r});break;case"near":this.rpcProviders[e]=new De({namespace:r});break;case"tezos":this.rpcProviders[e]=new Me({namespace:r});break;default:this.rpcProviders[m]?this.rpcProviders[m].updateNamespace(r):this.rpcProviders[m]=new qe({namespace:r})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:s}=e;s===(null==(t=this.session)?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:s,topic:i}=e;if(i!==(null==(t=this.session)?void 0:t.topic))return;const{event:n}=s;if("accountsChanged"===n.name){const e=n.data;e&&(0,r.OP1)(e)&&this.events.emit("accountsChanged",e.map(J))}else if("chainChanged"===n.name){const e=s.chainId,t=s.event.data,i=(0,r.kob)(e),n=Y(e)!==Y(t)?`${i}:${Y(t)}`:e;this.onChainChanged(n)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var s,i;if(e!==(null==(s=this.session)?void 0:s.topic))return;const{namespaces:r}=t,n=null==(i=this.client)?void 0:i.session.get(e);this.session=Xe(Je({},n),{namespaces:r}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===(null==(t=this.session)?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Xe(Je({},(0,r.Hjj)("USER_DISCONNECTED")),{data:e.topic})))}),this.on(w,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[m]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace(null==(t=this.session)?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:s={},sessionProperties:i,scopedProperties:r}=e;this.optionalNamespaces=K(t,s),this.sessionProperties=i,this.scopedProperties=r}validateChain(e){const[t,s]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(e=>(0,r.kob)(e)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&s)return[t,s];const i=(0,r.kob)(Object.keys(this.namespaces)[0]);return[i,this.rpcProviders[i].getDefaultChain()]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[s,i]=this.validateChain(e);if(!i)return;this.updateNamespaceChain(s,i),this.events.emit("chainChanged",i);const r=this.getProvider(s).getDefaultChain();t||this.getProvider(s).setDefaultChain(i),this.emitAccountsChangedOnChainChange({namespace:s,previousChainId:r,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:s}){var i,n;try{if(t===s)return;const o=null==(n=null==(i=this.session)?void 0:i.namespaces[e])?void 0:n.accounts;if(!o)return;const a=o.filter(e=>e.includes(`${s}:`)).map(J);if(!(0,r.OP1)(a))return;this.events.emit("accountsChanged",a)}catch(e){this.logger.warn("Failed to emit accountsChanged on chain change",e)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const s=this.namespaces[e]?e:`${e}:${t}`,i={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[s]?this.namespaces[s]&&(this.namespaces[s].defaultChain=t):this.namespaces[s]=i}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var s;const i=(null==(s=this.session)?void 0:s.topic)||"";await this.client.core.storage.setItem(`${u}/${e}${i}`,t)}async getFromStore(e){var t;const s=(null==(t=this.session)?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${u}/${e}${s}`)}async deleteFromStore(e){var t;const s=(null==(t=this.session)?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${u}/${e}${s}`)}async cleanupStorage(){var e;try{if((null==(e=this.client)?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const e of t)e.startsWith(u)&&await this.client.core.storage.removeItem(e)}catch(e){this.logger.warn("Failed to cleanup storage",e)}}}},18496:(e,t,s)=>{s.d(t,{v:()=>a});var i=s(29972),r=s(34311),n=s(89604),o=s(72269);const a={getERC20Abi:e=>o.o.USDT_CONTRACT_ADDRESSES.includes(e)?n.r:i.F,getSwapAbi:()=>r.Q}},18898:(e,t,s)=>{s.d(t,{$Q:()=>b,GF:()=>y,S9:()=>C,Vx:()=>f,ZP:()=>c,dQ:()=>h,lZ:()=>d,m5:()=>u,mF:()=>m,pi:()=>g,qE:()=>p,yJ:()=>I,zl:()=>w});var i=s(94549),r=s(50046),n=s.n(r),o=Object.defineProperty,a=(e,t,s)=>((e,t,s)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class c extends i.H{constructor(e){super(),this.opts=e,a(this,"protocol","wc"),a(this,"version",2)}}var l=Object.defineProperty;class d extends i.H{constructor(e,t){super(),this.core=e,this.logger=t,((e,t,s)=>{((e,t,s)=>{t in e?l(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s})(e,"symbol"!=typeof t?t+"":t,s)})(this,"records",new Map)}}class h{constructor(e,t){this.logger=e,this.core=t}}class p extends i.H{constructor(e,t){super(),this.relayer=e,this.logger=t}}class u extends i.H{constructor(e){super()}}class g{constructor(e,t,s,i){this.core=e,this.logger=t,this.name=s}}Object.defineProperty;class m extends i.H{constructor(e,t){super(),this.relayer=e,this.logger=t}}class f extends i.H{constructor(e,t){super(),this.core=e,this.logger=t}}class w{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}}class y{constructor(e,t){this.projectId=e,this.logger=t}}class b{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}}var v=Object.defineProperty,E=(e,t,s)=>((e,t,s)=>t in e?v(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);n();class C{constructor(e){this.opts=e,E(this,"protocol","wc"),E(this,"version",2)}}r.EventEmitter;class I{constructor(e){this.client=e}}},20475:(e,t,s)=>{s.d(t,{_:()=>q});var i=s(18338),r=s(67902),n=s(72269),o=s(55611),a=s(88759),c=s(72397),l=s(46362),d=s(98299),h=s(89305),p=s(86792),u=s(83077),g=s(92492),m=s(93474),f=s(49951),w=s(1420),y=s(16444),b=s(68251),v=s(47981),E=s(37686),C=s(13766),I=s(31100),N=s(86454),A=s(3555),_=s(22143),S=s(11847),P=s(36507),T=s(41607),O=s(44242),k=s(69658),R=s(83229),x=s(51765),U=s(20602),D=s(2974),L=s(38097),W=s(36347),M=s(28873),B=s(62410),j=s(25598);class q{constructor(e){this.chainNamespaces=[],this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(e,t)=>{if(e){const s=d.W.getNetworkData(e)?.requestedCaipNetworks?.find(e=>e.id===t);if(s)return s;const i=d.W.getNetworkData(e)?.caipNetwork;if(i)return i;const r=d.W.getRequestedCaipNetworks(e);return r.filter(t=>t.chainNamespace===e)?.[0]}return d.W.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const e=this.getCaipNetwork();if(e)return e.id},this.getCaipNetworks=e=>d.W.getCaipNetworks(e),this.getActiveChainNamespace=()=>d.W.state.activeChain,this.setRequestedCaipNetworks=(e,t)=>{d.W.setRequestedCaipNetworks(e,t)},this.getApprovedCaipNetworkIds=()=>d.W.getAllApprovedCaipNetworkIds(),this.getCaipAddress=e=>d.W.state.activeChain!==e&&e?d.W.getAccountProp("caipAddress",e):d.W.state.activeCaipAddress,this.setClientId=e=>{y.T.setClientId(e)},this.getProvider=e=>W.A.getProvider(e),this.getProviderType=e=>W.A.getProviderId(e),this.getPreferredAccountType=e=>l.U.state.preferredAccountTypes?.[e],this.setCaipAddress=(e,t)=>{l.U.setCaipAddress(e,t),e&&w.H.state.enableEmbedded&&this.close()},this.setBalance=(e,t,s)=>{l.U.setBalance(e,t,s)},this.setProfileName=(e,t)=>{l.U.setProfileName(e,t)},this.setProfileImage=(e,t)=>{l.U.setProfileImage(e,t)},this.setUser=(e,t)=>{l.U.setUser(e,t)},this.resetAccount=e=>{l.U.resetAccount(e)},this.setCaipNetwork=e=>{d.W.setActiveCaipNetwork(e)},this.setCaipNetworkOfNamespace=(e,t)=>{d.W.setChainNetworkData(t,{caipNetwork:e})},this.setAllAccounts=(e,t)=>{l.U.setAllAccounts(e,t),w.H.setHasMultipleAddresses(e?.length>1)},this.setStatus=(e,t)=>{l.U.setStatus(e,t),u.a.isConnected()?S.i.setConnectionStatus("connected"):S.i.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=e=>d.W.getAccountProp("address",e),this.setConnectors=e=>{const t=[...u.a.state.allConnectors,...e];u.a.setConnectors(t)},this.setConnections=(e,t)=>{p.x.setConnections(e,t)},this.fetchIdentity=e=>y.T.fetchIdentity(e),this.getReownName=e=>C.f.getNamesForAddress(e),this.getConnectors=()=>u.a.getConnectors(),this.getConnectorImage=e=>N.$.getConnectorImage(e),this.setConnectedWalletInfo=(e,t)=>{const s=W.A.getProviderId(t),i=e?{...e,type:s}:void 0;l.U.setConnectedWalletInfo(i,t)},this.getIsConnectedState=()=>Boolean(d.W.state.activeCaipAddress),this.addAddressLabel=(e,t,s)=>{l.U.addAddressLabel(e,t,s)},this.removeAddressLabel=(e,t)=>{l.U.removeAddressLabel(e,t)},this.getAddress=e=>d.W.state.activeChain!==e&&e?d.W.getAccountProp("address",e):l.U.state.address,this.setApprovedCaipNetworksData=e=>d.W.setApprovedCaipNetworksData(e),this.resetNetwork=e=>{d.W.resetNetwork(e)},this.addConnector=e=>{u.a.addConnector(e)},this.resetWcConnection=()=>{p.x.resetWcConnection()},this.setAddressExplorerUrl=(e,t)=>{l.U.setAddressExplorerUrl(e,t)},this.setSmartAccountDeployed=(e,t)=>{l.U.setSmartAccountDeployed(e,t)},this.setSmartAccountEnabledNetworks=(e,t)=>{d.W.setSmartAccountEnabledNetworks(e,t)},this.setPreferredAccountType=(e,t)=>{l.U.setPreferredAccountType(e,t)},this.setEIP6963Enabled=e=>{w.H.setEIP6963Enabled(e)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,t){const s=e?.map(e=>e.namespace).filter(e=>Boolean(e));if(s?.length)return[...new Set(s)];const i=t?.map(e=>e.chainNamespace);return[...new Set(i)]}async initialize(e){this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),await this.syncExistingConnection(),this.remoteFeatures=await B.x.fetchRemoteFeatures(e),w.H.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&h.aG.setOnrampProviders(this.remoteFeatures.onramp),(w.H.state.remoteFeatures?.email||Array.isArray(w.H.state.remoteFeatures?.socials)&&w.H.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){const e=await m.N.fetchAllowedOrigins();if(e&&_.w.isClient()){const t=window.location.origin;j.kl.isOriginAllowed(t,e,j.E1.DEFAULT_ALLOWED_ANCESTORS)||I.h.open(U.R.ALERT_ERRORS.INVALID_APP_CONFIGURATION,"error")}else I.h.open(U.R.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}sendInitializeEvent(e){const{...t}=e;delete t.adapters,delete t.universalProvider,v.E.sendEvent({type:"track",event:"INITIALIZE",properties:{...t,networks:e.networks.map(e=>e.id),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&f.W.setThemeMode(e.themeMode),e.themeVariables&&f.W.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");d.W.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&d.W.setActiveCaipNetwork(t)}initializeConnectionController(e){p.x.setWcBasic(e.basic??!1)}initializeConnectorController(){u.a.initialize(this.chainNamespaces)}initializeProjectSettings(e){w.H.setProjectId(e.projectId),w.H.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){w.H.setDebug(!1!==e.debug),w.H.setEnableWalletConnect(!1!==e.enableWalletConnect),w.H.setEnableWalletGuide(!1!==e.enableWalletGuide),w.H.setEnableWallets(!1!==e.enableWallets),w.H.setEIP6963Enabled(!1!==e.enableEIP6963),w.H.setEnableNetworkSwitch(!1!==e.enableNetworkSwitch),w.H.setEnableAuthLogger(!1!==e.enableAuthLogger),w.H.setCustomRpcUrls(e.customRpcUrls),w.H.setEnableEmbedded(e.enableEmbedded),w.H.setAllWallets(e.allWallets),w.H.setIncludeWalletIds(e.includeWalletIds),w.H.setExcludeWalletIds(e.excludeWalletIds),w.H.setFeaturedWalletIds(e.featuredWalletIds),w.H.setTokens(e.tokens),w.H.setTermsConditionsUrl(e.termsConditionsUrl),w.H.setPrivacyPolicyUrl(e.privacyPolicyUrl),w.H.setCustomWallets(e.customWallets),w.H.setFeatures(e.features),w.H.setAllowUnsupportedChain(e.allowUnsupportedChain),w.H.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),w.H.setPreferUniversalLinks(e.experimental_preferUniversalLinks),w.H.setDefaultAccountTypes(e.defaultAccountTypes);const t=S.i.getPreferredAccountTypes()||{},s={...w.H.state.defaultAccountTypes,...t};l.U.setPreferredAccountTypes(s);const i=this.getDefaultMetaData();if(!e.metadata&&i&&(e.metadata=i),w.H.setMetadata(e.metadata),w.H.setDisableAppend(e.disableAppend),w.H.setEnableEmbedded(e.enableEmbedded),w.H.setSIWX(e.siwx),!e.projectId)return void I.h.open(U.R.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");const r=e.adapters?.find(e=>e.namespace===n.o.CHAIN.EVM);if(r&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");w.H.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return _.w.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const t=this.getActiveChainNamespace();if(t){const s=L.R.getUnsupportedNetwork(`${t}:${e}`);d.W.setActiveCaipNetwork(s)}}getDefaultNetwork(){return L.R.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return L.R.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return L.R.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const t=e.networks.find(t=>t.id===e.defaultNetwork?.id);return t?L.R.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectNamespace(e){try{const t=this.getAdapter(e),s=W.A.getProvider(e),i=W.A.getProviderId(e),{caipAddress:r}=d.W.getAccountData(e)||{};this.setLoading(!0,e),r&&t?.disconnect&&await t.disconnect({provider:s,providerType:i}),S.i.removeConnectedNamespace(e),W.A.resetChain(e),this.setUser(void 0,e),this.setStatus("disconnected",e),this.setConnectedWalletInfo(void 0,e),u.a.removeConnectorId(e),d.W.resetAccount(e),d.W.resetNetwork(e),this.setLoading(!1,e)}catch(t){throw this.setLoading(!1,e),new Error(`Failed to disconnect chain ${e}: ${t.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const e=d.W.state.activeChain,t=this.getAdapter(e),s=this.getCaipNetwork(e)?.id;if(!t)throw new Error("Adapter not found");const i=await t.connectWalletConnect(s);this.close(),this.setClientId(i?.clientId||null),S.i.setConnectedNamespaces([...d.W.state.chains.keys()]),this.chainNamespaces.forEach(e=>{u.a.setConnectorId(R.o.CONNECTOR_TYPE_WALLET_CONNECT,e)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:t,type:s,provider:i,chain:r,caipNetwork:n,socialUri:o})=>{const a=d.W.state.activeChain,c=r||a,h=this.getAdapter(c);if(r&&r!==a&&!n){const e=this.getCaipNetworks().find(e=>e.chainNamespace===r);e&&this.setCaipNetwork(e)}if(!h)throw new Error("Adapter not found");const p=this.getCaipNetwork(c),u=await h.connect({id:e,info:t,type:s,provider:i,socialUri:o,chainId:n?.id||p?.id,rpcUrl:n?.rpcUrls?.default?.http?.[0]||p?.rpcUrls?.default?.http?.[0]});if(!u)return;S.i.addConnectedNamespace(c),this.syncProvider({...u,chainNamespace:c});const g=l.U.state.allAccounts,{accounts:m}=g?.length>0?{accounts:[...g]}:await h.getAccounts({namespace:c,id:e});this.setAllAccounts(m,c),this.setStatus("connected",c),this.syncConnectedWalletInfo(c)},reconnectExternal:async({id:e,info:t,type:s,provider:i})=>{const r=d.W.state.activeChain,n=this.getAdapter(r);n?.reconnect&&(await(n?.reconnect({id:e,info:t,type:s,provider:i,chainId:this.getCaipNetwork()?.id})),S.i.addConnectedNamespace(r),this.syncConnectedWalletInfo(r))},disconnect:async e=>{const t=(0,T.g)(e);try{const s=await Promise.allSettled(t.map(async([e])=>this.disconnectNamespace(e)));E.R.resetSend(),p.x.resetWcConnection(),await P.U.clearSessions(),u.a.setFilterByNamespace(void 0);const i=s.filter(e=>"rejected"===e.status);if(i.length>0)throw new Error(i.map(e=>e.reason.message).join(", "));S.i.deleteConnectedSocialProvider(),v.E.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:e||"all"}})}catch(e){throw new Error(`Failed to disconnect chains: ${e.message}`)}},checkInstalled:e=>e?e.some(e=>Boolean(window.ethereum?.[String(e)])):Boolean(window.ethereum),signMessage:async e=>{const t=this.getAdapter(d.W.state.activeChain),s=await(t?.signMessage({message:e,address:l.U.state.address,provider:W.A.getProvider(d.W.state.activeChain)}));return s?.signature||""},sendTransaction:async e=>{const t=e.chainNamespace;if(A.oU.SEND_SUPPORTED_NAMESPACES.includes(t)){const s=this.getAdapter(d.W.state.activeChain),i=W.A.getProvider(t),r=await(s?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}));return r?.hash||""}return""},estimateGas:async e=>{if(e.chainNamespace===n.o.CHAIN.EVM){const t=this.getAdapter(d.W.state.activeChain),s=W.A.getProvider(d.W.state.activeChain),i=this.getCaipNetwork();if(!i)throw new Error("CaipNetwork is undefined");const r=await(t?.estimateGas({...e,provider:s,caipNetwork:i}));return r?.gas||0n}return 0n},getEnsAvatar:async()=>(await this.syncIdentity({address:l.U.state.address,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:d.W.state.activeChain}),l.U.state.profileImage||!1),getEnsAddress:async e=>await j.kl.resolveReownName(e),writeContract:async e=>{const t=this.getAdapter(d.W.state.activeChain),s=this.getCaipNetwork(),i=this.getCaipAddress(),r=W.A.getProvider(d.W.state.activeChain);if(!s||!i)throw new Error("CaipNetwork or CaipAddress is undefined");const n=await(t?.writeContract({...e,caipNetwork:s,provider:r,caipAddress:i}));return n?.hash},parseUnits:(e,t)=>{const s=this.getAdapter(d.W.state.activeChain);return s?.parseUnits({value:e,decimals:t})??0n},formatUnits:(e,t)=>{const s=this.getAdapter(d.W.state.activeChain);return s?.formatUnits({value:e,decimals:t})??"0"},getCapabilities:async e=>{const t=this.getAdapter(d.W.state.activeChain);return await(t?.getCapabilities(e))},grantPermissions:async e=>{const t=this.getAdapter(d.W.state.activeChain);return await(t?.grantPermissions(e))},revokePermissions:async e=>{const t=this.getAdapter(d.W.state.activeChain);return t?.revokePermissions?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>{const t=this.getAdapter(d.W.state.activeChain);return await(t?.walletGetAssets(e))??{}},updateBalance:e=>{const t=this.getCaipNetwork(e);t&&l.U.state.address&&this.updateNativeBalance(l.U.state.address,t?.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},p.x.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){if(W.A.getProviderId(d.W.state.activeChain)===R.o.CONNECTOR_TYPE_WALLET_CONNECT){const e=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:"MetaMask Wallet"===this.universalProvider?.session?.peer?.metadata.name,approvedCaipNetworkIds:this.getChainsFromNamespaces(e)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const t=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const s=W.A.getProvider(t),i=W.A.getProviderId(t);if(e.chainNamespace===d.W.state.activeChain){const r=this.getAdapter(t);await(r?.switchNetwork({caipNetwork:e,provider:s,providerType:i}))}else if(this.setCaipNetwork(e),i===R.o.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const s=this.getAddressByChainNamespace(t);s&&this.syncAccount({address:s,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(e=>{const t=e.chains||[],s=e.accounts.map(e=>{const{chainId:t,chainNamespace:s}=o.C.parseCaipAddress(e);return`${s}:${t}`});return Array.from(new Set([...t,...s]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((t,s)=>{const i=e?.find(e=>e.namespace===s);return i?(i.construct({namespace:s,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),t[s]=i):t[s]=new M.n({namespace:s,networks:this.getCaipNetworks()}),t},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e),await(this.chainAdapters?.[e].syncConnectors(this.options,this)),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){const t=this.getAdapter(e);t?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const t=this.getAdapter(e);if(!t)return;const s=S.i.getConnectionStatus();"connected"===s?this.setStatus("connecting",e):"disconnected"===s?(S.i.clearAddressCache(),this.setStatus(s,e)):this.setStatus(s,e),t.on("switchNetwork",({address:t,chainId:s})=>{const i=this.getCaipNetworks().find(e=>e.id===s||e.caipNetworkId===s),r=d.W.state.activeChain===e,n=d.W.getAccountProp("address",e);if(i){const s=r&&t?t:n;s&&this.syncAccount({address:s,chainId:i.id,chainNamespace:e})}else this.setUnsupportedNetwork(s)}),t.on("disconnect",this.disconnect.bind(this,e)),t.on("connections",t=>{this.setConnections(t,e)}),t.on("pendingTransactions",()=>{const e=l.U.state.address,t=d.W.state.activeCaipNetwork;e&&t?.id&&this.updateNativeBalance(e,t.id,t.chainNamespace)}),t.on("accountChanged",({address:t,chainId:s})=>{const i=d.W.state.activeChain===e;i&&s?this.syncAccount({address:t,chainId:s,chainNamespace:e}):i&&d.W.state.activeCaipNetwork?.id?this.syncAccount({address:t,chainId:d.W.state.activeCaipNetwork?.id,chainNamespace:e}):this.syncAccountInfo(t,s,e),this.syncAllAccounts(e)})}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{e===n.o.CHAIN.EVM&&_.w.isSafeApp()&&u.a.setConnectorId(n.o.CONNECTOR_ID.SAFE,e);const t=u.a.getConnectorId(e);switch(this.setStatus("connecting",e),t){case n.o.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case n.o.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(t){console.warn("AppKit couldn't sync existing connection",t),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){const t=this.getAdapter(e),s=u.a.getConnectorId(e),i=this.getCaipNetwork(e),r=u.a.getConnectors(e).find(e=>e.id===s);try{if(!t||!r)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!i?.id)throw new Error("CaipNetwork not found");const s=await(t?.syncConnection({namespace:e,id:r.id,chainId:i.id,rpcUrl:i?.rpcUrls?.default?.http?.[0]}));if(s){const i=await(t?.getAccounts({namespace:e,id:r.id}));i&&i.accounts.length>0?this.setAllAccounts(i.accounts,e):this.setAllAccounts([_.w.createAccount(e,s.address,"eoa")],e),this.syncProvider({...s,chainNamespace:e}),await this.syncAccount({...s,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch(t){this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async e=>{const t=this.getAdapter(e),s=this.universalProvider?.session?.namespaces?.[e]?.accounts||[],i=d.W.state.activeCaipNetwork?.id,r=s.find(e=>{const{chainId:t}=o.C.parseCaipAddress(e);return t===i?.toString()})||s[0];if(r){const s=o.C.validateCaipAddress(r),{chainId:i,address:a}=o.C.parseCaipAddress(s);if(W.A.setProviderId(e,R.o.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&d.W.state.activeCaipNetwork&&t?.namespace!==n.o.CHAIN.EVM){const s=t?.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:d.W.state.activeCaipNetwork});W.A.setProvider(e,s)}else W.A.setProvider(e,this.universalProvider);u.a.setConnectorId(n.o.CONNECTOR_ID.WALLET_CONNECT,e),S.i.addConnectedNamespace(e),this.syncWalletConnectAccounts(e),await this.syncAccount({address:a,chainId:i,chainNamespace:e})}else this.setStatus("disconnected",e);this.syncConnectedWalletInfo(e),await d.W.setApprovedCaipNetworksData(e)});await Promise.all(e)}syncWalletConnectAccounts(e){const t=this.universalProvider?.session?.namespaces?.[e]?.accounts?.map(e=>{const{address:t}=o.C.parseCaipAddress(e);return t}).filter((e,t,s)=>s.indexOf(e)===t);t&&this.setAllAccounts(t.map(t=>_.w.createAccount(e,t,"bip122"===e?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:s,chainNamespace:i}){W.A.setProviderId(i,e),W.A.setProvider(i,t),u.a.setConnectorId(s,i)}async syncAllAccounts(e){const t=u.a.getConnectorId(e);if(!t)return;const s=this.getAdapter(e),i=await(s?.getAccounts({namespace:e,id:t}));i&&i.accounts.length>0&&this.setAllAccounts(i.accounts,e)}async syncAccount(e){const t=e.chainNamespace===d.W.state.activeChain,s=d.W.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:i,chainId:r,chainNamespace:a}=e,{chainId:c}=S.i.getActiveNetworkProps(),h=r||c,p=d.W.state.activeCaipNetwork?.name===n.o.UNSUPPORTED_NETWORK_NAME,u=d.W.getNetworkProp("supportsAllNetworks",a);if(this.setStatus("connected",a),(!p||u)&&h){let e=this.getCaipNetworks().find(e=>e.id.toString()===h.toString()),r=this.getCaipNetworks().find(e=>e.chainNamespace===a);if(!u&&!e&&!r){const t=this.getApprovedCaipNetworkIds()||[],s=t.find(e=>o.C.parseCaipNetworkId(e)?.chainId===h.toString()),i=t.find(e=>o.C.parseCaipNetworkId(e)?.chainNamespace===a);e=this.getCaipNetworks().find(e=>e.caipNetworkId===s),r=this.getCaipNetworks().find(e=>e.caipNetworkId===i||"deprecatedCaipNetworkId"in e&&e.deprecatedCaipNetworkId===i)}const c=e||r;c?.chainNamespace===d.W.state.activeChain?w.H.state.enableNetworkSwitch&&!w.H.state.allowUnsupportedChain&&d.W.state.activeCaipNetwork?.name===n.o.UNSUPPORTED_NETWORK_NAME?d.W.showUnsupportedChainUI():this.setCaipNetwork(c):t||s&&this.setCaipNetworkOfNamespace(s,a),this.syncConnectedWalletInfo(a),x.y.isLowerCaseMatch(i,l.U.state.address)||this.syncAccountInfo(i,c?.id,a),t?await this.syncBalance({address:i,chainId:c?.id,chainNamespace:a}):await this.syncBalance({address:i,chainId:s?.id,chainNamespace:a})}}async syncAccountInfo(e,t,s){const i=this.getCaipAddress(s),r=t||i?.split(":")[1];if(!r)return;const n=`${s}:${r}:${e}`;this.setCaipAddress(n,s),await this.syncIdentity({address:e,chainId:r,chainNamespace:s})}async syncReownName(e,t){try{const s=await this.getReownName(e);if(s[0]){const e=s[0];this.setProfileName(e.name,t)}else this.setProfileName(null,t)}catch{this.setProfileName(null,t)}}syncConnectedWalletInfo(e){const t=u.a.getConnectorId(e),s=W.A.getProviderId(e);if(s===R.o.CONNECTOR_TYPE_ANNOUNCED||s===R.o.CONNECTOR_TYPE_INJECTED){if(t){const s=this.getConnectors().find(e=>e.id===t);if(s){const{info:t,name:i,imageUrl:r}=s,n=r||this.getConnectorImage(s);this.setConnectedWalletInfo({name:i,icon:n,...t},e)}}}else if(s===R.o.CONNECTOR_TYPE_WALLET_CONNECT){const t=W.A.getProvider(e);t?.session&&this.setConnectedWalletInfo({...t.session.peer.metadata,name:t.session.peer.metadata.name,icon:t.session.peer.metadata.icons?.[0]},e)}else if(t&&t===n.o.CONNECTOR_ID.COINBASE){const t=this.getConnectors().find(e=>e.id===n.o.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(t)},e)}}async syncBalance(e){r.L.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(t=>t.id.toString()===e.chainId?.toString())&&e.chainId&&await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,t,s){const i=this.getAdapter(s),r=d.W.getCaipNetworkByNamespace(s,t);if(i){const n=await i.getBalance({address:e,chainId:t,caipNetwork:r,tokens:this.options.tokens});return this.setBalance(n.balance,n.symbol,s),n}}async initializeUniversalAdapter(){const e=D.r.createLogger((e,...t)=>{e&&this.handleAlertError(e),console.error(...t)}),t={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};w.H.setManualWCControl(Boolean(this.options?.manualWCControl)),this.universalProvider=this.options.universalProvider??await i.A.init(t),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{p.x.setUri(e)}),this.universalProvider.on("connect",p.x.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),p.x.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{const t=this.getCaipNetworks().find(t=>t.id==e),s=this.getCaipNetwork();t?s?.id!==t?.id&&this.setCaipNetwork(t):this.setUnsupportedNetwork(e)}),this.universalProvider.on("session_event",e=>{if(j.kl.isSessionEventData(e)){const{name:t,data:s}=e.params.event;"accountsChanged"===t&&Array.isArray(s)&&_.w.isCaipAddress(s[0])&&this.syncAccount(o.C.parseCaipAddress(s[0]))}}))}createUniversalProvider(){return!this.universalProviderInitPromise&&_.w.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){v.E.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const t=Object.entries(U.R.UniversalProviderErrors).find(([,{message:t}])=>e.message.includes(t)),[s,i]=t??[],{message:r,alertErrorKey:n}=i??{};if(s&&r&&!this.reportedAlertErrors[s]){const e=U.R.ALERT_ERRORS[n];e&&(I.h.open(e,"error"),this.reportedAlertErrors[s]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const t=e.namespace;if(!t)return;this.createClients();const s=e;s.namespace=t,s.construct({namespace:t,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),this.chainNamespaces.includes(t)||this.chainNamespaces.push(t),this.chainAdapters&&(this.chainAdapters[t]=s)}async open(e){return await this.injectModalUi(),e?.uri&&p.x.setUri(e.uri),e?.arguments&&"Swap"===e?.view?a.W.open({...e,data:{swap:e.arguments}}):a.W.open(e)}async close(){await this.injectModalUi(),a.W.close()}setLoading(e,t){a.W.setLoading(e,t)}async disconnect(e){await p.x.disconnect(e)}getSIWX(){return w.H.state.siwx}getError(){return""}getChainId(){return d.W.state.activeCaipNetwork?.id}async switchNetwork(e){const t=this.getCaipNetworks().find(t=>t.id===e.id);t?await d.W.switchActiveNetwork(t):I.h.open(U.R.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error")}getWalletProvider(){return d.W.state.activeChain?W.A.state.providers[d.W.state.activeChain]:null}getWalletProviderType(){return W.A.getProviderId(d.W.state.activeChain)}subscribeProviders(e){return W.A.subscribeProviders(e)}getThemeMode(){return f.W.state.themeMode}getThemeVariables(){return f.W.state.themeVariables}setThemeMode(e){f.W.setThemeMode(e),(0,k.JX)(f.W.state.themeMode)}setTermsConditionsUrl(e){w.H.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){w.H.setPrivacyPolicyUrl(e)}setThemeVariables(e){f.W.setThemeVariables(e),(0,k.ds)(f.W.state.themeVariables)}subscribeTheme(e){return f.W.subscribe(e)}getWalletInfo(){return l.U.state.connectedWalletInfo}getAccount(e){const t=u.a.getAuthConnector(e),s=d.W.getAccountData(e),i=d.W.state.activeChain,r=S.i.getConnectedConnectorId(e||i);if(s)return{allAccounts:s.allAccounts,caipAddress:s.caipAddress,address:_.w.getPlainAddress(s.caipAddress),isConnected:Boolean(s.caipAddress),status:s.status,embeddedWalletInfo:t&&r===n.o.CONNECTOR_ID.AUTH?{user:s.user?{...s.user,username:S.i.getConnectedSocialUsername()}:void 0,authProvider:s.socialProvider||"email",accountType:s.preferredAccountTypes?.[e||i],isSmartAccountDeployed:Boolean(s.smartAccountDeployed)}:void 0}}subscribeAccount(e,t){const s=()=>{const s=this.getAccount(t);s&&e(s)};t?d.W.subscribeChainProp("accountState",s,t):d.W.subscribe(s),u.a.subscribe(s)}subscribeNetwork(e){return d.W.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t?.id,caipNetworkId:t?.caipNetworkId})})}subscribeWalletInfo(e){return l.U.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){l.U.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){d.W.subscribeKey("activeCaipNetwork",e)}getState(){return b.z.state}subscribeState(e){return b.z.subscribe(e)}showErrorMessage(e){g.P.showError(e)}showSuccessMessage(e){g.P.showSuccess(e)}getEvent(){return{...v.E.state}}subscribeEvents(e){return v.E.subscribe(e)}replace(e){c.I.replace(e)}redirect(e){c.I.push(e)}popTransactionStack(e){c.I.popTransactionStack(e)}isOpen(){return a.W.state.open}isTransactionStackEmpty(){return 0===c.I.state.transactionStack.length}static getInstance(){return this.instance}updateFeatures(e){w.H.setFeatures(e)}updateRemoteFeatures(e){w.H.setRemoteFeatures(e)}updateOptions(e){const t={...w.H.state||{},...e};w.H.setOptions(t)}setConnectMethodsOrder(e){w.H.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){w.H.setWalletFeaturesOrder(e)}setCollapseWallets(e){w.H.setCollapseWallets(e)}setSocialsOrder(e){w.H.setSocialsOrder(e)}getConnectMethodsOrder(){return O.Aj.getConnectOrderMethod(w.H.state.features,u.a.getConnectors())}addNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const s=this.extendCaipNetwork(t,this.options);this.getCaipNetworks().find(e=>e.id===s.id)||d.W.addNetwork(s)}removeNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(e=>e.id===t)&&d.W.removeNetwork(e,t)}}},20602:(e,t,s)=>{s.d(t,{R:()=>i});const i={EmbeddedWalletAbortController:new AbortController,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"INVALID_APP_CONFIGURATION"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{shortMessage:"Network Not Found",longMessage:"Network not found - please make sure it is included in 'networks' array in createAppKit function"},INVALID_APP_CONFIGURATION:{shortMessage:"Invalid App Configuration",longMessage:()=>`Origin ${"undefined"!=typeof window?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},IFRAME_LOAD_FAILED:{shortMessage:"Network Error - Could not load embedded wallet",longMessage:()=>"There was an issue loading the embedded wallet. Please try again later."},IFRAME_REQUEST_TIMEOUT:{shortMessage:"Embedded Wallet Request Timed Out",longMessage:()=>"There was an issue doing the request to the embedded wallet. Please try again later."},UNVERIFIED_DOMAIN:{shortMessage:"Invalid App Configuration",longMessage:()=>"There was an issue loading the embedded wallet. Please verify that your domain is allowed at cloud.reown.com"},JWT_TOKEN_NOT_VALID:{shortMessage:"Session Expired",longMessage:"Invalid session found on UniversalProvider - please check your time settings and connect again"},INVALID_PROJECT_ID:{shortMessage:"Invalid App Configuration",longMessage:"Invalid Project ID - update configuration"},PROJECT_ID_NOT_CONFIGURED:{shortMessage:"Project ID Not Configured",longMessage:"Project ID Not Configured - update configuration on cloud.reown.com"}}}},22129:(e,t,s)=>{s.d(t,{F:()=>l}),s(18338);var i=s(72269),r=s(98299),n=s(1420),o=s(36507),a=s(82868),c=s(25598);class l{constructor({provider:e,namespace:t}){this.id=i.o.CONNECTOR_ID.WALLET_CONNECT,this.name=a.L.ConnectorNamesMap[i.o.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=a.L.ConnectorImageIds[i.o.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=r.W.getCaipNetworks.bind(r.W),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=t}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const e=this.getCaipNetworks(),t=n.H.state.universalProviderConfigOverride,s=c.kl.createNamespaces(e,t);await this.provider.connect({optionalNamespaces:s})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(e=>e.caipNetworkId);return o.U.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:d})}}const d=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"]},22143:(e,t,s)=>{s.d(t,{w:()=>o});var i=s(72269),r=s(3555),n=s(11847);const o={isMobile(){return!!this.isClient()&&Boolean("function"==typeof window?.matchMedia&&window?.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent))},checkCaipNetwork:(e,t="")=>e?.caipNetworkId.toLocaleLowerCase().includes(t.toLowerCase()),isAndroid(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return o.isMobile()&&e.includes("android")},isIos(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")},isSafari(){if(!this.isClient())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("safari")},isClient:()=>"undefined"!=typeof window,isPairingExpired:e=>!e||e-Date.now()<=r.oU.TEN_SEC_MS,isAllowedRetry:(e,t=r.oU.ONE_SEC_MS)=>Date.now()-e>=t,copyToClopboard(e){navigator.clipboard.writeText(e)},isIframe(){try{return window?.self!==window?.top}catch(e){return!1}},isSafeApp(){if(o.isClient()&&window.self!==window.top)try{const e=window?.location?.ancestorOrigins?.[0],t="https://app.safe.global";if(e){const s=new URL(e),i=new URL(t);return s.hostname===i.hostname}}catch{return!1}return!1},getPairingExpiry:()=>Date.now()+r.oU.FOUR_MINUTES_MS,getNetworkId:e=>e?.split(":")[1],getPlainAddress:e=>e?.split(":")[2],wait:async e=>new Promise(t=>{setTimeout(t,e)}),debounce(e,t=500){let s;return(...i)=>{s&&clearTimeout(s),s=setTimeout(function(){e(...i)},t)}},isHttpUrl:e=>e.startsWith("http://")||e.startsWith("https://"),formatNativeUrl(e,t,s=null){if(o.isHttpUrl(e))return this.formatUniversalUrl(e,t);let i=e,r=s;i.includes("://")||(i=e.replaceAll("/","").replaceAll(":",""),i=`${i}://`),i.endsWith("/")||(i=`${i}/`),r&&!r?.endsWith("/")&&(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));const n=encodeURIComponent(t);return{redirect:`${i}wc?uri=${n}`,redirectUniversalLink:r?`${r}wc?uri=${n}`:void 0,href:i}},formatUniversalUrl(e,t){if(!o.isHttpUrl(e))return this.formatNativeUrl(e,t);let s=e;return s.endsWith("/")||(s=`${s}/`),{redirect:`${s}wc?uri=${encodeURIComponent(t)}`,href:s}},getOpenTargetForPlatform(e){return"popupWindow"===e?e:this.isTelegram()?n.i.getTelegramSocialProvider()?"_top":"_blank":e},openHref(e,t,s){window?.open(e,this.getOpenTargetForPlatform(t),s||"noreferrer noopener")},returnOpenHref(e,t,s){return window?.open(e,this.getOpenTargetForPlatform(t),s||"noreferrer noopener")},isTelegram:()=>"undefined"!=typeof window&&(Boolean(window.TelegramWebviewProxy)||Boolean(window.Telegram)||Boolean(window.TelegramWebviewProxyProto)),isPWA(){if("undefined"==typeof window)return!1;const e=window.matchMedia?.("(display-mode: standalone)")?.matches,t=window?.navigator?.standalone;return Boolean(e||t)},async preloadImage(e){const t=new Promise((t,s)=>{const i=new Image;i.onload=t,i.onerror=s,i.crossOrigin="anonymous",i.src=e});return Promise.race([t,o.wait(2e3)])},formatBalance(e,t){let s="0.000";if("string"==typeof e){const t=Number(e);if(t){const e=Math.floor(1e3*t)/1e3;e&&(s=e.toString())}}return`${s}${t?` ${t}`:""}`},formatBalance2(e,t){let s;if("0"===e)s="0";else if("string"==typeof e){const t=Number(e);t&&(s=t.toString().match(/^-?\d+(?:\.\d{0,3})?/u)?.[0])}return{value:s??"0",rest:"0"===s?"000":"",symbol:t}},getApiUrl:()=>i.o.W3M_API_URL,getBlockchainApiUrl:()=>i.o.BLOCKCHAIN_API_RPC_URL,getAnalyticsUrl:()=>i.o.PULSE_API_URL,getUUID:()=>crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),parseError:e=>"string"==typeof e?e:"string"==typeof e?.issues?.[0]?.message?e.issues[0].message:e instanceof Error?e.message:"Unknown error",sortRequestedNetworks(e,t=[]){const s={};return t&&e&&(e.forEach((e,t)=>{s[e]=t}),t.sort((e,t)=>{const i=s[e.id],r=s[t.id];return void 0!==i&&void 0!==r?i-r:void 0!==i?-1:void 0!==r?1:0})),t},calculateBalance(e){let t=0;for(const s of e)t+=s.value??0;return t},formatTokenBalance(e){const t=e.toFixed(2),[s,i]=t.split(".");return{dollars:s,pennies:i}},isAddress(e,t="eip155"){switch(t){case"eip155":return!(!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)||!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)&&!/^(?:0x)?[0-9A-F]{40}$/iu.test(e));case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(e);default:return!1}},uniqueBy(e,t){const s=new Set;return e.filter(e=>{const i=e[t];return!s.has(i)&&(s.add(i),!0)})},generateSdkVersion:(e,t,s)=>`${t}-${0===e.length?r.oU.ADAPTER_TYPES.UNIVERSAL:e.map(e=>e.adapterType).join(",")}-${s}`,createAccount:(e,t,s,i,r)=>({namespace:e,address:t,type:s,publicKey:i,path:r}),isCaipAddress(e){if("string"!=typeof e)return!1;const t=e.split(":"),s=t[0];return 3===t.filter(Boolean).length&&s in i.o.CHAIN_NAME_MAP},isMac(){const e=window?.navigator.userAgent.toLowerCase();return e.includes("macintosh")&&!e.includes("safari")},formatTelegramSocialLoginUrl(e){const t=`--${encodeURIComponent(window?.location.href)}`,s="state=";if("auth.magic.link"===new URL(e).host){const i="provider_authorization_url=",r=e.substring(e.indexOf(i)+i.length),n=this.injectIntoUrl(decodeURIComponent(r),s,t);return e.replace(r,encodeURIComponent(n))}return this.injectIntoUrl(e,s,t)},injectIntoUrl(e,t,s){const i=e.indexOf(t);if(-1===i)throw new Error(`${t} parameter not found in the URL: ${e}`);const r=e.indexOf("&",i),n=t.length,o=-1!==r?r:e.length;return e.substring(0,i+n)+(e.substring(i+n,o)+s)+e.substring(r)}}},25598:(e,t,s)=>{s.d(t,{E1:()=>i.E,kl:()=>r.k});var i=s(1435),r=s(61387)},27811:(e,t,s)=>{s.d(t,{Ay:()=>K});var i=s(90169),r=s(70255),n=s(18898),o=s(91315),a=s(15529),c=s(50046),l=s.n(c),d=s(14350);const h="client",p=`wc@2:${h}:`,u=h,g="WALLETCONNECT_DEEPLINK_CHOICE",m="Proposal expired",f=o.SEVEN_DAYS,w={wc_sessionPropose:{req:{ttl:o.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:o.ONE_DAY,prompt:!1,tag:1104},res:{ttl:o.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:o.ONE_DAY,prompt:!1,tag:1106},res:{ttl:o.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:o.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:o.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:o.ONE_DAY,prompt:!1,tag:1112},res:{ttl:o.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:o.ONE_DAY,prompt:!1,tag:1114},res:{ttl:o.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:o.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:o.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:o.FIVE_MINUTES,prompt:!1,tag:1119}}},y={min:o.FIVE_MINUTES,max:o.SEVEN_DAYS},b="IDLE",v="ACTIVE",E={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},C=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],I="wc@1.5:auth:",N=`${I}:PUB_KEY`;var A=Object.defineProperty,_=Object.defineProperties,S=Object.getOwnPropertyDescriptors,P=Object.getOwnPropertySymbols,T=Object.prototype.hasOwnProperty,O=Object.prototype.propertyIsEnumerable,k=(e,t,s)=>t in e?A(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,R=(e,t)=>{for(var s in t||(t={}))T.call(t,s)&&k(e,s,t[s]);if(P)for(var s of P(t))O.call(t,s)&&k(e,s,t[s]);return e},x=(e,t)=>_(e,S(t)),U=(e,t,s)=>k(e,"symbol"!=typeof t?t+"":t,s);class D extends n.yJ{constructor(e){super(e),U(this,"name","engine"),U(this,"events",new(l())),U(this,"initialized",!1),U(this,"requestQueue",{state:b,queue:[]}),U(this,"sessionRequestQueue",{state:b,queue:[]}),U(this,"requestQueueDelay",o.ONE_SECOND),U(this,"expectedPairingMethodMap",new Map),U(this,"recentlyDeletedMap",new Map),U(this,"recentlyDeletedLimit",200),U(this,"relayMessageCache",[]),U(this,"pendingSessions",new Map),U(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(w)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,o.toMiliseconds)(this.requestQueueDelay)))}),U(this,"connect",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t=x(R({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(t),t.optionalNamespaces=(0,a.XEe)(t.requiredNamespaces,t.optionalNamespaces),t.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:c,scopedProperties:l,relays:h}=t;let p,u=s,g=!1;try{if(u){const e=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),g=e.active}}catch(e){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),e}if(!u||!g){const{topic:e,uri:t}=await this.client.core.pairing.create();u=e,p=t}if(!u){const{message:e}=(0,a.GuA)("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(e)}const f=await this.client.core.crypto.generateKeyPair(),y=w.wc_sessionPropose.req.ttl||o.FIVE_MINUTES,b=(0,a.Xw0)(y),v=x(R(R({requiredNamespaces:r,optionalNamespaces:n,relays:h??[{protocol:i.sD}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:b,pairingTopic:u},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:(0,d.payloadId)()}),E=(0,a.hEn)("session_connect",v.id),{reject:C,resolve:I,done:N}=(0,a.Wx8)(y,m),A=({id:e})=>{e===v.id&&(this.client.events.off("proposal_expire",A),this.pendingSessions.delete(v.id),this.events.emit(E,{error:{message:m,code:0}}))};return this.client.events.on("proposal_expire",A),this.events.once(E,({error:e,session:t})=>{this.client.events.off("proposal_expire",A),e?C(e):t&&I(t)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:v,throwOnFailedPublish:!0,clientRpcId:v.id}),await this.setProposal(v.id,v),{uri:p,approval:N}}),U(this,"pair",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(e){throw this.client.logger.error("pair() failed"),e}}),U(this,"approve",async e=>{var t,s,r;const n=this.client.core.eventClient.createEvent({properties:{topic:null==(t=e?.id)?void 0:t.toString(),trace:[i.$I.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(e){throw n.setError(i.U.no_internet_connection),e}try{await this.isValidProposalId(e?.id)}catch(t){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),n.setError(i.U.proposal_not_found),t}try{await this.isValidApprove(e)}catch(e){throw this.client.logger.error("approve() -> isValidApprove() failed"),n.setError(i.U.session_approve_namespace_validation_failure),e}const{id:o,relayProtocol:c,namespaces:l,sessionProperties:d,scopedProperties:h,sessionConfig:p}=e,u=this.client.proposal.get(o);this.client.core.eventClient.deleteEvent({eventId:n.eventId});const{pairingTopic:g,proposer:m,requiredNamespaces:w,optionalNamespaces:y}=u;let b=null==(s=this.client.core.eventClient)?void 0:s.getEvent({topic:g});b||(b=null==(r=this.client.core.eventClient)?void 0:r.createEvent({type:i.$I.session_approve_started,properties:{topic:g,trace:[i.$I.session_approve_started,i.$I.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),E=m.publicKey,C=await this.client.core.crypto.generateSharedKey(v,E),I=R(R(R({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:(0,a.Xw0)(f)},d&&{sessionProperties:d}),h&&{scopedProperties:h}),p&&{sessionConfig:p}),N=i.cV.relay;b.addTrace(i.$I.subscribing_session_topic);try{await this.client.core.relayer.subscribe(C,{transportType:N})}catch(e){throw b.setError(i.U.subscribe_session_topic_failure),e}b.addTrace(i.$I.subscribe_session_topic_success);const A=x(R({},I),{topic:C,requiredNamespaces:w,optionalNamespaces:y,pairingTopic:g,acknowledged:!1,self:I.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:v,transportType:i.cV.relay});await this.client.session.set(C,A),b.addTrace(i.$I.store_session);try{b.addTrace(i.$I.publishing_session_settle),await this.sendRequest({topic:C,method:"wc_sessionSettle",params:I,throwOnFailedPublish:!0}).catch(e=>{throw b?.setError(i.U.session_settle_publish_failure),e}),b.addTrace(i.$I.session_settle_publish_success),b.addTrace(i.$I.publishing_session_approve),await this.sendResult({id:o,topic:g,result:{relay:{protocol:c??"irn"},responderPublicKey:v},throwOnFailedPublish:!0}).catch(e=>{throw b?.setError(i.U.session_approve_publish_failure),e}),b.addTrace(i.$I.session_approve_publish_success)}catch(e){throw this.client.logger.error(e),this.client.session.delete(C,(0,a.Hjj)("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(C),e}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:m.metadata}),await this.client.proposal.delete(o,(0,a.Hjj)("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(C,(0,a.Xw0)(f)),{topic:C,acknowledged:()=>Promise.resolve(this.client.session.get(C))}}),U(this,"reject",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(e){throw this.client.logger.error("reject() -> isValidReject() failed"),e}const{id:t,reason:s}=e;let i;try{i=this.client.proposal.get(t).pairingTopic}catch(e){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),e}i&&(await this.sendError({id:t,topic:i,error:s,rpcOpts:w.wc_sessionPropose.reject}),await this.client.proposal.delete(t,(0,a.Hjj)("USER_DISCONNECTED")))}),U(this,"update",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(e){throw this.client.logger.error("update() -> isValidUpdate() failed"),e}const{topic:t,namespaces:s}=e,{done:i,resolve:r,reject:n}=(0,a.Wx8)(),o=(0,d.payloadId)(),c=(0,d.getBigIntRpcId)().toString(),l=this.client.session.get(t).namespaces;return this.events.once((0,a.hEn)("session_update",o),({error:e})=>{e?n(e):r()}),await this.client.session.update(t,{namespaces:s}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:c}).catch(e=>{this.client.logger.error(e),this.client.session.update(t,{namespaces:l}),n(e)}),{acknowledged:i}}),U(this,"extend",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(e){throw this.client.logger.error("extend() -> isValidExtend() failed"),e}const{topic:t}=e,s=(0,d.payloadId)(),{done:i,resolve:r,reject:n}=(0,a.Wx8)();return this.events.once((0,a.hEn)("session_extend",s),({error:e})=>{e?n(e):r()}),await this.setExpiry(t,(0,a.Xw0)(f)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(e=>{n(e)}),{acknowledged:i}}),U(this,"request",async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(e){throw this.client.logger.error("request() -> isValidRequest() failed"),e}const{chainId:t,request:s,topic:r,expiry:n=w.wc_sessionRequest.req.ttl}=e,o=this.client.session.get(r);o?.transportType===i.cV.relay&&await this.confirmOnlineStateOrThrow();const c=(0,d.payloadId)(),l=(0,d.getBigIntRpcId)().toString(),{done:h,resolve:p,reject:u}=(0,a.Wx8)(n,"Request expired. Please try again.");this.events.once((0,a.hEn)("session_request",c),({error:e,result:t})=>{e?u(e):p(t)});const m="wc_sessionRequest",f=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:r,method:m,params:{request:x(R({},s),{expiryTimestamp:(0,a.Xw0)(n)}),chainId:t},expiry:n,throwOnFailedPublish:!0,appLink:f}).catch(e=>u(e)),this.client.events.emit("session_request_sent",{topic:r,request:s,chainId:t,id:c}),await h();const y={request:x(R({},s),{expiryTimestamp:(0,a.Xw0)(n)}),chainId:t},b=this.shouldSetTVF(m,y);return await Promise.all([new Promise(async e=>{await this.sendRequest(R({clientRpcId:c,relayRpcId:l,topic:r,method:m,params:y,expiry:n,throwOnFailedPublish:!0},b&&{tvf:this.getTVFParams(c,y)})).catch(e=>u(e)),this.client.events.emit("session_request_sent",{topic:r,request:s,chainId:t,id:c}),e()}),new Promise(async e=>{var t;if(null==(t=o.sessionConfig)||!t.disableDeepLink){const e=await(0,a.jTh)(this.client.core.storage,g);await(0,a.n3s)({id:c,topic:r,wcDeepLink:e})}e()}),h()]).then(e=>e[2])}),U(this,"respond",async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:s}=e,{id:r}=s,n=this.client.session.get(t);n.transportType===i.cV.relay&&await this.confirmOnlineStateOrThrow();const o=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);(0,d.isJsonRpcResult)(s)?await this.sendResult({id:r,topic:t,result:s.result,throwOnFailedPublish:!0,appLink:o}):(0,d.isJsonRpcError)(s)&&await this.sendError({id:r,topic:t,error:s.error,appLink:o}),this.cleanupAfterResponse(e)}),U(this,"ping",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(e){throw this.client.logger.error("ping() -> isValidPing() failed"),e}const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=(0,d.payloadId)(),s=(0,d.getBigIntRpcId)().toString(),{done:i,resolve:r,reject:n}=(0,a.Wx8)();this.events.once((0,a.hEn)("session_ping",e),({error:e})=>{e?n(e):r()}),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:e,relayRpcId:s}),i()])}else this.client.core.pairing.pairings.keys.includes(t)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:t}))}),U(this,"emit",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:s,chainId:i}=e,r=(0,d.getBigIntRpcId)().toString(),n=(0,d.payloadId)();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:r,clientRpcId:n})}),U(this,"disconnect",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:(0,a.Hjj)("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else{if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:e}=(0,a.GuA)("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(e)}await this.client.core.pairing.disconnect({topic:t})}}),U(this,"find",e=>(this.isInitialized(),this.client.session.getAll().filter(t=>(0,a.HNf)(t,e)))),U(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),U(this,"authenticate",async(e,t)=>{var s;this.isInitialized(),this.isValidAuthenticate(e);const r=t&&this.client.core.linkModeSupportedApps.includes(t)&&(null==(s=this.client.metadata.redirect)?void 0:s.linkMode),n=r?i.cV.link_mode:i.cV.relay;n===i.cV.relay&&await this.confirmOnlineStateOrThrow();const{chains:o,statement:c="",uri:l,domain:h,nonce:p,type:u,exp:g,nbf:m,methods:y=[],expiry:b}=e,v=[...e.resources||[]],{topic:E,uri:C}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:n});this.client.logger.info({message:"Generated new pairing",pairing:{topic:E,uri:C}});const I=await this.client.core.crypto.generateKeyPair(),A=(0,a.EN$)(I);if(await Promise.all([this.client.auth.authKeys.set(N,{responseTopic:A,publicKey:I}),this.client.auth.pairingTopics.set(A,{topic:A,pairingTopic:E})]),await this.client.core.relayer.subscribe(A,{transportType:n}),this.client.logger.info(`sending request to new pairing topic: ${E}`),y.length>0){const{namespace:e}=(0,a._Yb)(o[0]);let t=(0,a.e8_)(e,"request",y);(0,a.VBM)(v)&&(t=(0,a.hVC)(t,v.pop())),v.push(t)}const _=b&&b>w.wc_sessionAuthenticate.req.ttl?b:w.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:u??"caip122",chains:o,statement:c,aud:l,domain:h,version:"1",nonce:p,iat:(new Date).toISOString(),exp:g,nbf:m,resources:v},requester:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:(0,a.Xw0)(_)},P={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:o,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:E,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:(0,a.Xw0)(w.wc_sessionPropose.req.ttl),id:(0,d.payloadId)()},{done:T,resolve:O,reject:k}=(0,a.Wx8)(_,"Request expired"),U=(0,d.payloadId)(),D=(0,a.hEn)("session_connect",P.id),L=(0,a.hEn)("session_request",U),W=async({error:e,session:t})=>{this.events.off(L,M),e?k(e):t&&O({session:t})},M=async e=>{var s,r,o;if(await this.deletePendingAuthRequest(U,{message:"fulfilled",code:0}),e.error){const t=(0,a.Hjj)("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(D,W),k(e.error.message))}await this.deleteProposal(P.id),this.events.off(D,W);const{cacaos:c,responder:l}=e.result,d=[],h=[];for(const e of c){await(0,a.IjX)({cacao:e,projectId:this.client.core.projectId})||(this.client.logger.error(e,"Signature verification failed"),k((0,a.Hjj)("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:t}=e,s=(0,a.VBM)(t.resources),i=[(0,a.xkc)(t.iss)],r=(0,a.q_h)(t.iss);if(s){const e=(0,a.sc_)(s),t=(0,a.WWN)(s);d.push(...e),i.push(...t)}for(const e of i)h.push(`${e}:${r}`)}const p=await this.client.core.crypto.generateSharedKey(I,l.publicKey);let u;d.length>0&&(u={topic:p,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:l,controller:l.publicKey,expiry:(0,a.Xw0)(f),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:E,namespaces:(0,a.Van)([...new Set(d)],[...new Set(h)]),transportType:n},await this.client.core.relayer.subscribe(p,{transportType:n}),await this.client.session.set(p,u),E&&await this.client.core.pairing.updateMetadata({topic:E,metadata:l.metadata}),u=this.client.session.get(p)),null!=(s=this.client.metadata.redirect)&&s.linkMode&&null!=(r=l.metadata.redirect)&&r.linkMode&&null!=(o=l.metadata.redirect)&&o.universal&&t&&(this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.session.update(p,{transportType:i.cV.link_mode})),O({auths:c,session:u})};let B;this.events.once(D,W),this.events.once(L,M);try{if(r){const e=(0,d.formatJsonRpcRequest)("wc_sessionAuthenticate",S,U);this.client.core.history.set(E,e);const s=await this.client.core.crypto.encode("",e,{type:a.EHS,encoding:a.Pa8});B=(0,a.$Bq)(t,E,s)}else await Promise.all([this.sendRequest({topic:E,method:"wc_sessionAuthenticate",params:S,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:U}),this.sendRequest({topic:E,method:"wc_sessionPropose",params:P,expiry:w.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:P.id})])}catch(e){throw this.events.off(D,W),this.events.off(L,M),e}return await this.setProposal(P.id,P),await this.setAuthRequest(U,{request:x(R({},S),{verifyContext:{}}),pairingTopic:E,transportType:n}),{uri:B??C,response:T}}),U(this,"approveSessionAuthenticate",async e=>{const{id:t,auths:s}=e,r=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[i.U$.authenticated_session_approve_started]}});try{this.isInitialized()}catch(e){throw r.setError(i.Tn.no_internet_connection),e}const n=this.getPendingAuthRequest(t);if(!n)throw r.setError(i.Tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${t}`);const o=n.transportType||i.cV.relay;o===i.cV.relay&&await this.confirmOnlineStateOrThrow();const c=n.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=(0,a.EN$)(c),h={type:a.Lp_,receiverPublicKey:c,senderPublicKey:l},p=[],u=[];for(const e of s){if(!await(0,a.IjX)({cacao:e,projectId:this.client.core.projectId})){r.setError(i.Tn.invalid_cacao);const e=(0,a.Hjj)("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:d,error:e,encodeOpts:h}),new Error(e.message)}r.addTrace(i.U$.cacaos_verified);const{p:s}=e,n=(0,a.VBM)(s.resources),o=[(0,a.xkc)(s.iss)],c=(0,a.q_h)(s.iss);if(n){const e=(0,a.sc_)(n),t=(0,a.WWN)(n);p.push(...e),o.push(...t)}for(const e of o)u.push(`${e}:${c}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);let m;if(r.addTrace(i.U$.create_authenticated_session_topic),p?.length>0){m={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:n.requester.metadata},controller:c,expiry:(0,a.Xw0)(f),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:n.pairingTopic,namespaces:(0,a.Van)([...new Set(p)],[...new Set(u)]),transportType:o},r.addTrace(i.U$.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:o})}catch(e){throw r.setError(i.Tn.subscribe_authenticated_session_topic_failure),e}r.addTrace(i.U$.subscribe_authenticated_session_topic_success),await this.client.session.set(g,m),r.addTrace(i.U$.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:n.pairingTopic,metadata:n.requester.metadata})}r.addTrace(i.U$.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:t,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(n.requester.metadata,o)})}catch(e){throw r.setError(i.Tn.authenticated_session_approve_publish_failure),e}return await this.client.auth.requests.delete(t,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:n.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:r.eventId}),{session:m}}),U(this,"rejectSessionAuthenticate",async e=>{this.isInitialized();const{id:t,reason:s}=e,r=this.getPendingAuthRequest(t);if(!r)throw new Error(`Could not find pending auth request with id ${t}`);r.transportType===i.cV.relay&&await this.confirmOnlineStateOrThrow();const n=r.requester.publicKey,o=await this.client.core.crypto.generateKeyPair(),c=(0,a.EN$)(n),l={type:a.Lp_,receiverPublicKey:n,senderPublicKey:o};await this.sendError({id:t,topic:c,error:s,encodeOpts:l,rpcOpts:w.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(r.requester.metadata,r.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.client.proposal.delete(t,(0,a.Hjj)("USER_DISCONNECTED"))}),U(this,"formatAuthMessage",e=>{this.isInitialized();const{request:t,iss:s}=e;return(0,a.hwK)(t,s)}),U(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(0!==this.relayMessageCache.length)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}},50)}),U(this,"cleanupDuplicatePairings",async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(s=>{var i,r;return(null==(i=s.peerMetadata)?void 0:i.url)&&(null==(r=s.peerMetadata)?void 0:r.url)===e.peer.metadata.url&&s.topic&&s.topic!==t.topic});if(0===s.length)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(e=>this.client.core.pairing.disconnect({topic:e.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}}),U(this,"deleteSession",async e=>{var t;const{topic:s,expirerHasDeleted:i=!1,emitEvent:r=!0,id:n=0}=e,{self:o}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,(0,a.Hjj)("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(o.publicKey)&&await this.client.core.crypto.deleteKeyPair(o.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),i||this.client.core.expirer.del(s),this.client.core.storage.removeItem(g).catch(e=>this.client.logger.warn(e)),this.getPendingSessionRequests().forEach(e=>{e.topic===s&&this.deletePendingSessionRequest(e.id,(0,a.Hjj)("USER_DISCONNECTED"))}),s===(null==(t=this.sessionRequestQueue.queue[0])?void 0:t.topic)&&(this.sessionRequestQueue.state=b),r&&this.client.events.emit("session_delete",{id:n,topic:s})}),U(this,"deleteProposal",async(e,t)=>{if(t)try{const t=this.client.proposal.get(e),s=this.client.core.eventClient.getEvent({topic:t.pairingTopic});s?.setError(i.U.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(e,(0,a.Hjj)("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")}),U(this,"deletePendingSessionRequest",async(e,t,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(t=>t.id!==e),s&&(this.sessionRequestQueue.state=b,this.client.events.emit("session_request_expire",{id:e}))}),U(this,"deletePendingAuthRequest",async(e,t,s=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)])}),U(this,"setExpiry",async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))}),U(this,"setProposal",async(e,t)=>{this.client.core.expirer.set(e,(0,a.Xw0)(w.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)}),U(this,"setAuthRequest",async(e,t)=>{const{request:s,pairingTopic:r,transportType:n=i.cV.relay}=t;this.client.core.expirer.set(e,s.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:e,pairingTopic:r,verifyContext:s.verifyContext,transportType:n})}),U(this,"setPendingSessionRequest",async e=>{const{id:t,topic:s,params:i,verifyContext:r}=e,n=i.request.expiryTimestamp||(0,a.Xw0)(w.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,n),await this.client.pendingRequest.set(t,{id:t,topic:s,params:i,verifyContext:r})}),U(this,"sendRequest",async e=>{const{topic:t,method:i,params:r,expiry:n,relayRpcId:o,clientRpcId:c,throwOnFailedPublish:l,appLink:h,tvf:p}=e,u=(0,d.formatJsonRpcRequest)(i,r,c);let g;const m=!!h;try{const e=m?a.Pa8:a.EWt;g=await this.client.core.crypto.encode(t,u,{encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`),e}let f;if(C.includes(i)){const e=(0,a.ALl)(JSON.stringify(u)),t=(0,a.ALl)(g);f=await this.client.core.verify.register({id:t,decryptedId:e})}const y=w[i].req;if(y.attestation=f,n&&(y.ttl=n),o&&(y.id=o),this.client.core.history.set(t,u),m){const e=(0,a.$Bq)(h,t,g);await s.g.Linking.openURL(e,this.client.name)}else{const e=w[i].req;n&&(e.ttl=n),o&&(e.id=o),e.tvf=x(R({},p),{correlationId:u.id}),l?(e.internal=x(R({},e.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(t,g,e)):this.client.core.relayer.publish(t,g,e).catch(e=>this.client.logger.error(e))}return u.id}),U(this,"sendResult",async e=>{const{id:t,topic:i,result:r,throwOnFailedPublish:n,encodeOpts:o,appLink:c}=e,l=(0,d.formatJsonRpcResult)(t,r);let h;const p=c&&typeof(null==s.g?void 0:s.g.Linking)<"u";try{const e=p?a.Pa8:a.EWt;h=await this.client.core.crypto.encode(i,l,x(R({},o||{}),{encoding:e}))}catch(e){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),e}let u,g;try{u=await this.client.core.history.get(i,t);const e=u.request;try{this.shouldSetTVF(e.method,e.params)&&(g=this.getTVFParams(t,e.params,r))}catch(e){this.client.logger.warn("sendResult() -> getTVFParams() failed",e)}}catch(e){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${t}) failed`),e}if(p){const e=(0,a.$Bq)(c,i,h);await s.g.Linking.openURL(e,this.client.name)}else{const e=u.request.method,s=w[e].res;s.tvf=x(R({},g),{correlationId:t}),n?(s.internal=x(R({},s.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,h,s)):this.client.core.relayer.publish(i,h,s).catch(e=>this.client.logger.error(e))}await this.client.core.history.resolve(l)}),U(this,"sendError",async e=>{const{id:t,topic:i,error:r,encodeOpts:n,rpcOpts:o,appLink:c}=e,l=(0,d.formatJsonRpcError)(t,r);let h;const p=c&&typeof(null==s.g?void 0:s.g.Linking)<"u";try{const e=p?a.Pa8:a.EWt;h=await this.client.core.crypto.encode(i,l,x(R({},n||{}),{encoding:e}))}catch(e){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),e}let u;try{u=await this.client.core.history.get(i,t)}catch(e){throw this.client.logger.error(`sendError() -> history.get(${i}, ${t}) failed`),e}if(p){const e=(0,a.$Bq)(c,i,h);await s.g.Linking.openURL(e,this.client.name)}else{const e=u.request.method,t=o||w[e].res;this.client.core.relayer.publish(i,h,t)}await this.client.core.history.resolve(l)}),U(this,"cleanup",async()=>{const e=[],t=[];this.client.session.getAll().forEach(t=>{let s=!1;(0,a._dF)(t.expiry)&&(s=!0),this.client.core.crypto.keychain.has(t.topic)||(s=!0),s&&e.push(t.topic)}),this.client.proposal.getAll().forEach(e=>{(0,a._dF)(e.expiryTimestamp)&&t.push(e.id)}),await Promise.all([...e.map(e=>this.deleteSession({topic:e})),...t.map(e=>this.deleteProposal(e))])}),U(this,"onProviderMessageEvent",async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)}),U(this,"onRelayEventRequest",async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()}),U(this,"processRequestsQueue",async()=>{if(this.requestQueue.state!==v){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=v;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=b}else this.client.logger.info("Request queue already active, skipping...")}),U(this,"processRequest",async e=>{const{topic:t,payload:s,attestation:i,transportType:r,encryptedId:n}=e,o=s.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:o}))switch(o){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:t,payload:s,attestation:i,encryptedId:n});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,s);case"wc_sessionPing":return await this.onSessionPingRequest(t,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});case"wc_sessionEvent":return await this.onSessionEventRequest(t,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});default:return this.client.logger.info(`Unsupported request method ${o}`)}}),U(this,"onRelayEventResponse",async e=>{const{topic:t,payload:s,transportType:i}=e,r=(await this.client.core.history.get(t,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(t,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,s);case"wc_sessionExtend":return this.onSessionExtendResponse(t,s);case"wc_sessionPing":return this.onSessionPingResponse(t,s);case"wc_sessionRequest":return this.onSessionRequestResponse(t,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}}),U(this,"onRelayEventUnknownPayload",e=>{const{topic:t}=e,{message:s}=(0,a.GuA)("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),U(this,"shouldIgnorePairingRequest",e=>{const{topic:t,requestMethod:s}=e,i=this.expectedPairingMethodMap.get(t);return!(!i||i.includes(s)||!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0))}),U(this,"onSessionProposeRequest",async e=>{const{topic:t,payload:s,attestation:r,encryptedId:n}=e,{params:o,id:c}=s;try{const e=this.client.core.eventClient.getEvent({topic:t});0===this.client.events.listenerCount("session_proposal")&&(console.warn("No listener for session_proposal event"),e?.setError(i.S$.proposal_listener_not_found)),this.isValidConnect(R({},s.params));const l=o.expiryTimestamp||(0,a.Xw0)(w.wc_sessionPropose.req.ttl),d=R({id:c,pairingTopic:t,expiryTimestamp:l},o);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:r,hash:(0,a.ALl)(JSON.stringify(s)),encryptedId:n,metadata:d.proposer.metadata});e?.addTrace(i.$w.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(e){await this.sendError({id:c,topic:t,error:e,rpcOpts:w.wc_sessionPropose.autoReject}),this.client.logger.error(e)}}),U(this,"onSessionProposeResponse",async(e,t,s)=>{const{id:i}=t;if((0,d.isJsonRpcResult)(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const n=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const o=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:o});const a=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});const c=await this.client.core.crypto.generateSharedKey(o,a);this.pendingSessions.set(i,{sessionTopic:c,pairingTopic:e,proposalId:i,publicKey:o});const l=await this.client.core.relayer.subscribe(c,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:e})}else if((0,d.isJsonRpcError)(t)){await this.client.proposal.delete(i,(0,a.Hjj)("USER_DISCONNECTED"));const e=(0,a.hEn)("session_connect",i);if(0===this.events.listenerCount(e))throw new Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:t.error})}}),U(this,"onSessionSettleRequest",async(e,t)=>{const{id:s,params:r}=t;try{this.isValidSessionSettleRequest(r);const{relay:s,controller:n,expiry:o,namespaces:c,sessionProperties:l,scopedProperties:d,sessionConfig:h}=t.params,p=[...this.pendingSessions.values()].find(t=>t.sessionTopic===e);if(!p)return this.client.logger.error(`Pending session not found for topic ${e}`);const u=this.client.proposal.get(p.proposalId),g=x(R(R(R({topic:e,relay:s,expiry:o,namespaces:c,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:u.requiredNamespaces,optionalNamespaces:u.optionalNamespaces,controller:n.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:n.publicKey,metadata:n.metadata}},l&&{sessionProperties:l}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:i.cV.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit((0,a.hEn)("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:t.id,topic:e,result:!0,throwOnFailedPublish:!0})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}}),U(this,"onSessionSettleResponse",async(e,t)=>{const{id:s}=t;(0,d.isJsonRpcResult)(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit((0,a.hEn)("session_approve",s),{})):(0,d.isJsonRpcError)(t)&&(await this.client.session.delete(e,(0,a.Hjj)("USER_DISCONNECTED")),this.events.emit((0,a.hEn)("session_approve",s),{error:t.error}))}),U(this,"onSessionUpdateRequest",async(e,t)=>{const{params:s,id:i}=t;try{const t=`${e}_session_update`,r=a.nyL.get(t);if(r&&this.isRequestOutOfSync(r,i))return this.client.logger.warn(`Discarding out of sync request - ${i}`),void this.sendError({id:i,topic:e,error:(0,a.Hjj)("INVALID_UPDATE_REQUEST")});this.isValidUpdate(R({topic:e},s));try{a.nyL.set(t,i),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:e,result:!0,throwOnFailedPublish:!0})}catch(e){throw a.nyL.delete(t),e}this.client.events.emit("session_update",{id:i,topic:e,params:s})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}}),U(this,"isRequestOutOfSync",(e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3)),U(this,"onSessionUpdateResponse",(e,t)=>{const{id:s}=t,i=(0,a.hEn)("session_update",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);(0,d.isJsonRpcResult)(t)?this.events.emit((0,a.hEn)("session_update",s),{}):(0,d.isJsonRpcError)(t)&&this.events.emit((0,a.hEn)("session_update",s),{error:t.error})}),U(this,"onSessionExtendRequest",async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,(0,a.Xw0)(f)),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:s,topic:e})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}}),U(this,"onSessionExtendResponse",(e,t)=>{const{id:s}=t,i=(0,a.hEn)("session_extend",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);(0,d.isJsonRpcResult)(t)?this.events.emit((0,a.hEn)("session_extend",s),{}):(0,d.isJsonRpcError)(t)&&this.events.emit((0,a.hEn)("session_extend",s),{error:t.error})}),U(this,"onSessionPingRequest",async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:e})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}}),U(this,"onSessionPingResponse",(e,t)=>{const{id:s}=t,i=(0,a.hEn)("session_ping",s);setTimeout(()=>{if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners 2176`);(0,d.isJsonRpcResult)(t)?this.events.emit((0,a.hEn)("session_ping",s),{}):(0,d.isJsonRpcError)(t)&&this.events.emit((0,a.hEn)("session_ping",s),{error:t.error})},500)}),U(this,"onSessionDeleteRequest",async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),Promise.all([new Promise(t=>{this.client.core.relayer.once(i.Jf.publish,async()=>{t(await this.deleteSession({topic:e,id:s}))})}),this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:e,error:(0,a.Hjj)("USER_DISCONNECTED")})]).catch(e=>this.client.logger.error(e))}catch(e){this.client.logger.error(e)}}),U(this,"onSessionRequest",async e=>{var t,s,r;const{topic:n,payload:o,attestation:c,encryptedId:l,transportType:h}=e,{id:p,params:u}=o;try{await this.isValidRequest(R({topic:n},u));const e=this.client.session.get(n),o={id:p,topic:n,params:u,verifyContext:await this.getVerifyContext({attestationId:c,hash:(0,a.ALl)(JSON.stringify((0,d.formatJsonRpcRequest)("wc_sessionRequest",u,p))),encryptedId:l,metadata:e.peer.metadata,transportType:h})};await this.setPendingSessionRequest(o),h===i.cV.link_mode&&null!=(t=e.peer.metadata.redirect)&&t.universal&&this.client.core.addLinkModeSupportedApp(null==(s=e.peer.metadata.redirect)?void 0:s.universal),null!=(r=this.client.signConfig)&&r.disableRequestQueue?this.emitSessionRequest(o):(this.addSessionRequestToSessionRequestQueue(o),this.processSessionRequestQueue())}catch(e){await this.sendError({id:p,topic:n,error:e}),this.client.logger.error(e)}}),U(this,"onSessionRequestResponse",(e,t)=>{const{id:s}=t,i=(0,a.hEn)("session_request",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);(0,d.isJsonRpcResult)(t)?this.events.emit((0,a.hEn)("session_request",s),{result:t.result}):(0,d.isJsonRpcError)(t)&&this.events.emit((0,a.hEn)("session_request",s),{error:t.error})}),U(this,"onSessionEventRequest",async(e,t)=>{const{id:s,params:i}=t;try{const t=`${e}_session_event_${i.event.name}`,r=a.nyL.get(t);if(r&&this.isRequestOutOfSync(r,s))return void this.client.logger.info(`Discarding out of sync request - ${s}`);this.isValidEmit(R({topic:e},i)),this.client.events.emit("session_event",{id:s,topic:e,params:i}),a.nyL.set(t,s)}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}}),U(this,"onSessionAuthenticateResponse",(e,t)=>{const{id:s}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),(0,d.isJsonRpcResult)(t)?this.events.emit((0,a.hEn)("session_request",s),{result:t.result}):(0,d.isJsonRpcError)(t)&&this.events.emit((0,a.hEn)("session_request",s),{error:t.error})}),U(this,"onSessionAuthenticateRequest",async e=>{var t;const{topic:s,payload:r,attestation:n,encryptedId:o,transportType:c}=e;try{const{requester:e,authPayload:l,expiryTimestamp:d}=r.params,h=await this.getVerifyContext({attestationId:n,hash:(0,a.ALl)(JSON.stringify(r)),encryptedId:o,metadata:e.metadata,transportType:c}),p={requester:e,pairingTopic:s,id:r.id,authPayload:l,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(r.id,{request:p,pairingTopic:s,transportType:c}),c===i.cV.link_mode&&null!=(t=e.metadata.redirect)&&t.universal&&this.client.core.addLinkModeSupportedApp(e.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:r.params,id:r.id,verifyContext:h})}catch(e){this.client.logger.error(e);const t=r.params.requester.publicKey,i=await this.client.core.crypto.generateKeyPair(),n=this.getAppLinkIfEnabled(r.params.requester.metadata,c),o={type:a.Lp_,receiverPublicKey:t,senderPublicKey:i};await this.sendError({id:r.id,topic:s,error:e,encodeOpts:o,rpcOpts:w.wc_sessionAuthenticate.autoReject,appLink:n})}}),U(this,"addSessionRequestToSessionRequestQueue",e=>{this.sessionRequestQueue.queue.push(e)}),U(this,"cleanupAfterResponse",e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=b,this.processSessionRequestQueue()},(0,o.toMiliseconds)(this.requestQueueDelay))}),U(this,"cleanupPendingSentRequestsForTopic",({topic:e,error:t})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(t=>t.topic===e&&"wc_sessionRequest"===t.request.method).forEach(e=>{const s=e.request.id,i=(0,a.hEn)("session_request",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);this.events.emit((0,a.hEn)("session_request",e.request.id),{error:t})})}),U(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===v)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.sessionRequestQueue.state=v,this.emitSessionRequest(e)}catch(e){this.client.logger.error(e)}else this.client.logger.info("session request queue is empty.")}),U(this,"emitSessionRequest",e=>{this.client.events.emit("session_request",e)}),U(this,"onPairingCreated",e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find(t=>t.pairingTopic===e.topic);t&&this.onSessionProposeRequest({topic:e.topic,payload:(0,d.formatJsonRpcRequest)("wc_sessionPropose",x(R({},t),{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties,scopedProperties:t.scopedProperties}),t.id)})}),U(this,"isValidConnect",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:r,scopedProperties:n,relays:o}=e;if((0,a.b07)(t)||await this.isValidPairingTopic(t),!(0,a.V9G)(o,!0)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`connect() relays: ${o}`);throw new Error(e)}if(!(0,a.b07)(s)&&0!==(0,a.aF0)(s)){const e="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(e):this.client.logger.warn(e),this.validateNamespaces(s,"requiredNamespaces")}if(!(0,a.b07)(i)&&0!==(0,a.aF0)(i)&&this.validateNamespaces(i,"optionalNamespaces"),(0,a.b07)(r)||this.validateSessionProps(r,"sessionProperties"),!(0,a.b07)(n)){this.validateSessionProps(n,"scopedProperties");const e=Object.keys(s||{}).concat(Object.keys(i||{}));if(!Object.keys(n).every(t=>e.includes(t)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(n)}, required/optional namespaces: ${JSON.stringify(e)}`)}}),U(this,"validateNamespaces",(e,t)=>{const s=(0,a.esh)(e,"connect()",t);if(s)throw new Error(s.message)}),U(this,"isValidApprove",async e=>{if(!(0,a.TeY)(e))throw new Error((0,a.GuA)("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:i,sessionProperties:r,scopedProperties:n}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const o=this.client.proposal.get(t),c=(0,a.FiO)(s,"approve()");if(c)throw new Error(c.message);const l=(0,a.XqR)(o.requiredNamespaces,s,"approve()");if(l)throw new Error(l.message);if(!(0,a.Qhg)(i,!0)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(e)}if((0,a.b07)(r)||this.validateSessionProps(r,"sessionProperties"),!(0,a.b07)(n)){this.validateSessionProps(n,"scopedProperties");const e=new Set(Object.keys(s));if(!Object.keys(n).every(t=>e.has(t)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(n)}, approved namespaces: ${Array.from(e).join(", ")}`)}}),U(this,"isValidReject",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:s}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!(0,a.X3c)(s)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(e)}}),U(this,"isValidSessionSettleRequest",e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:s,namespaces:i,expiry:r}=e;if(!(0,a.kuU)(t)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const n=(0,a.tk0)(s,"onSessionSettleRequest()");if(n)throw new Error(n.message);const o=(0,a.FiO)(i,"onSessionSettleRequest()");if(o)throw new Error(o.message);if((0,a._dF)(r)){const{message:e}=(0,a.GuA)("EXPIRED","onSessionSettleRequest()");throw new Error(e)}}),U(this,"isValidUpdate",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:s}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const i=this.client.session.get(t),r=(0,a.FiO)(s,"update()");if(r)throw new Error(r.message);const n=(0,a.XqR)(i.requiredNamespaces,s,"update()");if(n)throw new Error(n.message)}),U(this,"isValidExtend",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)}),U(this,"isValidRequest",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:s,chainId:i,expiry:r}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!(0,a.tLy)(n,i)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(e)}if(!(0,a.iV1)(s)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(e)}if(!(0,a.oKp)(n,i,s.method)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(e)}if(r&&!(0,a.Hbs)(r,y)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`request() expiry: ${r}. Expiry must be a number (in seconds) between ${y.min} and ${y.max}`);throw new Error(e)}}),U(this,"isValidRespond",async e=>{var t;if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:s,response:i}=e;try{await this.isValidSessionTopic(s)}catch(s){throw null!=(t=e?.response)&&t.id&&this.cleanupAfterResponse(e),s}if(!(0,a.M8n)(i)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(e)}}),U(this,"isValidPing",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),U(this,"isValidEmit",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:s,chainId:i}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!(0,a.tLy)(r,i)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(e)}if(!(0,a.FR8)(s)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}if(!(0,a.z2N)(r,i,s.name)){const{message:e}=(0,a.GuA)("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}}),U(this,"isValidDisconnect",async e=>{if(!(0,a.TeY)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),U(this,"isValidAuthenticate",e=>{const{chains:t,uri:s,domain:i,nonce:r}=e;if(!Array.isArray(t)||0===t.length)throw new Error("chains is required and must be a non-empty array");if(!(0,a.Qhg)(s,!1))throw new Error("uri is required parameter");if(!(0,a.Qhg)(i,!1))throw new Error("domain is required parameter");if(!(0,a.Qhg)(r,!1))throw new Error("nonce is required parameter");if([...new Set(t.map(e=>(0,a._Yb)(e).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:n}=(0,a._Yb)(t[0]);if("eip155"!==n)throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),U(this,"getVerifyContext",async e=>{const{attestationId:t,hash:s,encryptedId:r,metadata:n,transportType:o}=e,a={verified:{verifyUrl:n.verifyUrl||i.WB,validation:"UNKNOWN",origin:n.url||""}};try{if(o===i.cV.link_mode){const e=this.getAppLinkIfEnabled(n,o);return a.verified.validation=e&&new URL(e).origin===new URL(n.url).origin?"VALID":"INVALID",a}const e=await this.client.core.verify.resolve({attestationId:t,hash:s,encryptedId:r,verifyUrl:n.verifyUrl});e&&(a.verified.origin=e.origin,a.verified.isScam=e.isScam,a.verified.validation=e.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.warn(e)}return this.client.logger.debug(`Verify context: ${JSON.stringify(a)}`),a}),U(this,"validateSessionProps",(e,t)=>{Object.values(e).forEach((s,i)=>{if(null==s){const{message:r}=(0,a.GuA)("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${s} for key ${Object.keys(e)[i]}`);throw new Error(r)}})}),U(this,"getPendingAuthRequest",e=>{const t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0}),U(this,"addToRecentlyDeleted",(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0;const t=this.recentlyDeletedLimit/2;for(const s of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(s)}}}),U(this,"checkRecentlyDeleted",e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:s}=(0,a.GuA)("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(s)}}),U(this,"isLinkModeEnabled",(e,t)=>{var r,n,o,a,c,l,d,h,p;return!(!e||t!==i.cV.link_mode)&&!0===(null==(n=null==(r=this.client.metadata)?void 0:r.redirect)?void 0:n.linkMode)&&void 0!==(null==(a=null==(o=this.client.metadata)?void 0:o.redirect)?void 0:a.universal)&&""!==(null==(l=null==(c=this.client.metadata)?void 0:c.redirect)?void 0:l.universal)&&void 0!==(null==(d=e?.redirect)?void 0:d.universal)&&""!==(null==(h=e?.redirect)?void 0:h.universal)&&!0===(null==(p=e?.redirect)?void 0:p.linkMode)&&this.client.core.linkModeSupportedApps.includes(e.redirect.universal)&&typeof(null==s.g?void 0:s.g.Linking)<"u"}),U(this,"getAppLinkIfEnabled",(e,t)=>{var s;return this.isLinkModeEnabled(e,t)?null==(s=e?.redirect)?void 0:s.universal:void 0}),U(this,"handleLinkModeMessage",({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=(0,a.$hI)(e,"topic")||"",s=decodeURIComponent((0,a.$hI)(e,"wc_ev")||""),r=this.client.session.keys.includes(t);r&&this.client.session.update(t,{transportType:i.cV.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:s,sessionExists:r})}),U(this,"registerLinkModeListeners",async()=>{var e;if((0,a.w8K)()||(0,a.lVv)()&&null!=(e=this.client.metadata.redirect)&&e.linkMode){const e=null==s.g?void 0:s.g.Linking;if(typeof e<"u"){e.addEventListener("url",this.handleLinkModeMessage,this.client.name);const t=await e.getInitialURL();t&&setTimeout(()=>{this.handleLinkModeMessage({url:t})},50)}}}),U(this,"shouldSetTVF",(e,t)=>{if(!t||"wc_sessionRequest"!==e)return!1;const{request:s}=t;return Object.keys(E).includes(s.method)}),U(this,"getTVFParams",(e,t,s)=>{var i,r;try{const n=t.request.method,o=this.extractTxHashesFromResult(n,s);return x(R({correlationId:e,rpcMethods:[n],chainId:t.chainId},this.isValidContractData(t.request.params)&&{contractAddresses:[null==(r=null==(i=t.request.params)?void 0:i[0])?void 0:r.to]}),{txHashes:o})}catch(e){this.client.logger.warn("Error getting TVF params",e)}return{}}),U(this,"isValidContractData",e=>{var t;if(!e)return!1;try{const s=e?.data||(null==(t=e?.[0])?void 0:t.data);if(!s.startsWith("0x"))return!1;const i=s.slice(2);return!!/^[0-9a-fA-F]*$/.test(i)&&i.length%2==0}catch{}return!1}),U(this,"extractTxHashesFromResult",(e,t)=>{try{if("string"==typeof t)return[t];const s=t[E[e].key];if((0,a.OP1)(s))return"solana_signAllTransactions"===e?s.map(e=>(0,a.PAk)(e)):s;if("string"==typeof s)return[s]}catch(e){this.client.logger.warn("Error extracting tx hashes from result",e)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[e,s]of Object.entries(t))for(const t of s)try{await this.onProviderMessageEvent({topic:e,message:t,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${e}, message: ${t}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=(0,a.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(i.Jf.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(N)?this.client.auth.authKeys.get(N):{responseTopic:void 0,publicKey:void 0};try{const e=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===i.cV.link_mode?a.Pa8:a.EWt});(0,d.isJsonRpcRequest)(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:r,transportType:n,encryptedId:(0,a.ALl)(s)})):(0,d.isJsonRpcResponse)(e)?(await this.client.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e,transportType:n}),this.client.core.history.delete(t,e.id)):await this.onRelayEventUnknownPayload({topic:t,payload:e,transportType:n}),await this.client.core.relayer.messages.ack(t,s)}catch(e){this.client.logger.error(e)}}registerExpirerEvents(){this.client.core.expirer.on(i.wn.expired,async e=>{const{topic:t,id:s}=(0,a.c82)(e.target);return s&&this.client.pendingRequest.keys.includes(s)?await this.deletePendingSessionRequest(s,(0,a.GuA)("EXPIRED"),!0):s&&this.client.auth.requests.keys.includes(s)?await this.deletePendingAuthRequest(s,(0,a.GuA)("EXPIRED"),!0):void(t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):s&&(await this.deleteProposal(s,!0),this.client.events.emit("proposal_expire",{id:s})))})}registerPairingEvents(){this.client.core.pairing.events.on(i.zN.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(i.zN.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!(0,a.Qhg)(e,!1)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=(0,a.GuA)("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if((0,a._dF)(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=(0,a.GuA)("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!(0,a.Qhg)(e,!1)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=(0,a.GuA)("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if((0,a._dF)(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=(0,a.GuA)("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else{if(!this.client.core.pairing.pairings.keys.includes(e)){if((0,a.Qhg)(e,!1)){const{message:t}=(0,a.GuA)("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if(!(0,a.Alu)(e)){const{message:t}=(0,a.GuA)("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=(0,a.GuA)("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if((0,a._dF)(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=(0,a.GuA)("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class L extends i.il{constructor(e,t){super(e,t,"proposal",p),this.core=e,this.logger=t}}class W extends i.il{constructor(e,t){super(e,t,"session",p),this.core=e,this.logger=t}}class M extends i.il{constructor(e,t){super(e,t,"request",p,e=>e.id),this.core=e,this.logger=t}}class B extends i.il{constructor(e,t){super(e,t,"authKeys",I,()=>N),this.core=e,this.logger=t}}class j extends i.il{constructor(e,t){super(e,t,"pairingTopics",I),this.core=e,this.logger=t}}class q extends i.il{constructor(e,t){super(e,t,"requests",I,e=>e.id),this.core=e,this.logger=t}}var $=Object.defineProperty,H=(e,t,s)=>((e,t,s)=>t in e?$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class F{constructor(e,t){this.core=e,this.logger=t,H(this,"authKeys"),H(this,"pairingTopics"),H(this,"requests"),this.authKeys=new B(this.core,this.logger),this.pairingTopics=new j(this.core,this.logger),this.requests=new q(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var V=Object.defineProperty,z=(e,t,s)=>((e,t,s)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class K extends n.S9{constructor(e){super(e),z(this,"protocol","wc"),z(this,"version",2),z(this,"name",u),z(this,"metadata"),z(this,"core"),z(this,"logger"),z(this,"events",new c.EventEmitter),z(this,"engine"),z(this,"session"),z(this,"proposal"),z(this,"pendingRequest"),z(this,"auth"),z(this,"signConfig"),z(this,"on",(e,t)=>this.events.on(e,t)),z(this,"once",(e,t)=>this.events.once(e,t)),z(this,"off",(e,t)=>this.events.off(e,t)),z(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),z(this,"removeAllListeners",e=>this.events.removeAllListeners(e)),z(this,"connect",async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"pair",async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"approve",async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"reject",async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"update",async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"extend",async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"request",async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"respond",async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"ping",async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"emit",async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"disconnect",async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"find",e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}}),z(this,"authenticate",async(e,t)=>{try{return await this.engine.authenticate(e,t)}catch(e){throw this.logger.error(e.message),e}}),z(this,"formatAuthMessage",e=>{try{return this.engine.formatAuthMessage(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"approveSessionAuthenticate",async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}}),z(this,"rejectSessionAuthenticate",async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}}),this.name=e?.name||u,this.metadata=(0,a.Ds_)(e?.metadata),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&"string"!=typeof e?.logger?e.logger:(0,r.h6)((0,r.iP)({level:e?.logger||"error"}));this.core=e?.core||new i.iJ(e),this.logger=(0,r.U5)(t,this.name),this.session=new W(this.core,this.logger),this.proposal=new L(this.core,this.logger),this.pendingRequest=new M(this.core,this.logger),this.engine=new D(this),this.auth=new F(this.core,this.logger)}static async init(e){const t=new K(e);return await t.initialize(),t}get context(){return(0,r.oI)(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},(0,o.toMiliseconds)(o.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}},28873:(e,t,s)=>{s.d(t,{n:()=>u});var i=s(33244),r=s(38903),n=s(72269),o=s(46362),a=s(98299),c=s(3555),l=s(22143),d=s(96517),h=s(22129),p=s(1435);class u extends d.X{setUniversalProvider(e){this.addConnector(new h.F({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace}))}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{const e=this.getWalletConnectConnector();await e.disconnect()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){const t=this.provider,s=t?.session?.namespaces?.[e]?.accounts?.map(e=>{const[,,t]=e.split(":");return t}).filter((e,t,s)=>s.indexOf(e)===t)||[];return Promise.resolve({accounts:s.map(t=>l.w.createAccount(e,t,"bip122"===e?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!e.caipNetwork||!c.oU.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace)||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};if(o.U.state.balanceLoading&&e.chainId===a.W.state.activeCaipNetwork?.id)return{balance:o.U.state.balance||"0.00",symbol:o.U.state.balanceSymbol||""};const t=(await o.U.fetchTokenBalance()).find(t=>t.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&t.symbol===e.caipNetwork?.nativeCurrency.symbol);return{balance:t?.quantity.numeric||"0.00",symbol:t?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:t,message:s,address:r}=e;if(!t)throw new Error("UniversalAdapter:signMessage - provider is undefined");let o="";return o=a.W.state.activeCaipNetwork?.chainNamespace===n.o.CHAIN.SOLANA?(await t.request({method:"solana_signMessage",params:{message:i.A.encode((new TextEncoder).encode(s)),pubkey:r}},a.W.state.activeCaipNetwork?.caipNetworkId)).signature:await t.request({method:"personal_sign",params:[s,r]},a.W.state.activeCaipNetwork?.caipNetworkId),{signature:o}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){const{caipNetwork:t}=e,s=this.getWalletConnectConnector();if(t.chainNamespace===n.o.CHAIN.EVM)try{await(s.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:(0,r.nj)(t.id)}]}))}catch(e){if(e.code===p.E.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||e.code===p.E.ERROR_INVALID_CHAIN_ID||e.code===p.E.ERROR_CODE_DEFAULT||e?.data?.originalError?.code===p.E.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await(s.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:(0,r.nj)(t.id),rpcUrls:[t?.rpcUrls.chainDefault?.http],chainName:t.name,nativeCurrency:t.nativeCurrency,blockExplorerUrls:[t.blockExplorers?.default.url]}]}))}catch(e){throw new Error("Chain is not supported")}}s.provider.setDefaultChain(t.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(e=>"WALLET_CONNECT"===e.type),t=e?.provider;return t}}},29972:(e,t,s)=>{s.d(t,{F:()=>i});const i=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}]},31100:(e,t,s)=>{s.d(t,{h:()=>l});var i=s(89168),r=s(39150),n=s(37834),o=s(1420);const a=(0,i.BX)({message:"",variant:"info",open:!1}),c={state:a,subscribeKey:(e,t)=>(0,r.u$)(a,e,t),open(e,t){const{debug:s}=o.H.state,{shortMessage:i,longMessage:r}=e;s&&(a.message=i,a.variant=t,a.open=!0),r&&console.error("function"==typeof r?r():r)},close(){a.open=!1,a.message="",a.variant="info"}},l=(0,n.X)(c)},32523:(e,t,s)=>{s.d(t,{g:()=>u});var i=s(72269),r=s(98299),n=s(86792),o=s(83077),a=s(93474),c=s(1420),l=s(22143),d=s(11847),h=s(51765),p=s(84279);const u={getConnectorsByType(e,t,s){const{customWallets:i}=c.H.state,r=d.i.getRecentWallets(),n=p.A.filterOutDuplicateWallets(t),o=p.A.filterOutDuplicateWallets(s),a=e.filter(e=>"MULTI_CHAIN"===e.type),l=e.filter(e=>"ANNOUNCED"===e.type),h=e.filter(e=>"INJECTED"===e.type);return{custom:i,recent:r,external:e.filter(e=>"EXTERNAL"===e.type),multiChain:a,announced:l,injected:h,recommended:n,featured:o}},showConnector(e){const t=e.info?.rdns,s=Boolean(t)&&a.N.state.excludedWallets.some(e=>Boolean(e.rdns)&&e.rdns===t),i=Boolean(e.name)&&a.N.state.excludedWallets.some(t=>h.y.isLowerCaseMatch(t.name,e.name));if("INJECTED"===e.type){if("Browser Wallet"===e.name){if(!l.w.isMobile())return!1;if(l.w.isMobile()&&!t&&!n.x.checkInstalled())return!1}if(s||i)return!1}return"ANNOUNCED"!==e.type&&"EXTERNAL"!==e.type||!s&&!i},getIsConnectedWithWC:()=>Array.from(r.W.state.chains.values()).some(e=>o.a.getConnectorId(e.namespace)===i.o.CONNECTOR_ID.WALLET_CONNECT),getConnectorTypeOrder({recommended:e,featured:t,custom:s,recent:i,announced:r,injected:n,multiChain:o,external:a,overriddenConnectors:l=c.H.state.features?.connectorTypeOrder??[]}){const d=u.getIsConnectedWithWC(),h=[{type:"walletConnect",isEnabled:c.H.state.enableWalletConnect&&!d},{type:"recent",isEnabled:i.length>0},{type:"injected",isEnabled:[...n,...r,...o].length>0},{type:"featured",isEnabled:t.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:e.length>0}].filter(e=>e.isEnabled),p=new Set(h.map(e=>e.type)),g=l.filter(e=>p.has(e)).map(e=>({type:e,isEnabled:!0})),m=h.filter(({type:e})=>!g.some(({type:t})=>t===e));return Array.from(new Set([...g,...m].map(({type:e})=>e)))}}},33868:(e,t,s)=>{var i=s(39275);(0,i.x)({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}}),(0,i.x)({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0})},34311:(e,t,s)=>{s.d(t,{Q:()=>i});const i=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}]},34631:(e,t,s)=>{},35646:(e,t,s)=>{async function i(...e){const t=await fetch(...e);if(!t.ok)throw new Error(`HTTP status code: ${t.status}`,{cause:t});return t}s.d(t,{Z:()=>r});class r{constructor({baseUrl:e,clientId:t}){this.baseUrl=e,this.clientId=t}async get({headers:e,signal:t,cache:s,...r}){const n=this.createUrl(r);return(await i(n,{method:"GET",headers:e,signal:t,cache:s})).json()}async getBlob({headers:e,signal:t,...s}){const r=this.createUrl(s);return(await i(r,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:s,...r}){const n=this.createUrl(r);return(await i(n,{method:"POST",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}async put({body:e,headers:t,signal:s,...r}){const n=this.createUrl(r);return(await i(n,{method:"PUT",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}async delete({body:e,headers:t,signal:s,...r}){const n=this.createUrl(r);return(await i(n,{method:"DELETE",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}createUrl({path:e,params:t}){const s=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([e,t])=>{t&&s.searchParams.append(e,t)}),this.clientId&&s.searchParams.append("clientId",this.clientId),s}}},36347:(e,t,s)=>{s.d(t,{A:()=>a});var i=s(89168),r=s(39150);const n={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},o=(0,i.BX)({providers:{...n},providerIds:{...n}}),a={state:o,subscribeKey:(e,t)=>(0,r.u$)(o,e,t),subscribe:e=>(0,i.B1)(o,()=>{e(o)}),subscribeProviders:e=>(0,i.B1)(o.providers,()=>e(o.providers)),setProvider(e,t){t&&(o.providers[e]=(0,i.KR)(t))},getProvider:e=>o.providers[e],setProviderId(e,t){t&&(o.providerIds[e]=t)},getProviderId(e){if(e)return o.providerIds[e]},reset(){o.providers={...n},o.providerIds={...n}},resetChain(e){o.providers[e]=void 0,o.providerIds[e]=void 0}}},36507:(e,t,s)=>{s.d(t,{U:()=>m}),s(18338);var i=s(72269),r=s(88889),n=s(46362),o=s(98299),a=s(86792),c=s(83077),l=s(47981),d=s(88759),h=s(1420),p=s(72397),u=s(92492),g=s(22143);const m={getSIWX:()=>h.H.state.siwx,async initializeIfEnabled(){const e=h.H.state.siwx,t=o.W.getActiveCaipAddress();if(!e||!t)return;const[s,i,r]=t.split(":");if(o.W.checkIfSupportedNetwork(s))try{if((await e.getSessions(`${s}:${i}`,r)).length)return;await d.W.open({view:"SIWXSignMessage"})}catch(e){console.error("SIWXUtil:initializeIfEnabled",e),l.E.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await(a.x._getClient()?.disconnect().catch(console.error)),p.I.reset("Connect"),u.P.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const e=h.H.state.siwx,t=g.w.getPlainAddress(o.W.getActiveCaipAddress()),s=o.W.getActiveCaipNetwork(),r=a.x._getClient();if(!e)throw new Error("SIWX is not enabled");if(!t)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");if(!r)throw new Error("No ConnectionController client found");try{const n=await e.createMessage({chainId:s.caipNetworkId,accountAddress:t}),o=n.toString();c.a.getConnectorId(s.chainNamespace)===i.o.CONNECTOR_ID.AUTH&&p.I.pushTransactionStack({});const a=await r.signMessage(o);await e.addSession({data:n,message:o,signature:a}),d.W.close(),l.E.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(e){const t=this.getSIWXEventProperties();d.W.state.open&&"ApproveTransaction"!==p.I.state.view||await d.W.open({view:"SIWXSignMessage"}),t.isSmartAccount?u.P.showError("This application might not support Smart Accounts"):u.P.showError("Signature declined"),l.E.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:t}),console.error("SWIXUtil:requestSignMessage",e)}},async cancelSignMessage(){try{const e=this.getSIWX(),t=e?.getRequired?.();t?await a.x.disconnect():d.W.close(),p.I.reset("Connect"),l.E.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getSessions(){const e=h.H.state.siwx,t=g.w.getPlainAddress(o.W.getActiveCaipAddress()),s=o.W.getActiveCaipNetwork();return e&&t&&s?e.getSessions(s.caipNetworkId,t):[]},async isSIWXCloseDisabled(){const e=this.getSIWX();if(e){const t="ApproveTransaction"===p.I.state.view,s="SIWXSignMessage"===p.I.state.view;if(t||s)return e.getRequired?.()&&0===(await this.getSessions()).length}return!1},async universalProviderAuthenticate({universalProvider:e,chains:t,methods:s}){const i=m.getSIWX(),r=new Set(t.map(e=>e.split(":")[0]));if(!i||1!==r.size||!r.has("eip155"))return!1;const a=await i.createMessage({chainId:o.W.getActiveCaipNetwork()?.caipNetworkId||"",accountAddress:""}),c=await e.authenticate({nonce:a.nonce,domain:a.domain,uri:a.uri,exp:a.expirationTime,iat:a.issuedAt,nbf:a.notBefore,requestId:a.requestId,version:a.version,resources:a.resources,statement:a.statement,chainId:a.chainId,methods:s,chains:[a.chainId,...t.filter(e=>e!==a.chainId)]});if(u.P.showLoading("Authenticating...",{autoClose:!1}),n.U.setConnectedWalletInfo({...c.session.peer.metadata,name:c.session.peer.metadata.name,icon:c.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"},Array.from(r)[0]),c?.auths?.length){const t=c.auths.map(t=>{const s=e.client.formatAuthMessage({request:t.p,iss:t.p.iss});return{data:{...t.p,accountAddress:t.p.iss.split(":").slice(-1).join(""),chainId:t.p.iss.split(":").slice(2,4).join(":"),uri:t.p.aud,version:t.p.version||a.version,expirationTime:t.p.exp,issuedAt:t.p.iat,notBefore:t.p.nbf},message:s,signature:t.s.s,cacao:t}});try{await i.setSessions(t),l.E.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:m.getSIWXEventProperties()})}catch(t){throw console.error("SIWX:universalProviderAuth - failed to set sessions",t),l.E.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:m.getSIWXEventProperties()}),await e.disconnect().catch(console.error),t}finally{u.P.hide()}}return!0},getSIWXEventProperties(){const e=o.W.state.activeChain;return{network:o.W.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:n.U.state.preferredAccountTypes?.[e]===r.Vl.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const e=this.getSIWX();e&&await e.setSessions([])}}},37686:(e,t,s)=>{s.d(t,{R:()=>v});var i=s(89168),r=s(39150),n=s(4159),o=s(18496),a=s(88889),c=s(3555),l=s(22143),d=s(11148),h=s(37834),p=s(46362),u=s(98299),g=s(86792),m=s(47981),f=s(72397),w=s(92492);const y=(0,i.BX)({tokenBalances:[],loading:!1}),b={state:y,subscribe:e=>(0,i.B1)(y,()=>e(y)),subscribeKey:(e,t)=>(0,r.u$)(y,e,t),setToken(e){e&&(y.token=(0,i.KR)(e))},setTokenAmount(e){y.sendTokenAmount=e},setReceiverAddress(e){y.receiverAddress=e},setReceiverProfileImageUrl(e){y.receiverProfileImageUrl=e},setReceiverProfileName(e){y.receiverProfileName=e},setNetworkBalanceInUsd(e){y.networkBalanceInUSD=e},setLoading(e){y.loading=e},async sendToken(){try{switch(v.setLoading(!0),u.W.state.activeCaipNetwork?.chainNamespace){case"eip155":return void await v.sendEvmToken();case"solana":return void await v.sendSolanaToken();default:throw new Error("Unsupported chain")}}finally{v.setLoading(!1)}},async sendEvmToken(){const e=u.W.state.activeChain,t=p.U.state.preferredAccountTypes?.[e];if(!v.state.sendTokenAmount||!v.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!v.state.token)throw new Error("A token is required");v.state.token?.address?(m.E.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===a.Vl.ACCOUNT_TYPES.SMART_ACCOUNT,token:v.state.token.address,amount:v.state.sendTokenAmount,network:u.W.state.activeCaipNetwork?.caipNetworkId||""}}),await v.sendERC20Token({receiverAddress:v.state.receiverAddress,tokenAddress:v.state.token.address,sendTokenAmount:v.state.sendTokenAmount,decimals:v.state.token.quantity.decimals})):(m.E.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===a.Vl.ACCOUNT_TYPES.SMART_ACCOUNT,token:v.state.token.symbol||"",amount:v.state.sendTokenAmount,network:u.W.state.activeCaipNetwork?.caipNetworkId||""}}),await v.sendNativeToken({receiverAddress:v.state.receiverAddress,sendTokenAmount:v.state.sendTokenAmount,decimals:v.state.token.quantity.decimals}))},async fetchTokenBalance(e){y.loading=!0;const t=u.W.state.activeCaipNetwork?.caipNetworkId,s=u.W.state.activeCaipNetwork?.chainNamespace,i=u.W.state.activeCaipAddress,r=i?l.w.getPlainAddress(i):void 0;if(y.lastRetry&&!l.w.isAllowedRetry(y.lastRetry,30*c.oU.ONE_SEC_MS))return y.loading=!1,[];try{if(r&&t&&s){const e=await d.t.getMyTokensWithBalance();return y.tokenBalances=e,y.lastRetry=void 0,e}}catch(t){y.lastRetry=Date.now(),e?.(t),w.P.showError("Token Balance Unavailable")}finally{y.loading=!1}return[]},fetchNetworkBalance(){if(0===y.tokenBalances.length)return;const e=d.t.mapBalancesToSwapTokens(y.tokenBalances);if(!e)return;const t=e.find(e=>e.address===u.W.getActiveNetworkTokenAddress());t&&(y.networkBalanceInUSD=t?n.S.multiply(t.quantity.numeric,t.price).toString():"0")},async sendNativeToken(e){f.I.pushTransactionStack({});const t=e.receiverAddress,s=p.U.state.address,i=g.x.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals));await g.x.sendTransaction({chainNamespace:"eip155",to:t,address:s,data:"0x",value:i??BigInt(0)}),m.E.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:p.U.state.preferredAccountTypes?.eip155===a.Vl.ACCOUNT_TYPES.SMART_ACCOUNT,token:v.state.token?.symbol||"",amount:e.sendTokenAmount,network:u.W.state.activeCaipNetwork?.caipNetworkId||""}}),g.x._getClient()?.updateBalance("eip155"),v.resetSend()},async sendERC20Token(e){f.I.pushTransactionStack({onSuccess(){f.I.replace("Account")}});const t=g.x.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals));if(p.U.state.address&&e.sendTokenAmount&&e.receiverAddress&&e.tokenAddress){const s=l.w.getPlainAddress(e.tokenAddress);await g.x.writeContract({fromAddress:p.U.state.address,tokenAddress:s,args:[e.receiverAddress,t??BigInt(0)],method:"transfer",abi:o.v.getERC20Abi(s),chainNamespace:"eip155"}),v.resetSend()}},async sendSolanaToken(){if(!v.state.sendTokenAmount||!v.state.receiverAddress)throw new Error("An amount and receiver address are required");f.I.pushTransactionStack({onSuccess(){f.I.replace("Account")}}),await g.x.sendTransaction({chainNamespace:"solana",to:v.state.receiverAddress,value:v.state.sendTokenAmount}),g.x._getClient()?.updateBalance("solana"),v.resetSend()},resetSend(){y.token=void 0,y.sendTokenAmount=void 0,y.receiverAddress=void 0,y.receiverProfileImageUrl=void 0,y.receiverProfileName=void 0,y.loading=!1,y.tokenBalances=[]}},v=(0,h.X)(b)},37834:(e,t,s)=>{s.d(t,{A:()=>r,X:()=>o});var i=s(63917);class r extends Error{constructor(e,t,s){super(e),this.name="AppKitError",this.category=t,this.originalError=s,Object.setPrototypeOf(this,r.prototype);let i=!1;if(s instanceof Error&&"string"==typeof s.stack&&s.stack){const e=s.stack,t=e.indexOf("\n");if(t>-1){const s=e.substring(t+1);this.stack=`${this.name}: ${this.message}\n${s}`,i=!0}}i||(Error.captureStackTrace?Error.captureStackTrace(this,r):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function n(e,t){const s=e instanceof r?e:new r(e instanceof Error?e.message:String(e),t,e);throw i.s.sendError(s,s.category),s}function o(e,t="INTERNAL_SDK_ERROR"){const s={};return Object.keys(e).forEach(i=>{const r=e[i];if("function"==typeof r){let e=r;e="AsyncFunction"===r.constructor.name?async(...e)=>{try{return await r(...e)}catch(e){return n(e,t)}}:(...e)=>{try{return r(...e)}catch(e){return n(e,t)}},s[i]=e}else s[i]=r}),s}},38097:(e,t,s)=>{s.d(t,{R:()=>h});var i=s(4443),r=s(30393),n=s(72269),o=s(98299),a=s(11847),c=s(82868);function l(e,t){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",e),s.searchParams.set("projectId",t),s.toString()}const d=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],h={extendRpcUrlWithProjectId(e,t){let s=!1;try{s="rpc.walletconnect.org"===new URL(e).host}catch(e){s=!1}if(s){const s=new URL(e);return s.searchParams.has("projectId")||s.searchParams.set("projectId",t),s.toString()}return e},isCaipNetwork:e=>"chainNamespace"in e&&"caipNetworkId"in e,getChainNamespace(e){return this.isCaipNetwork(e)?e.chainNamespace:n.o.CHAIN.EVM},getCaipNetworkId(e){return this.isCaipNetwork(e)?e.caipNetworkId:`${n.o.CHAIN.EVM}:${e.id}`},getDefaultRpcUrl(e,t,s){const i=e.rpcUrls?.default?.http?.[0];return d.includes(t)?l(t,s):i||""},extendCaipNetwork(e,{customNetworkImageUrls:t,projectId:s,customRpcUrls:i}){const r=this.getChainNamespace(e),n=this.getCaipNetworkId(e),o=e.rpcUrls.default.http?.[0],a=this.getDefaultRpcUrl(e,n,s),l=e?.rpcUrls?.chainDefault?.http?.[0]||o,d=i?.[n]?.map(e=>e.url)||[],h=[...d,a],p=[...d];return l&&!p.includes(l)&&p.push(l),{...e,chainNamespace:r,caipNetworkId:n,assets:{imageId:c.L.NetworkImageIds[e.id],imageUrl:t?.[e.id]},rpcUrls:{...e.rpcUrls,default:{http:h},chainDefault:{http:p}}}},extendCaipNetworks:(e,{customNetworkImageUrls:t,projectId:s,customRpcUrls:i})=>e.map(e=>h.extendCaipNetwork(e,{customNetworkImageUrls:t,customRpcUrls:i,projectId:s})),getViemTransport(e,t,s){const n=[];return s?.forEach(e=>{n.push((0,r.L)(e.url,e.config))}),d.includes(e.caipNetworkId)&&n.push((0,r.L)(l(e.caipNetworkId,t),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),e?.rpcUrls?.default?.http?.forEach(e=>{n.push((0,r.L)(e))}),(0,i.Np)(n)},extendWagmiTransports(e,t,s){if(d.includes(e.caipNetworkId)){const n=this.getDefaultRpcUrl(e,e.caipNetworkId,t);return(0,i.Np)([s,(0,r.L)(n)])}return s},getUnsupportedNetwork:e=>({id:e.split(":")[1],caipNetworkId:e,name:n.o.UNSUPPORTED_NETWORK_NAME,chainNamespace:e.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}),getCaipNetworkFromStorage(e){const t=a.i.getActiveCaipNetworkId(),s=o.W.getAllRequestedCaipNetworks(),i=Array.from(o.W.state.chains?.keys()||[]),r=t?.split(":")[0],n=!!r&&i.includes(r),c=s?.find(e=>e.caipNetworkId===t);return n&&!c&&t?this.getUnsupportedNetwork(t):c||e||s?.[0]}}},39030:(e,t,s)=>{s.d(t,{p:()=>r});const i=2147483648,r={convertEVMChainIdToCoinType(e){if(e>=i)throw new Error("Invalid chainId");return(i|e)>>>0}}},39194:(e,t,s)=>{s.d(t,{createAppKit:()=>n});var i=s(42594),r=s(11628);function n(e){return new i._({...e,basic:!0,sdkVersion:`html-core-${r.i}`})}},39275:(e,t,s)=>{function i(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}s.d(t,{x:()=>i})},41607:(e,t,s)=>{s.d(t,{g:()=>o});var i=s(72269),r=s(98299),n=s(79217);function o(e){const t=Array.from(r.W.state.chains.keys());let s=[];return e?(s.push([e,r.W.state.chains.get(e)]),(0,n.Q)(e,i.o.CONNECTOR_ID.WALLET_CONNECT)?t.forEach(t=>{t!==e&&(0,n.Q)(t,i.o.CONNECTOR_ID.WALLET_CONNECT)&&s.push([t,r.W.state.chains.get(t)])}):(0,n.Q)(e,i.o.CONNECTOR_ID.AUTH)&&t.forEach(t=>{t!==e&&(0,n.Q)(t,i.o.CONNECTOR_ID.AUTH)&&s.push([t,r.W.state.chains.get(t)])})):s=Array.from(r.W.state.chains.entries()),s}},42177:(e,t,s)=>{s.d(t,{o:()=>r});var i=s(39907);const r={ACCOUNT_TABS:[{label:"Tokens"},{label:"NFTs"},{label:"Activity"}],SECURE_SITE_ORIGIN:(void 0!==i&&void 0!==i.env?i.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}}},42594:(e,t,s)=>{s.d(t,{_:()=>l});var i=s(86792),r=s(83077),n=s(1420),o=s(22143),a=s(20475);let c=!1;class l extends a._{async open(e){r.a.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&i.x.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!c&&o.w.isClient()){if(await Promise.all([s.e(6484),s.e(674),s.e(8373)]).then(s.bind(s,58373)),await Promise.all([s.e(674),s.e(4150)]).then(s.bind(s,54150)),!document.querySelector("w3m-modal")){const e=document.createElement("w3m-modal");n.H.state.disableAppend||n.H.state.enableEmbedded||document.body.insertAdjacentElement("beforeend",e)}c=!0}}}},44242:(e,t,s)=>{s.d(t,{Aj:()=>i.A}),s(32523),s(42177);var i=s(84279)},46362:(e,t,s)=>{s.d(t,{U:()=>p});var i=s(89168),r=s(3555),n=s(22143),o=s(37834),a=s(16444),c=s(98299),l=s(92492);const d=(0,i.BX)({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),h={state:d,replaceState(e){e&&Object.assign(d,(0,i.KR)(e))},subscribe:e=>c.W.subscribeChainProp("accountState",t=>{if(t)return e(t)}),subscribeKey(e,t,s){let i;return c.W.subscribeChainProp("accountState",s=>{if(s){const r=s[e];i!==r&&(i=r,t(r))}},s)},setStatus(e,t){c.W.setAccountProp("status",e,t)},getCaipAddress:e=>c.W.getAccountProp("caipAddress",e),setCaipAddress(e,t){const s=e?n.w.getPlainAddress(e):void 0;t===c.W.state.activeChain&&(c.W.state.activeCaipAddress=e),c.W.setAccountProp("caipAddress",e,t),c.W.setAccountProp("address",s,t)},setBalance(e,t,s){c.W.setAccountProp("balance",e,s),c.W.setAccountProp("balanceSymbol",t,s)},setProfileName(e,t){c.W.setAccountProp("profileName",e,t)},setProfileImage(e,t){c.W.setAccountProp("profileImage",e,t)},setUser(e,t){c.W.setAccountProp("user",e,t)},setAddressExplorerUrl(e,t){c.W.setAccountProp("addressExplorerUrl",e,t)},setSmartAccountDeployed(e,t){c.W.setAccountProp("smartAccountDeployed",e,t)},setCurrentTab(e){c.W.setAccountProp("currentTab",e,c.W.state.activeChain)},setTokenBalance(e,t){e&&c.W.setAccountProp("tokenBalance",e,t)},setShouldUpdateToAddress(e,t){c.W.setAccountProp("shouldUpdateToAddress",e,t)},setAllAccounts(e,t){c.W.setAccountProp("allAccounts",e,t)},addAddressLabel(e,t,s){const i=c.W.getAccountProp("addressLabels",s)||new Map;i.set(e,t),c.W.setAccountProp("addressLabels",i,s)},removeAddressLabel(e,t){const s=c.W.getAccountProp("addressLabels",t)||new Map;s.delete(e),c.W.setAccountProp("addressLabels",s,t)},setConnectedWalletInfo(e,t){c.W.setAccountProp("connectedWalletInfo",e,t,!1)},setPreferredAccountType(e,t){c.W.setAccountProp("preferredAccountTypes",{...d.preferredAccountTypes,[t]:e},t)},setPreferredAccountTypes(e){d.preferredAccountTypes=e},setSocialProvider(e,t){e&&c.W.setAccountProp("socialProvider",e,t)},setSocialWindow(e,t){c.W.setAccountProp("socialWindow",e?(0,i.KR)(e):void 0,t)},setFarcasterUrl(e,t){c.W.setAccountProp("farcasterUrl",e,t)},async fetchTokenBalance(e){d.balanceLoading=!0;const t=c.W.state.activeCaipNetwork?.caipNetworkId,s=c.W.state.activeCaipNetwork?.chainNamespace,i=c.W.state.activeCaipAddress,o=i?n.w.getPlainAddress(i):void 0;if(d.lastRetry&&!n.w.isAllowedRetry(d.lastRetry,30*r.oU.ONE_SEC_MS))return d.balanceLoading=!1,[];try{if(o&&t&&s){const e=(await a.T.getBalance(o,t)).balances.filter(e=>"0"!==e.quantity.decimals);return p.setTokenBalance(e,s),d.lastRetry=void 0,d.balanceLoading=!1,e}}catch(t){d.lastRetry=Date.now(),e?.(t),l.P.showError("Token Balance Unavailable")}finally{d.balanceLoading=!1}return[]},resetAccount(e){c.W.resetAccount(e)}},p=(0,o.X)(h)},47436:(e,t,s)=>{s.d(t,{D:()=>n});var i=s(3555),r=s(22143);const n={getFeatureValue(e,t){const s=t?.[e];return void 0===s?i.oU.DEFAULT_FEATURES[e]:s},filterSocialsByPlatform(e){if(!e||!e.length)return e;if(r.w.isTelegram()){if(r.w.isIos())return e.filter(e=>"google"!==e);if(r.w.isMac())return e.filter(e=>"x"!==e);if(r.w.isAndroid())return e.filter(e=>!["facebook","x"].includes(e))}return e}}},47981:(e,t,s)=>{s.d(t,{E:()=>m});var i=s(89168),r=s(72269),n=s(80971),o=s(22143),a=s(35646),c=s(46362),l=s(31100),d=s(1420);const h=o.w.getAnalyticsUrl(),p=new a.Z({baseUrl:h,clientId:null}),u=["MODAL_CREATED"],g=(0,i.BX)({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),m={state:g,subscribe:e=>(0,i.B1)(g,()=>e(g)),getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=d.H.state;return{projectId:e,st:t,sv:s||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(e){try{const t=c.U.state.address;if(u.includes(e.data.event)||"undefined"==typeof window)return;await p.post({path:"/e",params:m.getSdkProperties(),body:{eventId:o.w.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:e.timestamp,props:{...e.data,address:t}}}),g.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===r.o.HTTP_STATUS_CODES.FORBIDDEN&&!g.reportedErrors.FORBIDDEN&&(l.h.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${(0,n.IP)()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),g.reportedErrors.FORBIDDEN=!0)}},sendEvent(e){g.timestamp=Date.now(),g.data=e,d.H.state.features?.analytics&&m._sendAnalyticsEvent(g)}}},49402:(e,t,s)=>{s.d(t,{Rn0:()=>i.Rn,tWt:()=>i.tW});var i=s(94311);s(33868)},49951:(e,t,s)=>{s.d(t,{W:()=>l});var i=s(89168),r=s(80989),n=s(37834),o=s(83077);const a=(0,i.BX)({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),c={state:a,subscribe:e=>(0,i.B1)(a,()=>e(a)),setThemeMode(e){a.themeMode=e;try{const t=o.a.getAuthConnector();if(t){const s=c.getSnapshot().themeVariables;t.provider.syncTheme({themeMode:e,themeVariables:s,w3mThemeVariables:(0,r.o)(s,e)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(e){a.themeVariables={...a.themeVariables,...e};try{const e=o.a.getAuthConnector();if(e){const t=c.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:(0,r.o)(a.themeVariables,a.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot:()=>(0,i.P9)(a)},l=(0,n.X)(c)},51765:(e,t,s)=>{s.d(t,{y:()=>r});var i=s(83229);const r={getCaipTokens(e){if(!e)return;const t={};return Object.entries(e).forEach(([e,s])=>{t[`${i.o.EIP155}:${e}`]=s}),t},isLowerCaseMatch:(e,t)=>e?.toLowerCase()===t?.toLowerCase()}},52788:(e,t,s)=>{s.d(t,{AH:()=>i.AH,JW:()=>i.JW,WF:()=>i.WF,iz:()=>i.iz,qy:()=>i.qy}),s(58207),s(80181);var i=s(46477)},53561:(e,t,s)=>{s(93797),s(15179)},54947:(e,t,s)=>{s.d(t,{T:()=>r});var i=s(88612);const r={createBalance(e,t){const s={name:e.metadata.name||"",symbol:e.metadata.symbol||"",decimals:e.metadata.decimals||0,value:e.metadata.value||0,price:e.metadata.price||0,iconUrl:e.metadata.iconUrl||""};return{name:s.name,symbol:s.symbol,chainId:t,address:"native"===e.address?void 0:this.convertAddressToCAIP10Address(e.address,t),value:s.value,price:s.price,quantity:{decimals:s.decimals.toString(),numeric:this.convertHexToBalance({hex:e.balance,decimals:s.decimals})},iconUrl:s.iconUrl}},convertHexToBalance:({hex:e,decimals:t})=>(0,i.J)(BigInt(e),t),convertAddressToCAIP10Address:(e,t)=>`${t}:${e}`,createCAIP2ChainId:(e,t)=>`${t}:${parseInt(e,16)}`,getChainIdHexFromCAIP2ChainId(e){const t=e.split(":");if(t.length<2||!t[1])return"0x0";const s=t[1],i=parseInt(s,10);return isNaN(i)?"0x0":`0x${i.toString(16)}`},isWalletGetAssetsResponse(e){return"object"==typeof e&&null!==e&&Object.values(e).every(e=>Array.isArray(e)&&e.every(e=>this.isValidAsset(e)))},isValidAsset:e=>"object"==typeof e&&null!==e&&"string"==typeof e.address&&"string"==typeof e.balance&&("ERC20"===e.type||"NATIVE"===e.type)&&"object"==typeof e.metadata&&null!==e.metadata&&"string"==typeof e.metadata.name&&"string"==typeof e.metadata.symbol&&"number"==typeof e.metadata.decimals&&"number"==typeof e.metadata.price&&"string"==typeof e.metadata.iconUrl}},55611:(e,t,s)=>{s.d(t,{C:()=>i});const i={validateCaipAddress(e){if(3!==e.split(":")?.length)throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){const t=e.split(":");if(3!==t.length)throw new Error(`Invalid CAIP-10 address: ${e}`);const[s,i,r]=t;if(!s||!i||!r)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:s,chainId:i,address:r}},parseCaipNetworkId(e){const t=e.split(":");if(2!==t.length)throw new Error(`Invalid CAIP-2 network id: ${e}`);const[s,i]=t;if(!s||!i)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:s,chainId:i}}}},56335:(e,t,s)=>{s.d(t,{t:()=>i});const i=(0,s(39275).x)({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"})},60032:(e,t,s)=>{s.d(t,{L:()=>c});var i=s(72269),r=s(46362),n=s(98299),o=s(83077),a=s(72397);const c={onSwitchNetwork({network:e,ignoreSwitchConfirmation:t=!1}){const s=n.W.state.activeCaipNetwork,c=a.I.state.data;if(e.id===s?.id)return;const l=r.U.getCaipAddress(n.W.state.activeChain),d=e.chainNamespace!==n.W.state.activeChain,h=r.U.getCaipAddress(e.chainNamespace),p=o.a.getConnectorId(n.W.state.activeChain)===i.o.CONNECTOR_ID.AUTH,u=i.o.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(t=>t===e.chainNamespace);t||p&&u?a.I.push("SwitchNetwork",{...c,network:e}):l&&d&&!h?a.I.push("SwitchActiveChain",{switchToChain:e.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:e}):a.I.push("SwitchNetwork",{...c,network:e})}}},61387:(e,t,s)=>{s.d(t,{k:()=>o});var i=s(13766),r=s(49402);const n={solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"]},o={getMethodsByChainNamespace:e=>n[e]||[],createDefaultNamespace(e){return{methods:this.getMethodsByChainNamespace(e),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(e,t){if(!t)return{...e};const s={...e},i=new Set;if(t.methods&&Object.keys(t.methods).forEach(e=>i.add(e)),t.chains&&Object.keys(t.chains).forEach(e=>i.add(e)),t.events&&Object.keys(t.events).forEach(e=>i.add(e)),t.rpcMap&&Object.keys(t.rpcMap).forEach(e=>{const[t]=e.split(":");t&&i.add(t)}),i.forEach(e=>{s[e]||(s[e]=this.createDefaultNamespace(e))}),t.methods&&Object.entries(t.methods).forEach(([e,t])=>{s[e]&&(s[e].methods=t)}),t.chains&&Object.entries(t.chains).forEach(([e,t])=>{s[e]&&(s[e].chains=t)}),t.events&&Object.entries(t.events).forEach(([e,t])=>{s[e]&&(s[e].events=t)}),t.rpcMap){const e=new Set;Object.entries(t.rpcMap).forEach(([t,i])=>{const[r,n]=t.split(":");r&&n&&s[r]&&(s[r].rpcMap||(s[r].rpcMap={}),e.has(r)||(s[r].rpcMap={},e.add(r)),s[r].rpcMap[n]=i)})}return s},createNamespaces(e,t){const s=e.reduce((e,t)=>{const{id:s,chainNamespace:i,rpcUrls:n}=t,o=n.default.http[0];e[i]||(e[i]=this.createDefaultNamespace(i));const a=`${i}:${s}`,c=e[i];switch(c.chains.push(a),a){case r.tWt.caipNetworkId:c.chains.push(r.tWt.deprecatedCaipNetworkId);break;case r.Rn0.caipNetworkId:c.chains.push(r.Rn0.deprecatedCaipNetworkId)}return c?.rpcMap&&o&&(c.rpcMap[s]=o),e},{});return this.applyNamespaceOverrides(s,t)},resolveReownName:async e=>{const t=await i.f.resolveName(e),s=Object.values(t?.addresses)||[];return s[0]?.address||!1},getChainsFromNamespaces:(e={})=>Object.values(e).flatMap(e=>{const t=e.chains||[],s=e.accounts.map(e=>{const[t,s]=e.split(":");return`${t}:${s}`});return Array.from(new Set([...t,...s]))}),isSessionEventData:e=>"object"==typeof e&&null!==e&&"id"in e&&"topic"in e&&"params"in e&&"object"==typeof e.params&&null!==e.params&&"chainId"in e.params&&"event"in e.params&&"object"==typeof e.params.event&&null!==e.params.event,isOriginAllowed(e,t,s){for(const i of[...t,...s])if(i.includes("*")){const t=`^${i.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(t,"u").test(e))return!0}else try{if(new URL(i).origin===e)return!0}catch(t){if(i===e)return!0}return!1}}},62410:(e,t,s)=>{s.d(t,{x:()=>c});var i=s(93474),r=s(31100),n=s(3555);const o=["email","socials","swaps","onramp","activity","reownBranding"],a={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return Boolean(e.isEnabled)&&t.includes("email")},processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.email:Boolean(e)},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t.filter(e=>"email"!==e)},processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.socials:"boolean"==typeof e?!!e&&n.oU.DEFAULT_REMOTE_FEATURES.socials:e},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t},processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.swaps:"boolean"==typeof e?!!e&&n.oU.DEFAULT_REMOTE_FEATURES.swaps:e},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t},processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.onramp:"boolean"==typeof e?!!e&&n.oU.DEFAULT_REMOTE_FEATURES.onramp:e},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.activity:Boolean(e)},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:e=>void 0===e?n.oU.DEFAULT_REMOTE_FEATURES.reownBranding:Boolean(e)}},c={localSettingsOverridden:new Set,getApiConfig:(e,t)=>t?.find(t=>t.id===e),addWarning(e,t){if(void 0!==e){const e=a[t],s=e.isLegacy?`"features.${e.localFeatureName}" (now "${t}")`:`"features.${t}"`;this.localSettingsOverridden.add(s)}},processFeature(e,t,s,i,r){const n=a[e],o=t[n.localFeatureName];if(r&&!n.isAvailableOnBasic)return!1;if(i){const t=this.getApiConfig(n.apiFeatureName,s);return null===t?.config?this.processFallbackFeature(e,o):!!t?.config&&(void 0!==o&&this.addWarning(o,e),this.processApiFeature(e,t))}return this.processFallbackFeature(e,o)},processApiFeature:(e,t)=>a[e].processApi(t),processFallbackFeature:(e,t)=>a[e].processFallback(t),async fetchRemoteFeatures(e){const t=e.basic??!1,s=e.features||{};this.localSettingsOverridden.clear();let a=null,c=!1;try{a=await i.N.fetchProjectConfig(),c=null!=a}catch(e){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",e)}const l=c&&!t?n.oU.DEFAULT_REMOTE_FEATURES:n.oU.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const e of o){const i=this.processFeature(e,s,a,c,t);Object.assign(l,{[e]:i})}}catch(e){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",e),n.oU.DEFAULT_REMOTE_FEATURES}if(c&&this.localSettingsOverridden.size>0){const e=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;r.h.open({shortMessage:"Local configuration ignored",longMessage:`[Reown Config Notice] ${e}`},"warning")}return l}}},63917:(e,t,s)=>{s.d(t,{s:()=>h});var i=s(89168),r=s(39150),n=s(22143),o=s(35646),a=s(1420);const c=Object.freeze({enabled:!0,events:[]}),l=new o.Z({baseUrl:n.w.getAnalyticsUrl(),clientId:null}),d=(0,i.BX)({...c}),h={state:d,subscribeKey:(e,t)=>(0,r.u$)(d,e,t),async sendError(e,t){if(!d.enabled)return;const s=Date.now();if(d.events.filter(e=>{const t=new Date(e.properties.timestamp||"").getTime();return s-t<6e4}).length>=5)return;const i={type:"error",event:t,properties:{errorType:e.name,errorMessage:e.message,stackTrace:e.stack,timestamp:(new Date).toISOString()}};d.events.push(i);try{if("undefined"==typeof window)return;const{projectId:s,sdkType:i,sdkVersion:r}=a.H.state;await l.post({path:"/e",params:{projectId:s,st:i,sv:r||"html-wagmi-4.2.2"},body:{eventId:n.w.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:(new Date).toISOString(),props:{type:"error",event:t,errorType:e.name,errorMessage:e.message,stackTrace:e.stack}}})}catch{}},enable(){d.enabled=!0},disable(){d.enabled=!1},clearEvents(){d.events=[]}}},64525:(e,t,s)=>{s.d(t,{R:()=>i});const i=(0,s(39275).x)({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"})},65508:(e,t,s)=>{(0,s(39275).x)({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"})},67232:(e,t,s)=>{s.d(t,{JX:()=>l,RF:()=>c,W5:()=>p,ck:()=>g,ds:()=>d,fD:()=>u});var i=s(52788),r=s(80989);let n,o,a;function c(e,t){n=document.createElement("style"),o=document.createElement("style"),a=document.createElement("style"),n.textContent=h(e).core.cssText,o.textContent=h(e).dark.cssText,a.textContent=h(e).light.cssText,document.head.appendChild(n),document.head.appendChild(o),document.head.appendChild(a),l(t)}function l(e){o&&a&&("light"===e?(o.removeAttribute("media"),a.media="enabled"):(a.removeAttribute("media"),o.media="enabled"))}function d(e){n&&o&&a&&(n.textContent=h(e).core.cssText,o.textContent=h(e).dark.cssText,a.textContent=h(e).light.cssText)}function h(e){return{core:i.AH`
3
3
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
4
4
  @keyframes w3m-shake {
5
5
  0% {
@@ -875,4 +875,4 @@ export const __webpack_esm_id__=9194;export const __webpack_esm_ids__=[9194];exp
875
875
  .wui-color-fg-350 {
876
876
  background-color: var(--wui-color-fg-350);
877
877
  }
878
- `},67902:(e,t,s)=>{s.d(t,{L:()=>r});var i=s(72269);const r={caipNetworkIdToNumber:e=>e?Number(e.split(":")[1]):void 0,parseEvmChainId(e){return"string"==typeof e?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace:(e,t)=>e?.filter(e=>e.chainNamespace===t)||[],getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){if(!t)return;const s=e.find(e=>e.caipNetworkId===t);if(s)return s.name;const[r]=t.split(":");return i.o.CHAIN_NAME_MAP?.[r]||void 0}}},68251:(e,t,s)=>{s.d(t,{z:()=>o});var i=s(89168),r=s(39150);const n=(0,i.BX)({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),o={state:n,subscribe:e=>(0,i.B1)(n,()=>e(n)),subscribeOpen:e=>(0,r.u$)(n,"open",e),set(e){Object.assign(n,{...n,...e})}}},69658:(e,t,s)=>{s.d(t,{EM:()=>n.E,JX:()=>i.JX,RF:()=>i.RF,Zv:()=>r.Z,ds:()=>i.ds}),s(34631);var i=s(67232),r=s(15179),n=(s(53561),s(13679))},72269:(e,t,s)=>{s.d(t,{o:()=>r});var i=s(39907);const r={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(void 0!==i&&void 0!==i.env?i.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"}},72397:(e,t,s)=>{s.d(t,{I:()=>u});var i=s(89168),r=s(39150),n=s(37834),o=s(23981),a=s(98299),c=s(83077),l=s(88759),d=s(1420);const h=(0,i.BX)({view:"Connect",history:["Connect"],transactionStack:[]}),p={state:h,subscribeKey:(e,t)=>(0,r.u$)(h,e,t),pushTransactionStack(e){h.transactionStack.push(e)},popTransactionStack(e){const t=h.transactionStack.pop();if(!t)return;const{onSuccess:s,onError:i,onCancel:r}=t;switch(e){case"success":s?.();break;case"error":i?.(),u.goBack();break;case"cancel":r?.(),u.goBack()}},push(e,t){e!==h.view&&(h.view=e,h.history.push(e),h.data=t)},reset(e,t){h.view=e,h.history=[e],h.data=t},replace(e,t){h.history.at(-1)===e||(h.view=e,h.history[h.history.length-1]=e,h.data=t)},goBack(){const e=a.W.state.activeCaipAddress,t="ConnectingFarcaster"===u.state.view,s=!e&&t;if(h.history.length>1){h.history.pop();const[t]=h.history.slice(-1);if(t){const s="Connect"===t;h.view=e&&s?"Account":t}}else l.W.close();h.data?.wallet&&(h.data.wallet=void 0),setTimeout(()=>{if(s){o.U.setFarcasterUrl(void 0,a.W.state.activeChain);const e=c.a.getAuthConnector();e?.provider?.reload();const t=(0,i.P9)(d.H.state);e?.provider?.syncDappData?.({metadata:t.metadata,sdkVersion:t.sdkVersion,projectId:t.projectId,sdkType:t.sdkType})}},100)},goBackToIndex(e){if(h.history.length>1){h.history=h.history.slice(0,e+1);const[t]=h.history.slice(-1);t&&(h.view=t)}},goBackOrCloseModal(){u.state.history.length>1?u.goBack():l.W.close()}},u=(0,n.X)(p)},79217:(e,t,s)=>{s.d(t,{Q:()=>r});var i=s(83077);function r(e,t){return i.a.getConnectorId(e)===t}},80971:(e,t,s)=>{s.d(t,{IP:()=>o,T8:()=>r,Ud:()=>n,Ws:()=>i});const i={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections"};function r(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const n={setItem(e,t){o()&&void 0!==t&&localStorage.setItem(e,t)},getItem(e){if(o())return localStorage.getItem(e)||void 0},removeItem(e){o()&&localStorage.removeItem(e)},clear(){o()&&localStorage.clear()}};function o(){return"undefined"!=typeof window&&"undefined"!=typeof localStorage}},80989:(e,t,s)=>{function i(e,t){return"light"===t?{"--w3m-accent":e?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":e?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}s.d(t,{o:()=>i})},82868:(e,t,s)=>{s.d(t,{L:()=>n});var i=s(72269),r=s(83229);const n={ConnectorExplorerIds:{[i.o.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[i.o.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[i.o.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[i.o.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[i.o.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[r.o.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[r.o.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[r.o.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[r.o.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[r.o.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[r.o.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[r.o.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[r.o.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[r.o.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[r.o.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[r.o.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200"},ConnectorImageIds:{[i.o.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[i.o.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[i.o.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[i.o.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[i.o.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[i.o.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[i.o.CONNECTOR_ID.INJECTED]:"Browser Wallet",[i.o.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[i.o.CONNECTOR_ID.COINBASE]:"Coinbase",[i.o.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[i.o.CONNECTOR_ID.LEDGER]:"Ledger",[i.o.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[i.o.CONNECTOR_ID.INJECTED]:"INJECTED",[i.o.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[i.o.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[i.o.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]}},83077:(e,t,s)=>{s.d(t,{a:()=>y});var i=s(89168),r=s(39150),n=s(72269),o=s(80989),a=s(9732),c=s(11847),l=s(37834),d=s(93474),h=s(98299),p=s(1420),u=s(72397),g=s(49951);const m={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},f=(0,i.BX)({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...m},filterByNamespaceMap:{eip155:!0,solana:!0,polkadot:!0,bip122:!0,cosmos:!0}}),w={state:f,subscribe:e=>(0,i.B1)(f,()=>{e(f)}),subscribeKey:(e,t)=>(0,r.u$)(f,e,t),initialize(e){e.forEach(e=>{const t=c.i.getConnectedConnectorId(e);t&&y.setConnectorId(t,e)})},setActiveConnector(e){e&&(f.activeConnector=(0,i.KR)(e))},setConnectors(e){e.filter(e=>!f.allConnectors.some(t=>t.id===e.id&&y.getConnectorName(t.name)===y.getConnectorName(e.name)&&t.chain===e.chain)).forEach(e=>{"MULTI_CHAIN"!==e.type&&f.allConnectors.push((0,i.KR)(e))});const t=y.getEnabledNamespaces(),s=y.getEnabledConnectors(t);f.connectors=y.mergeMultiChainConnectors(s)},filterByNamespaces(e){Object.keys(f.filterByNamespaceMap).forEach(e=>{f.filterByNamespaceMap[e]=!1}),e.forEach(e=>{f.filterByNamespaceMap[e]=!0}),y.updateConnectorsForEnabledNamespaces()},filterByNamespace(e,t){f.filterByNamespaceMap[e]=t,y.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const e=y.getEnabledNamespaces(),t=y.getEnabledConnectors(e),s=y.areAllNamespacesEnabled();f.connectors=y.mergeMultiChainConnectors(t),s?d.N.clearFilterByNamespaces():d.N.filterByNamespaces(e)},getEnabledNamespaces:()=>Object.entries(f.filterByNamespaceMap).filter(([e,t])=>t).map(([e])=>e),getEnabledConnectors:e=>f.allConnectors.filter(t=>e.includes(t.chain)),areAllNamespacesEnabled:()=>Object.values(f.filterByNamespaceMap).every(e=>e),mergeMultiChainConnectors(e){const t=y.generateConnectorMapByName(e),s=[];return t.forEach(e=>{const t=e[0],i=t?.id===n.o.CONNECTOR_ID.AUTH;e.length>1&&t?s.push({name:t.name,imageUrl:t.imageUrl,imageId:t.imageId,connectors:[...e],type:i?"AUTH":"MULTI_CHAIN",chain:"eip155",id:t?.id||""}):t&&s.push(t)}),s},generateConnectorMapByName(e){const t=new Map;return e.forEach(e=>{const{name:s}=e,i=y.getConnectorName(s);if(!i)return;const r=t.get(i)||[];r.find(t=>t.chain===e.chain)||r.push(e),t.set(i,r)}),t},getConnectorName:e=>e&&{"Trust Wallet":"Trust"}[e]||e,getUniqueConnectorsByName(e){const t=[];return e.forEach(e=>{t.find(t=>t.chain===e.chain)||t.push(e)}),t},addConnector(e){if(e.id===n.o.CONNECTOR_ID.AUTH){const t=e,s=(0,i.P9)(p.H.state),r=g.W.getSnapshot().themeMode,n=g.W.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,projectId:s.projectId,sdkType:s.sdkType}),t?.provider?.syncTheme({themeMode:r,themeVariables:n,w3mThemeVariables:(0,o.o)(n,r)}),y.setConnectors([e])}else y.setConnectors([e])},getAuthConnector(e){const t=e||h.W.state.activeChain,s=f.connectors.find(e=>e.id===n.o.CONNECTOR_ID.AUTH);if(s)return s?.connectors?.length?s.connectors.find(e=>e.chain===t):s},getAnnouncedConnectorRdns:()=>f.connectors.filter(e=>"ANNOUNCED"===e.type).map(e=>e.info?.rdns),getConnectorById:e=>f.allConnectors.find(t=>t.id===e),getConnector:(e,t)=>f.allConnectors.filter(e=>e.chain===h.W.state.activeChain).find(s=>s.explorerId===e||s.info?.rdns===t),syncIfAuthConnector(e){if("ID_AUTH"!==e.id)return;const t=e,s=(0,i.P9)(p.H.state),r=g.W.getSnapshot().themeMode,n=g.W.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),t.provider.syncTheme({themeMode:r,themeVariables:n,w3mThemeVariables:(0,o.o)(n,r)})},getConnectorsByNamespace(e){const t=f.allConnectors.filter(t=>t.chain===e);return y.mergeMultiChainConnectors(t)},selectWalletConnector(e){const t=y.getConnector(e.id,e.rdns),s=h.W.state.activeChain;a.W.handleMobileDeeplinkRedirect(t?.explorerId||e.id,s),t?u.I.push("ConnectingExternal",{connector:t}):u.I.push("ConnectingWalletConnect",{wallet:e})},getConnectors:e=>e?y.getConnectorsByNamespace(e):y.mergeMultiChainConnectors(f.allConnectors),setFilterByNamespace(e){f.filterByNamespace=e,f.connectors=y.getConnectors(e),d.N.setFilterByNamespace(e)},setConnectorId(e,t){e&&(f.activeConnectorIds={...f.activeConnectorIds,[t]:e},c.i.setConnectedConnectorId(t,e))},removeConnectorId(e){f.activeConnectorIds={...f.activeConnectorIds,[e]:void 0},c.i.deleteConnectedConnectorId(e)},getConnectorId(e){if(e)return f.activeConnectorIds[e]},isConnected:e=>e?Boolean(f.activeConnectorIds[e]):Object.values(f.activeConnectorIds).some(e=>Boolean(e)),resetConnectorIds(){f.activeConnectorIds={...m}}},y=(0,l.X)(w)},83229:(e,t,s)=>{s.d(t,{o:()=>i});const i={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"ID_AUTH"}},84279:(e,t,s)=>{s.d(t,{A:()=>h});var i=s(83077),r=s(93474),n=s(1420),o=s(22143),a=s(11847),c=s(51765),l=s(32523),d=s(42177);const h={filterOutDuplicatesByRDNS(e){const t=n.H.state.enableEIP6963?i.a.state.connectors:[],s=a.i.getRecentWallets(),r=t.map(e=>e.info?.rdns).filter(Boolean),c=s.map(e=>e.rdns).filter(Boolean),l=r.concat(c);if(l.includes("io.metamask.mobile")&&o.w.isMobile()){const e=l.indexOf("io.metamask.mobile");l[e]="io.metamask"}return e.filter(e=>!l.includes(String(e?.rdns)))},filterOutDuplicatesByIds(e){const t=i.a.state.connectors.filter(e=>"ANNOUNCED"===e.type||"INJECTED"===e.type),s=a.i.getRecentWallets(),r=t.map(e=>e.explorerId),n=s.map(e=>e.id),o=r.concat(n);return e.filter(e=>!o.includes(e?.id))},filterOutDuplicateWallets(e){const t=this.filterOutDuplicatesByRDNS(e);return this.filterOutDuplicatesByIds(t)},markWalletsAsInstalled(e){const{connectors:t}=i.a.state,{featuredWalletIds:s}=n.H.state,r=t.filter(e=>"ANNOUNCED"===e.type).reduce((e,t)=>t.info?.rdns?(e[t.info.rdns]=!0,e):e,{});return e.map(e=>({...e,installed:Boolean(e.rdns)&&Boolean(r[e.rdns??""])})).sort((e,t)=>{const i=Number(t.installed)-Number(e.installed);if(0!==i)return i;if(s?.length){const i=s.indexOf(e.id),r=s.indexOf(t.id);if(-1!==i&&-1!==r)return i-r;if(-1!==i)return-1;if(-1!==r)return 1}return 0})},getConnectOrderMethod(e,t){const s=e?.connectMethodsOrder||n.H.state.features?.connectMethodsOrder,o=t||i.a.state.connectors;if(s)return s;const{injected:a,announced:c}=l.g.getConnectorsByType(o,r.N.state.recommended,r.N.state.featured),h=a.filter(l.g.showConnector),p=c.filter(l.g.showConnector);return h.length||p.length?["wallet","email","social"]:d.o.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(e){const t=Boolean(e.rdns)&&r.N.state.excludedWallets.some(t=>t.rdns===e.rdns),s=Boolean(e.name)&&r.N.state.excludedWallets.some(t=>c.y.isLowerCaseMatch(t.name,e.name));return t||s}}},86454:(e,t,s)=>{s.d(t,{$:()=>c});var i=s(89168),r=s(93474),n=s(6262);const o={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:""},a=(0,i.BX)({networkImagePromises:{}}),c={async fetchWalletImage(e){if(e)return await r.N._fetchWalletImage(e),this.getWalletImageById(e)},async fetchNetworkImage(e){if(!e)return;return this.getNetworkImageById(e)||(a.networkImagePromises[e]||(a.networkImagePromises[e]=r.N._fetchNetworkImage(e)),await a.networkImagePromises[e],this.getNetworkImageById(e))},getWalletImageById(e){if(e)return n.j.state.walletImages[e]},getWalletImage:e=>e?.image_url?e?.image_url:e?.image_id?n.j.state.walletImages[e.image_id]:void 0,getNetworkImage:e=>e?.assets?.imageUrl?e?.assets?.imageUrl:e?.assets?.imageId?n.j.state.networkImages[e.assets.imageId]:void 0,getNetworkImageById(e){if(e)return n.j.state.networkImages[e]},getConnectorImage:e=>e?.imageUrl?e.imageUrl:e?.imageId?n.j.state.connectorImages[e.imageId]:void 0,getChainImage:e=>n.j.state.networkImages[o[e]]}},86792:(e,t,s)=>{s.d(t,{x:()=>y});var i=s(89168),r=s(39150),n=s(22143),o=s(11847),a=s(37834),c=s(23981),l=s(98299),d=s(83077),h=s(47981),p=s(88759),u=s(72397),g=s(87193);const m=(0,i.BX)({connections:new Map,wcError:!1,buffering:!1,status:"disconnected"});let f;const w={state:m,subscribeKey:(e,t)=>(0,r.u$)(m,e,t),_getClient:()=>m._client,setClient(e){m._client=(0,i.KR)(e)},async connectWalletConnect(){if(n.w.isTelegram()||n.w.isSafari()&&n.w.isIos()){if(f)return await f,void(f=void 0);if(!n.w.isPairingExpired(m?.wcPairingExpiry)){const e=m.wcUri;return void(m.wcUri=e)}f=y._getClient()?.connectWalletConnect?.().catch(()=>{}),y.state.status="connecting",await f,f=void 0,m.wcPairingExpiry=void 0,y.state.status="connected"}else await(y._getClient()?.connectWalletConnect?.())},async connectExternal(e,t,s=!0){await(y._getClient()?.connectExternal?.(e)),s&&l.W.setActiveNamespace(t)},async reconnectExternal(e){await(y._getClient()?.reconnectExternal?.(e));const t=e.chain||l.W.state.activeChain;t&&d.a.setConnectorId(e.id,t)},async setPreferredAccountType(e,t){p.W.setLoading(!0,l.W.state.activeChain);const s=d.a.getAuthConnector();s&&(c.U.setPreferredAccountType(e,t),await s.provider.setPreferredAccount(e),o.i.setPreferredAccountTypes(c.U.state.preferredAccountTypes??{[t]:e}),await y.reconnectExternal(s),p.W.setLoading(!1,l.W.state.activeChain),h.E.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:e,network:l.W.state.activeCaipNetwork?.caipNetworkId||""}}))},signMessage:async e=>y._getClient()?.signMessage(e),parseUnits:(e,t)=>y._getClient()?.parseUnits(e,t),formatUnits:(e,t)=>y._getClient()?.formatUnits(e,t),sendTransaction:async e=>y._getClient()?.sendTransaction(e),getCapabilities:async e=>y._getClient()?.getCapabilities(e),grantPermissions:async e=>y._getClient()?.grantPermissions(e),walletGetAssets:async e=>y._getClient()?.walletGetAssets(e)??{},estimateGas:async e=>y._getClient()?.estimateGas(e),writeContract:async e=>y._getClient()?.writeContract(e),getEnsAddress:async e=>y._getClient()?.getEnsAddress(e),getEnsAvatar:async e=>y._getClient()?.getEnsAvatar(e),checkInstalled:e=>y._getClient()?.checkInstalled?.(e)||!1,resetWcConnection(){m.wcUri=void 0,m.wcPairingExpiry=void 0,m.wcLinking=void 0,m.recentWallet=void 0,m.status="disconnected",g.W.resetTransactions(),o.i.deleteWalletConnectDeepLink()},resetUri(){m.wcUri=void 0,m.wcPairingExpiry=void 0,f=void 0},finalizeWcConnection(){const{wcLinking:e,recentWallet:t}=y.state;e&&o.i.setWalletConnectDeepLink(e),t&&o.i.setAppKitRecent(t),h.E.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:e?"mobile":"qrcode",name:u.I.state.data?.wallet?.name||"Unknown"}})},setWcBasic(e){m.wcBasic=e},setUri(e){m.wcUri=e,m.wcPairingExpiry=n.w.getPairingExpiry()},setWcLinking(e){m.wcLinking=e},setWcError(e){m.wcError=e,m.buffering=!1},setRecentWallet(e){m.recentWallet=e},setBuffering(e){m.buffering=e},setStatus(e){m.status=e},async disconnect(e){try{await(y._getClient()?.disconnect(e))}catch(e){throw new a.A("Failed to disconnect","INTERNAL_SDK_ERROR",e)}},setConnections(e,t){m.connections.set(t,e)},switchAccount({connection:e,address:t,namespace:s}){if(d.a.state.activeConnectorIds[s]===e.connectorId){const e=l.W.state.activeCaipNetwork;if(e){const i=`${s}:${e.id}:${t}`;c.U.setCaipAddress(i,s)}else console.warn(`No current network found for namespace "${s}"`)}else{const t=d.a.getConnector(e.connectorId);t?y.connectExternal(t,s):console.warn(`No connector found for namespace "${s}"`)}}},y=(0,a.X)(w)},87193:(e,t,s)=>{s.d(t,{W:()=>g});var i=s(89168),r=s(88889),n=s(37834),o=s(23981),a=s(16444),c=s(98299),l=s(47981),d=s(1420),h=s(92492);const p=(0,i.BX)({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),u={state:p,subscribe:e=>(0,i.B1)(p,()=>e(p)),setLastNetworkInView(e){p.lastNetworkInView=e},async fetchTransactions(e,t){if(!e)throw new Error("Transactions can't be fetched without an accountAddress");p.loading=!0;try{const s=await a.T.fetchTransactions({account:e,cursor:p.next,onramp:t,cache:"coinbase"===t?"no-cache":void 0,chainId:c.W.state.activeCaipNetwork?.caipNetworkId}),i=g.filterSpamTransactions(s.data),r=g.filterByConnectedChain(i),n=[...p.transactions,...r];p.loading=!1,"coinbase"===t?p.coinbaseTransactions=g.groupTransactionsByYearAndMonth(p.coinbaseTransactions,s.data):(p.transactions=n,p.transactionsByYear=g.groupTransactionsByYearAndMonth(p.transactionsByYear,r)),p.empty=0===n.length,p.next=s.next?s.next:void 0}catch(t){const s=c.W.state.activeChain;l.E.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:e,projectId:d.H.state.projectId,cursor:p.next,isSmartAccount:o.U.state.preferredAccountTypes?.[s]===r.Vl.ACCOUNT_TYPES.SMART_ACCOUNT}}),h.P.showError("Failed to fetch transactions"),p.loading=!1,p.empty=!0,p.next=void 0}},groupTransactionsByYearAndMonth(e={},t=[]){const s=e;return t.forEach(e=>{const t=new Date(e.metadata.minedAt).getFullYear(),i=new Date(e.metadata.minedAt).getMonth(),r=s[t]??{},n=(r[i]??[]).filter(t=>t.id!==e.id);s[t]={...r,[i]:[...n,e].sort((e,t)=>new Date(t.metadata.minedAt).getTime()-new Date(e.metadata.minedAt).getTime())}}),s},filterSpamTransactions:e=>e.filter(e=>!e.transfers.every(e=>!0===e.nft_info?.flags.is_spam)),filterByConnectedChain(e){const t=c.W.state.activeCaipNetwork?.caipNetworkId;return e.filter(e=>e.metadata.chain===t)},clearCursor(){p.next=void 0},resetTransactions(){p.transactions=[],p.transactionsByYear={},p.lastNetworkInView=void 0,p.loading=!1,p.empty=!1,p.next=void 0}},g=(0,n.X)(u,"API_ERROR")},88759:(e,t,s)=>{s.d(t,{W:()=>b});var i=s(89168),r=s(39150),n=s(22143),o=s(60032),a=s(37834),c=s(23981),l=s(93474),d=s(98299),h=s(86792),p=s(83077),u=s(47981),g=s(1420),m=s(68251),f=s(72397);const w=(0,i.BX)({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),y={state:w,subscribe:e=>(0,i.B1)(w,()=>e(w)),subscribeKey:(e,t)=>(0,r.u$)(w,e,t),async open(e){const t="connected"===c.U.state.status,s=e?.namespace,i=d.W.state.activeChain,r=s&&s!==i,a=d.W.getAccountData(e?.namespace)?.caipAddress;if(h.x.state.wcBasic?l.N.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await l.N.prefetch({fetchConnectorImages:!t,fetchFeaturedWallets:!t,fetchRecommendedWallets:!t}),p.a.setFilterByNamespace(e?.namespace),b.setLoading(!0,s),s&&r){const e=d.W.getNetworkData(s)?.caipNetwork||d.W.getRequestedCaipNetworks(s)[0];e&&o.L.onSwitchNetwork({network:e,ignoreSwitchConfirmation:!0})}else{const t=d.W.state.noAdapters;g.H.state.manualWCControl||t&&!a?n.w.isMobile()?f.I.reset("AllWallets"):f.I.reset("ConnectingWalletConnectBasic"):e?.view?f.I.reset(e.view,e.data):a?f.I.reset("Account"):f.I.reset("Connect")}w.open=!0,m.z.set({open:!0}),u.E.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:Boolean(a)}})},close(){const e=g.H.state.enableEmbedded,t=Boolean(d.W.state.activeCaipAddress);w.open&&u.E.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:t}}),w.open=!1,f.I.reset("Connect"),b.clearLoading(),e?t?f.I.replace("Account"):f.I.push("Connect"):m.z.set({open:!1}),h.x.resetUri()},setLoading(e,t){t&&w.loadingNamespaceMap.set(t,e),w.loading=e,m.z.set({loading:e})},clearLoading(){w.loadingNamespaceMap.clear(),w.loading=!1},shake(){w.shake||(w.shake=!0,setTimeout(()=>{w.shake=!1},500))}},b=(0,a.X)(y)},88889:(e,t,s)=>{s.d(t,{Vl:()=>r});var i=s(39907);void 0!==i&&void 0!==i.env&&i.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL,void 0!==i&&void 0!==i.env&&i.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL,void 0!==i&&void 0!==i.env&&i.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const r={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}}},89305:(e,t,s)=>{s.d(t,{aG:()=>y});var i=s(89168),r=s(39150),n=s(72269),o=s(3555),a=s(37834),c=s(23981),l=s(93474),d=s(16444),h=s(98299),p=s(1420);const u={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},g={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},m={providers:o.tM,selectedProvider:null,error:null,purchaseCurrency:u,paymentCurrency:g,purchaseCurrencies:[u],paymentCurrencies:[],quotesLoading:!1},f=(0,i.BX)(m),w={state:f,subscribe:e=>(0,i.B1)(f,()=>e(f)),subscribeKey:(e,t)=>(0,r.u$)(f,e,t),setSelectedProvider(e){if(e&&"meld"===e.name){const t=h.W.state.activeChain===n.o.CHAIN.SOLANA?"SOL":"USDC",s=c.U.state.address??"",i=new URL(e.url);i.searchParams.append("publicKey",o.Db),i.searchParams.append("destinationCurrencyCode",t),i.searchParams.append("walletAddress",s),i.searchParams.append("externalCustomerId",p.H.state.projectId),f.selectedProvider={...e,url:i.toString()}}else f.selectedProvider=e},setOnrampProviders(e){if(Array.isArray(e)&&e.every(e=>"string"==typeof e)){const t=e,s=o.tM.filter(e=>t.includes(e.name));f.providers=s}else f.providers=[]},setPurchaseCurrency(e){f.purchaseCurrency=e},setPaymentCurrency(e){f.paymentCurrency=e},setPurchaseAmount(e){y.state.purchaseAmount=e},setPaymentAmount(e){y.state.paymentAmount=e},async getAvailableCurrencies(){const e=await d.T.getOnrampOptions();f.purchaseCurrencies=e.purchaseCurrencies,f.paymentCurrencies=e.paymentCurrencies,f.paymentCurrency=e.paymentCurrencies[0]||g,f.purchaseCurrency=e.purchaseCurrencies[0]||u,await l.N.fetchCurrencyImages(e.paymentCurrencies.map(e=>e.id)),await l.N.fetchTokenImages(e.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){f.quotesLoading=!0;try{const e=await d.T.getOnrampQuote({purchaseCurrency:f.purchaseCurrency,paymentCurrency:f.paymentCurrency,amount:f.paymentAmount?.toString()||"0",network:f.purchaseCurrency?.symbol});return f.quotesLoading=!1,f.purchaseAmount=Number(e?.purchaseAmount.amount),e}catch(e){return f.error=e.message,f.quotesLoading=!1,null}finally{f.quotesLoading=!1}},resetState(){f.selectedProvider=null,f.error=null,f.purchaseCurrency=u,f.paymentCurrency=g,f.purchaseCurrencies=[u],f.paymentCurrencies=[],f.paymentAmount=void 0,f.purchaseAmount=void 0,f.quotesLoading=!1}},y=(0,a.X)(w)},89604:(e,t,s)=>{s.d(t,{r:()=>i});const i=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}]},90169:(e,t,s)=>{s.d(t,{$I:()=>Y,$w:()=>J,Jf:()=>P,S$:()=>X,Tn:()=>ee,U:()=>Z,U$:()=>Q,WB:()=>z,cV:()=>U,iJ:()=>di,il:()=>Rs,sD:()=>_,wn:()=>F,zN:()=>j});var i=s(50046),r=s.n(i),n=s(37147),o=s(81030),a=s(70255),c=s(18898),l=s(91315),d=s(25607),h=s(97353),p=s(15529),u=s(1030),g=s(93786),m=s(14350),f=s(63342),w=s(20635),y=s(48526).hp,b=s(39907);const v="core",E=`wc@2:${v}:`,C={database:":memory:"},I="client_ed25519_seed",N=l.ONE_DAY,A=l.SIX_HOURS,_="irn",S="wss://relay.walletconnect.org",P={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},T="payload",O="connect",k="disconnect",R="error",x="2.21.0",U={link_mode:"link_mode",relay:"relay"},D="inbound",L="WALLETCONNECT_LINK_MODE_APPS",W="subscription_created",M="subscription_deleted",B=(l.FIVE_SECONDS,{wc_pairingDelete:{req:{ttl:l.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:l.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:l.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:l.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:l.ONE_DAY,prompt:!1,tag:0},res:{ttl:l.ONE_DAY,prompt:!1,tag:0}}}),j={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},q="history_created",$="history_updated",H="history_deleted",F={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},V="https://verify.walletconnect.org",z=V,K=`${z}/v3`,G=["https://verify.walletconnect.com",V],J={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},X={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Y={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Z={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Q={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},ee={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"};const te=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class se{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class ie{constructor(e,t,s){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=s}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return ne(this,e)}}class re{constructor(e){this.decoders=e}or(e){return ne(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ne=(e,t)=>new re({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class oe{constructor(e,t,s,i){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=i,this.encoder=new se(e,t,s),this.decoder=new ie(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ae=({name:e,prefix:t,encode:s,decode:i})=>new oe(e,t,s,i),ce=({prefix:e,name:t,alphabet:s})=>{const{encode:i,decode:r}=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),i=0;i<s.length;i++)s[i]=255;for(var r=0;r<e.length;r++){var n=e.charAt(r),o=n.charCodeAt(0);if(255!==s[o])throw new TypeError(n+" is ambiguous");s[o]=r}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var i=0,r=0;e[t]===c;)i++,t++;for(var n=(e.length-t)*l+1>>>0,o=new Uint8Array(n);e[t];){var d=s[e.charCodeAt(t)];if(255===d)return;for(var h=0,p=n-1;(0!==d||h<r)&&-1!==p;p--,h++)d+=a*o[p]>>>0,o[p]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");r=h,t++}if(" "!==e[t]){for(var u=n-r;u!==n&&0===o[u];)u++;for(var g=new Uint8Array(i+(n-u)),m=i;u!==n;)g[m++]=o[u++];return g}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var s=0,i=0,r=0,n=t.length;r!==n&&0===t[r];)r++,s++;for(var o=(n-r)*d+1>>>0,l=new Uint8Array(o);r!==n;){for(var h=t[r],p=0,u=o-1;(0!==h||p<i)&&-1!==u;u--,p++)h+=256*l[u]>>>0,l[u]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");i=p,r++}for(var g=o-i;g!==o&&0===l[g];)g++;for(var m=c.repeat(s);g<o;++g)m+=e.charAt(l[g]);return m},decodeUnsafe:h,decode:function(e){var s=h(e);if(s)return s;throw new Error(`Non-${t} character`)}}}(s,t);return ae({prefix:e,name:t,encode:i,decode:e=>te(r(e))})},le=({name:e,prefix:t,bitsPerChar:s,alphabet:i})=>ae({prefix:t,name:e,encode:e=>((e,t,s)=>{const i="="===t[t.length-1],r=(1<<s)-1;let n="",o=0,a=0;for(let i=0;i<e.length;++i)for(a=a<<8|e[i],o+=8;o>s;)o-=s,n+=t[r&a>>o];if(o&&(n+=t[r&a<<s-o]),i)for(;n.length*s&7;)n+="=";return n})(e,i,s),decode:t=>((e,t,s,i)=>{const r={};for(let e=0;e<t.length;++e)r[t[e]]=e;let n=e.length;for(;"="===e[n-1];)--n;const o=new Uint8Array(n*s/8|0);let a=0,c=0,l=0;for(let t=0;t<n;++t){const n=r[e[t]];if(void 0===n)throw new SyntaxError(`Non-${i} character`);c=c<<s|n,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,i,s,e)}),de=ae({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var he=Object.freeze({__proto__:null,identity:de});const pe=le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ue=Object.freeze({__proto__:null,base2:pe});const ge=le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var me=Object.freeze({__proto__:null,base8:ge});const fe=ce({prefix:"9",name:"base10",alphabet:"0123456789"});var we=Object.freeze({__proto__:null,base10:fe});const ye=le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),be=le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ve=Object.freeze({__proto__:null,base16:ye,base16upper:be});const Ee=le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ce=le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ie=le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ne=le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ae=le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_e=le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Se=le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Pe=le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Te=le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Oe=Object.freeze({__proto__:null,base32:Ee,base32upper:Ce,base32pad:Ie,base32padupper:Ne,base32hex:Ae,base32hexupper:_e,base32hexpad:Se,base32hexpadupper:Pe,base32z:Te});const ke=ce({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Re=ce({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var xe=Object.freeze({__proto__:null,base36:ke,base36upper:Re});const Ue=ce({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),De=ce({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Le=Object.freeze({__proto__:null,base58btc:Ue,base58flickr:De});const We=le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Me=le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Be=le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),je=le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var qe=Object.freeze({__proto__:null,base64:We,base64pad:Me,base64url:Be,base64urlpad:je});const $e=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),He=$e.reduce((e,t,s)=>(e[s]=t,e),[]),Fe=$e.reduce((e,t,s)=>(e[t.codePointAt(0)]=s,e),[]),Ve=ae({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+He[t],"")},decode:function(e){const t=[];for(const s of e){const e=Fe[s.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${s}`);t.push(e)}return new Uint8Array(t)}});var ze=Object.freeze({__proto__:null,base256emoji:Ve}),Ke=128,Ge=-128,Je=Math.pow(2,31),Xe=Math.pow(2,7),Ye=Math.pow(2,14),Ze=Math.pow(2,21),Qe=Math.pow(2,28),et=Math.pow(2,35),tt=Math.pow(2,42),st=Math.pow(2,49),it=Math.pow(2,56),rt=Math.pow(2,63),nt=function e(t,s,i){s=s||[];for(var r=i=i||0;t>=Je;)s[i++]=255&t|Ke,t/=128;for(;t&Ge;)s[i++]=255&t|Ke,t>>>=7;return s[i]=0|t,e.bytes=i-r+1,s},ot=function(e){return e<Xe?1:e<Ye?2:e<Ze?3:e<Qe?4:e<et?5:e<tt?6:e<st?7:e<it?8:e<rt?9:10};const at=(e,t,s=0)=>(nt(e,t,s),t),ct=e=>ot(e),lt=(e,t)=>{const s=t.byteLength,i=ct(e),r=i+ct(s),n=new Uint8Array(r+s);return at(e,n,0),at(s,n,i),n.set(t,r),new dt(e,s,t,n)};class dt{constructor(e,t,s,i){this.code=e,this.size=t,this.digest=s,this.bytes=i}}const ht=({name:e,code:t,encode:s})=>new pt(e,t,s);class pt{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?lt(this.code,t):t.then(e=>lt(this.code,e))}throw Error("Unknown type, must be binary type")}}const ut=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),gt=ht({name:"sha2-256",code:18,encode:ut("SHA-256")}),mt=ht({name:"sha2-512",code:19,encode:ut("SHA-512")});Object.freeze({__proto__:null,sha256:gt,sha512:mt});const ft=te,wt={code:0,name:"identity",encode:ft,digest:e=>lt(0,ft(e))};Object.freeze({__proto__:null,identity:wt}),new TextEncoder,new TextDecoder;const yt={...he,...ue,...me,...we,...ve,...Oe,...xe,...Le,...qe,...ze};function bt(e,t,s,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:s},decoder:{decode:i}}}const vt=bt("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),Et=bt("ascii","a",e=>{let t="a";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return t},e=>{const t=function(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?globalThis.Buffer.allocUnsafe(e):new Uint8Array(e)}((e=e.substring(1)).length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}),Ct={utf8:vt,"utf-8":vt,hex:yt.base16,latin1:Et,ascii:Et,binary:Et,...yt};var It=Object.defineProperty,Nt=(e,t,s)=>((e,t,s)=>t in e?It(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class At{constructor(e,t){this.core=e,this.logger=t,Nt(this,"keychain",new Map),Nt(this,"name","keychain"),Nt(this,"version","0.3"),Nt(this,"initialized",!1),Nt(this,"storagePrefix",E),Nt(this,"init",async()=>{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}}),Nt(this,"has",e=>(this.isInitialized(),this.keychain.has(e))),Nt(this,"set",async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()}),Nt(this,"get",e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}),Nt(this,"del",async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()}),this.core=e,this.logger=(0,a.U5)(t,this.name)}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,(0,p.h0Y)(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?(0,p.PUk)(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _t=Object.defineProperty,St=(e,t,s)=>((e,t,s)=>t in e?_t(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Pt{constructor(e,t,s){this.core=e,this.logger=t,St(this,"name","crypto"),St(this,"keychain"),St(this,"randomSessionIdentifier",(0,p.two)()),St(this,"initialized",!1),St(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),St(this,"hasKeys",e=>(this.isInitialized(),this.keychain.has(e))),St(this,"getClientId",async()=>{this.isInitialized();const e=await this.getClientSeed(),t=h.TZ(e);return h.UF(t.publicKey)}),St(this,"generateKeyPair",()=>{this.isInitialized();const e=(0,p.TZl)();return this.setPrivateKey(e.publicKey,e.privateKey)}),St(this,"signJWT",async e=>{this.isInitialized();const t=await this.getClientSeed(),s=h.TZ(t),i=this.randomSessionIdentifier,r=N;return await h.FA(i,e,r,s)}),St(this,"generateSharedKey",(e,t,s)=>{this.isInitialized();const i=this.getPrivateKey(e),r=(0,p.ovp)(i,t);return this.setSymKey(r,s)}),St(this,"setSymKey",async(e,t)=>{this.isInitialized();const s=t||(0,p.EN$)(e);return await this.keychain.set(s,e),s}),St(this,"deleteKeyPair",async e=>{this.isInitialized(),await this.keychain.del(e)}),St(this,"deleteSymKey",async e=>{this.isInitialized(),await this.keychain.del(e)}),St(this,"encode",async(e,t,s)=>{this.isInitialized();const i=(0,p.AwN)(s),r=(0,d.h)(t);if((0,p.ps1)(i))return(0,p.Tw2)(r,s?.encoding);if((0,p.V7m)(i)){const t=i.senderPublicKey,s=i.receiverPublicKey;e=await this.generateSharedKey(t,s)}const n=this.getSymKey(e),{type:o,senderPublicKey:a}=i;return(0,p.wa2)({type:o,symKey:n,message:r,senderPublicKey:a,encoding:s?.encoding})}),St(this,"decode",async(e,t,s)=>{this.isInitialized();const i=(0,p.C5G)(t,s);if((0,p.ps1)(i)){const e=(0,p.F$L)(t,s?.encoding);return(0,d.j)(e)}if((0,p.V7m)(i)){const t=i.receiverPublicKey,s=i.senderPublicKey;e=await this.generateSharedKey(t,s)}try{const i=this.getSymKey(e),r=(0,p.YcA)({symKey:i,encoded:t,encoding:s?.encoding});return(0,d.j)(r)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}}),St(this,"getPayloadType",(e,t=p.EWt)=>{const s=(0,p.iui)({encoded:e,encoding:t});return(0,p.x0t)(s.type)}),St(this,"getPayloadSenderPublicKey",(e,t=p.EWt)=>{const s=(0,p.iui)({encoded:e,encoding:t});return s.senderPublicKey?(0,u.dI)(s.senderPublicKey,p.bEt):void 0}),this.core=e,this.logger=(0,a.U5)(t,this.name),this.keychain=s||new At(this.core,this.logger)}get context(){return(0,a.oI)(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(I)}catch{e=(0,p.two)(),await this.keychain.set(I,e)}return function(e,t="utf8"){const s=Ct[t];if(!s)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?s.decoder.decode(`${s.prefix}${e}`):globalThis.Buffer.from(e,"utf8")}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Tt=Object.defineProperty,Ot=Object.defineProperties,kt=Object.getOwnPropertyDescriptors,Rt=Object.getOwnPropertySymbols,xt=Object.prototype.hasOwnProperty,Ut=Object.prototype.propertyIsEnumerable,Dt=(e,t,s)=>t in e?Tt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Lt=(e,t,s)=>Dt(e,"symbol"!=typeof t?t+"":t,s);class Wt extends c.dQ{constructor(e,t){super(e,t),this.logger=e,this.core=t,Lt(this,"messages",new Map),Lt(this,"messagesWithoutClientAck",new Map),Lt(this,"name","messages"),Lt(this,"version","0.3"),Lt(this,"initialized",!1),Lt(this,"storagePrefix",E),Lt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e);const t=await this.getRelayerMessagesWithoutClientAck();typeof t<"u"&&(this.messagesWithoutClientAck=t),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}}),Lt(this,"set",async(e,t,s)=>{this.isInitialized();const i=(0,p.ALl)(t);let r=this.messages.get(e);if(typeof r>"u"&&(r={}),typeof r[i]<"u")return i;if(r[i]=t,this.messages.set(e,r),s===D){const s=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,((e,t)=>Ot(e,kt(t)))(((e,t)=>{for(var s in t||(t={}))xt.call(t,s)&&Dt(e,s,t[s]);if(Rt)for(var s of Rt(t))Ut.call(t,s)&&Dt(e,s,t[s]);return e})({},s),{[i]:t}))}return await this.persist(),i}),Lt(this,"get",e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t}),Lt(this,"getWithoutAck",e=>{this.isInitialized();const t={};for(const s of e){const e=this.messagesWithoutClientAck.get(s)||{};t[s]=Object.values(e)}return t}),Lt(this,"has",(e,t)=>(this.isInitialized(),typeof this.get(e)[(0,p.ALl)(t)]<"u")),Lt(this,"ack",async(e,t)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(e);typeof s>"u"||(delete s[(0,p.ALl)(t)],0===Object.keys(s).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,s),await this.persist())}),Lt(this,"del",async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()}),this.logger=(0,a.U5)(e,this.name),this.core=t}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,(0,p.h0Y)(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,(0,p.h0Y)(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?(0,p.PUk)(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?(0,p.PUk)(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Mt=Object.defineProperty,Bt=Object.defineProperties,jt=Object.getOwnPropertyDescriptors,qt=Object.getOwnPropertySymbols,$t=Object.prototype.hasOwnProperty,Ht=Object.prototype.propertyIsEnumerable,Ft=(e,t,s)=>t in e?Mt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Vt=(e,t)=>{for(var s in t||(t={}))$t.call(t,s)&&Ft(e,s,t[s]);if(qt)for(var s of qt(t))Ht.call(t,s)&&Ft(e,s,t[s]);return e},zt=(e,t)=>Bt(e,jt(t)),Kt=(e,t,s)=>Ft(e,"symbol"!=typeof t?t+"":t,s);class Gt extends c.qE{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Kt(this,"events",new i.EventEmitter),Kt(this,"name","publisher"),Kt(this,"queue",new Map),Kt(this,"publishTimeout",(0,l.toMiliseconds)(l.ONE_MINUTE)),Kt(this,"initialPublishTimeout",(0,l.toMiliseconds)(15*l.ONE_SECOND)),Kt(this,"needsTransportRestart",!1),Kt(this,"publish",async(e,t,s)=>{var i;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:s}});const r=s?.ttl||A,n=(0,p.n6V)(s),o=s?.prompt||!1,a=s?.tag||0,c=s?.id||(0,m.getBigIntRpcId)().toString(),l={topic:e,message:t,opts:{ttl:r,relay:n,prompt:o,tag:a,id:c,attestation:s?.attestation,tvf:s?.tvf}},d=`Failed to publish payload, please try again. id:${c} tag:${a}`;try{const i=new Promise(async i=>{const n=({id:e})=>{l.opts.id===e&&(this.removeRequestFromQueue(e),this.relayer.events.removeListener(P.publish,n),i(l))};this.relayer.events.on(P.publish,n);const d=(0,p.K3g)(new Promise((i,n)=>{this.rpcPublish({topic:e,message:t,ttl:r,prompt:o,tag:a,id:c,attestation:s?.attestation,tvf:s?.tvf}).then(i).catch(e=>{this.logger.warn(e,e?.message),n(e)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${c} tag:${a}`);try{await d,this.events.removeListener(P.publish,n)}catch(e){this.queue.set(c,zt(Vt({},l),{attempt:1})),this.logger.warn(e,e?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:c,topic:e,message:t,opts:s}}),await(0,p.K3g)(i,this.publishTimeout,d)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),null!=(i=s?.internal)&&i.throwOnFailedPublish)throw e}finally{this.queue.delete(c)}}),Kt(this,"on",(e,t)=>{this.events.on(e,t)}),Kt(this,"once",(e,t)=>{this.events.once(e,t)}),Kt(this,"off",(e,t)=>{this.events.off(e,t)}),Kt(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.relayer=e,this.logger=(0,a.U5)(t,this.name),this.registerEventListeners()}get context(){return(0,a.oI)(this.logger)}async rpcPublish(e){var t,s,i,r;const{topic:n,message:o,ttl:a=A,prompt:c,tag:l,id:d,attestation:h,tvf:u}=e,g={method:(0,p.aa1)((0,p.n6V)().protocol).publish,params:Vt({topic:n,message:o,ttl:a,prompt:c,tag:l,attestation:h},u),id:d};(0,p.b07)(null==(t=g.params)?void 0:t.prompt)&&(null==(s=g.params)||delete s.prompt),(0,p.b07)(null==(i=g.params)?void 0:i.tag)&&(null==(r=g.params)||delete r.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const m=await this.relayer.request(g);return this.relayer.events.emit(P.publish,e),this.logger.debug("Successfully Published Payload"),m}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,zt(Vt({},e),{attempt:s}));const{topic:i,message:r,opts:n,attestation:o}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${s}`),await this.rpcPublish(zt(Vt({},e),{topic:i,message:r,ttl:n.ttl,prompt:n.prompt,tag:n.tag,id:n.id,attestation:o,tvf:n.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(n.li.pulse,()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(P.connection_stalled);this.checkQueue()}),this.relayer.on(P.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var Jt=Object.defineProperty,Xt=(e,t,s)=>((e,t,s)=>t in e?Jt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Yt{constructor(){Xt(this,"map",new Map),Xt(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),Xt(this,"get",e=>this.map.get(e)||[]),Xt(this,"exists",(e,t)=>this.get(e).includes(t)),Xt(this,"delete",(e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const i=s.filter(e=>e!==t);i.length?this.map.set(e,i):this.map.delete(e)}),Xt(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Zt=Object.defineProperty,Qt=Object.defineProperties,es=Object.getOwnPropertyDescriptors,ts=Object.getOwnPropertySymbols,ss=Object.prototype.hasOwnProperty,is=Object.prototype.propertyIsEnumerable,rs=(e,t,s)=>t in e?Zt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ns=(e,t)=>{for(var s in t||(t={}))ss.call(t,s)&&rs(e,s,t[s]);if(ts)for(var s of ts(t))is.call(t,s)&&rs(e,s,t[s]);return e},os=(e,t)=>Qt(e,es(t)),as=(e,t,s)=>rs(e,"symbol"!=typeof t?t+"":t,s);class cs extends c.mF{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,as(this,"subscriptions",new Map),as(this,"topicMap",new Yt),as(this,"events",new i.EventEmitter),as(this,"name","subscription"),as(this,"version","0.3"),as(this,"pending",new Map),as(this,"cached",[]),as(this,"initialized",!1),as(this,"storagePrefix",E),as(this,"subscribeTimeout",(0,l.toMiliseconds)(l.ONE_MINUTE)),as(this,"initialSubscribeTimeout",(0,l.toMiliseconds)(15*l.ONE_SECOND)),as(this,"clientId"),as(this,"batchSubscribeTopicsLimit",500),as(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),as(this,"subscribe",async(e,t)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const s=(0,p.n6V)(t),i={topic:e,relay:s,transportType:t?.transportType};this.pending.set(e,i);const r=await this.rpcSubscribe(e,s,t);return"string"==typeof r&&(this.onSubscribe(r,i),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}})),r}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}}),as(this,"unsubscribe",async(e,t)=>{this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)}),as(this,"isSubscribed",e=>new Promise(t=>{t(this.topicMap.topics.includes(e))})),as(this,"isKnownTopic",e=>new Promise(t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some(t=>t.topic===e))})),as(this,"on",(e,t)=>{this.events.on(e,t)}),as(this,"once",(e,t)=>{this.events.once(e,t)}),as(this,"off",(e,t)=>{this.events.off(e,t)}),as(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),as(this,"start",async()=>{await this.onConnect()}),as(this,"stop",async()=>{await this.onDisconnect()}),as(this,"restart",async()=>{await this.restore(),await this.onRestart()}),as(this,"checkPending",async()=>{if(!(0!==this.pending.size||this.initialized&&this.relayer.connected))return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e)}),as(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(n.li.pulse,async()=>{await this.checkPending()}),this.events.on(W,async e=>{const t=W;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(M,async e=>{const t=M;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})}),this.relayer=e,this.logger=(0,a.U5)(t,this.name),this.clientId=""}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async s=>await this.unsubscribeById(e,s,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const i=(0,p.n6V)(s);await this.restartToComplete({topic:e,id:t,relay:i}),await this.rpcUnsubscribe(e,t,i);const r=(0,p.Hjj)("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t,s){var i;(!s||s?.transportType===U.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const r={method:(0,p.aa1)(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});const n=null==(i=s?.internal)?void 0:i.throwOnFailedPublish;try{const t=await this.getSubscriptionId(e);if(s?.transportType===U.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(r).catch(e=>this.logger.warn(e))},(0,l.toMiliseconds)(l.ONE_SECOND)),t;const i=new Promise(async t=>{const s=i=>{i.topic===e&&(this.events.removeListener(W,s),t(i.id))};this.events.on(W,s);try{const i=await(0,p.K3g)(new Promise((e,t)=>{this.relayer.request(r).catch(e=>{this.logger.warn(e,e?.message),t(e)}).then(e)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(W,s),t(i)}catch{}}),o=await(0,p.K3g)(i,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!o&&n)throw new Error(`Subscribing to ${e} failed, please try again`);return o?t:null}catch(e){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(P.connection_stalled),n)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:(0,p.aa1)(t.protocol).batchSubscribe,params:{topics:e.map(e=>e.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await(0,p.K3g)(new Promise(e=>{this.relayer.request(s).catch(e=>this.logger.warn(e)).then(e)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(P.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:(0,p.aa1)(t.protocol).batchFetchMessages,params:{topics:e.map(e=>e.topic)}};let i;this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{i=await await(0,p.K3g)(new Promise((e,t)=>{this.relayer.request(s).catch(e=>{this.logger.warn(e),t(e)}).then(e)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(P.connection_stalled)}return i}rpcUnsubscribe(e,t,s){const i={method:(0,p.aa1)(s.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,t){this.setSubscription(e,os(ns({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(e=>{this.setSubscription(e.id,ns({},e)),this.pending.delete(e.topic)})}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,ns({},t)),this.topicMap.set(t.topic,e),this.events.emit(W,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(M,os(ns({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit("subscription_sync")}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let s=0;s<t;s++){const t=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(t)}}this.events.emit("subscription_resubscribed")}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async e=>os(ns({},e),{id:await this.getSubscriptionId(e.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await(0,p.yy4)((0,l.toMiliseconds)(l.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return(0,p.ALl)(e+await this.getClientId())}}var ls=Object.defineProperty,ds=Object.getOwnPropertySymbols,hs=Object.prototype.hasOwnProperty,ps=Object.prototype.propertyIsEnumerable,us=(e,t,s)=>t in e?ls(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,gs=(e,t)=>{for(var s in t||(t={}))hs.call(t,s)&&us(e,s,t[s]);if(ds)for(var s of ds(t))ps.call(t,s)&&us(e,s,t[s]);return e},ms=(e,t,s)=>us(e,"symbol"!=typeof t?t+"":t,s);class fs extends c.m5{constructor(e){super(e),ms(this,"protocol","wc"),ms(this,"version",2),ms(this,"core"),ms(this,"logger"),ms(this,"events",new i.EventEmitter),ms(this,"provider"),ms(this,"messages"),ms(this,"subscriber"),ms(this,"publisher"),ms(this,"name","relayer"),ms(this,"transportExplicitlyClosed",!1),ms(this,"initialized",!1),ms(this,"connectionAttemptInProgress",!1),ms(this,"relayUrl"),ms(this,"projectId"),ms(this,"packageName"),ms(this,"bundleId"),ms(this,"hasExperiencedNetworkDisruption",!1),ms(this,"pingTimeout"),ms(this,"heartBeatTimeout",(0,l.toMiliseconds)(l.THIRTY_SECONDS+l.FIVE_SECONDS)),ms(this,"reconnectTimeout"),ms(this,"connectPromise"),ms(this,"reconnectInProgress",!1),ms(this,"requestsInFlight",[]),ms(this,"connectTimeout",(0,l.toMiliseconds)(15*l.ONE_SECOND)),ms(this,"request",async e=>{var t,s;this.logger.debug("Publishing Request Payload");const i=e.id||(0,m.getBigIntRpcId)().toString();await this.toEstablishConnection();try{this.logger.trace({id:i,method:e.method,topic:null==(t=e.params)?void 0:t.topic},"relayer.request - publishing...");const r=`${i}:${(null==(s=e.params)?void 0:s.tag)||""}`;this.requestsInFlight.push(r);const n=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter(e=>e!==r),n}catch(e){throw this.logger.debug(`Failed to Publish Request: ${i}`),e}}),ms(this,"resetPingTimeout",()=>{(0,p.Lln)()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var e,t,s,i;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),null==(i=null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.terminate)||i.call(s)}catch(e){this.logger.warn(e,e?.message)}},this.heartBeatTimeout))}),ms(this,"onPayloadHandler",e=>{this.onProviderPayload(e),this.resetPingTimeout()}),ms(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(P.connect)}),ms(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ms(this,"onProviderErrorHandler",e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit(P.error,e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ms(this,"registerProviderListeners",()=>{this.provider.on(T,this.onPayloadHandler),this.provider.on(O,this.onConnectHandler),this.provider.on(k,this.onDisconnectHandler),this.provider.on(R,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&"string"!=typeof e.logger?(0,a.U5)(e.logger,this.name):(0,a.h6)((0,a.iP)({level:e.logger||"error"})),this.messages=new Wt(this.logger,e.core),this.subscriber=new cs(this,this.logger),this.publisher=new Gt(this,this.logger),this.relayUrl=e?.relayUrl||S,this.projectId=e.projectId,(0,p.m01)()?this.packageName=(0,p.R7U)():(0,p.aRZ)()&&(this.bundleId=(0,p.R7U)()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return(0,a.oI)(this.logger)}get connected(){var e,t,s;return 1===(null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.readyState)||!1}get connecting(){var e,t,s;return 0===(null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.readyState)||void 0!==this.connectPromise||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:U.relay},"outbound")}async subscribe(e,t){var s,i,r;this.isInitialized(),(null==t||!t.transportType||"relay"===t?.transportType)&&await this.toEstablishConnection();const n=typeof(null==(s=t?.internal)?void 0:s.throwOnFailedPublish)>"u"||(null==(i=t?.internal)?void 0:i.throwOnFailedPublish);let o,a=(null==(r=this.subscriber.topicMap.get(e))?void 0:r[0])||"";const c=t=>{t.topic===e&&(this.subscriber.off(W,c),o())};return await Promise.all([new Promise(e=>{o=e,this.subscriber.on(W,c)}),new Promise(async(s,i)=>{a=await this.subscriber.subscribe(e,gs({internal:{throwOnFailedPublish:n}},t)).catch(e=>{n&&i(e)})||a,s()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await(0,p.K3g)(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(this.subscriber.hasAnyTopics){if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,s)=>{await this.connect(e).then(t).catch(s).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}else this.logger.warn("Starting WS connection skipped because the client has no topics to work with.")}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await(0,p.sc7)())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(0===e?.length)return void this.logger.trace("Batch message events is empty. Ignoring...");const t=e.sort((e,t)=>e.publishedAt-t.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const e of t)try{await this.onMessageEvent(e)}catch(e){this.logger.warn(e,"Error while processing batch message event: "+e?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:s}=e;if(!t.sessionExists){const e={topic:s,expiry:(0,p.Xw0)(l.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,e)}this.events.emit(P.message,e),await this.recordMessageEvent(e,D)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(e,t)=>{const s=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(k,s),await(0,p.K3g)(new Promise((e,t)=>{this.provider.connect().then(e).catch(t)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(e=>{t(e)}).finally(()=>{this.provider.off(k,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(e,t)=>{const s=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(k,s),await this.subscriber.start().then(e).catch(t).finally(()=>{this.provider.off(k,s)})}),this.hasExperiencedNetworkDisruption=!1,e()})}catch(e){await this.subscriber.stop();const t=e;this.logger.warn({},t.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(e=>setTimeout(e,(0,l.toMiliseconds)(1*t))),t++}}startPingTimeout(){var e,t,s,i,r;if((0,p.Lln)())try{null!=(t=null==(e=this.provider)?void 0:e.connection)&&t.socket&&(null==(r=null==(i=null==(s=this.provider)?void 0:s.connection)?void 0:i.socket)||r.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new g.F(new f.A((0,p.jUZ)({sdkVersion:x,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:s,message:i}=e;await this.messages.set(s,i,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||0===s.length)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const i=this.messages.has(t,s);return i&&this.logger.warn(`Ignoring duplicate message: ${s}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),(0,m.isJsonRpcRequest)(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:s,message:i,publishedAt:r,attestation:n}=t.data,o={topic:s,message:i,publishedAt:r,transportType:U.relay,attestation:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(gs({type:"event",event:t.id},o)),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else(0,m.isJsonRpcResponse)(e)&&this.events.emit(P.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,D),this.events.emit(P.message,e))}async acknowledgePayload(e){const t=(0,m.formatJsonRpcResult)(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(T,this.onPayloadHandler),this.provider.off(O,this.onConnectHandler),this.provider.off(k,this.onDisconnectHandler),this.provider.off(R,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await(0,p.sc7)();(0,p.uym)(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(e=>this.logger.error(e,e?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(n.li.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&(0,p.sKr)())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(P.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},(0,l.toMiliseconds)(.1)))))}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise)return void await this.connectPromise;await this.connect()}}}function ws(){}function ys(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&"[object Object]"===Object.prototype.toString.call(e)}function bs(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function vs(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Es="[object Arguments]",Cs="[object Object]";function Is(e,t,s,i,r,n,o){const a=o(e,t,s,i,r,n);if(void 0!==a)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":case"function":return e===t;case"number":return e===t||Object.is(e,t);case"object":return Ns(e,t,n,o)}return Ns(e,t,n,o)}function Ns(e,t,s,i){if(Object.is(e,t))return!0;let r=vs(e),n=vs(t);if(r===Es&&(r=Cs),n===Es&&(n=Cs),r!==n)return!1;switch(r){case"[object String]":return e.toString()===t.toString();case"[object Number]":return function(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}(e.valueOf(),t.valueOf());case"[object Boolean]":case"[object Date]":case"[object Symbol]":return Object.is(e.valueOf(),t.valueOf());case"[object RegExp]":return e.source===t.source&&e.flags===t.flags;case"[object Function]":return e===t}const o=(s=s??new Map).get(e),a=s.get(t);if(null!=o&&null!=a)return o===t;s.set(e,t),s.set(t,e);try{switch(r){case"[object Map]":if(e.size!==t.size)return!1;for(const[r,n]of e.entries())if(!t.has(r)||!Is(n,t.get(r),r,e,t,s,i))return!1;return!0;case"[object Set]":{if(e.size!==t.size)return!1;const r=Array.from(e.values()),n=Array.from(t.values());for(let o=0;o<r.length;o++){const a=r[o],c=n.findIndex(r=>Is(a,r,void 0,e,t,s,i));if(-1===c)return!1;n.splice(c,1)}return!0}case"[object Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":case"[object BigUint64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object BigInt64Array]":case"[object Float32Array]":case"[object Float64Array]":if(typeof y<"u"&&y.isBuffer(e)!==y.isBuffer(t)||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Is(e[r],t[r],r,e,t,s,i))return!1;return!0;case"[object ArrayBuffer]":return e.byteLength===t.byteLength&&Ns(new Uint8Array(e),new Uint8Array(t),s,i);case"[object DataView]":return e.byteLength===t.byteLength&&e.byteOffset===t.byteOffset&&Ns(new Uint8Array(e),new Uint8Array(t),s,i);case"[object Error]":return e.name===t.name&&e.message===t.message;case Cs:{if(!(Ns(e.constructor,t.constructor,s,i)||ys(e)&&ys(t)))return!1;const r=[...Object.keys(e),...bs(e)],n=[...Object.keys(t),...bs(t)];if(r.length!==n.length)return!1;for(let n=0;n<r.length;n++){const o=r[n],a=e[o];if(!Object.hasOwn(t,o))return!1;if(!Is(a,t[o],o,e,t,s,i))return!1}return!0}default:return!1}}finally{s.delete(e),s.delete(t)}}var As=Object.defineProperty,_s=Object.getOwnPropertySymbols,Ss=Object.prototype.hasOwnProperty,Ps=Object.prototype.propertyIsEnumerable,Ts=(e,t,s)=>t in e?As(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Os=(e,t)=>{for(var s in t||(t={}))Ss.call(t,s)&&Ts(e,s,t[s]);if(_s)for(var s of _s(t))Ps.call(t,s)&&Ts(e,s,t[s]);return e},ks=(e,t,s)=>Ts(e,"symbol"!=typeof t?t+"":t,s);class Rs extends c.pi{constructor(e,t,s,i=E,r=void 0){super(e,t,s,i),this.core=e,this.logger=t,this.name=s,ks(this,"map",new Map),ks(this,"version","0.3"),ks(this,"cached",[]),ks(this,"initialized",!1),ks(this,"getKey"),ks(this,"storagePrefix",E),ks(this,"recentlyDeleted",[]),ks(this,"recentlyDeletedLimit",200),ks(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>{this.getKey&&null!==e&&!(0,p.b07)(e)?this.map.set(this.getKey(e),e):(0,p.CTo)(e)?this.map.set(e.id,e):(0,p.mr0)(e)&&this.map.set(e.topic,e)}),this.cached=[],this.initialized=!0)}),ks(this,"set",async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())}),ks(this,"get",e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e))),ks(this,"getAll",e=>(this.isInitialized(),e?this.values.filter(t=>Object.keys(e).every(s=>function(e,t){return function(e,t,s){return Is(e,t,void 0,void 0,void 0,void 0,s)}(e,t,ws)}(t[s],e[s]))):this.values)),ks(this,"update",async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const s=Os(Os({},this.getData(e)),t);this.map.set(e,s),await this.persist()}),ks(this,"delete",async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())}),this.logger=(0,a.U5)(t,this.name),this.storagePrefix=i,this.getKey=r}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xs=Object.defineProperty,Us=(e,t,s)=>((e,t,s)=>t in e?xs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ds{constructor(e,t){this.core=e,this.logger=t,Us(this,"name","pairing"),Us(this,"version","0.3"),Us(this,"events",new(r())),Us(this,"pairings"),Us(this,"initialized",!1),Us(this,"storagePrefix",E),Us(this,"ignoredPayloadTypes",[p.Lp_]),Us(this,"registeredMethods",[]),Us(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Us(this,"register",({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]}),Us(this,"create",async e=>{this.isInitialized();const t=(0,p.two)(),s=await this.core.crypto.setSymKey(t),i=(0,p.Xw0)(l.FIVE_MINUTES),r={protocol:_},n={topic:s,expiry:i,relay:r,active:!1,methods:e?.methods},o=(0,p.QJh)({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:t,relay:r,expiryTimestamp:i,methods:e?.methods});return this.events.emit(j.create,n),this.core.expirer.set(s,i),await this.pairings.set(s,n),await this.core.relayer.subscribe(s,{transportType:e?.transportType}),{topic:s,uri:o}}),Us(this,"pair",async e=>{this.isInitialized();const t=this.core.eventClient.createEvent({properties:{topic:e?.uri,trace:[J.pairing_started]}});this.isValidPair(e,t);const{topic:s,symKey:i,relay:r,expiryTimestamp:n,methods:o}=(0,p.wYp)(e.uri);let a;if(t.props.properties.topic=s,t.addTrace(J.pairing_uri_validation_success),t.addTrace(J.pairing_uri_not_expired),this.pairings.keys.includes(s)){if(a=this.pairings.get(s),t.addTrace(J.existing_pairing),a.active)throw t.setError(X.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);t.addTrace(J.pairing_not_expired)}const c=n||(0,p.Xw0)(l.FIVE_MINUTES),d={topic:s,relay:r,expiry:c,active:!1,methods:o};this.core.expirer.set(s,c),await this.pairings.set(s,d),t.addTrace(J.store_new_pairing),e.activatePairing&&await this.activate({topic:s}),this.events.emit(j.create,d),t.addTrace(J.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(i,s),t.addTrace(J.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{t.setError(X.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:r})}catch(e){throw t.setError(X.subscribe_pairing_topic_failure),e}return t.addTrace(J.subscribe_pairing_topic_success),d}),Us(this,"activate",async({topic:e})=>{this.isInitialized();const t=(0,p.Xw0)(l.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})}),Us(this,"ping",async e=>{this.isInitialized(),await this.isValidPing(e),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:s,resolve:i,reject:r}=(0,p.Wx8)();this.events.once((0,p.hEn)("pairing_ping",e),({error:e})=>{e?r(e):i()}),await s()}}),Us(this,"updateExpiry",async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})}),Us(this,"updateMetadata",async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})}),Us(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Us(this,"disconnect",async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",(0,p.Hjj)("USER_DISCONNECTED")),await this.deletePairing(t))}),Us(this,"formatUriFromPairing",e=>{this.isInitialized();const{topic:t,relay:s,expiry:i,methods:r}=e,n=this.core.crypto.keychain.get(t);return(0,p.QJh)({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:n,relay:s,expiryTimestamp:i,methods:r})}),Us(this,"sendRequest",async(e,t,s)=>{const i=(0,m.formatJsonRpcRequest)(t,s),r=await this.core.crypto.encode(e,i),n=B[t].req;return this.core.history.set(e,i),this.core.relayer.publish(e,r,n),i.id}),Us(this,"sendResult",async(e,t,s)=>{const i=(0,m.formatJsonRpcResult)(e,s),r=await this.core.crypto.encode(t,i),n=(await this.core.history.get(t,e)).request.method,o=B[n].res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(i)}),Us(this,"sendError",async(e,t,s)=>{const i=(0,m.formatJsonRpcError)(e,s),r=await this.core.crypto.encode(t,i),n=(await this.core.history.get(t,e)).request.method,o=B[n]?B[n].res:B.unregistered_method.res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(i)}),Us(this,"deletePairing",async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,(0,p.Hjj)("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])}),Us(this,"cleanup",async()=>{const e=this.pairings.getAll().filter(e=>(0,p._dF)(e.expiry));await Promise.all(e.map(e=>this.deletePairing(e.topic)))}),Us(this,"onRelayEventRequest",async e=>{const{topic:t,payload:s}=e;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(t,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(t,s);default:return await this.onUnknownRpcMethodRequest(t,s)}}),Us(this,"onRelayEventResponse",async e=>{const{topic:t,payload:s}=e,i=(await this.core.history.get(t,s.id)).request.method;return"wc_pairingPing"===i?this.onPairingPingResponse(t,s):this.onUnknownRpcMethodResponse(i)}),Us(this,"onPairingPingRequest",async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.events.emit(j.ping,{id:s,topic:e})}catch(t){await this.sendError(s,e,t),this.logger.error(t)}}),Us(this,"onPairingPingResponse",(e,t)=>{const{id:s}=t;setTimeout(()=>{(0,m.isJsonRpcResult)(t)?this.events.emit((0,p.hEn)("pairing_ping",s),{}):(0,m.isJsonRpcError)(t)&&this.events.emit((0,p.hEn)("pairing_ping",s),{error:t.error})},500)}),Us(this,"onPairingDeleteRequest",async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(j.delete,{id:s,topic:e})}catch(t){await this.sendError(s,e,t),this.logger.error(t)}}),Us(this,"onUnknownRpcMethodRequest",async(e,t)=>{const{id:s,method:i}=t;try{if(this.registeredMethods.includes(i))return;const t=(0,p.Hjj)("WC_METHOD_UNSUPPORTED",i);await this.sendError(s,e,t),this.logger.error(t)}catch(t){await this.sendError(s,e,t),this.logger.error(t)}}),Us(this,"onUnknownRpcMethodResponse",e=>{this.registeredMethods.includes(e)||this.logger.error((0,p.Hjj)("WC_METHOD_UNSUPPORTED",e))}),Us(this,"isValidPair",(e,t)=>{var s;if(!(0,p.TeY)(e)){const{message:s}=(0,p.GuA)("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(X.malformed_pairing_uri),new Error(s)}if(!(0,p.AYU)(e.uri)){const{message:s}=(0,p.GuA)("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(X.malformed_pairing_uri),new Error(s)}const i=(0,p.wYp)(e?.uri);if(null==(s=i?.relay)||!s.protocol){const{message:e}=(0,p.GuA)("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(X.malformed_pairing_uri),new Error(e)}if(null==i||!i.symKey){const{message:e}=(0,p.GuA)("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(X.malformed_pairing_uri),new Error(e)}if(null!=i&&i.expiryTimestamp&&(0,l.toMiliseconds)(i?.expiryTimestamp)<Date.now()){t.setError(X.pairing_expired);const{message:e}=(0,p.GuA)("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(e)}}),Us(this,"isValidPing",async e=>{if(!(0,p.TeY)(e)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)}),Us(this,"isValidDisconnect",async e=>{if(!(0,p.TeY)(e)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)}),Us(this,"isValidPairingTopic",async e=>{if(!(0,p.Qhg)(e,!1)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if((0,p._dF)(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=(0,p.GuA)("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}),this.core=e,this.logger=(0,a.U5)(t,this.name),this.pairings=new Rs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return(0,a.oI)(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(P.message,async e=>{const{topic:t,message:s,transportType:i}=e;if(this.pairings.keys.includes(t)&&i!==U.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const e=await this.core.crypto.decode(t,s);(0,m.isJsonRpcRequest)(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):(0,m.isJsonRpcResponse)(e)&&(await this.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e}),this.core.history.delete(t,e.id)),await this.core.relayer.messages.ack(t,s)}catch(e){this.logger.error(e)}})}registerExpirerEvents(){this.core.expirer.on(F.expired,async e=>{const{topic:t}=(0,p.c82)(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(j.expire,{topic:t}))})}}var Ls=Object.defineProperty,Ws=(e,t,s)=>((e,t,s)=>t in e?Ls(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ms extends c.lZ{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ws(this,"records",new Map),Ws(this,"events",new i.EventEmitter),Ws(this,"name","history"),Ws(this,"version","0.3"),Ws(this,"cached",[]),Ws(this,"initialized",!1),Ws(this,"storagePrefix",E),Ws(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.records.set(e.id,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ws(this,"set",(e,t,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:s}),this.records.has(t.id))return;const i={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:s,expiry:(0,p.Xw0)(l.THIRTY_DAYS)};this.records.set(i.id,i),this.persist(),this.events.emit(q,i)}),Ws(this,"resolve",async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response>"u"&&(t.response=(0,m.isJsonRpcError)(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit($,t))}),Ws(this,"get",async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t))),Ws(this,"delete",(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach(s=>{if(s.topic===e){if(typeof t<"u"&&s.id!==t)return;this.records.delete(s.id),this.events.emit(H,s)}}),this.persist()}),Ws(this,"exists",async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e)),Ws(this,"on",(e,t)=>{this.events.on(e,t)}),Ws(this,"once",(e,t)=>{this.events.once(e,t)}),Ws(this,"off",(e,t)=>{this.events.off(e,t)}),Ws(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=(0,a.U5)(t,this.name)}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:(0,m.formatJsonRpcRequest)(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit("history_sync")}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(q,e=>{const t=q;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on($,e=>{const t=$;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(H,e=>{const t=H;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(n.li.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{(0,l.toMiliseconds)(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(H,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Bs=Object.defineProperty,js=(e,t,s)=>((e,t,s)=>t in e?Bs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class qs extends c.Vx{constructor(e,t){super(e,t),this.core=e,this.logger=t,js(this,"expirations",new Map),js(this,"events",new i.EventEmitter),js(this,"name","expirer"),js(this,"version","0.3"),js(this,"cached",[]),js(this,"initialized",!1),js(this,"storagePrefix",E),js(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.expirations.set(e.target,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),js(this,"has",e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}}),js(this,"set",(e,t)=>{this.isInitialized();const s=this.formatTarget(e),i={target:s,expiry:t};this.expirations.set(s,i),this.checkExpiry(s,i),this.events.emit(F.created,{target:s,expiration:i})}),js(this,"get",e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)}),js(this,"del",e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),s=this.getExpiration(t);this.expirations.delete(t),this.events.emit(F.deleted,{target:t,expiration:s})}}),js(this,"on",(e,t)=>{this.events.on(e,t)}),js(this,"once",(e,t)=>{this.events.once(e,t)}),js(this,"off",(e,t)=>{this.events.off(e,t)}),js(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=(0,a.U5)(t,this.name)}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if("string"==typeof e)return(0,p.ADD)(e);if("number"==typeof e)return(0,p.gOF)(e);const{message:t}=(0,p.GuA)("UNKNOWN_TYPE","Target type: "+typeof e);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(F.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:s}=t;(0,l.toMiliseconds)(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(F.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(n.li.pulse,()=>this.checkExpirations()),this.events.on(F.created,e=>{const t=F.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(F.expired,e=>{const t=F.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(F.deleted,e=>{const t=F.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $s=Object.defineProperty,Hs=(e,t,s)=>((e,t,s)=>t in e?$s(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Fs extends c.zl{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,Hs(this,"name","verify-api"),Hs(this,"abortController"),Hs(this,"isDevEnv"),Hs(this,"verifyUrlV3",K),Hs(this,"storagePrefix",E),Hs(this,"version",2),Hs(this,"publicKey"),Hs(this,"fetchPromise"),Hs(this,"init",async()=>{var e;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,l.toMiliseconds)(null==(e=this.publicKey)?void 0:e.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Hs(this,"register",async e=>{if(!(0,p.BdH)()||this.isDevEnv)return;const t=window.location.origin,{id:s,decryptedId:i}=e,r=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${t}&id=${s}&decryptedId=${i}`;try{const e=(0,w.getDocument)(),t=this.startAbortTimer(5*l.ONE_SECOND),i=await new Promise((i,n)=>{const o=()=>{window.removeEventListener("message",c),e.body.removeChild(a),n("attestation aborted")};this.abortController.signal.addEventListener("abort",o);const a=e.createElement("iframe");a.src=r,a.style.display="none",a.addEventListener("error",o,{signal:this.abortController.signal});const c=r=>{if(r.data&&"string"==typeof r.data)try{const n=JSON.parse(r.data);if("verify_attestation"===n.type){if((0,h.Cq)(n.attestation).payload.id!==s)return;clearInterval(t),e.body.removeChild(a),this.abortController.signal.removeEventListener("abort",o),window.removeEventListener("message",c),i(null===n.attestation?"":n.attestation)}}catch(e){this.logger.warn(e)}};e.body.appendChild(a),window.addEventListener("message",c,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",i),i}catch(e){this.logger.warn(e)}return""}),Hs(this,"resolve",async e=>{if(this.isDevEnv)return"";const{attestationId:t,hash:s,encryptedId:i}=e;if(""===t)return void this.logger.debug("resolve: attestationId is empty, skipping");if(t){if((0,h.Cq)(t).payload.id!==i)return;const e=await this.isValidJwtAttestation(t);if(e)return e.isVerified?e:void this.logger.warn("resolve: jwt attestation: origin url not verified")}if(!s)return;const r=this.getVerifyUrl(e?.verifyUrl);return this.fetchAttestation(s,r)}),Hs(this,"fetchAttestation",async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);const s=this.startAbortTimer(5*l.ONE_SECOND),i=await fetch(`${t}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(s),200===i.status?await i.json():void 0}),Hs(this,"getVerifyUrl",e=>{let t=e||z;return G.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${z}`),t=z),t}),Hs(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(l.FIVE_SECONDS),t=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await t.json()}catch(e){this.logger.warn(e)}}),Hs(this,"persistPublicKey",async e=>{this.logger.debug("persisting public key to local storage",e),await this.store.setItem(this.storeKey,e),this.publicKey=e}),Hs(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Hs(this,"isValidJwtAttestation",async e=>{const t=await this.getPublicKey();try{if(t)return this.validateAttestation(e,t)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}const s=await this.fetchAndPersistPublicKey();try{if(s)return this.validateAttestation(e,s)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}}),Hs(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Hs(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async e=>{const t=await this.fetchPublicKey();t&&(await this.persistPublicKey(t),e(t))});const e=await this.fetchPromise;return this.fetchPromise=void 0,e}),Hs(this,"validateAttestation",(e,t)=>{const s=(0,p.U0i)(e,t.publicKey),i={hasExpired:(0,l.toMiliseconds)(s.exp)<Date.now(),payload:s};if(i.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:i.payload.origin,isScam:i.payload.isScam,isVerified:i.payload.isVerified}}),this.logger=(0,a.U5)(t,this.name),this.abortController=new AbortController,this.isDevEnv=(0,p.w8K)(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return(0,a.oI)(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),(0,l.toMiliseconds)(e))}}var Vs=Object.defineProperty,zs=(e,t,s)=>((e,t,s)=>t in e?Vs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ks extends c.GF{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,zs(this,"context","echo"),zs(this,"registerDeviceToken",async e=>{const{clientId:t,token:s,notificationType:i,enableEncrypted:r=!1}=e,n=`https://echo.walletconnect.com/${this.projectId}/clients`;await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t,type:i,token:s,always_raw:r})})}),this.logger=(0,a.U5)(t,this.context)}}var Gs=Object.defineProperty,Js=Object.getOwnPropertySymbols,Xs=Object.prototype.hasOwnProperty,Ys=Object.prototype.propertyIsEnumerable,Zs=(e,t,s)=>t in e?Gs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Qs=(e,t)=>{for(var s in t||(t={}))Xs.call(t,s)&&Zs(e,s,t[s]);if(Js)for(var s of Js(t))Ys.call(t,s)&&Zs(e,s,t[s]);return e},ei=(e,t,s)=>Zs(e,"symbol"!=typeof t?t+"":t,s);class ti extends c.$Q{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,ei(this,"context","event-client"),ei(this,"storagePrefix",E),ei(this,"storageVersion",.1),ei(this,"events",new Map),ei(this,"shouldPersist",!1),ei(this,"init",async()=>{if(!(0,p.w8K)())try{const e={eventId:(0,p.gZm)(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:(0,p.ojD)(this.core.relayer.protocol,this.core.relayer.version,x)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}}),ei(this,"createEvent",e=>{const{event:t="ERROR",type:s="",properties:{topic:i,trace:r}}=e,n=(0,p.gZm)(),o=this.core.projectId||"",a=Date.now(),c=Qs({eventId:n,timestamp:a,props:{event:t,type:s,properties:{topic:i,trace:r}},bundleId:o,domain:this.getAppDomain()},this.setMethods(n));return this.telemetryEnabled&&(this.events.set(n,c),this.shouldPersist=!0),c}),ei(this,"getEvent",e=>{const{eventId:t,topic:s}=e;if(t)return this.events.get(t);const i=Array.from(this.events.values()).find(e=>e.props.properties.topic===s);return i?Qs(Qs({},i),this.setMethods(i.eventId)):void 0}),ei(this,"deleteEvent",e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0}),ei(this,"setEventListeners",()=>{this.core.heartbeat.on(n.li.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(e=>{(0,l.fromMiliseconds)(Date.now())-(0,l.fromMiliseconds)(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)})})}),ei(this,"setMethods",e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)})),ei(this,"addTrace",(e,t)=>{const s=this.events.get(e);s&&(s.props.properties.trace.push(t),this.events.set(e,s),this.shouldPersist=!0)}),ei(this,"setError",(e,t)=>{const s=this.events.get(e);s&&(s.props.type=t,s.timestamp=Date.now(),this.events.set(e,s),this.shouldPersist=!0)}),ei(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),ei(this,"restore",async()=>{try{const e=await this.core.storage.getItem(this.storageKey)||[];if(!e.length)return;e.forEach(e=>{this.events.set(e.eventId,Qs(Qs({},e),this.setMethods(e.eventId)))})}catch(e){this.logger.warn(e)}}),ei(this,"submit",async()=>{if(!this.telemetryEnabled||0===this.events.size)return;const e=[];for(const[t,s]of this.events)s.props.type&&e.push(s);if(0!==e.length)try{if((await this.sendEvent(e)).ok)for(const t of e)this.events.delete(t.eventId),this.shouldPersist=!0}catch(e){this.logger.warn(e)}}),ei(this,"sendEvent",async e=>{const t=this.getAppDomain()?"":"&sp=desktop";return await fetch(`https://pulse.walletconnect.org/batch?projectId=${this.core.projectId}&st=events_sdk&sv=js-${x}${t}`,{method:"POST",body:JSON.stringify(e)})}),ei(this,"getAppDomain",()=>(0,p.lFF)().url),this.logger=(0,a.U5)(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var si=Object.defineProperty,ii=Object.getOwnPropertySymbols,ri=Object.prototype.hasOwnProperty,ni=Object.prototype.propertyIsEnumerable,oi=(e,t,s)=>t in e?si(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ai=(e,t)=>{for(var s in t||(t={}))ri.call(t,s)&&oi(e,s,t[s]);if(ii)for(var s of ii(t))ni.call(t,s)&&oi(e,s,t[s]);return e},ci=(e,t,s)=>oi(e,"symbol"!=typeof t?t+"":t,s);class li extends c.ZP{constructor(e){var t;super(e),ci(this,"protocol","wc"),ci(this,"version",2),ci(this,"name",v),ci(this,"relayUrl"),ci(this,"projectId"),ci(this,"customStoragePrefix"),ci(this,"events",new i.EventEmitter),ci(this,"logger"),ci(this,"heartbeat"),ci(this,"relayer"),ci(this,"crypto"),ci(this,"storage"),ci(this,"history"),ci(this,"expirer"),ci(this,"pairing"),ci(this,"verify"),ci(this,"echoClient"),ci(this,"linkModeSupportedApps"),ci(this,"eventClient"),ci(this,"initialized",!1),ci(this,"logChunkController"),ci(this,"on",(e,t)=>this.events.on(e,t)),ci(this,"once",(e,t)=>this.events.once(e,t)),ci(this,"off",(e,t)=>this.events.off(e,t)),ci(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),ci(this,"dispatchEnvelope",({topic:e,message:t,sessionExists:s})=>{if(!e||!t)return;const i={topic:e,message:t,publishedAt:Date.now(),transportType:U.link_mode};this.relayer.onLinkMessageEvent(i,{sessionExists:s})});const s=this.getGlobalCore(e?.customStoragePrefix);if(s)try{return this.customStoragePrefix=s.customStoragePrefix,this.logger=s.logger,this.heartbeat=s.heartbeat,this.crypto=s.crypto,this.history=s.history,this.expirer=s.expirer,this.storage=s.storage,this.relayer=s.relayer,this.pairing=s.pairing,this.verify=s.verify,this.echoClient=s.echoClient,this.linkModeSupportedApps=s.linkModeSupportedApps,this.eventClient=s.eventClient,this.initialized=s.initialized,this.logChunkController=s.logChunkController,s}catch(e){console.warn("Failed to copy global core",e)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||S,this.customStoragePrefix=null!=e&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=(0,a.iP)({level:"string"==typeof e?.logger&&e.logger?e.logger:"error",name:v}),{logger:c,chunkLoggerController:l}=(0,a.D5)({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=l,null!=(t=this.logChunkController)&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var e,t;null!=(e=this.logChunkController)&&e.downloadLogsBlobInBrowser&&(null==(t=this.logChunkController)||t.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=(0,a.U5)(c,this.name),this.heartbeat=new n.VH,this.crypto=new Pt(this,this.logger,e?.keychain),this.history=new Ms(this,this.logger),this.expirer=new qs(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new o.A(ai(ai({},C),e?.storageOptions)),this.relayer=new fs({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Ds(this,this.logger),this.verify=new Fs(this,this.logger,this.storage),this.echoClient=new Ks(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new ti(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new li(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem("WALLETCONNECT_CLIENT_ID",s),t}get context(){return(0,a.oI)(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return null==(e=this.logChunkController)?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(L,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(L)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,s=`${t}_count`;return globalThis[s]=(globalThis[s]||0)+1,globalThis[s]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[s]} times.`),globalThis[t]}catch(e){return void console.warn("Failed to get global WalletConnect core",e)}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${(null==(t=e.opts)?void 0:t.customStoragePrefix)||""}`;globalThis[s]=e}catch(e){console.warn("Failed to set global WalletConnect core",e)}}isGlobalCoreDisabled(){try{return typeof b<"u"&&"true"===b.env.DISABLE_GLOBAL_CORE}catch{return!0}}}const di=li},92492:(e,t,s)=>{s.d(t,{P:()=>c});var i=s(89168),r=s(39150),n=s(22143);const o=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),a=(0,i.BX)({...o}),c={state:a,subscribeKey:(e,t)=>(0,r.u$)(a,e,t),showLoading(e,t={}){this._showMessage({message:e,variant:"loading",...t})},showSuccess(e){this._showMessage({message:e,variant:"success"})},showSvg(e,t){this._showMessage({message:e,svg:t})},showError(e){const t=n.w.parseError(e);this._showMessage({message:t,variant:"error"})},hide(){a.message=o.message,a.variant=o.variant,a.svg=o.svg,a.open=o.open,a.autoClose=o.autoClose},_showMessage({message:e,svg:t,variant:s="success",autoClose:i=o.autoClose}){a.open?(a.open=!1,setTimeout(()=>{a.message=e,a.variant=s,a.svg=t,a.open=!0,a.autoClose=i},150)):(a.message=e,a.variant=s,a.svg=t,a.open=!0,a.autoClose=i)}}},93474:(e,t,s)=>{s.d(t,{N:()=>y});var i=s(89168),r=s(39150),n=s(86454),o=s(22143),a=s(35646),c=s(9732),l=s(11847),d=s(6262),h=s(98299),p=s(83077),u=s(47981),g=s(1420);const m=o.w.getApiUrl(),f=new a.Z({baseUrl:m,clientId:null}),w=(0,i.BX)({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),y={state:w,subscribeKey:(e,t)=>(0,r.u$)(w,e,t),_getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=g.H.state;return{projectId:e,st:t||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions:e=>g.H.state.isUniversalProvider?e.filter(e=>Boolean(e.mobile_link||e.desktop_link||e.webapp_link)):e,async _fetchWalletImage(e){const t=`${f.baseUrl}/getWalletImage/${e}`,s=await f.getBlob({path:t,params:y._getSdkProperties()});d.j.setWalletImage(e,URL.createObjectURL(s))},async _fetchNetworkImage(e){const t=`${f.baseUrl}/public/getAssetImage/${e}`,s=await f.getBlob({path:t,params:y._getSdkProperties()});d.j.setNetworkImage(e,URL.createObjectURL(s))},async _fetchConnectorImage(e){const t=`${f.baseUrl}/public/getAssetImage/${e}`,s=await f.getBlob({path:t,params:y._getSdkProperties()});d.j.setConnectorImage(e,URL.createObjectURL(s))},async _fetchCurrencyImage(e){const t=`${f.baseUrl}/public/getCurrencyImage/${e}`,s=await f.getBlob({path:t,params:y._getSdkProperties()});d.j.setCurrencyImage(e,URL.createObjectURL(s))},async _fetchTokenImage(e){const t=`${f.baseUrl}/public/getTokenImage/${e}`,s=await f.getBlob({path:t,params:y._getSdkProperties()});d.j.setTokenImage(e,URL.createObjectURL(s))},_filterWalletsByPlatform:e=>o.w.isMobile()?e?.filter(e=>!!e.mobile_link||(e.id===c.O.COINBASE.id||"solana"===h.W.state.activeChain&&(e.id===c.O.SOLFLARE.id||e.id===c.O.PHANTOM.id))):e,fetchProjectConfig:async()=>(await f.get({path:"/appkit/v1/config",params:y._getSdkProperties()})).features,async fetchAllowedOrigins(){try{const{allowedOrigins:e}=await f.get({path:"/projects/v1/origins",params:y._getSdkProperties()});return e}catch(e){return[]}},async fetchNetworkImages(){const e=h.W.getAllRequestedCaipNetworks(),t=e?.map(({assets:e})=>e?.imageId).filter(Boolean).filter(e=>!n.$.getNetworkImageById(e));t&&await Promise.allSettled(t.map(e=>y._fetchNetworkImage(e)))},async fetchConnectorImages(){const{connectors:e}=p.a.state,t=e.map(({imageId:e})=>e).filter(Boolean);await Promise.allSettled(t.map(e=>y._fetchConnectorImage(e)))},async fetchCurrencyImages(e=[]){await Promise.allSettled(e.map(e=>y._fetchCurrencyImage(e)))},async fetchTokenImages(e=[]){await Promise.allSettled(e.map(e=>y._fetchTokenImage(e)))},async fetchWallets(e){const t=e.exclude??[];y._getSdkProperties().sv.startsWith("html-core-")&&t.push(...Object.values(c.O).map(e=>e.id));const s=await f.get({path:"/getWallets",params:{...y._getSdkProperties(),...e,page:String(e.page),entries:String(e.entries),include:e.include?.join(","),exclude:t.join(",")}});return{data:y._filterWalletsByPlatform(s?.data)||[],count:s?.count}},async fetchFeaturedWallets(){const{featuredWalletIds:e}=g.H.state;if(e?.length){const t={...y._getSdkProperties(),page:1,entries:e?.length??4,include:e},{data:s}=await y.fetchWallets(t),i=[...s].sort((t,s)=>e.indexOf(t.id)-e.indexOf(s.id)),r=i.map(e=>e.image_id).filter(Boolean);await Promise.allSettled(r.map(e=>y._fetchWalletImage(e))),w.featured=i,w.allFeatured=i}},async fetchRecommendedWallets(){try{w.isFetchingRecommendedWallets=!0;const{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:s}=g.H.state,i={page:1,entries:4,include:e,exclude:[...t??[],...s??[]].filter(Boolean),chains:h.W.getRequestedCaipNetworkIds().join(",")},{data:r,count:n}=await y.fetchWallets(i),o=l.i.getRecentWallets(),a=r.map(e=>e.image_id).filter(Boolean),c=o.map(e=>e.image_id).filter(Boolean);await Promise.allSettled([...a,...c].map(e=>y._fetchWalletImage(e))),w.recommended=r,w.allRecommended=r,w.count=n??0}catch{}finally{w.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:e}){const{includeWalletIds:t,excludeWalletIds:s,featuredWalletIds:i}=g.H.state,r=h.W.getRequestedCaipNetworkIds().join(","),n={page:e,entries:40,include:t,exclude:[...w.recommended.map(({id:e})=>e),...s??[],...i??[]].filter(Boolean),chains:r},{data:a,count:c}=await y.fetchWallets(n),l=a.slice(0,20).map(e=>e.image_id).filter(Boolean);await Promise.allSettled(l.map(e=>y._fetchWalletImage(e))),w.wallets=o.w.uniqueBy([...w.wallets,...y._filterOutExtensions(a)],"id").filter(e=>e.chains?.some(e=>r.includes(e))),w.count=c>w.count?c:w.count,w.page=e},async initializeExcludedWallets({ids:e}){const t={page:1,entries:e.length,include:e},{data:s}=await y.fetchWallets(t);s&&s.forEach(e=>{w.excludedWallets.push({rdns:e.rdns,name:e.name})})},async searchWallet({search:e,badge:t}){const{includeWalletIds:s,excludeWalletIds:i}=g.H.state,r=h.W.getRequestedCaipNetworkIds().join(",");w.search=[];const n={page:1,entries:100,search:e?.trim(),badge_type:t,include:s,exclude:i,chains:r},{data:a}=await y.fetchWallets(n);u.E.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:t??"",search:e??""}});const c=a.map(e=>e.image_id).filter(Boolean);await Promise.allSettled([...c.map(e=>y._fetchWalletImage(e)),o.w.wait(300)]),w.search=y._filterOutExtensions(a)},initPromise:(e,t)=>w.promises[e]||(w.promises[e]=t()),prefetch({fetchConnectorImages:e=!0,fetchFeaturedWallets:t=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:i=!0}={}){const r=[e&&y.initPromise("connectorImages",y.fetchConnectorImages),t&&y.initPromise("featuredWallets",y.fetchFeaturedWallets),s&&y.initPromise("recommendedWallets",y.fetchRecommendedWallets),i&&y.initPromise("networkImages",y.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(r)},prefetchAnalyticsConfig(){g.H.state.features?.analytics&&y.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:e}=await f.get({path:"/getAnalyticsConfig",params:y._getSdkProperties()});g.H.setFeatures({analytics:e})}catch(e){g.H.setFeatures({analytics:!1})}},filterByNamespaces(e){if(!e?.length)return w.featured=w.allFeatured,void(w.recommended=w.allRecommended);const t=h.W.getRequestedCaipNetworkIds().join(",");w.featured=w.allFeatured.filter(e=>e.chains?.some(e=>t.includes(e))),w.recommended=w.allRecommended.filter(e=>e.chains?.some(e=>t.includes(e))),w.filteredWallets=w.wallets.filter(e=>e.chains?.some(e=>t.includes(e)))},clearFilterByNamespaces(){w.filteredWallets=[]},setFilterByNamespace(e){if(!e)return w.featured=w.allFeatured,void(w.recommended=w.allRecommended);const t=h.W.getRequestedCaipNetworkIds().join(",");w.featured=w.allFeatured.filter(e=>e.chains?.some(e=>t.includes(e))),w.recommended=w.allRecommended.filter(e=>e.chains?.some(e=>t.includes(e))),w.filteredWallets=w.wallets.filter(e=>e.chains?.some(e=>t.includes(e)))}}},93797:(e,t,s)=>{s.d(t,{r:()=>l});var i=s(23464),r=s(38851),n=s(25562),o=s(93384);i.extend(n),i.extend(o);const a={...r,name:"en-web3-modal",relativeTime:{future:"in %s",past:"%s ago",s:"%d sec",m:"1 min",mm:"%d min",h:"1 hr",hh:"%d hrs",d:"1 d",dd:"%d d",M:"1 mo",MM:"%d mo",y:"1 yr",yy:"%d yr"}},c=["January","February","March","April","May","June","July","August","September","October","November","December"];i.locale("en-web3-modal",a);const l={getMonthNameByIndex:e=>c[e],getYear:(e=(new Date).toISOString())=>i(e).year(),getRelativeDateFromNow:e=>i(e).locale("en-web3-modal").fromNow(!0),formatDate:(e,t="DD MMM")=>i(e).format(t)}},94311:(e,t,s)=>{s.d(t,{Rn:()=>r.R,tW:()=>i.t});var i=s(56335),r=s(64525);s(65508)},96517:(e,t,s)=>{s.d(t,{X:()=>c}),s(18338);var i=s(72269),r=s(23981),n=s(98299),o=s(82868),a=s(22129);class c{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,this.getCaipNetworks=e=>n.W.getCaipNetworks(e),e&&this.construct(e)}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.getCaipNetworks(this.namespace)}setAuthProvider(e){this.addConnector({id:i.o.CONNECTOR_ID.AUTH,type:"AUTH",name:i.o.CONNECTOR_NAMES.AUTH,provider:e,imageId:o.L.ConnectorImageIds[i.o.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(e=>!t.has(e.id)&&(t.add(e.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,t){r.U.setStatus(e,t)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(t)}off(e,t){const s=this.eventListeners.get(e);s&&s.delete(t)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,t){const s=this.eventListeners.get(e);s&&s.forEach(e=>e(t))}async connectWalletConnect(e){const t=this.getWalletConnectConnector();return{clientId:(await t.connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:t,providerType:s}=e;if(!e.provider)return;const i="provider"in e.provider?e.provider.provider:e.provider;if("WALLET_CONNECT"!==s){if(i&&"AUTH"===s){const e=i,s=r.U.state.preferredAccountTypes?.[t.chainNamespace];await e.switchNetwork(t.caipNetworkId);const n=await e.getUser({chainId:t.caipNetworkId,preferredAccountType:s});this.emit("switchNetwork",n)}}else i.setDefaultChain(t.caipNetworkId)}getWalletConnectConnector(){const e=this.connectors.find(e=>e instanceof a.F);if(!e)throw new Error("WalletConnectConnector not found");return e}}},98299:(e,t,s)=>{s.d(t,{W:()=>N});var i=s(89168),r=s(39150),n=s(67902),o=s(72269),a=s(3555),c=s(22143),l=s(11847),d=s(37834),h=s(23981),p=s(86792),u=s(83077),g=s(47981),m=s(88759),f=s(1420),w=s(68251),y=s(72397),b=s(37686);const v={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},E={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},C=(0,i.BX)({chains:(0,r.zC)(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),I={state:C,subscribe:e=>(0,i.B1)(C,()=>{e(C)}),subscribeKey:(e,t)=>(0,r.u$)(C,e,t),subscribeChainProp(e,t,s){let r;return(0,i.B1)(C.chains,()=>{const i=s||C.activeChain;if(i){const s=C.chains.get(i)?.[e];r!==s&&(r=s,t(s))}})},initialize(e,t,s){const{chainId:r,namespace:n}=l.i.getActiveNetworkProps(),o=t?.find(e=>e.id.toString()===r?.toString()),a=e.find(e=>e?.namespace===n)||e?.[0],c=e.map(e=>e.namespace).filter(e=>void 0!==e),d=f.H.state.enableEmbedded?new Set([...c]):new Set([...t?.map(e=>e.chainNamespace)??[]]);0!==e?.length&&a||(C.noAdapters=!0),C.noAdapters||(C.activeChain=a?.namespace,C.activeCaipNetwork=o,N.setChainNetworkData(a?.namespace,{caipNetwork:o}),C.activeChain&&w.z.set({activeChain:a?.namespace})),d.forEach(e=>{const r=t?.filter(t=>t.chainNamespace===e);N.state.chains.set(e,{namespace:e,networkState:(0,i.BX)({...E,caipNetwork:r?.[0]}),accountState:(0,i.BX)(v),caipNetworks:r??[],...s}),N.setRequestedCaipNetworks(r??[],e)})},removeAdapter(e){if(C.activeChain===e){const t=Array.from(C.chains.entries()).find(([t])=>t!==e);if(t){const e=t[1]?.caipNetworks?.[0];e&&N.setActiveCaipNetwork(e)}}C.chains.delete(e)},addAdapter(e,{networkControllerClient:t,connectionControllerClient:s},i){C.chains.set(e.namespace,{namespace:e.namespace,networkState:{...E,caipNetwork:i[0]},accountState:v,caipNetworks:i,connectionControllerClient:s,networkControllerClient:t}),N.setRequestedCaipNetworks(i?.filter(t=>t.chainNamespace===e.namespace)??[],e.namespace)},addNetwork(e){const t=C.chains.get(e.chainNamespace);if(t){const s=[...t.caipNetworks||[]];t.caipNetworks?.find(t=>t.id===e.id)||s.push(e),C.chains.set(e.chainNamespace,{...t,caipNetworks:s}),N.setRequestedCaipNetworks(s,e.chainNamespace),u.a.filterByNamespace(e.chainNamespace,!0)}},removeNetwork(e,t){const s=C.chains.get(e);if(s){const i=C.activeCaipNetwork?.id===t,r=[...s.caipNetworks?.filter(e=>e.id!==t)||[]];i&&s?.caipNetworks?.[0]&&N.setActiveCaipNetwork(s.caipNetworks[0]),C.chains.set(e,{...s,caipNetworks:r}),N.setRequestedCaipNetworks(r||[],e),0===r.length&&u.a.filterByNamespace(e,!1)}},setAdapterNetworkState(e,t){const s=C.chains.get(e);s&&(s.networkState={...s.networkState||E,...t},C.chains.set(e,s))},setChainAccountData(e,t,s=!0){if(!e)throw new Error("Chain is required to update chain account data");const i=C.chains.get(e);if(i){const s={...i.accountState||v,...t};C.chains.set(e,{...i,accountState:s}),1!==C.chains.size&&C.activeChain!==e||(t.caipAddress&&(C.activeCaipAddress=t.caipAddress),h.U.replaceState(s))}},setChainNetworkData(e,t){if(!e)return;const s=C.chains.get(e);if(s){const i={...s.networkState||E,...t};C.chains.set(e,{...s,networkState:i})}},setAccountProp(e,t,s,i=!0){N.setChainAccountData(s,{[e]:t},i),"status"===e&&"disconnected"===t&&s&&u.a.removeConnectorId(s)},setActiveNamespace(e){C.activeChain=e;const t=e?C.chains.get(e):void 0,s=t?.networkState?.caipNetwork;s?.id&&e&&(C.activeCaipAddress=t?.accountState?.caipAddress,C.activeCaipNetwork=s,N.setChainNetworkData(e,{caipNetwork:s}),l.i.setActiveCaipNetworkId(s?.caipNetworkId),w.z.set({activeChain:e,selectedNetworkId:s?.caipNetworkId}))},setActiveCaipNetwork(e){if(!e)return;C.activeChain!==e.chainNamespace&&N.setIsSwitchingNamespace(!0);const t=C.chains.get(e.chainNamespace);C.activeChain=e.chainNamespace,C.activeCaipNetwork=e,N.setChainNetworkData(e.chainNamespace,{caipNetwork:e}),C.activeCaipAddress=t?.accountState?.address?`${e.chainNamespace}:${e.id}:${t?.accountState?.address}`:void 0,N.setAccountProp("caipAddress",C.activeCaipAddress,e.chainNamespace),t&&h.U.replaceState(t.accountState),b.R.resetSend(),w.z.set({activeChain:C.activeChain,selectedNetworkId:C.activeCaipNetwork?.caipNetworkId}),l.i.setActiveCaipNetworkId(e.caipNetworkId),N.checkIfSupportedNetwork(e.chainNamespace)||!f.H.state.enableNetworkSwitch||f.H.state.allowUnsupportedChain||p.x.state.wcBasic||N.showUnsupportedChainUI()},addCaipNetwork(e){if(!e)return;const t=C.chains.get(e.chainNamespace);t&&t?.caipNetworks?.push(e)},async switchActiveNamespace(e){if(!e)return;const t=e!==N.state.activeChain,s=N.getNetworkData(e)?.caipNetwork,i=N.getCaipNetworkByNamespace(e,s?.id);t&&i&&await N.switchActiveNetwork(i)},async switchActiveNetwork(e){const t=N.state.chains.get(N.state.activeChain),s=!t?.caipNetworks?.some(e=>e.id===C.activeCaipNetwork?.id),i=N.getNetworkControllerClient(e.chainNamespace);if(i){try{await i.switchCaipNetwork(e),s&&m.W.close()}catch(e){y.I.goBack()}g.E.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:e.caipNetworkId}})}},getNetworkControllerClient(e){const t=e||C.activeChain,s=C.chains.get(t);if(!s)throw new Error("Chain adapter not found");if(!s.networkControllerClient)throw new Error("NetworkController client not set");return s.networkControllerClient},getConnectionControllerClient(e){const t=e||C.activeChain;if(!t)throw new Error("Chain is required to get connection controller client");const s=C.chains.get(t);if(!s?.connectionControllerClient)throw new Error("ConnectionController client not set");return s.connectionControllerClient},getAccountProp(e,t){let s=C.activeChain;if(t&&(s=t),!s)return;const i=C.chains.get(s)?.accountState;return i?i[e]:void 0},getNetworkProp(e,t){const s=C.chains.get(t)?.networkState;if(s)return s[e]},getRequestedCaipNetworks(e){const t=C.chains.get(e),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:i=[]}=t?.networkState||{};return c.w.sortRequestedNetworks(s,i)},getAllRequestedCaipNetworks(){const e=[];return C.chains.forEach(t=>{const s=N.getRequestedCaipNetworks(t.namespace);e.push(...s)}),e},setRequestedCaipNetworks(e,t){N.setAdapterNetworkState(t,{requestedCaipNetworks:e});const s=N.getAllRequestedCaipNetworks().map(e=>e.chainNamespace),i=Array.from(new Set(s));u.a.filterByNamespaces(i)},getAllApprovedCaipNetworkIds(){const e=[];return C.chains.forEach(t=>{const s=N.getApprovedCaipNetworkIds(t.namespace);e.push(...s)}),e},getActiveCaipNetwork:()=>C.activeCaipNetwork,getActiveCaipAddress:()=>C.activeCaipAddress,getApprovedCaipNetworkIds(e){const t=C.chains.get(e);return t?.networkState?.approvedCaipNetworkIds||[]},async setApprovedCaipNetworksData(e){const t=N.getNetworkControllerClient(),s=await(t?.getApprovedCaipNetworksData());N.setAdapterNetworkState(e,{approvedCaipNetworkIds:s?.approvedCaipNetworkIds,supportsAllNetworks:s?.supportsAllNetworks})},checkIfSupportedNetwork(e,t){const s=t||C.activeCaipNetwork,i=N.getRequestedCaipNetworks(e);return!i.length||i?.some(e=>e.id===s?.id)},checkIfSupportedChainId(e){if(!C.activeChain)return!0;const t=N.getRequestedCaipNetworks(C.activeChain);return t?.some(t=>t.id===e)},setSmartAccountEnabledNetworks(e,t){N.setAdapterNetworkState(t,{smartAccountEnabledNetworks:e})},checkIfSmartAccountEnabled(){const e=n.L.caipNetworkIdToNumber(C.activeCaipNetwork?.caipNetworkId),t=C.activeChain;if(!t||!e)return!1;const s=N.getNetworkProp("smartAccountEnabledNetworks",t);return Boolean(s?.includes(Number(e)))},getActiveNetworkTokenAddress(){const e=C.activeCaipNetwork?.chainNamespace||"eip155";return`${e}:${C.activeCaipNetwork?.id||1}:${a.oU.NATIVE_TOKEN_ADDRESS[e]}`},showUnsupportedChainUI(){m.W.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const e=C.activeCaipNetwork;return Boolean(e?.chainNamespace&&a.oU.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(e.chainNamespace))},resetNetwork(e){N.setAdapterNetworkState(e,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(e){const t=e;if(!t)throw new Error("Chain is required to set account prop");C.activeCaipAddress=void 0,N.setChainAccountData(t,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountTypes:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),u.a.removeConnectorId(t)},setIsSwitchingNamespace(e){C.isSwitchingNamespace=e},getFirstCaipNetworkSupportsAuthConnector(){const e=[];let t;if(C.chains.forEach(t=>{o.o.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(e=>e===t.namespace)&&t.namespace&&e.push(t.namespace)}),e.length>0){const s=e[0];return t=s?C.chains.get(s)?.caipNetworks?.[0]:void 0,t}},getAccountData:e=>e?N.state.chains.get(e)?.accountState:h.U.state,getNetworkData(e){const t=e||C.activeChain;if(t)return N.state.chains.get(t)?.networkState},getCaipNetworkByNamespace(e,t){if(!e)return;const s=N.state.chains.get(e),i=s?.caipNetworks?.find(e=>e.id===t);return i||s?.networkState?.caipNetwork||s?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){const e=u.a.state.filterByNamespace;return(e?[C.chains.get(e)]:Array.from(C.chains.values())).flatMap(e=>e?.caipNetworks||[]).map(e=>e.caipNetworkId)},getCaipNetworks:e=>e?N.getRequestedCaipNetworks(e):N.getAllRequestedCaipNetworks()},N=(0,d.X)(I)}};
878
+ `},67902:(e,t,s)=>{s.d(t,{L:()=>r});var i=s(72269);const r={caipNetworkIdToNumber:e=>e?Number(e.split(":")[1]):void 0,parseEvmChainId(e){return"string"==typeof e?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace:(e,t)=>e?.filter(e=>e.chainNamespace===t)||[],getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){if(!t)return;const s=e.find(e=>e.caipNetworkId===t);if(s)return s.name;const[r]=t.split(":");return i.o.CHAIN_NAME_MAP?.[r]||void 0}}},68251:(e,t,s)=>{s.d(t,{z:()=>o});var i=s(89168),r=s(39150);const n=(0,i.BX)({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),o={state:n,subscribe:e=>(0,i.B1)(n,()=>e(n)),subscribeOpen:e=>(0,r.u$)(n,"open",e),set(e){Object.assign(n,{...n,...e})}}},69658:(e,t,s)=>{s.d(t,{EM:()=>n.E,JX:()=>i.JX,RF:()=>i.RF,Zv:()=>r.Z,ds:()=>i.ds}),s(34631);var i=s(67232),r=s(15179),n=(s(53561),s(13679))},72269:(e,t,s)=>{s.d(t,{o:()=>r});var i=s(39907);const r={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(void 0!==i&&void 0!==i.env?i.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"}},72397:(e,t,s)=>{s.d(t,{I:()=>u});var i=s(89168),r=s(39150),n=s(37834),o=s(46362),a=s(98299),c=s(83077),l=s(88759),d=s(1420);const h=(0,i.BX)({view:"Connect",history:["Connect"],transactionStack:[]}),p={state:h,subscribeKey:(e,t)=>(0,r.u$)(h,e,t),pushTransactionStack(e){h.transactionStack.push(e)},popTransactionStack(e){const t=h.transactionStack.pop();if(!t)return;const{onSuccess:s,onError:i,onCancel:r}=t;switch(e){case"success":s?.();break;case"error":i?.(),u.goBack();break;case"cancel":r?.(),u.goBack()}},push(e,t){e!==h.view&&(h.view=e,h.history.push(e),h.data=t)},reset(e,t){h.view=e,h.history=[e],h.data=t},replace(e,t){h.history.at(-1)===e||(h.view=e,h.history[h.history.length-1]=e,h.data=t)},goBack(){const e=a.W.state.activeCaipAddress,t="ConnectingFarcaster"===u.state.view,s=!e&&t;if(h.history.length>1){h.history.pop();const[t]=h.history.slice(-1);if(t){const s="Connect"===t;h.view=e&&s?"Account":t}}else l.W.close();h.data?.wallet&&(h.data.wallet=void 0),setTimeout(()=>{if(s){o.U.setFarcasterUrl(void 0,a.W.state.activeChain);const e=c.a.getAuthConnector();e?.provider?.reload();const t=(0,i.P9)(d.H.state);e?.provider?.syncDappData?.({metadata:t.metadata,sdkVersion:t.sdkVersion,projectId:t.projectId,sdkType:t.sdkType})}},100)},goBackToIndex(e){if(h.history.length>1){h.history=h.history.slice(0,e+1);const[t]=h.history.slice(-1);t&&(h.view=t)}},goBackOrCloseModal(){u.state.history.length>1?u.goBack():l.W.close()}},u=(0,n.X)(p)},79217:(e,t,s)=>{s.d(t,{Q:()=>r});var i=s(83077);function r(e,t){return i.a.getConnectorId(e)===t}},80971:(e,t,s)=>{s.d(t,{IP:()=>o,T8:()=>r,Ud:()=>n,Ws:()=>i});const i={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections"};function r(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const n={setItem(e,t){o()&&void 0!==t&&localStorage.setItem(e,t)},getItem(e){if(o())return localStorage.getItem(e)||void 0},removeItem(e){o()&&localStorage.removeItem(e)},clear(){o()&&localStorage.clear()}};function o(){return"undefined"!=typeof window&&"undefined"!=typeof localStorage}},80989:(e,t,s)=>{function i(e,t){return"light"===t?{"--w3m-accent":e?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":e?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}s.d(t,{o:()=>i})},82868:(e,t,s)=>{s.d(t,{L:()=>n});var i=s(72269),r=s(83229);const n={ConnectorExplorerIds:{[i.o.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[i.o.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[i.o.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[i.o.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[i.o.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[r.o.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[r.o.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[r.o.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[r.o.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[r.o.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[r.o.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[r.o.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[r.o.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[r.o.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[r.o.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[r.o.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200"},ConnectorImageIds:{[i.o.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[i.o.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[i.o.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[i.o.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[i.o.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[i.o.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[i.o.CONNECTOR_ID.INJECTED]:"Browser Wallet",[i.o.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[i.o.CONNECTOR_ID.COINBASE]:"Coinbase",[i.o.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[i.o.CONNECTOR_ID.LEDGER]:"Ledger",[i.o.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[i.o.CONNECTOR_ID.INJECTED]:"INJECTED",[i.o.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[i.o.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[i.o.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]}},83077:(e,t,s)=>{s.d(t,{a:()=>y});var i=s(89168),r=s(39150),n=s(72269),o=s(80989),a=s(9732),c=s(11847),l=s(37834),d=s(93474),h=s(98299),p=s(1420),u=s(72397),g=s(49951);const m={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},f=(0,i.BX)({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...m},filterByNamespaceMap:{eip155:!0,solana:!0,polkadot:!0,bip122:!0,cosmos:!0}}),w={state:f,subscribe:e=>(0,i.B1)(f,()=>{e(f)}),subscribeKey:(e,t)=>(0,r.u$)(f,e,t),initialize(e){e.forEach(e=>{const t=c.i.getConnectedConnectorId(e);t&&y.setConnectorId(t,e)})},setActiveConnector(e){e&&(f.activeConnector=(0,i.KR)(e))},setConnectors(e){e.filter(e=>!f.allConnectors.some(t=>t.id===e.id&&y.getConnectorName(t.name)===y.getConnectorName(e.name)&&t.chain===e.chain)).forEach(e=>{"MULTI_CHAIN"!==e.type&&f.allConnectors.push((0,i.KR)(e))});const t=y.getEnabledNamespaces(),s=y.getEnabledConnectors(t);f.connectors=y.mergeMultiChainConnectors(s)},filterByNamespaces(e){Object.keys(f.filterByNamespaceMap).forEach(e=>{f.filterByNamespaceMap[e]=!1}),e.forEach(e=>{f.filterByNamespaceMap[e]=!0}),y.updateConnectorsForEnabledNamespaces()},filterByNamespace(e,t){f.filterByNamespaceMap[e]=t,y.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const e=y.getEnabledNamespaces(),t=y.getEnabledConnectors(e),s=y.areAllNamespacesEnabled();f.connectors=y.mergeMultiChainConnectors(t),s?d.N.clearFilterByNamespaces():d.N.filterByNamespaces(e)},getEnabledNamespaces:()=>Object.entries(f.filterByNamespaceMap).filter(([e,t])=>t).map(([e])=>e),getEnabledConnectors:e=>f.allConnectors.filter(t=>e.includes(t.chain)),areAllNamespacesEnabled:()=>Object.values(f.filterByNamespaceMap).every(e=>e),mergeMultiChainConnectors(e){const t=y.generateConnectorMapByName(e),s=[];return t.forEach(e=>{const t=e[0],i=t?.id===n.o.CONNECTOR_ID.AUTH;e.length>1&&t?s.push({name:t.name,imageUrl:t.imageUrl,imageId:t.imageId,connectors:[...e],type:i?"AUTH":"MULTI_CHAIN",chain:"eip155",id:t?.id||""}):t&&s.push(t)}),s},generateConnectorMapByName(e){const t=new Map;return e.forEach(e=>{const{name:s}=e,i=y.getConnectorName(s);if(!i)return;const r=t.get(i)||[];r.find(t=>t.chain===e.chain)||r.push(e),t.set(i,r)}),t},getConnectorName:e=>e&&{"Trust Wallet":"Trust"}[e]||e,getUniqueConnectorsByName(e){const t=[];return e.forEach(e=>{t.find(t=>t.chain===e.chain)||t.push(e)}),t},addConnector(e){if(e.id===n.o.CONNECTOR_ID.AUTH){const t=e,s=(0,i.P9)(p.H.state),r=g.W.getSnapshot().themeMode,n=g.W.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,projectId:s.projectId,sdkType:s.sdkType}),t?.provider?.syncTheme({themeMode:r,themeVariables:n,w3mThemeVariables:(0,o.o)(n,r)}),y.setConnectors([e])}else y.setConnectors([e])},getAuthConnector(e){const t=e||h.W.state.activeChain,s=f.connectors.find(e=>e.id===n.o.CONNECTOR_ID.AUTH);if(s)return s?.connectors?.length?s.connectors.find(e=>e.chain===t):s},getAnnouncedConnectorRdns:()=>f.connectors.filter(e=>"ANNOUNCED"===e.type).map(e=>e.info?.rdns),getConnectorById:e=>f.allConnectors.find(t=>t.id===e),getConnector:(e,t)=>f.allConnectors.filter(e=>e.chain===h.W.state.activeChain).find(s=>s.explorerId===e||s.info?.rdns===t),syncIfAuthConnector(e){if("ID_AUTH"!==e.id)return;const t=e,s=(0,i.P9)(p.H.state),r=g.W.getSnapshot().themeMode,n=g.W.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),t.provider.syncTheme({themeMode:r,themeVariables:n,w3mThemeVariables:(0,o.o)(n,r)})},getConnectorsByNamespace(e){const t=f.allConnectors.filter(t=>t.chain===e);return y.mergeMultiChainConnectors(t)},selectWalletConnector(e){const t=y.getConnector(e.id,e.rdns),s=h.W.state.activeChain;a.W.handleMobileDeeplinkRedirect(t?.explorerId||e.id,s),t?u.I.push("ConnectingExternal",{connector:t}):u.I.push("ConnectingWalletConnect",{wallet:e})},getConnectors:e=>e?y.getConnectorsByNamespace(e):y.mergeMultiChainConnectors(f.allConnectors),setFilterByNamespace(e){f.filterByNamespace=e,f.connectors=y.getConnectors(e),d.N.setFilterByNamespace(e)},setConnectorId(e,t){e&&(f.activeConnectorIds={...f.activeConnectorIds,[t]:e},c.i.setConnectedConnectorId(t,e))},removeConnectorId(e){f.activeConnectorIds={...f.activeConnectorIds,[e]:void 0},c.i.deleteConnectedConnectorId(e)},getConnectorId(e){if(e)return f.activeConnectorIds[e]},isConnected:e=>e?Boolean(f.activeConnectorIds[e]):Object.values(f.activeConnectorIds).some(e=>Boolean(e)),resetConnectorIds(){f.activeConnectorIds={...m}}},y=(0,l.X)(w)},83229:(e,t,s)=>{s.d(t,{o:()=>i});const i={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"ID_AUTH"}},84279:(e,t,s)=>{s.d(t,{A:()=>h});var i=s(83077),r=s(93474),n=s(1420),o=s(22143),a=s(11847),c=s(51765),l=s(32523),d=s(42177);const h={filterOutDuplicatesByRDNS(e){const t=n.H.state.enableEIP6963?i.a.state.connectors:[],s=a.i.getRecentWallets(),r=t.map(e=>e.info?.rdns).filter(Boolean),c=s.map(e=>e.rdns).filter(Boolean),l=r.concat(c);if(l.includes("io.metamask.mobile")&&o.w.isMobile()){const e=l.indexOf("io.metamask.mobile");l[e]="io.metamask"}return e.filter(e=>!l.includes(String(e?.rdns)))},filterOutDuplicatesByIds(e){const t=i.a.state.connectors.filter(e=>"ANNOUNCED"===e.type||"INJECTED"===e.type),s=a.i.getRecentWallets(),r=t.map(e=>e.explorerId),n=s.map(e=>e.id),o=r.concat(n);return e.filter(e=>!o.includes(e?.id))},filterOutDuplicateWallets(e){const t=this.filterOutDuplicatesByRDNS(e);return this.filterOutDuplicatesByIds(t)},markWalletsAsInstalled(e){const{connectors:t}=i.a.state,{featuredWalletIds:s}=n.H.state,r=t.filter(e=>"ANNOUNCED"===e.type).reduce((e,t)=>t.info?.rdns?(e[t.info.rdns]=!0,e):e,{});return e.map(e=>({...e,installed:Boolean(e.rdns)&&Boolean(r[e.rdns??""])})).sort((e,t)=>{const i=Number(t.installed)-Number(e.installed);if(0!==i)return i;if(s?.length){const i=s.indexOf(e.id),r=s.indexOf(t.id);if(-1!==i&&-1!==r)return i-r;if(-1!==i)return-1;if(-1!==r)return 1}return 0})},getConnectOrderMethod(e,t){const s=e?.connectMethodsOrder||n.H.state.features?.connectMethodsOrder,o=t||i.a.state.connectors;if(s)return s;const{injected:a,announced:c}=l.g.getConnectorsByType(o,r.N.state.recommended,r.N.state.featured),h=a.filter(l.g.showConnector),p=c.filter(l.g.showConnector);return h.length||p.length?["wallet","email","social"]:d.o.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(e){const t=Boolean(e.rdns)&&r.N.state.excludedWallets.some(t=>t.rdns===e.rdns),s=Boolean(e.name)&&r.N.state.excludedWallets.some(t=>c.y.isLowerCaseMatch(t.name,e.name));return t||s}}},86454:(e,t,s)=>{s.d(t,{$:()=>c});var i=s(89168),r=s(93474),n=s(6262);const o={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:""},a=(0,i.BX)({networkImagePromises:{}}),c={async fetchWalletImage(e){if(e)return await r.N._fetchWalletImage(e),this.getWalletImageById(e)},async fetchNetworkImage(e){if(!e)return;return this.getNetworkImageById(e)||(a.networkImagePromises[e]||(a.networkImagePromises[e]=r.N._fetchNetworkImage(e)),await a.networkImagePromises[e],this.getNetworkImageById(e))},getWalletImageById(e){if(e)return n.j.state.walletImages[e]},getWalletImage:e=>e?.image_url?e?.image_url:e?.image_id?n.j.state.walletImages[e.image_id]:void 0,getNetworkImage:e=>e?.assets?.imageUrl?e?.assets?.imageUrl:e?.assets?.imageId?n.j.state.networkImages[e.assets.imageId]:void 0,getNetworkImageById(e){if(e)return n.j.state.networkImages[e]},getConnectorImage:e=>e?.imageUrl?e.imageUrl:e?.imageId?n.j.state.connectorImages[e.imageId]:void 0,getChainImage:e=>n.j.state.networkImages[o[e]]}},86792:(e,t,s)=>{s.d(t,{x:()=>y});var i=s(89168),r=s(39150),n=s(22143),o=s(11847),a=s(37834),c=s(46362),l=s(98299),d=s(83077),h=s(47981),p=s(88759),u=s(72397),g=s(87193);const m=(0,i.BX)({connections:new Map,wcError:!1,buffering:!1,status:"disconnected"});let f;const w={state:m,subscribeKey:(e,t)=>(0,r.u$)(m,e,t),_getClient:()=>m._client,setClient(e){m._client=(0,i.KR)(e)},async connectWalletConnect(){if(n.w.isTelegram()||n.w.isSafari()&&n.w.isIos()){if(f)return await f,void(f=void 0);if(!n.w.isPairingExpired(m?.wcPairingExpiry)){const e=m.wcUri;return void(m.wcUri=e)}f=y._getClient()?.connectWalletConnect?.().catch(()=>{}),y.state.status="connecting",await f,f=void 0,m.wcPairingExpiry=void 0,y.state.status="connected"}else await(y._getClient()?.connectWalletConnect?.())},async connectExternal(e,t,s=!0){await(y._getClient()?.connectExternal?.(e)),s&&l.W.setActiveNamespace(t)},async reconnectExternal(e){await(y._getClient()?.reconnectExternal?.(e));const t=e.chain||l.W.state.activeChain;t&&d.a.setConnectorId(e.id,t)},async setPreferredAccountType(e,t){p.W.setLoading(!0,l.W.state.activeChain);const s=d.a.getAuthConnector();s&&(c.U.setPreferredAccountType(e,t),await s.provider.setPreferredAccount(e),o.i.setPreferredAccountTypes(c.U.state.preferredAccountTypes??{[t]:e}),await y.reconnectExternal(s),p.W.setLoading(!1,l.W.state.activeChain),h.E.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:e,network:l.W.state.activeCaipNetwork?.caipNetworkId||""}}))},signMessage:async e=>y._getClient()?.signMessage(e),parseUnits:(e,t)=>y._getClient()?.parseUnits(e,t),formatUnits:(e,t)=>y._getClient()?.formatUnits(e,t),sendTransaction:async e=>y._getClient()?.sendTransaction(e),getCapabilities:async e=>y._getClient()?.getCapabilities(e),grantPermissions:async e=>y._getClient()?.grantPermissions(e),walletGetAssets:async e=>y._getClient()?.walletGetAssets(e)??{},estimateGas:async e=>y._getClient()?.estimateGas(e),writeContract:async e=>y._getClient()?.writeContract(e),getEnsAddress:async e=>y._getClient()?.getEnsAddress(e),getEnsAvatar:async e=>y._getClient()?.getEnsAvatar(e),checkInstalled:e=>y._getClient()?.checkInstalled?.(e)||!1,resetWcConnection(){m.wcUri=void 0,m.wcPairingExpiry=void 0,m.wcLinking=void 0,m.recentWallet=void 0,m.status="disconnected",g.W.resetTransactions(),o.i.deleteWalletConnectDeepLink()},resetUri(){m.wcUri=void 0,m.wcPairingExpiry=void 0,f=void 0},finalizeWcConnection(){const{wcLinking:e,recentWallet:t}=y.state;e&&o.i.setWalletConnectDeepLink(e),t&&o.i.setAppKitRecent(t),h.E.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:e?"mobile":"qrcode",name:u.I.state.data?.wallet?.name||"Unknown"}})},setWcBasic(e){m.wcBasic=e},setUri(e){m.wcUri=e,m.wcPairingExpiry=n.w.getPairingExpiry()},setWcLinking(e){m.wcLinking=e},setWcError(e){m.wcError=e,m.buffering=!1},setRecentWallet(e){m.recentWallet=e},setBuffering(e){m.buffering=e},setStatus(e){m.status=e},async disconnect(e){try{await(y._getClient()?.disconnect(e))}catch(e){throw new a.A("Failed to disconnect","INTERNAL_SDK_ERROR",e)}},setConnections(e,t){m.connections.set(t,e)},switchAccount({connection:e,address:t,namespace:s}){if(d.a.state.activeConnectorIds[s]===e.connectorId){const e=l.W.state.activeCaipNetwork;if(e){const i=`${s}:${e.id}:${t}`;c.U.setCaipAddress(i,s)}else console.warn(`No current network found for namespace "${s}"`)}else{const t=d.a.getConnector(e.connectorId);t?y.connectExternal(t,s):console.warn(`No connector found for namespace "${s}"`)}}},y=(0,a.X)(w)},87193:(e,t,s)=>{s.d(t,{W:()=>g});var i=s(89168),r=s(88889),n=s(37834),o=s(46362),a=s(16444),c=s(98299),l=s(47981),d=s(1420),h=s(92492);const p=(0,i.BX)({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),u={state:p,subscribe:e=>(0,i.B1)(p,()=>e(p)),setLastNetworkInView(e){p.lastNetworkInView=e},async fetchTransactions(e,t){if(!e)throw new Error("Transactions can't be fetched without an accountAddress");p.loading=!0;try{const s=await a.T.fetchTransactions({account:e,cursor:p.next,onramp:t,cache:"coinbase"===t?"no-cache":void 0,chainId:c.W.state.activeCaipNetwork?.caipNetworkId}),i=g.filterSpamTransactions(s.data),r=g.filterByConnectedChain(i),n=[...p.transactions,...r];p.loading=!1,"coinbase"===t?p.coinbaseTransactions=g.groupTransactionsByYearAndMonth(p.coinbaseTransactions,s.data):(p.transactions=n,p.transactionsByYear=g.groupTransactionsByYearAndMonth(p.transactionsByYear,r)),p.empty=0===n.length,p.next=s.next?s.next:void 0}catch(t){const s=c.W.state.activeChain;l.E.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:e,projectId:d.H.state.projectId,cursor:p.next,isSmartAccount:o.U.state.preferredAccountTypes?.[s]===r.Vl.ACCOUNT_TYPES.SMART_ACCOUNT}}),h.P.showError("Failed to fetch transactions"),p.loading=!1,p.empty=!0,p.next=void 0}},groupTransactionsByYearAndMonth(e={},t=[]){const s=e;return t.forEach(e=>{const t=new Date(e.metadata.minedAt).getFullYear(),i=new Date(e.metadata.minedAt).getMonth(),r=s[t]??{},n=(r[i]??[]).filter(t=>t.id!==e.id);s[t]={...r,[i]:[...n,e].sort((e,t)=>new Date(t.metadata.minedAt).getTime()-new Date(e.metadata.minedAt).getTime())}}),s},filterSpamTransactions:e=>e.filter(e=>!e.transfers.every(e=>!0===e.nft_info?.flags.is_spam)),filterByConnectedChain(e){const t=c.W.state.activeCaipNetwork?.caipNetworkId;return e.filter(e=>e.metadata.chain===t)},clearCursor(){p.next=void 0},resetTransactions(){p.transactions=[],p.transactionsByYear={},p.lastNetworkInView=void 0,p.loading=!1,p.empty=!1,p.next=void 0}},g=(0,n.X)(u,"API_ERROR")},88759:(e,t,s)=>{s.d(t,{W:()=>b});var i=s(89168),r=s(39150),n=s(22143),o=s(60032),a=s(37834),c=s(46362),l=s(93474),d=s(98299),h=s(86792),p=s(83077),u=s(47981),g=s(1420),m=s(68251),f=s(72397);const w=(0,i.BX)({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),y={state:w,subscribe:e=>(0,i.B1)(w,()=>e(w)),subscribeKey:(e,t)=>(0,r.u$)(w,e,t),async open(e){const t="connected"===c.U.state.status,s=e?.namespace,i=d.W.state.activeChain,r=s&&s!==i,a=d.W.getAccountData(e?.namespace)?.caipAddress;if(h.x.state.wcBasic?l.N.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await l.N.prefetch({fetchConnectorImages:!t,fetchFeaturedWallets:!t,fetchRecommendedWallets:!t}),p.a.setFilterByNamespace(e?.namespace),b.setLoading(!0,s),s&&r){const e=d.W.getNetworkData(s)?.caipNetwork||d.W.getRequestedCaipNetworks(s)[0];e&&o.L.onSwitchNetwork({network:e,ignoreSwitchConfirmation:!0})}else{const t=d.W.state.noAdapters;g.H.state.manualWCControl||t&&!a?n.w.isMobile()?f.I.reset("AllWallets"):f.I.reset("ConnectingWalletConnectBasic"):e?.view?f.I.reset(e.view,e.data):a?f.I.reset("Account"):f.I.reset("Connect")}w.open=!0,m.z.set({open:!0}),u.E.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:Boolean(a)}})},close(){const e=g.H.state.enableEmbedded,t=Boolean(d.W.state.activeCaipAddress);w.open&&u.E.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:t}}),w.open=!1,f.I.reset("Connect"),b.clearLoading(),e?t?f.I.replace("Account"):f.I.push("Connect"):m.z.set({open:!1}),h.x.resetUri()},setLoading(e,t){t&&w.loadingNamespaceMap.set(t,e),w.loading=e,m.z.set({loading:e})},clearLoading(){w.loadingNamespaceMap.clear(),w.loading=!1},shake(){w.shake||(w.shake=!0,setTimeout(()=>{w.shake=!1},500))}},b=(0,a.X)(y)},88889:(e,t,s)=>{s.d(t,{Vl:()=>r});var i=s(39907);void 0!==i&&void 0!==i.env&&i.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL,void 0!==i&&void 0!==i.env&&i.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL,void 0!==i&&void 0!==i.env&&i.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const r={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}}},89305:(e,t,s)=>{s.d(t,{aG:()=>y});var i=s(89168),r=s(39150),n=s(72269),o=s(3555),a=s(37834),c=s(46362),l=s(93474),d=s(16444),h=s(98299),p=s(1420);const u={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},g={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},m={providers:o.tM,selectedProvider:null,error:null,purchaseCurrency:u,paymentCurrency:g,purchaseCurrencies:[u],paymentCurrencies:[],quotesLoading:!1},f=(0,i.BX)(m),w={state:f,subscribe:e=>(0,i.B1)(f,()=>e(f)),subscribeKey:(e,t)=>(0,r.u$)(f,e,t),setSelectedProvider(e){if(e&&"meld"===e.name){const t=h.W.state.activeChain===n.o.CHAIN.SOLANA?"SOL":"USDC",s=c.U.state.address??"",i=new URL(e.url);i.searchParams.append("publicKey",o.Db),i.searchParams.append("destinationCurrencyCode",t),i.searchParams.append("walletAddress",s),i.searchParams.append("externalCustomerId",p.H.state.projectId),f.selectedProvider={...e,url:i.toString()}}else f.selectedProvider=e},setOnrampProviders(e){if(Array.isArray(e)&&e.every(e=>"string"==typeof e)){const t=e,s=o.tM.filter(e=>t.includes(e.name));f.providers=s}else f.providers=[]},setPurchaseCurrency(e){f.purchaseCurrency=e},setPaymentCurrency(e){f.paymentCurrency=e},setPurchaseAmount(e){y.state.purchaseAmount=e},setPaymentAmount(e){y.state.paymentAmount=e},async getAvailableCurrencies(){const e=await d.T.getOnrampOptions();f.purchaseCurrencies=e.purchaseCurrencies,f.paymentCurrencies=e.paymentCurrencies,f.paymentCurrency=e.paymentCurrencies[0]||g,f.purchaseCurrency=e.purchaseCurrencies[0]||u,await l.N.fetchCurrencyImages(e.paymentCurrencies.map(e=>e.id)),await l.N.fetchTokenImages(e.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){f.quotesLoading=!0;try{const e=await d.T.getOnrampQuote({purchaseCurrency:f.purchaseCurrency,paymentCurrency:f.paymentCurrency,amount:f.paymentAmount?.toString()||"0",network:f.purchaseCurrency?.symbol});return f.quotesLoading=!1,f.purchaseAmount=Number(e?.purchaseAmount.amount),e}catch(e){return f.error=e.message,f.quotesLoading=!1,null}finally{f.quotesLoading=!1}},resetState(){f.selectedProvider=null,f.error=null,f.purchaseCurrency=u,f.paymentCurrency=g,f.purchaseCurrencies=[u],f.paymentCurrencies=[],f.paymentAmount=void 0,f.purchaseAmount=void 0,f.quotesLoading=!1}},y=(0,a.X)(w)},89604:(e,t,s)=>{s.d(t,{r:()=>i});const i=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}]},90169:(e,t,s)=>{s.d(t,{$I:()=>Y,$w:()=>J,Jf:()=>P,S$:()=>X,Tn:()=>ee,U:()=>Z,U$:()=>Q,WB:()=>z,cV:()=>U,iJ:()=>di,il:()=>Rs,sD:()=>_,wn:()=>F,zN:()=>j});var i=s(50046),r=s.n(i),n=s(37147),o=s(81030),a=s(70255),c=s(18898),l=s(91315),d=s(25607),h=s(97353),p=s(15529),u=s(1030),g=s(93786),m=s(14350),f=s(63342),w=s(20635),y=s(48526).hp,b=s(39907);const v="core",E=`wc@2:${v}:`,C={database:":memory:"},I="client_ed25519_seed",N=l.ONE_DAY,A=l.SIX_HOURS,_="irn",S="wss://relay.walletconnect.org",P={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},T="payload",O="connect",k="disconnect",R="error",x="2.21.0",U={link_mode:"link_mode",relay:"relay"},D="inbound",L="WALLETCONNECT_LINK_MODE_APPS",W="subscription_created",M="subscription_deleted",B=(l.FIVE_SECONDS,{wc_pairingDelete:{req:{ttl:l.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:l.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:l.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:l.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:l.ONE_DAY,prompt:!1,tag:0},res:{ttl:l.ONE_DAY,prompt:!1,tag:0}}}),j={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},q="history_created",$="history_updated",H="history_deleted",F={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},V="https://verify.walletconnect.org",z=V,K=`${z}/v3`,G=["https://verify.walletconnect.com",V],J={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},X={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Y={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Z={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Q={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},ee={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"};const te=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class se{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class ie{constructor(e,t,s){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=s}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return ne(this,e)}}class re{constructor(e){this.decoders=e}or(e){return ne(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ne=(e,t)=>new re({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class oe{constructor(e,t,s,i){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=i,this.encoder=new se(e,t,s),this.decoder=new ie(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ae=({name:e,prefix:t,encode:s,decode:i})=>new oe(e,t,s,i),ce=({prefix:e,name:t,alphabet:s})=>{const{encode:i,decode:r}=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),i=0;i<s.length;i++)s[i]=255;for(var r=0;r<e.length;r++){var n=e.charAt(r),o=n.charCodeAt(0);if(255!==s[o])throw new TypeError(n+" is ambiguous");s[o]=r}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var i=0,r=0;e[t]===c;)i++,t++;for(var n=(e.length-t)*l+1>>>0,o=new Uint8Array(n);e[t];){var d=s[e.charCodeAt(t)];if(255===d)return;for(var h=0,p=n-1;(0!==d||h<r)&&-1!==p;p--,h++)d+=a*o[p]>>>0,o[p]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");r=h,t++}if(" "!==e[t]){for(var u=n-r;u!==n&&0===o[u];)u++;for(var g=new Uint8Array(i+(n-u)),m=i;u!==n;)g[m++]=o[u++];return g}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var s=0,i=0,r=0,n=t.length;r!==n&&0===t[r];)r++,s++;for(var o=(n-r)*d+1>>>0,l=new Uint8Array(o);r!==n;){for(var h=t[r],p=0,u=o-1;(0!==h||p<i)&&-1!==u;u--,p++)h+=256*l[u]>>>0,l[u]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");i=p,r++}for(var g=o-i;g!==o&&0===l[g];)g++;for(var m=c.repeat(s);g<o;++g)m+=e.charAt(l[g]);return m},decodeUnsafe:h,decode:function(e){var s=h(e);if(s)return s;throw new Error(`Non-${t} character`)}}}(s,t);return ae({prefix:e,name:t,encode:i,decode:e=>te(r(e))})},le=({name:e,prefix:t,bitsPerChar:s,alphabet:i})=>ae({prefix:t,name:e,encode:e=>((e,t,s)=>{const i="="===t[t.length-1],r=(1<<s)-1;let n="",o=0,a=0;for(let i=0;i<e.length;++i)for(a=a<<8|e[i],o+=8;o>s;)o-=s,n+=t[r&a>>o];if(o&&(n+=t[r&a<<s-o]),i)for(;n.length*s&7;)n+="=";return n})(e,i,s),decode:t=>((e,t,s,i)=>{const r={};for(let e=0;e<t.length;++e)r[t[e]]=e;let n=e.length;for(;"="===e[n-1];)--n;const o=new Uint8Array(n*s/8|0);let a=0,c=0,l=0;for(let t=0;t<n;++t){const n=r[e[t]];if(void 0===n)throw new SyntaxError(`Non-${i} character`);c=c<<s|n,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,i,s,e)}),de=ae({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var he=Object.freeze({__proto__:null,identity:de});const pe=le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ue=Object.freeze({__proto__:null,base2:pe});const ge=le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var me=Object.freeze({__proto__:null,base8:ge});const fe=ce({prefix:"9",name:"base10",alphabet:"0123456789"});var we=Object.freeze({__proto__:null,base10:fe});const ye=le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),be=le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ve=Object.freeze({__proto__:null,base16:ye,base16upper:be});const Ee=le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ce=le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ie=le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ne=le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ae=le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_e=le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Se=le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Pe=le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Te=le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Oe=Object.freeze({__proto__:null,base32:Ee,base32upper:Ce,base32pad:Ie,base32padupper:Ne,base32hex:Ae,base32hexupper:_e,base32hexpad:Se,base32hexpadupper:Pe,base32z:Te});const ke=ce({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Re=ce({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var xe=Object.freeze({__proto__:null,base36:ke,base36upper:Re});const Ue=ce({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),De=ce({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Le=Object.freeze({__proto__:null,base58btc:Ue,base58flickr:De});const We=le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Me=le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Be=le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),je=le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var qe=Object.freeze({__proto__:null,base64:We,base64pad:Me,base64url:Be,base64urlpad:je});const $e=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),He=$e.reduce((e,t,s)=>(e[s]=t,e),[]),Fe=$e.reduce((e,t,s)=>(e[t.codePointAt(0)]=s,e),[]),Ve=ae({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+He[t],"")},decode:function(e){const t=[];for(const s of e){const e=Fe[s.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${s}`);t.push(e)}return new Uint8Array(t)}});var ze=Object.freeze({__proto__:null,base256emoji:Ve}),Ke=128,Ge=-128,Je=Math.pow(2,31),Xe=Math.pow(2,7),Ye=Math.pow(2,14),Ze=Math.pow(2,21),Qe=Math.pow(2,28),et=Math.pow(2,35),tt=Math.pow(2,42),st=Math.pow(2,49),it=Math.pow(2,56),rt=Math.pow(2,63),nt=function e(t,s,i){s=s||[];for(var r=i=i||0;t>=Je;)s[i++]=255&t|Ke,t/=128;for(;t&Ge;)s[i++]=255&t|Ke,t>>>=7;return s[i]=0|t,e.bytes=i-r+1,s},ot=function(e){return e<Xe?1:e<Ye?2:e<Ze?3:e<Qe?4:e<et?5:e<tt?6:e<st?7:e<it?8:e<rt?9:10};const at=(e,t,s=0)=>(nt(e,t,s),t),ct=e=>ot(e),lt=(e,t)=>{const s=t.byteLength,i=ct(e),r=i+ct(s),n=new Uint8Array(r+s);return at(e,n,0),at(s,n,i),n.set(t,r),new dt(e,s,t,n)};class dt{constructor(e,t,s,i){this.code=e,this.size=t,this.digest=s,this.bytes=i}}const ht=({name:e,code:t,encode:s})=>new pt(e,t,s);class pt{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?lt(this.code,t):t.then(e=>lt(this.code,e))}throw Error("Unknown type, must be binary type")}}const ut=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),gt=ht({name:"sha2-256",code:18,encode:ut("SHA-256")}),mt=ht({name:"sha2-512",code:19,encode:ut("SHA-512")});Object.freeze({__proto__:null,sha256:gt,sha512:mt});const ft=te,wt={code:0,name:"identity",encode:ft,digest:e=>lt(0,ft(e))};Object.freeze({__proto__:null,identity:wt}),new TextEncoder,new TextDecoder;const yt={...he,...ue,...me,...we,...ve,...Oe,...xe,...Le,...qe,...ze};function bt(e,t,s,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:s},decoder:{decode:i}}}const vt=bt("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),Et=bt("ascii","a",e=>{let t="a";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return t},e=>{const t=function(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?globalThis.Buffer.allocUnsafe(e):new Uint8Array(e)}((e=e.substring(1)).length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}),Ct={utf8:vt,"utf-8":vt,hex:yt.base16,latin1:Et,ascii:Et,binary:Et,...yt};var It=Object.defineProperty,Nt=(e,t,s)=>((e,t,s)=>t in e?It(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class At{constructor(e,t){this.core=e,this.logger=t,Nt(this,"keychain",new Map),Nt(this,"name","keychain"),Nt(this,"version","0.3"),Nt(this,"initialized",!1),Nt(this,"storagePrefix",E),Nt(this,"init",async()=>{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}}),Nt(this,"has",e=>(this.isInitialized(),this.keychain.has(e))),Nt(this,"set",async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()}),Nt(this,"get",e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}),Nt(this,"del",async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()}),this.core=e,this.logger=(0,a.U5)(t,this.name)}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,(0,p.h0Y)(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?(0,p.PUk)(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _t=Object.defineProperty,St=(e,t,s)=>((e,t,s)=>t in e?_t(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Pt{constructor(e,t,s){this.core=e,this.logger=t,St(this,"name","crypto"),St(this,"keychain"),St(this,"randomSessionIdentifier",(0,p.two)()),St(this,"initialized",!1),St(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),St(this,"hasKeys",e=>(this.isInitialized(),this.keychain.has(e))),St(this,"getClientId",async()=>{this.isInitialized();const e=await this.getClientSeed(),t=h.TZ(e);return h.UF(t.publicKey)}),St(this,"generateKeyPair",()=>{this.isInitialized();const e=(0,p.TZl)();return this.setPrivateKey(e.publicKey,e.privateKey)}),St(this,"signJWT",async e=>{this.isInitialized();const t=await this.getClientSeed(),s=h.TZ(t),i=this.randomSessionIdentifier,r=N;return await h.FA(i,e,r,s)}),St(this,"generateSharedKey",(e,t,s)=>{this.isInitialized();const i=this.getPrivateKey(e),r=(0,p.ovp)(i,t);return this.setSymKey(r,s)}),St(this,"setSymKey",async(e,t)=>{this.isInitialized();const s=t||(0,p.EN$)(e);return await this.keychain.set(s,e),s}),St(this,"deleteKeyPair",async e=>{this.isInitialized(),await this.keychain.del(e)}),St(this,"deleteSymKey",async e=>{this.isInitialized(),await this.keychain.del(e)}),St(this,"encode",async(e,t,s)=>{this.isInitialized();const i=(0,p.AwN)(s),r=(0,d.h)(t);if((0,p.ps1)(i))return(0,p.Tw2)(r,s?.encoding);if((0,p.V7m)(i)){const t=i.senderPublicKey,s=i.receiverPublicKey;e=await this.generateSharedKey(t,s)}const n=this.getSymKey(e),{type:o,senderPublicKey:a}=i;return(0,p.wa2)({type:o,symKey:n,message:r,senderPublicKey:a,encoding:s?.encoding})}),St(this,"decode",async(e,t,s)=>{this.isInitialized();const i=(0,p.C5G)(t,s);if((0,p.ps1)(i)){const e=(0,p.F$L)(t,s?.encoding);return(0,d.j)(e)}if((0,p.V7m)(i)){const t=i.receiverPublicKey,s=i.senderPublicKey;e=await this.generateSharedKey(t,s)}try{const i=this.getSymKey(e),r=(0,p.YcA)({symKey:i,encoded:t,encoding:s?.encoding});return(0,d.j)(r)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}}),St(this,"getPayloadType",(e,t=p.EWt)=>{const s=(0,p.iui)({encoded:e,encoding:t});return(0,p.x0t)(s.type)}),St(this,"getPayloadSenderPublicKey",(e,t=p.EWt)=>{const s=(0,p.iui)({encoded:e,encoding:t});return s.senderPublicKey?(0,u.dI)(s.senderPublicKey,p.bEt):void 0}),this.core=e,this.logger=(0,a.U5)(t,this.name),this.keychain=s||new At(this.core,this.logger)}get context(){return(0,a.oI)(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(I)}catch{e=(0,p.two)(),await this.keychain.set(I,e)}return function(e,t="utf8"){const s=Ct[t];if(!s)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?s.decoder.decode(`${s.prefix}${e}`):globalThis.Buffer.from(e,"utf8")}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Tt=Object.defineProperty,Ot=Object.defineProperties,kt=Object.getOwnPropertyDescriptors,Rt=Object.getOwnPropertySymbols,xt=Object.prototype.hasOwnProperty,Ut=Object.prototype.propertyIsEnumerable,Dt=(e,t,s)=>t in e?Tt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Lt=(e,t,s)=>Dt(e,"symbol"!=typeof t?t+"":t,s);class Wt extends c.dQ{constructor(e,t){super(e,t),this.logger=e,this.core=t,Lt(this,"messages",new Map),Lt(this,"messagesWithoutClientAck",new Map),Lt(this,"name","messages"),Lt(this,"version","0.3"),Lt(this,"initialized",!1),Lt(this,"storagePrefix",E),Lt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e);const t=await this.getRelayerMessagesWithoutClientAck();typeof t<"u"&&(this.messagesWithoutClientAck=t),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}}),Lt(this,"set",async(e,t,s)=>{this.isInitialized();const i=(0,p.ALl)(t);let r=this.messages.get(e);if(typeof r>"u"&&(r={}),typeof r[i]<"u")return i;if(r[i]=t,this.messages.set(e,r),s===D){const s=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,((e,t)=>Ot(e,kt(t)))(((e,t)=>{for(var s in t||(t={}))xt.call(t,s)&&Dt(e,s,t[s]);if(Rt)for(var s of Rt(t))Ut.call(t,s)&&Dt(e,s,t[s]);return e})({},s),{[i]:t}))}return await this.persist(),i}),Lt(this,"get",e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t}),Lt(this,"getWithoutAck",e=>{this.isInitialized();const t={};for(const s of e){const e=this.messagesWithoutClientAck.get(s)||{};t[s]=Object.values(e)}return t}),Lt(this,"has",(e,t)=>(this.isInitialized(),typeof this.get(e)[(0,p.ALl)(t)]<"u")),Lt(this,"ack",async(e,t)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(e);typeof s>"u"||(delete s[(0,p.ALl)(t)],0===Object.keys(s).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,s),await this.persist())}),Lt(this,"del",async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()}),this.logger=(0,a.U5)(e,this.name),this.core=t}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,(0,p.h0Y)(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,(0,p.h0Y)(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?(0,p.PUk)(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?(0,p.PUk)(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Mt=Object.defineProperty,Bt=Object.defineProperties,jt=Object.getOwnPropertyDescriptors,qt=Object.getOwnPropertySymbols,$t=Object.prototype.hasOwnProperty,Ht=Object.prototype.propertyIsEnumerable,Ft=(e,t,s)=>t in e?Mt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Vt=(e,t)=>{for(var s in t||(t={}))$t.call(t,s)&&Ft(e,s,t[s]);if(qt)for(var s of qt(t))Ht.call(t,s)&&Ft(e,s,t[s]);return e},zt=(e,t)=>Bt(e,jt(t)),Kt=(e,t,s)=>Ft(e,"symbol"!=typeof t?t+"":t,s);class Gt extends c.qE{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Kt(this,"events",new i.EventEmitter),Kt(this,"name","publisher"),Kt(this,"queue",new Map),Kt(this,"publishTimeout",(0,l.toMiliseconds)(l.ONE_MINUTE)),Kt(this,"initialPublishTimeout",(0,l.toMiliseconds)(15*l.ONE_SECOND)),Kt(this,"needsTransportRestart",!1),Kt(this,"publish",async(e,t,s)=>{var i;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:s}});const r=s?.ttl||A,n=(0,p.n6V)(s),o=s?.prompt||!1,a=s?.tag||0,c=s?.id||(0,m.getBigIntRpcId)().toString(),l={topic:e,message:t,opts:{ttl:r,relay:n,prompt:o,tag:a,id:c,attestation:s?.attestation,tvf:s?.tvf}},d=`Failed to publish payload, please try again. id:${c} tag:${a}`;try{const i=new Promise(async i=>{const n=({id:e})=>{l.opts.id===e&&(this.removeRequestFromQueue(e),this.relayer.events.removeListener(P.publish,n),i(l))};this.relayer.events.on(P.publish,n);const d=(0,p.K3g)(new Promise((i,n)=>{this.rpcPublish({topic:e,message:t,ttl:r,prompt:o,tag:a,id:c,attestation:s?.attestation,tvf:s?.tvf}).then(i).catch(e=>{this.logger.warn(e,e?.message),n(e)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${c} tag:${a}`);try{await d,this.events.removeListener(P.publish,n)}catch(e){this.queue.set(c,zt(Vt({},l),{attempt:1})),this.logger.warn(e,e?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:c,topic:e,message:t,opts:s}}),await(0,p.K3g)(i,this.publishTimeout,d)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),null!=(i=s?.internal)&&i.throwOnFailedPublish)throw e}finally{this.queue.delete(c)}}),Kt(this,"on",(e,t)=>{this.events.on(e,t)}),Kt(this,"once",(e,t)=>{this.events.once(e,t)}),Kt(this,"off",(e,t)=>{this.events.off(e,t)}),Kt(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.relayer=e,this.logger=(0,a.U5)(t,this.name),this.registerEventListeners()}get context(){return(0,a.oI)(this.logger)}async rpcPublish(e){var t,s,i,r;const{topic:n,message:o,ttl:a=A,prompt:c,tag:l,id:d,attestation:h,tvf:u}=e,g={method:(0,p.aa1)((0,p.n6V)().protocol).publish,params:Vt({topic:n,message:o,ttl:a,prompt:c,tag:l,attestation:h},u),id:d};(0,p.b07)(null==(t=g.params)?void 0:t.prompt)&&(null==(s=g.params)||delete s.prompt),(0,p.b07)(null==(i=g.params)?void 0:i.tag)&&(null==(r=g.params)||delete r.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const m=await this.relayer.request(g);return this.relayer.events.emit(P.publish,e),this.logger.debug("Successfully Published Payload"),m}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,zt(Vt({},e),{attempt:s}));const{topic:i,message:r,opts:n,attestation:o}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${s}`),await this.rpcPublish(zt(Vt({},e),{topic:i,message:r,ttl:n.ttl,prompt:n.prompt,tag:n.tag,id:n.id,attestation:o,tvf:n.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(n.li.pulse,()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(P.connection_stalled);this.checkQueue()}),this.relayer.on(P.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var Jt=Object.defineProperty,Xt=(e,t,s)=>((e,t,s)=>t in e?Jt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Yt{constructor(){Xt(this,"map",new Map),Xt(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),Xt(this,"get",e=>this.map.get(e)||[]),Xt(this,"exists",(e,t)=>this.get(e).includes(t)),Xt(this,"delete",(e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const i=s.filter(e=>e!==t);i.length?this.map.set(e,i):this.map.delete(e)}),Xt(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Zt=Object.defineProperty,Qt=Object.defineProperties,es=Object.getOwnPropertyDescriptors,ts=Object.getOwnPropertySymbols,ss=Object.prototype.hasOwnProperty,is=Object.prototype.propertyIsEnumerable,rs=(e,t,s)=>t in e?Zt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ns=(e,t)=>{for(var s in t||(t={}))ss.call(t,s)&&rs(e,s,t[s]);if(ts)for(var s of ts(t))is.call(t,s)&&rs(e,s,t[s]);return e},os=(e,t)=>Qt(e,es(t)),as=(e,t,s)=>rs(e,"symbol"!=typeof t?t+"":t,s);class cs extends c.mF{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,as(this,"subscriptions",new Map),as(this,"topicMap",new Yt),as(this,"events",new i.EventEmitter),as(this,"name","subscription"),as(this,"version","0.3"),as(this,"pending",new Map),as(this,"cached",[]),as(this,"initialized",!1),as(this,"storagePrefix",E),as(this,"subscribeTimeout",(0,l.toMiliseconds)(l.ONE_MINUTE)),as(this,"initialSubscribeTimeout",(0,l.toMiliseconds)(15*l.ONE_SECOND)),as(this,"clientId"),as(this,"batchSubscribeTopicsLimit",500),as(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),as(this,"subscribe",async(e,t)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const s=(0,p.n6V)(t),i={topic:e,relay:s,transportType:t?.transportType};this.pending.set(e,i);const r=await this.rpcSubscribe(e,s,t);return"string"==typeof r&&(this.onSubscribe(r,i),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}})),r}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}}),as(this,"unsubscribe",async(e,t)=>{this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)}),as(this,"isSubscribed",e=>new Promise(t=>{t(this.topicMap.topics.includes(e))})),as(this,"isKnownTopic",e=>new Promise(t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some(t=>t.topic===e))})),as(this,"on",(e,t)=>{this.events.on(e,t)}),as(this,"once",(e,t)=>{this.events.once(e,t)}),as(this,"off",(e,t)=>{this.events.off(e,t)}),as(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),as(this,"start",async()=>{await this.onConnect()}),as(this,"stop",async()=>{await this.onDisconnect()}),as(this,"restart",async()=>{await this.restore(),await this.onRestart()}),as(this,"checkPending",async()=>{if(!(0!==this.pending.size||this.initialized&&this.relayer.connected))return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e)}),as(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(n.li.pulse,async()=>{await this.checkPending()}),this.events.on(W,async e=>{const t=W;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(M,async e=>{const t=M;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})}),this.relayer=e,this.logger=(0,a.U5)(t,this.name),this.clientId=""}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async s=>await this.unsubscribeById(e,s,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const i=(0,p.n6V)(s);await this.restartToComplete({topic:e,id:t,relay:i}),await this.rpcUnsubscribe(e,t,i);const r=(0,p.Hjj)("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t,s){var i;(!s||s?.transportType===U.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const r={method:(0,p.aa1)(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});const n=null==(i=s?.internal)?void 0:i.throwOnFailedPublish;try{const t=await this.getSubscriptionId(e);if(s?.transportType===U.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(r).catch(e=>this.logger.warn(e))},(0,l.toMiliseconds)(l.ONE_SECOND)),t;const i=new Promise(async t=>{const s=i=>{i.topic===e&&(this.events.removeListener(W,s),t(i.id))};this.events.on(W,s);try{const i=await(0,p.K3g)(new Promise((e,t)=>{this.relayer.request(r).catch(e=>{this.logger.warn(e,e?.message),t(e)}).then(e)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(W,s),t(i)}catch{}}),o=await(0,p.K3g)(i,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!o&&n)throw new Error(`Subscribing to ${e} failed, please try again`);return o?t:null}catch(e){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(P.connection_stalled),n)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:(0,p.aa1)(t.protocol).batchSubscribe,params:{topics:e.map(e=>e.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await(0,p.K3g)(new Promise(e=>{this.relayer.request(s).catch(e=>this.logger.warn(e)).then(e)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(P.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:(0,p.aa1)(t.protocol).batchFetchMessages,params:{topics:e.map(e=>e.topic)}};let i;this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{i=await await(0,p.K3g)(new Promise((e,t)=>{this.relayer.request(s).catch(e=>{this.logger.warn(e),t(e)}).then(e)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(P.connection_stalled)}return i}rpcUnsubscribe(e,t,s){const i={method:(0,p.aa1)(s.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,t){this.setSubscription(e,os(ns({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(e=>{this.setSubscription(e.id,ns({},e)),this.pending.delete(e.topic)})}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,ns({},t)),this.topicMap.set(t.topic,e),this.events.emit(W,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(M,os(ns({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit("subscription_sync")}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let s=0;s<t;s++){const t=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(t)}}this.events.emit("subscription_resubscribed")}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async e=>os(ns({},e),{id:await this.getSubscriptionId(e.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await(0,p.yy4)((0,l.toMiliseconds)(l.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return(0,p.ALl)(e+await this.getClientId())}}var ls=Object.defineProperty,ds=Object.getOwnPropertySymbols,hs=Object.prototype.hasOwnProperty,ps=Object.prototype.propertyIsEnumerable,us=(e,t,s)=>t in e?ls(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,gs=(e,t)=>{for(var s in t||(t={}))hs.call(t,s)&&us(e,s,t[s]);if(ds)for(var s of ds(t))ps.call(t,s)&&us(e,s,t[s]);return e},ms=(e,t,s)=>us(e,"symbol"!=typeof t?t+"":t,s);class fs extends c.m5{constructor(e){super(e),ms(this,"protocol","wc"),ms(this,"version",2),ms(this,"core"),ms(this,"logger"),ms(this,"events",new i.EventEmitter),ms(this,"provider"),ms(this,"messages"),ms(this,"subscriber"),ms(this,"publisher"),ms(this,"name","relayer"),ms(this,"transportExplicitlyClosed",!1),ms(this,"initialized",!1),ms(this,"connectionAttemptInProgress",!1),ms(this,"relayUrl"),ms(this,"projectId"),ms(this,"packageName"),ms(this,"bundleId"),ms(this,"hasExperiencedNetworkDisruption",!1),ms(this,"pingTimeout"),ms(this,"heartBeatTimeout",(0,l.toMiliseconds)(l.THIRTY_SECONDS+l.FIVE_SECONDS)),ms(this,"reconnectTimeout"),ms(this,"connectPromise"),ms(this,"reconnectInProgress",!1),ms(this,"requestsInFlight",[]),ms(this,"connectTimeout",(0,l.toMiliseconds)(15*l.ONE_SECOND)),ms(this,"request",async e=>{var t,s;this.logger.debug("Publishing Request Payload");const i=e.id||(0,m.getBigIntRpcId)().toString();await this.toEstablishConnection();try{this.logger.trace({id:i,method:e.method,topic:null==(t=e.params)?void 0:t.topic},"relayer.request - publishing...");const r=`${i}:${(null==(s=e.params)?void 0:s.tag)||""}`;this.requestsInFlight.push(r);const n=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter(e=>e!==r),n}catch(e){throw this.logger.debug(`Failed to Publish Request: ${i}`),e}}),ms(this,"resetPingTimeout",()=>{(0,p.Lln)()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var e,t,s,i;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),null==(i=null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.terminate)||i.call(s)}catch(e){this.logger.warn(e,e?.message)}},this.heartBeatTimeout))}),ms(this,"onPayloadHandler",e=>{this.onProviderPayload(e),this.resetPingTimeout()}),ms(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(P.connect)}),ms(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ms(this,"onProviderErrorHandler",e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit(P.error,e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ms(this,"registerProviderListeners",()=>{this.provider.on(T,this.onPayloadHandler),this.provider.on(O,this.onConnectHandler),this.provider.on(k,this.onDisconnectHandler),this.provider.on(R,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&"string"!=typeof e.logger?(0,a.U5)(e.logger,this.name):(0,a.h6)((0,a.iP)({level:e.logger||"error"})),this.messages=new Wt(this.logger,e.core),this.subscriber=new cs(this,this.logger),this.publisher=new Gt(this,this.logger),this.relayUrl=e?.relayUrl||S,this.projectId=e.projectId,(0,p.m01)()?this.packageName=(0,p.R7U)():(0,p.aRZ)()&&(this.bundleId=(0,p.R7U)()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return(0,a.oI)(this.logger)}get connected(){var e,t,s;return 1===(null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.readyState)||!1}get connecting(){var e,t,s;return 0===(null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.readyState)||void 0!==this.connectPromise||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:U.relay},"outbound")}async subscribe(e,t){var s,i,r;this.isInitialized(),(null==t||!t.transportType||"relay"===t?.transportType)&&await this.toEstablishConnection();const n=typeof(null==(s=t?.internal)?void 0:s.throwOnFailedPublish)>"u"||(null==(i=t?.internal)?void 0:i.throwOnFailedPublish);let o,a=(null==(r=this.subscriber.topicMap.get(e))?void 0:r[0])||"";const c=t=>{t.topic===e&&(this.subscriber.off(W,c),o())};return await Promise.all([new Promise(e=>{o=e,this.subscriber.on(W,c)}),new Promise(async(s,i)=>{a=await this.subscriber.subscribe(e,gs({internal:{throwOnFailedPublish:n}},t)).catch(e=>{n&&i(e)})||a,s()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await(0,p.K3g)(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(this.subscriber.hasAnyTopics){if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,s)=>{await this.connect(e).then(t).catch(s).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}else this.logger.warn("Starting WS connection skipped because the client has no topics to work with.")}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await(0,p.sc7)())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(0===e?.length)return void this.logger.trace("Batch message events is empty. Ignoring...");const t=e.sort((e,t)=>e.publishedAt-t.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const e of t)try{await this.onMessageEvent(e)}catch(e){this.logger.warn(e,"Error while processing batch message event: "+e?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:s}=e;if(!t.sessionExists){const e={topic:s,expiry:(0,p.Xw0)(l.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,e)}this.events.emit(P.message,e),await this.recordMessageEvent(e,D)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(e,t)=>{const s=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(k,s),await(0,p.K3g)(new Promise((e,t)=>{this.provider.connect().then(e).catch(t)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(e=>{t(e)}).finally(()=>{this.provider.off(k,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(e,t)=>{const s=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(k,s),await this.subscriber.start().then(e).catch(t).finally(()=>{this.provider.off(k,s)})}),this.hasExperiencedNetworkDisruption=!1,e()})}catch(e){await this.subscriber.stop();const t=e;this.logger.warn({},t.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(e=>setTimeout(e,(0,l.toMiliseconds)(1*t))),t++}}startPingTimeout(){var e,t,s,i,r;if((0,p.Lln)())try{null!=(t=null==(e=this.provider)?void 0:e.connection)&&t.socket&&(null==(r=null==(i=null==(s=this.provider)?void 0:s.connection)?void 0:i.socket)||r.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new g.F(new f.A((0,p.jUZ)({sdkVersion:x,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:s,message:i}=e;await this.messages.set(s,i,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||0===s.length)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const i=this.messages.has(t,s);return i&&this.logger.warn(`Ignoring duplicate message: ${s}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),(0,m.isJsonRpcRequest)(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:s,message:i,publishedAt:r,attestation:n}=t.data,o={topic:s,message:i,publishedAt:r,transportType:U.relay,attestation:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(gs({type:"event",event:t.id},o)),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else(0,m.isJsonRpcResponse)(e)&&this.events.emit(P.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,D),this.events.emit(P.message,e))}async acknowledgePayload(e){const t=(0,m.formatJsonRpcResult)(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(T,this.onPayloadHandler),this.provider.off(O,this.onConnectHandler),this.provider.off(k,this.onDisconnectHandler),this.provider.off(R,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await(0,p.sc7)();(0,p.uym)(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(e=>this.logger.error(e,e?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(n.li.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&(0,p.sKr)())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(P.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},(0,l.toMiliseconds)(.1)))))}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise)return void await this.connectPromise;await this.connect()}}}function ws(){}function ys(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&"[object Object]"===Object.prototype.toString.call(e)}function bs(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function vs(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Es="[object Arguments]",Cs="[object Object]";function Is(e,t,s,i,r,n,o){const a=o(e,t,s,i,r,n);if(void 0!==a)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":case"function":return e===t;case"number":return e===t||Object.is(e,t);case"object":return Ns(e,t,n,o)}return Ns(e,t,n,o)}function Ns(e,t,s,i){if(Object.is(e,t))return!0;let r=vs(e),n=vs(t);if(r===Es&&(r=Cs),n===Es&&(n=Cs),r!==n)return!1;switch(r){case"[object String]":return e.toString()===t.toString();case"[object Number]":return function(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}(e.valueOf(),t.valueOf());case"[object Boolean]":case"[object Date]":case"[object Symbol]":return Object.is(e.valueOf(),t.valueOf());case"[object RegExp]":return e.source===t.source&&e.flags===t.flags;case"[object Function]":return e===t}const o=(s=s??new Map).get(e),a=s.get(t);if(null!=o&&null!=a)return o===t;s.set(e,t),s.set(t,e);try{switch(r){case"[object Map]":if(e.size!==t.size)return!1;for(const[r,n]of e.entries())if(!t.has(r)||!Is(n,t.get(r),r,e,t,s,i))return!1;return!0;case"[object Set]":{if(e.size!==t.size)return!1;const r=Array.from(e.values()),n=Array.from(t.values());for(let o=0;o<r.length;o++){const a=r[o],c=n.findIndex(r=>Is(a,r,void 0,e,t,s,i));if(-1===c)return!1;n.splice(c,1)}return!0}case"[object Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":case"[object BigUint64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object BigInt64Array]":case"[object Float32Array]":case"[object Float64Array]":if(typeof y<"u"&&y.isBuffer(e)!==y.isBuffer(t)||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Is(e[r],t[r],r,e,t,s,i))return!1;return!0;case"[object ArrayBuffer]":return e.byteLength===t.byteLength&&Ns(new Uint8Array(e),new Uint8Array(t),s,i);case"[object DataView]":return e.byteLength===t.byteLength&&e.byteOffset===t.byteOffset&&Ns(new Uint8Array(e),new Uint8Array(t),s,i);case"[object Error]":return e.name===t.name&&e.message===t.message;case Cs:{if(!(Ns(e.constructor,t.constructor,s,i)||ys(e)&&ys(t)))return!1;const r=[...Object.keys(e),...bs(e)],n=[...Object.keys(t),...bs(t)];if(r.length!==n.length)return!1;for(let n=0;n<r.length;n++){const o=r[n],a=e[o];if(!Object.hasOwn(t,o))return!1;if(!Is(a,t[o],o,e,t,s,i))return!1}return!0}default:return!1}}finally{s.delete(e),s.delete(t)}}var As=Object.defineProperty,_s=Object.getOwnPropertySymbols,Ss=Object.prototype.hasOwnProperty,Ps=Object.prototype.propertyIsEnumerable,Ts=(e,t,s)=>t in e?As(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Os=(e,t)=>{for(var s in t||(t={}))Ss.call(t,s)&&Ts(e,s,t[s]);if(_s)for(var s of _s(t))Ps.call(t,s)&&Ts(e,s,t[s]);return e},ks=(e,t,s)=>Ts(e,"symbol"!=typeof t?t+"":t,s);class Rs extends c.pi{constructor(e,t,s,i=E,r=void 0){super(e,t,s,i),this.core=e,this.logger=t,this.name=s,ks(this,"map",new Map),ks(this,"version","0.3"),ks(this,"cached",[]),ks(this,"initialized",!1),ks(this,"getKey"),ks(this,"storagePrefix",E),ks(this,"recentlyDeleted",[]),ks(this,"recentlyDeletedLimit",200),ks(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>{this.getKey&&null!==e&&!(0,p.b07)(e)?this.map.set(this.getKey(e),e):(0,p.CTo)(e)?this.map.set(e.id,e):(0,p.mr0)(e)&&this.map.set(e.topic,e)}),this.cached=[],this.initialized=!0)}),ks(this,"set",async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())}),ks(this,"get",e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e))),ks(this,"getAll",e=>(this.isInitialized(),e?this.values.filter(t=>Object.keys(e).every(s=>function(e,t){return function(e,t,s){return Is(e,t,void 0,void 0,void 0,void 0,s)}(e,t,ws)}(t[s],e[s]))):this.values)),ks(this,"update",async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const s=Os(Os({},this.getData(e)),t);this.map.set(e,s),await this.persist()}),ks(this,"delete",async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())}),this.logger=(0,a.U5)(t,this.name),this.storagePrefix=i,this.getKey=r}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xs=Object.defineProperty,Us=(e,t,s)=>((e,t,s)=>t in e?xs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ds{constructor(e,t){this.core=e,this.logger=t,Us(this,"name","pairing"),Us(this,"version","0.3"),Us(this,"events",new(r())),Us(this,"pairings"),Us(this,"initialized",!1),Us(this,"storagePrefix",E),Us(this,"ignoredPayloadTypes",[p.Lp_]),Us(this,"registeredMethods",[]),Us(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Us(this,"register",({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]}),Us(this,"create",async e=>{this.isInitialized();const t=(0,p.two)(),s=await this.core.crypto.setSymKey(t),i=(0,p.Xw0)(l.FIVE_MINUTES),r={protocol:_},n={topic:s,expiry:i,relay:r,active:!1,methods:e?.methods},o=(0,p.QJh)({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:t,relay:r,expiryTimestamp:i,methods:e?.methods});return this.events.emit(j.create,n),this.core.expirer.set(s,i),await this.pairings.set(s,n),await this.core.relayer.subscribe(s,{transportType:e?.transportType}),{topic:s,uri:o}}),Us(this,"pair",async e=>{this.isInitialized();const t=this.core.eventClient.createEvent({properties:{topic:e?.uri,trace:[J.pairing_started]}});this.isValidPair(e,t);const{topic:s,symKey:i,relay:r,expiryTimestamp:n,methods:o}=(0,p.wYp)(e.uri);let a;if(t.props.properties.topic=s,t.addTrace(J.pairing_uri_validation_success),t.addTrace(J.pairing_uri_not_expired),this.pairings.keys.includes(s)){if(a=this.pairings.get(s),t.addTrace(J.existing_pairing),a.active)throw t.setError(X.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);t.addTrace(J.pairing_not_expired)}const c=n||(0,p.Xw0)(l.FIVE_MINUTES),d={topic:s,relay:r,expiry:c,active:!1,methods:o};this.core.expirer.set(s,c),await this.pairings.set(s,d),t.addTrace(J.store_new_pairing),e.activatePairing&&await this.activate({topic:s}),this.events.emit(j.create,d),t.addTrace(J.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(i,s),t.addTrace(J.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{t.setError(X.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:r})}catch(e){throw t.setError(X.subscribe_pairing_topic_failure),e}return t.addTrace(J.subscribe_pairing_topic_success),d}),Us(this,"activate",async({topic:e})=>{this.isInitialized();const t=(0,p.Xw0)(l.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})}),Us(this,"ping",async e=>{this.isInitialized(),await this.isValidPing(e),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:s,resolve:i,reject:r}=(0,p.Wx8)();this.events.once((0,p.hEn)("pairing_ping",e),({error:e})=>{e?r(e):i()}),await s()}}),Us(this,"updateExpiry",async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})}),Us(this,"updateMetadata",async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})}),Us(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Us(this,"disconnect",async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",(0,p.Hjj)("USER_DISCONNECTED")),await this.deletePairing(t))}),Us(this,"formatUriFromPairing",e=>{this.isInitialized();const{topic:t,relay:s,expiry:i,methods:r}=e,n=this.core.crypto.keychain.get(t);return(0,p.QJh)({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:n,relay:s,expiryTimestamp:i,methods:r})}),Us(this,"sendRequest",async(e,t,s)=>{const i=(0,m.formatJsonRpcRequest)(t,s),r=await this.core.crypto.encode(e,i),n=B[t].req;return this.core.history.set(e,i),this.core.relayer.publish(e,r,n),i.id}),Us(this,"sendResult",async(e,t,s)=>{const i=(0,m.formatJsonRpcResult)(e,s),r=await this.core.crypto.encode(t,i),n=(await this.core.history.get(t,e)).request.method,o=B[n].res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(i)}),Us(this,"sendError",async(e,t,s)=>{const i=(0,m.formatJsonRpcError)(e,s),r=await this.core.crypto.encode(t,i),n=(await this.core.history.get(t,e)).request.method,o=B[n]?B[n].res:B.unregistered_method.res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(i)}),Us(this,"deletePairing",async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,(0,p.Hjj)("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])}),Us(this,"cleanup",async()=>{const e=this.pairings.getAll().filter(e=>(0,p._dF)(e.expiry));await Promise.all(e.map(e=>this.deletePairing(e.topic)))}),Us(this,"onRelayEventRequest",async e=>{const{topic:t,payload:s}=e;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(t,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(t,s);default:return await this.onUnknownRpcMethodRequest(t,s)}}),Us(this,"onRelayEventResponse",async e=>{const{topic:t,payload:s}=e,i=(await this.core.history.get(t,s.id)).request.method;return"wc_pairingPing"===i?this.onPairingPingResponse(t,s):this.onUnknownRpcMethodResponse(i)}),Us(this,"onPairingPingRequest",async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.events.emit(j.ping,{id:s,topic:e})}catch(t){await this.sendError(s,e,t),this.logger.error(t)}}),Us(this,"onPairingPingResponse",(e,t)=>{const{id:s}=t;setTimeout(()=>{(0,m.isJsonRpcResult)(t)?this.events.emit((0,p.hEn)("pairing_ping",s),{}):(0,m.isJsonRpcError)(t)&&this.events.emit((0,p.hEn)("pairing_ping",s),{error:t.error})},500)}),Us(this,"onPairingDeleteRequest",async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(j.delete,{id:s,topic:e})}catch(t){await this.sendError(s,e,t),this.logger.error(t)}}),Us(this,"onUnknownRpcMethodRequest",async(e,t)=>{const{id:s,method:i}=t;try{if(this.registeredMethods.includes(i))return;const t=(0,p.Hjj)("WC_METHOD_UNSUPPORTED",i);await this.sendError(s,e,t),this.logger.error(t)}catch(t){await this.sendError(s,e,t),this.logger.error(t)}}),Us(this,"onUnknownRpcMethodResponse",e=>{this.registeredMethods.includes(e)||this.logger.error((0,p.Hjj)("WC_METHOD_UNSUPPORTED",e))}),Us(this,"isValidPair",(e,t)=>{var s;if(!(0,p.TeY)(e)){const{message:s}=(0,p.GuA)("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(X.malformed_pairing_uri),new Error(s)}if(!(0,p.AYU)(e.uri)){const{message:s}=(0,p.GuA)("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(X.malformed_pairing_uri),new Error(s)}const i=(0,p.wYp)(e?.uri);if(null==(s=i?.relay)||!s.protocol){const{message:e}=(0,p.GuA)("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(X.malformed_pairing_uri),new Error(e)}if(null==i||!i.symKey){const{message:e}=(0,p.GuA)("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(X.malformed_pairing_uri),new Error(e)}if(null!=i&&i.expiryTimestamp&&(0,l.toMiliseconds)(i?.expiryTimestamp)<Date.now()){t.setError(X.pairing_expired);const{message:e}=(0,p.GuA)("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(e)}}),Us(this,"isValidPing",async e=>{if(!(0,p.TeY)(e)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)}),Us(this,"isValidDisconnect",async e=>{if(!(0,p.TeY)(e)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)}),Us(this,"isValidPairingTopic",async e=>{if(!(0,p.Qhg)(e,!1)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if((0,p._dF)(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=(0,p.GuA)("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}),this.core=e,this.logger=(0,a.U5)(t,this.name),this.pairings=new Rs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return(0,a.oI)(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(P.message,async e=>{const{topic:t,message:s,transportType:i}=e;if(this.pairings.keys.includes(t)&&i!==U.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const e=await this.core.crypto.decode(t,s);(0,m.isJsonRpcRequest)(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):(0,m.isJsonRpcResponse)(e)&&(await this.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e}),this.core.history.delete(t,e.id)),await this.core.relayer.messages.ack(t,s)}catch(e){this.logger.error(e)}})}registerExpirerEvents(){this.core.expirer.on(F.expired,async e=>{const{topic:t}=(0,p.c82)(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(j.expire,{topic:t}))})}}var Ls=Object.defineProperty,Ws=(e,t,s)=>((e,t,s)=>t in e?Ls(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ms extends c.lZ{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ws(this,"records",new Map),Ws(this,"events",new i.EventEmitter),Ws(this,"name","history"),Ws(this,"version","0.3"),Ws(this,"cached",[]),Ws(this,"initialized",!1),Ws(this,"storagePrefix",E),Ws(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.records.set(e.id,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ws(this,"set",(e,t,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:s}),this.records.has(t.id))return;const i={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:s,expiry:(0,p.Xw0)(l.THIRTY_DAYS)};this.records.set(i.id,i),this.persist(),this.events.emit(q,i)}),Ws(this,"resolve",async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response>"u"&&(t.response=(0,m.isJsonRpcError)(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit($,t))}),Ws(this,"get",async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t))),Ws(this,"delete",(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach(s=>{if(s.topic===e){if(typeof t<"u"&&s.id!==t)return;this.records.delete(s.id),this.events.emit(H,s)}}),this.persist()}),Ws(this,"exists",async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e)),Ws(this,"on",(e,t)=>{this.events.on(e,t)}),Ws(this,"once",(e,t)=>{this.events.once(e,t)}),Ws(this,"off",(e,t)=>{this.events.off(e,t)}),Ws(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=(0,a.U5)(t,this.name)}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:(0,m.formatJsonRpcRequest)(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit("history_sync")}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(q,e=>{const t=q;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on($,e=>{const t=$;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(H,e=>{const t=H;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(n.li.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{(0,l.toMiliseconds)(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(H,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Bs=Object.defineProperty,js=(e,t,s)=>((e,t,s)=>t in e?Bs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class qs extends c.Vx{constructor(e,t){super(e,t),this.core=e,this.logger=t,js(this,"expirations",new Map),js(this,"events",new i.EventEmitter),js(this,"name","expirer"),js(this,"version","0.3"),js(this,"cached",[]),js(this,"initialized",!1),js(this,"storagePrefix",E),js(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.expirations.set(e.target,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),js(this,"has",e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}}),js(this,"set",(e,t)=>{this.isInitialized();const s=this.formatTarget(e),i={target:s,expiry:t};this.expirations.set(s,i),this.checkExpiry(s,i),this.events.emit(F.created,{target:s,expiration:i})}),js(this,"get",e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)}),js(this,"del",e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),s=this.getExpiration(t);this.expirations.delete(t),this.events.emit(F.deleted,{target:t,expiration:s})}}),js(this,"on",(e,t)=>{this.events.on(e,t)}),js(this,"once",(e,t)=>{this.events.once(e,t)}),js(this,"off",(e,t)=>{this.events.off(e,t)}),js(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=(0,a.U5)(t,this.name)}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if("string"==typeof e)return(0,p.ADD)(e);if("number"==typeof e)return(0,p.gOF)(e);const{message:t}=(0,p.GuA)("UNKNOWN_TYPE","Target type: "+typeof e);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(F.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:s}=t;(0,l.toMiliseconds)(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(F.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(n.li.pulse,()=>this.checkExpirations()),this.events.on(F.created,e=>{const t=F.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(F.expired,e=>{const t=F.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(F.deleted,e=>{const t=F.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $s=Object.defineProperty,Hs=(e,t,s)=>((e,t,s)=>t in e?$s(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Fs extends c.zl{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,Hs(this,"name","verify-api"),Hs(this,"abortController"),Hs(this,"isDevEnv"),Hs(this,"verifyUrlV3",K),Hs(this,"storagePrefix",E),Hs(this,"version",2),Hs(this,"publicKey"),Hs(this,"fetchPromise"),Hs(this,"init",async()=>{var e;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,l.toMiliseconds)(null==(e=this.publicKey)?void 0:e.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Hs(this,"register",async e=>{if(!(0,p.BdH)()||this.isDevEnv)return;const t=window.location.origin,{id:s,decryptedId:i}=e,r=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${t}&id=${s}&decryptedId=${i}`;try{const e=(0,w.getDocument)(),t=this.startAbortTimer(5*l.ONE_SECOND),i=await new Promise((i,n)=>{const o=()=>{window.removeEventListener("message",c),e.body.removeChild(a),n("attestation aborted")};this.abortController.signal.addEventListener("abort",o);const a=e.createElement("iframe");a.src=r,a.style.display="none",a.addEventListener("error",o,{signal:this.abortController.signal});const c=r=>{if(r.data&&"string"==typeof r.data)try{const n=JSON.parse(r.data);if("verify_attestation"===n.type){if((0,h.Cq)(n.attestation).payload.id!==s)return;clearInterval(t),e.body.removeChild(a),this.abortController.signal.removeEventListener("abort",o),window.removeEventListener("message",c),i(null===n.attestation?"":n.attestation)}}catch(e){this.logger.warn(e)}};e.body.appendChild(a),window.addEventListener("message",c,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",i),i}catch(e){this.logger.warn(e)}return""}),Hs(this,"resolve",async e=>{if(this.isDevEnv)return"";const{attestationId:t,hash:s,encryptedId:i}=e;if(""===t)return void this.logger.debug("resolve: attestationId is empty, skipping");if(t){if((0,h.Cq)(t).payload.id!==i)return;const e=await this.isValidJwtAttestation(t);if(e)return e.isVerified?e:void this.logger.warn("resolve: jwt attestation: origin url not verified")}if(!s)return;const r=this.getVerifyUrl(e?.verifyUrl);return this.fetchAttestation(s,r)}),Hs(this,"fetchAttestation",async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);const s=this.startAbortTimer(5*l.ONE_SECOND),i=await fetch(`${t}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(s),200===i.status?await i.json():void 0}),Hs(this,"getVerifyUrl",e=>{let t=e||z;return G.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${z}`),t=z),t}),Hs(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(l.FIVE_SECONDS),t=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await t.json()}catch(e){this.logger.warn(e)}}),Hs(this,"persistPublicKey",async e=>{this.logger.debug("persisting public key to local storage",e),await this.store.setItem(this.storeKey,e),this.publicKey=e}),Hs(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Hs(this,"isValidJwtAttestation",async e=>{const t=await this.getPublicKey();try{if(t)return this.validateAttestation(e,t)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}const s=await this.fetchAndPersistPublicKey();try{if(s)return this.validateAttestation(e,s)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}}),Hs(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Hs(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async e=>{const t=await this.fetchPublicKey();t&&(await this.persistPublicKey(t),e(t))});const e=await this.fetchPromise;return this.fetchPromise=void 0,e}),Hs(this,"validateAttestation",(e,t)=>{const s=(0,p.U0i)(e,t.publicKey),i={hasExpired:(0,l.toMiliseconds)(s.exp)<Date.now(),payload:s};if(i.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:i.payload.origin,isScam:i.payload.isScam,isVerified:i.payload.isVerified}}),this.logger=(0,a.U5)(t,this.name),this.abortController=new AbortController,this.isDevEnv=(0,p.w8K)(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return(0,a.oI)(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),(0,l.toMiliseconds)(e))}}var Vs=Object.defineProperty,zs=(e,t,s)=>((e,t,s)=>t in e?Vs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ks extends c.GF{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,zs(this,"context","echo"),zs(this,"registerDeviceToken",async e=>{const{clientId:t,token:s,notificationType:i,enableEncrypted:r=!1}=e,n=`https://echo.walletconnect.com/${this.projectId}/clients`;await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t,type:i,token:s,always_raw:r})})}),this.logger=(0,a.U5)(t,this.context)}}var Gs=Object.defineProperty,Js=Object.getOwnPropertySymbols,Xs=Object.prototype.hasOwnProperty,Ys=Object.prototype.propertyIsEnumerable,Zs=(e,t,s)=>t in e?Gs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Qs=(e,t)=>{for(var s in t||(t={}))Xs.call(t,s)&&Zs(e,s,t[s]);if(Js)for(var s of Js(t))Ys.call(t,s)&&Zs(e,s,t[s]);return e},ei=(e,t,s)=>Zs(e,"symbol"!=typeof t?t+"":t,s);class ti extends c.$Q{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,ei(this,"context","event-client"),ei(this,"storagePrefix",E),ei(this,"storageVersion",.1),ei(this,"events",new Map),ei(this,"shouldPersist",!1),ei(this,"init",async()=>{if(!(0,p.w8K)())try{const e={eventId:(0,p.gZm)(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:(0,p.ojD)(this.core.relayer.protocol,this.core.relayer.version,x)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}}),ei(this,"createEvent",e=>{const{event:t="ERROR",type:s="",properties:{topic:i,trace:r}}=e,n=(0,p.gZm)(),o=this.core.projectId||"",a=Date.now(),c=Qs({eventId:n,timestamp:a,props:{event:t,type:s,properties:{topic:i,trace:r}},bundleId:o,domain:this.getAppDomain()},this.setMethods(n));return this.telemetryEnabled&&(this.events.set(n,c),this.shouldPersist=!0),c}),ei(this,"getEvent",e=>{const{eventId:t,topic:s}=e;if(t)return this.events.get(t);const i=Array.from(this.events.values()).find(e=>e.props.properties.topic===s);return i?Qs(Qs({},i),this.setMethods(i.eventId)):void 0}),ei(this,"deleteEvent",e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0}),ei(this,"setEventListeners",()=>{this.core.heartbeat.on(n.li.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(e=>{(0,l.fromMiliseconds)(Date.now())-(0,l.fromMiliseconds)(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)})})}),ei(this,"setMethods",e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)})),ei(this,"addTrace",(e,t)=>{const s=this.events.get(e);s&&(s.props.properties.trace.push(t),this.events.set(e,s),this.shouldPersist=!0)}),ei(this,"setError",(e,t)=>{const s=this.events.get(e);s&&(s.props.type=t,s.timestamp=Date.now(),this.events.set(e,s),this.shouldPersist=!0)}),ei(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),ei(this,"restore",async()=>{try{const e=await this.core.storage.getItem(this.storageKey)||[];if(!e.length)return;e.forEach(e=>{this.events.set(e.eventId,Qs(Qs({},e),this.setMethods(e.eventId)))})}catch(e){this.logger.warn(e)}}),ei(this,"submit",async()=>{if(!this.telemetryEnabled||0===this.events.size)return;const e=[];for(const[t,s]of this.events)s.props.type&&e.push(s);if(0!==e.length)try{if((await this.sendEvent(e)).ok)for(const t of e)this.events.delete(t.eventId),this.shouldPersist=!0}catch(e){this.logger.warn(e)}}),ei(this,"sendEvent",async e=>{const t=this.getAppDomain()?"":"&sp=desktop";return await fetch(`https://pulse.walletconnect.org/batch?projectId=${this.core.projectId}&st=events_sdk&sv=js-${x}${t}`,{method:"POST",body:JSON.stringify(e)})}),ei(this,"getAppDomain",()=>(0,p.lFF)().url),this.logger=(0,a.U5)(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var si=Object.defineProperty,ii=Object.getOwnPropertySymbols,ri=Object.prototype.hasOwnProperty,ni=Object.prototype.propertyIsEnumerable,oi=(e,t,s)=>t in e?si(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ai=(e,t)=>{for(var s in t||(t={}))ri.call(t,s)&&oi(e,s,t[s]);if(ii)for(var s of ii(t))ni.call(t,s)&&oi(e,s,t[s]);return e},ci=(e,t,s)=>oi(e,"symbol"!=typeof t?t+"":t,s);class li extends c.ZP{constructor(e){var t;super(e),ci(this,"protocol","wc"),ci(this,"version",2),ci(this,"name",v),ci(this,"relayUrl"),ci(this,"projectId"),ci(this,"customStoragePrefix"),ci(this,"events",new i.EventEmitter),ci(this,"logger"),ci(this,"heartbeat"),ci(this,"relayer"),ci(this,"crypto"),ci(this,"storage"),ci(this,"history"),ci(this,"expirer"),ci(this,"pairing"),ci(this,"verify"),ci(this,"echoClient"),ci(this,"linkModeSupportedApps"),ci(this,"eventClient"),ci(this,"initialized",!1),ci(this,"logChunkController"),ci(this,"on",(e,t)=>this.events.on(e,t)),ci(this,"once",(e,t)=>this.events.once(e,t)),ci(this,"off",(e,t)=>this.events.off(e,t)),ci(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),ci(this,"dispatchEnvelope",({topic:e,message:t,sessionExists:s})=>{if(!e||!t)return;const i={topic:e,message:t,publishedAt:Date.now(),transportType:U.link_mode};this.relayer.onLinkMessageEvent(i,{sessionExists:s})});const s=this.getGlobalCore(e?.customStoragePrefix);if(s)try{return this.customStoragePrefix=s.customStoragePrefix,this.logger=s.logger,this.heartbeat=s.heartbeat,this.crypto=s.crypto,this.history=s.history,this.expirer=s.expirer,this.storage=s.storage,this.relayer=s.relayer,this.pairing=s.pairing,this.verify=s.verify,this.echoClient=s.echoClient,this.linkModeSupportedApps=s.linkModeSupportedApps,this.eventClient=s.eventClient,this.initialized=s.initialized,this.logChunkController=s.logChunkController,s}catch(e){console.warn("Failed to copy global core",e)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||S,this.customStoragePrefix=null!=e&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=(0,a.iP)({level:"string"==typeof e?.logger&&e.logger?e.logger:"error",name:v}),{logger:c,chunkLoggerController:l}=(0,a.D5)({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=l,null!=(t=this.logChunkController)&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var e,t;null!=(e=this.logChunkController)&&e.downloadLogsBlobInBrowser&&(null==(t=this.logChunkController)||t.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=(0,a.U5)(c,this.name),this.heartbeat=new n.VH,this.crypto=new Pt(this,this.logger,e?.keychain),this.history=new Ms(this,this.logger),this.expirer=new qs(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new o.A(ai(ai({},C),e?.storageOptions)),this.relayer=new fs({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Ds(this,this.logger),this.verify=new Fs(this,this.logger,this.storage),this.echoClient=new Ks(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new ti(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new li(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem("WALLETCONNECT_CLIENT_ID",s),t}get context(){return(0,a.oI)(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return null==(e=this.logChunkController)?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(L,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(L)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,s=`${t}_count`;return globalThis[s]=(globalThis[s]||0)+1,globalThis[s]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[s]} times.`),globalThis[t]}catch(e){return void console.warn("Failed to get global WalletConnect core",e)}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${(null==(t=e.opts)?void 0:t.customStoragePrefix)||""}`;globalThis[s]=e}catch(e){console.warn("Failed to set global WalletConnect core",e)}}isGlobalCoreDisabled(){try{return typeof b<"u"&&"true"===b.env.DISABLE_GLOBAL_CORE}catch{return!0}}}const di=li},92492:(e,t,s)=>{s.d(t,{P:()=>c});var i=s(89168),r=s(39150),n=s(22143);const o=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),a=(0,i.BX)({...o}),c={state:a,subscribeKey:(e,t)=>(0,r.u$)(a,e,t),showLoading(e,t={}){this._showMessage({message:e,variant:"loading",...t})},showSuccess(e){this._showMessage({message:e,variant:"success"})},showSvg(e,t){this._showMessage({message:e,svg:t})},showError(e){const t=n.w.parseError(e);this._showMessage({message:t,variant:"error"})},hide(){a.message=o.message,a.variant=o.variant,a.svg=o.svg,a.open=o.open,a.autoClose=o.autoClose},_showMessage({message:e,svg:t,variant:s="success",autoClose:i=o.autoClose}){a.open?(a.open=!1,setTimeout(()=>{a.message=e,a.variant=s,a.svg=t,a.open=!0,a.autoClose=i},150)):(a.message=e,a.variant=s,a.svg=t,a.open=!0,a.autoClose=i)}}},93474:(e,t,s)=>{s.d(t,{N:()=>y});var i=s(89168),r=s(39150),n=s(86454),o=s(22143),a=s(35646),c=s(9732),l=s(11847),d=s(6262),h=s(98299),p=s(83077),u=s(47981),g=s(1420);const m=o.w.getApiUrl(),f=new a.Z({baseUrl:m,clientId:null}),w=(0,i.BX)({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),y={state:w,subscribeKey:(e,t)=>(0,r.u$)(w,e,t),_getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=g.H.state;return{projectId:e,st:t||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions:e=>g.H.state.isUniversalProvider?e.filter(e=>Boolean(e.mobile_link||e.desktop_link||e.webapp_link)):e,async _fetchWalletImage(e){const t=`${f.baseUrl}/getWalletImage/${e}`,s=await f.getBlob({path:t,params:y._getSdkProperties()});d.j.setWalletImage(e,URL.createObjectURL(s))},async _fetchNetworkImage(e){const t=`${f.baseUrl}/public/getAssetImage/${e}`,s=await f.getBlob({path:t,params:y._getSdkProperties()});d.j.setNetworkImage(e,URL.createObjectURL(s))},async _fetchConnectorImage(e){const t=`${f.baseUrl}/public/getAssetImage/${e}`,s=await f.getBlob({path:t,params:y._getSdkProperties()});d.j.setConnectorImage(e,URL.createObjectURL(s))},async _fetchCurrencyImage(e){const t=`${f.baseUrl}/public/getCurrencyImage/${e}`,s=await f.getBlob({path:t,params:y._getSdkProperties()});d.j.setCurrencyImage(e,URL.createObjectURL(s))},async _fetchTokenImage(e){const t=`${f.baseUrl}/public/getTokenImage/${e}`,s=await f.getBlob({path:t,params:y._getSdkProperties()});d.j.setTokenImage(e,URL.createObjectURL(s))},_filterWalletsByPlatform:e=>o.w.isMobile()?e?.filter(e=>!!e.mobile_link||(e.id===c.O.COINBASE.id||"solana"===h.W.state.activeChain&&(e.id===c.O.SOLFLARE.id||e.id===c.O.PHANTOM.id))):e,fetchProjectConfig:async()=>(await f.get({path:"/appkit/v1/config",params:y._getSdkProperties()})).features,async fetchAllowedOrigins(){try{const{allowedOrigins:e}=await f.get({path:"/projects/v1/origins",params:y._getSdkProperties()});return e}catch(e){return[]}},async fetchNetworkImages(){const e=h.W.getAllRequestedCaipNetworks(),t=e?.map(({assets:e})=>e?.imageId).filter(Boolean).filter(e=>!n.$.getNetworkImageById(e));t&&await Promise.allSettled(t.map(e=>y._fetchNetworkImage(e)))},async fetchConnectorImages(){const{connectors:e}=p.a.state,t=e.map(({imageId:e})=>e).filter(Boolean);await Promise.allSettled(t.map(e=>y._fetchConnectorImage(e)))},async fetchCurrencyImages(e=[]){await Promise.allSettled(e.map(e=>y._fetchCurrencyImage(e)))},async fetchTokenImages(e=[]){await Promise.allSettled(e.map(e=>y._fetchTokenImage(e)))},async fetchWallets(e){const t=e.exclude??[];y._getSdkProperties().sv.startsWith("html-core-")&&t.push(...Object.values(c.O).map(e=>e.id));const s=await f.get({path:"/getWallets",params:{...y._getSdkProperties(),...e,page:String(e.page),entries:String(e.entries),include:e.include?.join(","),exclude:t.join(",")}});return{data:y._filterWalletsByPlatform(s?.data)||[],count:s?.count}},async fetchFeaturedWallets(){const{featuredWalletIds:e}=g.H.state;if(e?.length){const t={...y._getSdkProperties(),page:1,entries:e?.length??4,include:e},{data:s}=await y.fetchWallets(t),i=[...s].sort((t,s)=>e.indexOf(t.id)-e.indexOf(s.id)),r=i.map(e=>e.image_id).filter(Boolean);await Promise.allSettled(r.map(e=>y._fetchWalletImage(e))),w.featured=i,w.allFeatured=i}},async fetchRecommendedWallets(){try{w.isFetchingRecommendedWallets=!0;const{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:s}=g.H.state,i={page:1,entries:4,include:e,exclude:[...t??[],...s??[]].filter(Boolean),chains:h.W.getRequestedCaipNetworkIds().join(",")},{data:r,count:n}=await y.fetchWallets(i),o=l.i.getRecentWallets(),a=r.map(e=>e.image_id).filter(Boolean),c=o.map(e=>e.image_id).filter(Boolean);await Promise.allSettled([...a,...c].map(e=>y._fetchWalletImage(e))),w.recommended=r,w.allRecommended=r,w.count=n??0}catch{}finally{w.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:e}){const{includeWalletIds:t,excludeWalletIds:s,featuredWalletIds:i}=g.H.state,r=h.W.getRequestedCaipNetworkIds().join(","),n={page:e,entries:40,include:t,exclude:[...w.recommended.map(({id:e})=>e),...s??[],...i??[]].filter(Boolean),chains:r},{data:a,count:c}=await y.fetchWallets(n),l=a.slice(0,20).map(e=>e.image_id).filter(Boolean);await Promise.allSettled(l.map(e=>y._fetchWalletImage(e))),w.wallets=o.w.uniqueBy([...w.wallets,...y._filterOutExtensions(a)],"id").filter(e=>e.chains?.some(e=>r.includes(e))),w.count=c>w.count?c:w.count,w.page=e},async initializeExcludedWallets({ids:e}){const t={page:1,entries:e.length,include:e},{data:s}=await y.fetchWallets(t);s&&s.forEach(e=>{w.excludedWallets.push({rdns:e.rdns,name:e.name})})},async searchWallet({search:e,badge:t}){const{includeWalletIds:s,excludeWalletIds:i}=g.H.state,r=h.W.getRequestedCaipNetworkIds().join(",");w.search=[];const n={page:1,entries:100,search:e?.trim(),badge_type:t,include:s,exclude:i,chains:r},{data:a}=await y.fetchWallets(n);u.E.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:t??"",search:e??""}});const c=a.map(e=>e.image_id).filter(Boolean);await Promise.allSettled([...c.map(e=>y._fetchWalletImage(e)),o.w.wait(300)]),w.search=y._filterOutExtensions(a)},initPromise:(e,t)=>w.promises[e]||(w.promises[e]=t()),prefetch({fetchConnectorImages:e=!0,fetchFeaturedWallets:t=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:i=!0}={}){const r=[e&&y.initPromise("connectorImages",y.fetchConnectorImages),t&&y.initPromise("featuredWallets",y.fetchFeaturedWallets),s&&y.initPromise("recommendedWallets",y.fetchRecommendedWallets),i&&y.initPromise("networkImages",y.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(r)},prefetchAnalyticsConfig(){g.H.state.features?.analytics&&y.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:e}=await f.get({path:"/getAnalyticsConfig",params:y._getSdkProperties()});g.H.setFeatures({analytics:e})}catch(e){g.H.setFeatures({analytics:!1})}},filterByNamespaces(e){if(!e?.length)return w.featured=w.allFeatured,void(w.recommended=w.allRecommended);const t=h.W.getRequestedCaipNetworkIds().join(",");w.featured=w.allFeatured.filter(e=>e.chains?.some(e=>t.includes(e))),w.recommended=w.allRecommended.filter(e=>e.chains?.some(e=>t.includes(e))),w.filteredWallets=w.wallets.filter(e=>e.chains?.some(e=>t.includes(e)))},clearFilterByNamespaces(){w.filteredWallets=[]},setFilterByNamespace(e){if(!e)return w.featured=w.allFeatured,void(w.recommended=w.allRecommended);const t=h.W.getRequestedCaipNetworkIds().join(",");w.featured=w.allFeatured.filter(e=>e.chains?.some(e=>t.includes(e))),w.recommended=w.allRecommended.filter(e=>e.chains?.some(e=>t.includes(e))),w.filteredWallets=w.wallets.filter(e=>e.chains?.some(e=>t.includes(e)))}}},93797:(e,t,s)=>{s.d(t,{r:()=>l});var i=s(23464),r=s(38851),n=s(25562),o=s(93384);i.extend(n),i.extend(o);const a={...r,name:"en-web3-modal",relativeTime:{future:"in %s",past:"%s ago",s:"%d sec",m:"1 min",mm:"%d min",h:"1 hr",hh:"%d hrs",d:"1 d",dd:"%d d",M:"1 mo",MM:"%d mo",y:"1 yr",yy:"%d yr"}},c=["January","February","March","April","May","June","July","August","September","October","November","December"];i.locale("en-web3-modal",a);const l={getMonthNameByIndex:e=>c[e],getYear:(e=(new Date).toISOString())=>i(e).year(),getRelativeDateFromNow:e=>i(e).locale("en-web3-modal").fromNow(!0),formatDate:(e,t="DD MMM")=>i(e).format(t)}},94311:(e,t,s)=>{s.d(t,{Rn:()=>r.R,tW:()=>i.t});var i=s(56335),r=s(64525);s(65508)},96517:(e,t,s)=>{s.d(t,{X:()=>c}),s(18338);var i=s(72269),r=s(46362),n=s(98299),o=s(82868),a=s(22129);class c{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,this.getCaipNetworks=e=>n.W.getCaipNetworks(e),e&&this.construct(e)}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.getCaipNetworks(this.namespace)}setAuthProvider(e){this.addConnector({id:i.o.CONNECTOR_ID.AUTH,type:"AUTH",name:i.o.CONNECTOR_NAMES.AUTH,provider:e,imageId:o.L.ConnectorImageIds[i.o.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(e=>!t.has(e.id)&&(t.add(e.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,t){r.U.setStatus(e,t)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(t)}off(e,t){const s=this.eventListeners.get(e);s&&s.delete(t)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,t){const s=this.eventListeners.get(e);s&&s.forEach(e=>e(t))}async connectWalletConnect(e){const t=this.getWalletConnectConnector();return{clientId:(await t.connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:t,providerType:s}=e;if(!e.provider)return;const i="provider"in e.provider?e.provider.provider:e.provider;if("WALLET_CONNECT"!==s){if(i&&"AUTH"===s){const e=i,s=r.U.state.preferredAccountTypes?.[t.chainNamespace];await e.switchNetwork(t.caipNetworkId);const n=await e.getUser({chainId:t.caipNetworkId,preferredAccountType:s});this.emit("switchNetwork",n)}}else i.setDefaultChain(t.caipNetworkId)}getWalletConnectConnector(){const e=this.connectors.find(e=>e instanceof a.F);if(!e)throw new Error("WalletConnectConnector not found");return e}}},98299:(e,t,s)=>{s.d(t,{W:()=>N});var i=s(89168),r=s(39150),n=s(67902),o=s(72269),a=s(3555),c=s(22143),l=s(11847),d=s(37834),h=s(46362),p=s(86792),u=s(83077),g=s(47981),m=s(88759),f=s(1420),w=s(68251),y=s(72397),b=s(37686);const v={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},E={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},C=(0,i.BX)({chains:(0,r.zC)(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),I={state:C,subscribe:e=>(0,i.B1)(C,()=>{e(C)}),subscribeKey:(e,t)=>(0,r.u$)(C,e,t),subscribeChainProp(e,t,s){let r;return(0,i.B1)(C.chains,()=>{const i=s||C.activeChain;if(i){const s=C.chains.get(i)?.[e];r!==s&&(r=s,t(s))}})},initialize(e,t,s){const{chainId:r,namespace:n}=l.i.getActiveNetworkProps(),o=t?.find(e=>e.id.toString()===r?.toString()),a=e.find(e=>e?.namespace===n)||e?.[0],c=e.map(e=>e.namespace).filter(e=>void 0!==e),d=f.H.state.enableEmbedded?new Set([...c]):new Set([...t?.map(e=>e.chainNamespace)??[]]);0!==e?.length&&a||(C.noAdapters=!0),C.noAdapters||(C.activeChain=a?.namespace,C.activeCaipNetwork=o,N.setChainNetworkData(a?.namespace,{caipNetwork:o}),C.activeChain&&w.z.set({activeChain:a?.namespace})),d.forEach(e=>{const r=t?.filter(t=>t.chainNamespace===e);N.state.chains.set(e,{namespace:e,networkState:(0,i.BX)({...E,caipNetwork:r?.[0]}),accountState:(0,i.BX)(v),caipNetworks:r??[],...s}),N.setRequestedCaipNetworks(r??[],e)})},removeAdapter(e){if(C.activeChain===e){const t=Array.from(C.chains.entries()).find(([t])=>t!==e);if(t){const e=t[1]?.caipNetworks?.[0];e&&N.setActiveCaipNetwork(e)}}C.chains.delete(e)},addAdapter(e,{networkControllerClient:t,connectionControllerClient:s},i){C.chains.set(e.namespace,{namespace:e.namespace,networkState:{...E,caipNetwork:i[0]},accountState:v,caipNetworks:i,connectionControllerClient:s,networkControllerClient:t}),N.setRequestedCaipNetworks(i?.filter(t=>t.chainNamespace===e.namespace)??[],e.namespace)},addNetwork(e){const t=C.chains.get(e.chainNamespace);if(t){const s=[...t.caipNetworks||[]];t.caipNetworks?.find(t=>t.id===e.id)||s.push(e),C.chains.set(e.chainNamespace,{...t,caipNetworks:s}),N.setRequestedCaipNetworks(s,e.chainNamespace),u.a.filterByNamespace(e.chainNamespace,!0)}},removeNetwork(e,t){const s=C.chains.get(e);if(s){const i=C.activeCaipNetwork?.id===t,r=[...s.caipNetworks?.filter(e=>e.id!==t)||[]];i&&s?.caipNetworks?.[0]&&N.setActiveCaipNetwork(s.caipNetworks[0]),C.chains.set(e,{...s,caipNetworks:r}),N.setRequestedCaipNetworks(r||[],e),0===r.length&&u.a.filterByNamespace(e,!1)}},setAdapterNetworkState(e,t){const s=C.chains.get(e);s&&(s.networkState={...s.networkState||E,...t},C.chains.set(e,s))},setChainAccountData(e,t,s=!0){if(!e)throw new Error("Chain is required to update chain account data");const i=C.chains.get(e);if(i){const s={...i.accountState||v,...t};C.chains.set(e,{...i,accountState:s}),1!==C.chains.size&&C.activeChain!==e||(t.caipAddress&&(C.activeCaipAddress=t.caipAddress),h.U.replaceState(s))}},setChainNetworkData(e,t){if(!e)return;const s=C.chains.get(e);if(s){const i={...s.networkState||E,...t};C.chains.set(e,{...s,networkState:i})}},setAccountProp(e,t,s,i=!0){N.setChainAccountData(s,{[e]:t},i),"status"===e&&"disconnected"===t&&s&&u.a.removeConnectorId(s)},setActiveNamespace(e){C.activeChain=e;const t=e?C.chains.get(e):void 0,s=t?.networkState?.caipNetwork;s?.id&&e&&(C.activeCaipAddress=t?.accountState?.caipAddress,C.activeCaipNetwork=s,N.setChainNetworkData(e,{caipNetwork:s}),l.i.setActiveCaipNetworkId(s?.caipNetworkId),w.z.set({activeChain:e,selectedNetworkId:s?.caipNetworkId}))},setActiveCaipNetwork(e){if(!e)return;C.activeChain!==e.chainNamespace&&N.setIsSwitchingNamespace(!0);const t=C.chains.get(e.chainNamespace);C.activeChain=e.chainNamespace,C.activeCaipNetwork=e,N.setChainNetworkData(e.chainNamespace,{caipNetwork:e}),C.activeCaipAddress=t?.accountState?.address?`${e.chainNamespace}:${e.id}:${t?.accountState?.address}`:void 0,N.setAccountProp("caipAddress",C.activeCaipAddress,e.chainNamespace),t&&h.U.replaceState(t.accountState),b.R.resetSend(),w.z.set({activeChain:C.activeChain,selectedNetworkId:C.activeCaipNetwork?.caipNetworkId}),l.i.setActiveCaipNetworkId(e.caipNetworkId),N.checkIfSupportedNetwork(e.chainNamespace)||!f.H.state.enableNetworkSwitch||f.H.state.allowUnsupportedChain||p.x.state.wcBasic||N.showUnsupportedChainUI()},addCaipNetwork(e){if(!e)return;const t=C.chains.get(e.chainNamespace);t&&t?.caipNetworks?.push(e)},async switchActiveNamespace(e){if(!e)return;const t=e!==N.state.activeChain,s=N.getNetworkData(e)?.caipNetwork,i=N.getCaipNetworkByNamespace(e,s?.id);t&&i&&await N.switchActiveNetwork(i)},async switchActiveNetwork(e){const t=N.state.chains.get(N.state.activeChain),s=!t?.caipNetworks?.some(e=>e.id===C.activeCaipNetwork?.id),i=N.getNetworkControllerClient(e.chainNamespace);if(i){try{await i.switchCaipNetwork(e),s&&m.W.close()}catch(e){y.I.goBack()}g.E.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:e.caipNetworkId}})}},getNetworkControllerClient(e){const t=e||C.activeChain,s=C.chains.get(t);if(!s)throw new Error("Chain adapter not found");if(!s.networkControllerClient)throw new Error("NetworkController client not set");return s.networkControllerClient},getConnectionControllerClient(e){const t=e||C.activeChain;if(!t)throw new Error("Chain is required to get connection controller client");const s=C.chains.get(t);if(!s?.connectionControllerClient)throw new Error("ConnectionController client not set");return s.connectionControllerClient},getAccountProp(e,t){let s=C.activeChain;if(t&&(s=t),!s)return;const i=C.chains.get(s)?.accountState;return i?i[e]:void 0},getNetworkProp(e,t){const s=C.chains.get(t)?.networkState;if(s)return s[e]},getRequestedCaipNetworks(e){const t=C.chains.get(e),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:i=[]}=t?.networkState||{};return c.w.sortRequestedNetworks(s,i)},getAllRequestedCaipNetworks(){const e=[];return C.chains.forEach(t=>{const s=N.getRequestedCaipNetworks(t.namespace);e.push(...s)}),e},setRequestedCaipNetworks(e,t){N.setAdapterNetworkState(t,{requestedCaipNetworks:e});const s=N.getAllRequestedCaipNetworks().map(e=>e.chainNamespace),i=Array.from(new Set(s));u.a.filterByNamespaces(i)},getAllApprovedCaipNetworkIds(){const e=[];return C.chains.forEach(t=>{const s=N.getApprovedCaipNetworkIds(t.namespace);e.push(...s)}),e},getActiveCaipNetwork:()=>C.activeCaipNetwork,getActiveCaipAddress:()=>C.activeCaipAddress,getApprovedCaipNetworkIds(e){const t=C.chains.get(e);return t?.networkState?.approvedCaipNetworkIds||[]},async setApprovedCaipNetworksData(e){const t=N.getNetworkControllerClient(),s=await(t?.getApprovedCaipNetworksData());N.setAdapterNetworkState(e,{approvedCaipNetworkIds:s?.approvedCaipNetworkIds,supportsAllNetworks:s?.supportsAllNetworks})},checkIfSupportedNetwork(e,t){const s=t||C.activeCaipNetwork,i=N.getRequestedCaipNetworks(e);return!i.length||i?.some(e=>e.id===s?.id)},checkIfSupportedChainId(e){if(!C.activeChain)return!0;const t=N.getRequestedCaipNetworks(C.activeChain);return t?.some(t=>t.id===e)},setSmartAccountEnabledNetworks(e,t){N.setAdapterNetworkState(t,{smartAccountEnabledNetworks:e})},checkIfSmartAccountEnabled(){const e=n.L.caipNetworkIdToNumber(C.activeCaipNetwork?.caipNetworkId),t=C.activeChain;if(!t||!e)return!1;const s=N.getNetworkProp("smartAccountEnabledNetworks",t);return Boolean(s?.includes(Number(e)))},getActiveNetworkTokenAddress(){const e=C.activeCaipNetwork?.chainNamespace||"eip155";return`${e}:${C.activeCaipNetwork?.id||1}:${a.oU.NATIVE_TOKEN_ADDRESS[e]}`},showUnsupportedChainUI(){m.W.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const e=C.activeCaipNetwork;return Boolean(e?.chainNamespace&&a.oU.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(e.chainNamespace))},resetNetwork(e){N.setAdapterNetworkState(e,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(e){const t=e;if(!t)throw new Error("Chain is required to set account prop");C.activeCaipAddress=void 0,N.setChainAccountData(t,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountTypes:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),u.a.removeConnectorId(t)},setIsSwitchingNamespace(e){C.isSwitchingNamespace=e},getFirstCaipNetworkSupportsAuthConnector(){const e=[];let t;if(C.chains.forEach(t=>{o.o.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(e=>e===t.namespace)&&t.namespace&&e.push(t.namespace)}),e.length>0){const s=e[0];return t=s?C.chains.get(s)?.caipNetworks?.[0]:void 0,t}},getAccountData:e=>e?N.state.chains.get(e)?.accountState:h.U.state,getNetworkData(e){const t=e||C.activeChain;if(t)return N.state.chains.get(t)?.networkState},getCaipNetworkByNamespace(e,t){if(!e)return;const s=N.state.chains.get(e),i=s?.caipNetworks?.find(e=>e.id===t);return i||s?.networkState?.caipNetwork||s?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){const e=u.a.state.filterByNamespace;return(e?[C.chains.get(e)]:Array.from(C.chains.values())).flatMap(e=>e?.caipNetworks||[]).map(e=>e.caipNetworkId)},getCaipNetworks:e=>e?N.getRequestedCaipNetworks(e):N.getAllRequestedCaipNetworks()},N=(0,d.X)(I)}};