@hashgraphonline/hashinal-wc 2.0.8 → 2.0.9
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.
|
@@ -463,7 +463,7 @@ NPM Registry: https://www.npmjs.com/package/@reown/appkit`}},PresetsUtil={Networ
|
|
|
463
463
|
`},hexToRgb(Fs){const Ps=parseInt(Fs,16),Ws=Ps>>16&255,Hs=Ps>>8&255,Zs=Ps&255;return[Ws,Hs,Zs]},tintColor(Fs,Ps){const[Ws,Hs,Zs]=Fs,zs=Math.round(Ws+(255-Ws)*Ps),Xs=Math.round(Hs+(255-Hs)*Ps),Va=Math.round(Zs+(255-Zs)*Ps);return[zs,Xs,Va]},isNumber(Fs){return{number:/^[0-9]+$/u}.number.test(Fs)},getColorTheme(Fs){return Fs||(typeof window<"u"&&window.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)")?.matches?"dark":"light":"dark")},splitBalance(Fs){const Ps=Fs.split(".");return Ps.length===2?[Ps[0],Ps[1]]:["0","00"]},roundNumber(Fs,Ps,Ws){return Fs.toString().length>=Ps?Number(Fs).toFixed(Ws):Fs},cssDurationToNumber(Fs){return Fs.endsWith("s")?Number(Fs.replace("s",""))*1e3:Fs.endsWith("ms")?Number(Fs.replace("ms","")):0},maskInput({value:Fs,decimals:Ps,integers:Ws}){if(Fs=Fs.replace(",","."),Fs===DECIMAL_POINT)return`0${DECIMAL_POINT}`;const[Hs="",Zs]=Fs.split(DECIMAL_POINT).map(qs=>qs.replace(/[^0-9]/gu,"")),zs=Ws?Hs.substring(0,Ws):Hs,Xs=zs.length===2?String(Number(zs)):zs,Va=typeof Ps=="number"?Zs?.substring(0,Ps):Zs,Js=typeof Ps!="number"||Ps>0;return(typeof Va=="string"&&Js?[Xs,Va].join(DECIMAL_POINT):Xs)??""},capitalize(Fs){return Fs?Fs.charAt(0).toUpperCase()+Fs.slice(1):""}},FLOAT_FIXED_VALUE=3,GAS_FEE_THRESHOLD=.1,plusTypes=["receive","deposit","borrow","claim"],minusTypes=["withdraw","repay","burn"],TransactionUtil={getTransactionGroupTitle(Fs,Ps){const Ws=DateUtil.getYear(),Hs=DateUtil.getMonthNameByIndex(Ps);return Fs===Ws?Hs:`${Hs} ${Fs}`},getTransactionImages(Fs){const[Ps]=Fs;return Fs?.length>1?Fs.map(Hs=>this.getTransactionImage(Hs)):[this.getTransactionImage(Ps)]},getTransactionImage(Fs){return{type:TransactionUtil.getTransactionTransferTokenType(Fs),url:TransactionUtil.getTransactionImageURL(Fs)}},getTransactionImageURL(Fs){let Ps;const Ws=!!Fs?.nft_info,Hs=!!Fs?.fungible_info;return Fs&&Ws?Ps=Fs?.nft_info?.content?.preview?.url:Fs&&Hs&&(Ps=Fs?.fungible_info?.icon?.url),Ps},getTransactionTransferTokenType(Fs){if(Fs?.fungible_info)return"FUNGIBLE";if(Fs?.nft_info)return"NFT"},getTransactionDescriptions(Fs,Ps){const Ws=Fs?.metadata?.operationType,Hs=Ps||Fs?.transfers,Zs=Hs?.length>0,zs=Hs?.length>1,Xs=Zs&&Hs?.every(Hc=>!!Hc?.fungible_info),[Va,Js]=Hs;let Ma=this.getTransferDescription(Va),qs=this.getTransferDescription(Js);if(!Zs)return(Ws==="send"||Ws==="receive")&&Xs?(Ma=UiHelperUtil.getTruncateString({string:Fs?.metadata.sentFrom,charsStart:4,charsEnd:6,truncate:"middle"}),qs=UiHelperUtil.getTruncateString({string:Fs?.metadata.sentTo,charsStart:4,charsEnd:6,truncate:"middle"}),[Ma,qs]):[Fs.metadata.status];if(zs)return Hs.map(Hc=>this.getTransferDescription(Hc));let Ys="";return plusTypes.includes(Ws)?Ys="+":minusTypes.includes(Ws)&&(Ys="-"),Ma=Ys.concat(Ma),[Ma]},getTransferDescription(Fs){let Ps="";return Fs&&(Fs?.nft_info?Ps=Fs?.nft_info?.name||"-":Fs?.fungible_info&&(Ps=this.getFungibleTransferDescription(Fs)||"-")),Ps},getFungibleTransferDescription(Fs){return Fs?[this.getQuantityFixedValue(Fs?.quantity.numeric),Fs?.fungible_info?.symbol].join(" ").trim():null},mergeTransfers(Fs){if(Fs?.length<=1)return Fs;const Ws=this.filterGasFeeTransfers(Fs).reduce((Zs,zs)=>{const Xs=zs?.fungible_info?.name,Va=Zs.find(({fungible_info:Js,direction:Ma})=>Xs&&Xs===Js?.name&&Ma===zs.direction);if(Va){const Js=Number(Va.quantity.numeric)+Number(zs.quantity.numeric);Va.quantity.numeric=Js.toString(),Va.value=(Va.value||0)+(zs.value||0)}else Zs.push(zs);return Zs},[]);let Hs=Ws;return Ws.length>2&&(Hs=Ws.sort((Zs,zs)=>(zs.value||0)-(Zs.value||0)).slice(0,2)),Hs=Hs.sort((Zs,zs)=>Zs.direction==="out"&&zs.direction==="in"?-1:Zs.direction==="in"&&zs.direction==="out"?1:0),Hs},filterGasFeeTransfers(Fs){const Ps=Fs.reduce((Hs,Zs)=>{const zs=Zs?.fungible_info?.name;return zs&&(Hs[zs]||(Hs[zs]=[]),Hs[zs].push(Zs)),Hs},{}),Ws=[];return Object.values(Ps).forEach(Hs=>{if(Hs.length===1){const Zs=Hs[0];Zs&&Ws.push(Zs)}else{const Zs=Hs.filter(Xs=>Xs.direction==="in"),zs=Hs.filter(Xs=>Xs.direction==="out");if(Zs.length===1&&zs.length===1){const Xs=Zs[0],Va=zs[0];let Js=!1;if(Xs&&Va){const Ma=Number(Xs.quantity.numeric),qs=Number(Va.quantity.numeric);qs<Ma*GAS_FEE_THRESHOLD?(Ws.push(Xs),Js=!0):Ma<qs*GAS_FEE_THRESHOLD&&(Ws.push(Va),Js=!0)}Js||Ws.push(...Hs)}else{const Xs=this.filterGasFeesFromTokenGroup(Hs);Ws.push(...Xs)}}}),Fs.forEach(Hs=>{Hs?.fungible_info?.name||Ws.push(Hs)}),Ws},filterGasFeesFromTokenGroup(Fs){if(Fs.length<=1)return Fs;const Ps=Fs.map(Va=>Number(Va.quantity.numeric)),Ws=Math.max(...Ps),Hs=Math.min(...Ps),Zs=.01;if(Hs<Ws*Zs)return Fs.filter(Js=>Number(Js.quantity.numeric)>=Ws*Zs);const zs=Fs.filter(Va=>Va.direction==="in"),Xs=Fs.filter(Va=>Va.direction==="out");if(zs.length===1&&Xs.length===1){const Va=zs[0],Js=Xs[0];if(Va&&Js){const Ma=Number(Va.quantity.numeric),qs=Number(Js.quantity.numeric);if(qs<Ma*GAS_FEE_THRESHOLD)return[Va];if(Ma<qs*GAS_FEE_THRESHOLD)return[Js]}}return Fs},getQuantityFixedValue(Fs){return Fs?parseFloat(Fs).toFixed(FLOAT_FIXED_VALUE):null}};function standardCustomElement(Fs,Ps){const{kind:Ws,elements:Hs}=Ps;return{kind:Ws,elements:Hs,finisher(Zs){customElements.get(Fs)||customElements.define(Fs,Zs)}}}function legacyCustomElement(Fs,Ps){return customElements.get(Fs)||customElements.define(Fs,Ps),Ps}function customElement(Fs){return function(Ws){return typeof Ws=="function"?legacyCustomElement(Fs,Ws):standardCustomElement(Fs,Ws)}}const WcConstantsUtil={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};class UniversalAdapter extends AdapterBlueprint{async setUniversalProvider(Ps){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new WalletConnectConnector({provider:Ps,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(Ps){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(Ps.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect(),this.emit("disconnect")}catch(Ps){console.warn("UniversalAdapter:disconnect - error",Ps)}return{connections:[]}}syncConnections(){return Promise.resolve()}async getAccounts({namespace:Ps}){const Hs=this.provider?.session?.namespaces?.[Ps]?.accounts?.map(Zs=>{const[,,zs]=Zs.split(":");return zs}).filter((Zs,zs,Xs)=>Xs.indexOf(Zs)===zs)||[];return Promise.resolve({accounts:Hs.map(Zs=>CoreHelperUtil.createAccount(Ps,Zs,Ps==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(Ps){if(!(Ps.caipNetwork&&ConstantsUtil$2.BALANCE_SUPPORTED_CHAINS.includes(Ps.caipNetwork?.chainNamespace))||Ps.caipNetwork?.testnet)return{balance:"0.00",symbol:Ps.caipNetwork?.nativeCurrency.symbol||""};const Hs=ChainController.getAccountData();if(Hs?.balanceLoading&&Ps.chainId===ChainController.state.activeCaipNetwork?.id)return{balance:Hs?.balance||"0.00",symbol:Hs?.balanceSymbol||""};const zs=(await ChainController.fetchTokenBalance()).find(Xs=>Xs.chainId===`${Ps.caipNetwork?.chainNamespace}:${Ps.chainId}`&&Xs.symbol===Ps.caipNetwork?.nativeCurrency.symbol);return{balance:zs?.quantity.numeric||"0.00",symbol:zs?.symbol||Ps.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(Ps){const{provider:Ws,message:Hs,address:Zs}=Ps;if(!Ws)throw new Error("UniversalAdapter:signMessage - provider is undefined");let zs="";return ChainController.state.activeCaipNetwork?.chainNamespace===ConstantsUtil$3.CHAIN.SOLANA?zs=(await Ws.request({method:"solana_signMessage",params:{message:bs58.encode(new TextEncoder().encode(Hs)),pubkey:Zs}},ChainController.state.activeCaipNetwork?.caipNetworkId)).signature:zs=await Ws.request({method:"personal_sign",params:[Hs,Zs]},ChainController.state.activeCaipNetwork?.caipNetworkId),{signature:zs}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(Ps){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}emitFirstAvailableConnection(){}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(Ps){const{caipNetwork:Ws}=Ps,Hs=this.getWalletConnectConnector();if(Ws.chainNamespace===ConstantsUtil$3.CHAIN.EVM)try{await Hs.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:toHex$1(Ws.id)}]})}catch(Zs){if(Zs.code===WcConstantsUtil.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||Zs.code===WcConstantsUtil.ERROR_INVALID_CHAIN_ID||Zs.code===WcConstantsUtil.ERROR_CODE_DEFAULT||Zs?.data?.originalError?.code===WcConstantsUtil.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await Hs.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:toHex$1(Ws.id),rpcUrls:[Ws?.rpcUrls.chainDefault?.http],chainName:Ws.name,nativeCurrency:Ws.nativeCurrency,blockExplorerUrls:[Ws.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}Hs.provider.setDefaultChain(Ws.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(Hs=>Hs.type==="WALLET_CONNECT")?.provider}}const FEATURE_KEYS=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication"],featureConfig={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>{if(!Fs?.config)return!1;const Ps=Fs.config;return!!Fs.isEnabled&&Ps.includes("email")},processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.email:!!Fs},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>{if(!Fs?.config)return!1;const Ps=Fs.config;return Fs.isEnabled&&Ps.length>0?Ps.filter(Ws=>Ws!=="email"):!1},processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.socials:typeof Fs=="boolean"?Fs?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.socials:!1:Fs},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>{if(!Fs?.config)return!1;const Ps=Fs.config;return Fs.isEnabled&&Ps.length>0?Ps:!1},processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.swaps:typeof Fs=="boolean"?Fs?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.swaps:!1:Fs},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>{if(!Fs?.config)return!1;const Ps=Fs.config;return Fs.isEnabled&&Ps.length>0?Ps:!1},processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.onramp:typeof Fs=="boolean"?Fs?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.onramp:!1:Fs},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.activity:!!Fs},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:Fs=>Fs===void 0?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.reownBranding:!!Fs},emailCapture:{apiFeatureName:"email_capture",localFeatureName:"emailCapture",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>Fs.isEnabled&&(Fs.config??[]),processFallback:Fs=>!1},multiWallet:{apiFeatureName:"multi_wallet",localFeatureName:"multiWallet",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:()=>ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:()=>ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:()=>ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.payments},reownAuthentication:{apiFeatureName:"reown_authentication",localFeatureName:"reownAuthentication",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:Fs=>!!Fs.isEnabled,processFallback:Fs=>typeof Fs>"u"?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES.reownAuthentication:!!Fs}},ConfigUtil={localSettingsOverridden:new Set,getApiConfig(Fs,Ps){return Ps?.find(Ws=>Ws.id===Fs)},addWarning(Fs,Ps){if(Fs!==void 0){const Ws=featureConfig[Ps],Hs=Ws.isLegacy?`"features.${Ws.localFeatureName}" (now "${Ps}")`:`"features.${Ps}"`;this.localSettingsOverridden.add(Hs)}},processFeature(Fs,Ps,Ws,Hs,Zs){const zs=featureConfig[Fs],Xs=Ps[zs.localFeatureName];if(Zs&&!zs.isAvailableOnBasic)return!1;if(Hs){const Va=this.getApiConfig(zs.apiFeatureName,Ws);return Va?.config===null?this.processFallbackFeature(Fs,Xs):Va?.config?(Xs!==void 0&&this.addWarning(Xs,Fs),this.processApiFeature(Fs,Va)):!1}return this.processFallbackFeature(Fs,Xs)},processApiFeature(Fs,Ps){return featureConfig[Fs].processApi(Ps)},processFallbackFeature(Fs,Ps){return featureConfig[Fs].processFallback(Ps)},async fetchRemoteFeatures(Fs){const Ps=Fs.basic??!1,Ws=Fs.features||{};this.localSettingsOverridden.clear();let Hs=null,Zs=!1;try{Hs=await ApiController.fetchProjectConfig(),Zs=Hs!=null}catch(Xs){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",Xs)}const zs=Zs&&!Ps?ConstantsUtil$2.DEFAULT_REMOTE_FEATURES:ConstantsUtil$2.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const Xs of FEATURE_KEYS){const Va=this.processFeature(Xs,Ws,Hs,Zs,Ps);Object.assign(zs,{[Xs]:Va})}}catch(Xs){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",Xs),ConstantsUtil$2.DEFAULT_REMOTE_FEATURES}if(Zs&&this.localSettingsOverridden.size>0){const Xs=`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.`;AlertController.open({debugMessage:ErrorUtil.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(Xs)},"warning")}return zs}};class AppKitBaseClient{constructor(Ps){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(Ws,Hs)=>{if(Ws){const Zs=ChainController.getCaipNetworks(Ws)?.find(Va=>Va.id===Hs);if(Zs)return Zs;const zs=ChainController.getNetworkData(Ws)?.caipNetwork;return zs||ChainController.getRequestedCaipNetworks(Ws).filter(Va=>Va.chainNamespace===Ws)?.[0]}return ChainController.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const Ws=this.getCaipNetwork();if(Ws)return Ws.id},this.getCaipNetworks=Ws=>ChainController.getCaipNetworks(Ws),this.getActiveChainNamespace=()=>ChainController.state.activeChain,this.setRequestedCaipNetworks=(Ws,Hs)=>{ChainController.setRequestedCaipNetworks(Ws,Hs)},this.getApprovedCaipNetworkIds=()=>ChainController.getAllApprovedCaipNetworkIds(),this.getCaipAddress=Ws=>ChainController.state.activeChain===Ws||!Ws?ChainController.state.activeCaipAddress:ChainController.state.chains.get(Ws)?.accountState?.caipAddress,this.setClientId=Ws=>{BlockchainApiController.setClientId(Ws)},this.getProvider=Ws=>ProviderController.getProvider(Ws),this.getProviderType=Ws=>ProviderController.getProviderId(Ws),this.getPreferredAccountType=Ws=>getPreferredAccountType(Ws),this.setCaipAddress=(Ws,Hs,Zs=!1)=>{ChainController.setAccountProp("caipAddress",Ws,Hs,Zs),ChainController.setAccountProp("address",CoreHelperUtil.getPlainAddress(Ws),Hs,Zs)},this.setBalance=(Ws,Hs,Zs)=>{ChainController.setAccountProp("balance",Ws,Zs),ChainController.setAccountProp("balanceSymbol",Hs,Zs)},this.setProfileName=(Ws,Hs)=>{ChainController.setAccountProp("profileName",Ws,Hs)},this.setProfileImage=(Ws,Hs)=>{ChainController.setAccountProp("profileImage",Ws,Hs)},this.setUser=(Ws,Hs)=>{ChainController.setAccountProp("user",Ws,Hs)},this.resetAccount=Ws=>{ChainController.resetAccount(Ws)},this.setCaipNetwork=Ws=>{ChainController.setActiveCaipNetwork(Ws)},this.setCaipNetworkOfNamespace=(Ws,Hs)=>{ChainController.setChainNetworkData(Hs,{caipNetwork:Ws})},this.setStatus=(Ws,Hs)=>{ChainController.setAccountProp("status",Ws,Hs),ConnectorController.isConnected()?StorageUtil.setConnectionStatus("connected"):StorageUtil.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=Ws=>ChainController.getAccountData(Ws)?.address,this.setConnectors=Ws=>{const Hs=[...ConnectorController.state.allConnectors,...Ws];ConnectorController.setConnectors(Hs)},this.setConnections=(Ws,Hs)=>{StorageUtil.setConnections(Ws,Hs),ConnectionController.setConnections(Ws,Hs)},this.fetchIdentity=Ws=>BlockchainApiController.fetchIdentity(Ws),this.getReownName=Ws=>EnsController.getNamesForAddress(Ws),this.getConnectors=()=>ConnectorController.getConnectors(),this.getConnectorImage=Ws=>AssetUtil.getConnectorImage(Ws),this.getConnections=Ws=>this.remoteFeatures.multiWallet?ConnectionControllerUtil.getConnectionsData(Ws).connections:(AlertController.open(ConstantsUtil$3.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=Ws=>this.remoteFeatures.multiWallet?ConnectionControllerUtil.getConnectionsData(Ws).recentConnections:(AlertController.open(ConstantsUtil$3.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async Ws=>{if(!this.remoteFeatures.multiWallet){AlertController.open(ConstantsUtil$3.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await ConnectionController.switchConnection(Ws)},this.deleteConnection=Ws=>{if(!this.remoteFeatures.multiWallet){AlertController.open(ConstantsUtil$3.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}StorageUtil.deleteAddressFromConnection(Ws),ConnectionController.syncStorageConnections()},this.setConnectedWalletInfo=(Ws,Hs)=>{const Zs=ProviderController.getProviderId(Hs),zs=Ws?{...Ws,type:Zs}:void 0;ChainController.setAccountProp("connectedWalletInfo",zs,Hs)},this.getIsConnectedState=()=>!!ChainController.state.activeCaipAddress,this.addAddressLabel=(Ws,Hs,Zs)=>{const zs=ChainController.getAccountData(Zs)?.addressLabels||{};ChainController.setAccountProp("addressLabels",{...zs,[Ws]:Hs},Zs)},this.removeAddressLabel=(Ws,Hs)=>{const Zs=ChainController.getAccountData(Hs)?.addressLabels||{};ChainController.setAccountProp("addressLabels",{...Zs,[Ws]:void 0},Hs)},this.getAddress=Ws=>{const Hs=Ws||ChainController.state.activeChain;return ChainController.getAccountData(Hs)?.address},this.resetNetwork=Ws=>{ChainController.resetNetwork(Ws)},this.addConnector=Ws=>{ConnectorController.addConnector(Ws)},this.resetWcConnection=()=>{ConnectionController.resetWcConnection()},this.setAddressExplorerUrl=(Ws,Hs)=>{ChainController.setAccountProp("addressExplorerUrl",Ws,Hs)},this.setSmartAccountDeployed=(Ws,Hs)=>{ChainController.setAccountProp("smartAccountDeployed",Ws,Hs)},this.setPreferredAccountType=(Ws,Hs)=>{ChainController.setAccountProp("preferredAccountType",Ws,Hs)},this.setEIP6963Enabled=Ws=>{OptionsController.setEIP6963Enabled(Ws)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=Ps,this.version=Ps.sdkVersion,this.caipNetworks=this.extendCaipNetworks(Ps),this.chainNamespaces=this.getChainNamespacesSet(Ps.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(Ps),this.chainAdapters=this.createAdapters(Ps.adapters),this.readyPromise=this.initialize(Ps),SemVerUtils.checkSDKVersion(Ps.sdkVersion)}getChainNamespacesSet(Ps,Ws){const Hs=Ps?.map(zs=>zs.namespace).filter(zs=>!!zs);if(Hs?.length)return[...new Set(Hs)];const Zs=Ws?.map(zs=>zs.chainNamespace);return[...new Set(Zs)]}async initialize(Ps){if(this.initializeProjectSettings(Ps),this.initControllers(Ps),await this.initChainAdapters(),this.sendInitializeEvent(Ps),OptionsController.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),this.remoteFeatures=await ConfigUtil.fetchRemoteFeatures(Ps),OptionsController.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&OnRampController.setOnrampProviders(this.remoteFeatures.onramp),(OptionsController.state.remoteFeatures?.email||Array.isArray(OptionsController.state.remoteFeatures?.socials)&&OptionsController.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins(),OptionsController.state.features?.reownAuthentication||OptionsController.state.remoteFeatures?.reownAuthentication){const{ReownAuthentication:Ws}=await Promise.resolve().then(()=>features),Hs=OptionsController.state.siwx;Hs instanceof Ws||(Hs&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),OptionsController.setSIWX(new Ws))}}async openSend(Ps){const Ws=Ps.namespace||ChainController.state.activeChain,Hs=this.getCaipAddress(Ws),Zs=this.getCaipNetwork(Ws)?.id;if(!Hs)throw new Error("openSend: caipAddress not found");if(Zs?.toString()!==Ps.chainId.toString()){const zs=ChainController.getCaipNetworkById(Ps.chainId,Ws);if(!zs)throw new Error(`openSend: caipNetwork with chainId ${Ps.chainId} not found`);await this.switchNetwork(zs,{throwOnFailure:!0})}try{const zs=TokenUtil.getTokenSymbolByAddress(Ps.assetAddress);zs&&await ApiController.fetchTokenImages([zs])}catch{}return await ModalController.open({view:"WalletSend",data:{send:Ps}}),new Promise((zs,Xs)=>{const Va=SendController.subscribeKey("hash",qs=>{qs&&(Ma(),zs({hash:qs}))}),Js=ModalController.subscribe(qs=>{qs.open||(Ma(),Xs(new Error("Modal closed")))}),Ma=this.createCleanupHandler([Va,Js])})}toModalOptions(){function Ps(Hs){return Hs?.view==="Swap"}function Ws(Hs){return Hs?.view==="WalletSend"}return{isSwap:Ps,isSend:Ws}}async checkAllowedOrigins(){try{const Ps=await ApiController.fetchAllowedOrigins();if(!CoreHelperUtil.isClient())return;const Ws=window.location.origin;WcHelpersUtil.isOriginAllowed(Ws,Ps,ConstantsUtil$3.DEFAULT_ALLOWED_ANCESTORS)||AlertController.open(ErrorUtil.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(Ps){if(!(Ps instanceof Error))return;switch(Ps.message){case"RATE_LIMITED":AlertController.open(ErrorUtil.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const Ws=Ps.cause instanceof Error?Ps.cause:Ps;AlertController.open({displayMessage:ErrorUtil.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:ErrorUtil.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(Ws.message)},"error");break}}}}createCleanupHandler(Ps){return()=>{Ps.forEach(Ws=>{try{Ws()}catch{}})}}sendInitializeEvent(Ps){const{...Ws}=Ps;delete Ws.adapters,delete Ws.universalProvider,EventsController.sendEvent({type:"track",event:"INITIALIZE",properties:{...Ws,networks:Ps.networks.map(Hs=>Hs.id),siweConfig:{options:Ps.siweConfig?.options||{}}}})}initControllers(Ps){this.initializeOptionsController(Ps),this.initializeChainController(Ps),this.initializeThemeController(Ps),this.initializeConnectionController(Ps),this.initializeConnectorController()}initAdapterController(){AdapterController.initialize(this.chainAdapters)}initializeThemeController(Ps){Ps.themeMode&&ThemeController.setThemeMode(Ps.themeMode),Ps.themeVariables&&ThemeController.setThemeVariables(Ps.themeVariables)}initializeChainController(Ps){if(!this.connectionControllerClient)throw new Error("ConnectionControllerClient must be set");ChainController.initialize(Ps.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient});const Ws=this.getDefaultNetwork();Ws&&ChainController.setActiveCaipNetwork(Ws)}initializeConnectionController(Ps){ConnectionController.initialize(Ps.adapters??[]),ConnectionController.setWcBasic(Ps.basic??!1)}initializeConnectorController(){ConnectorController.initialize(this.chainNamespaces)}initializeProjectSettings(Ps){OptionsController.setProjectId(Ps.projectId),OptionsController.setSdkVersion(Ps.sdkVersion)}initializeOptionsController(Ps){OptionsController.setDebug(Ps.debug!==!1),OptionsController.setEnableWalletGuide(Ps.enableWalletGuide!==!1),OptionsController.setEnableWallets(Ps.enableWallets!==!1),OptionsController.setEIP6963Enabled(Ps.enableEIP6963!==!1),OptionsController.setEnableNetworkSwitch(Ps.enableNetworkSwitch!==!1),OptionsController.setEnableReconnect(Ps.enableReconnect!==!1),OptionsController.setEnableMobileFullScreen(Ps.enableMobileFullScreen===!0),OptionsController.setCoinbasePreference(Ps.coinbasePreference),OptionsController.setEnableAuthLogger(Ps.enableAuthLogger!==!1),OptionsController.setCustomRpcUrls(Ps.customRpcUrls),OptionsController.setEnableEmbedded(Ps.enableEmbedded),OptionsController.setAllWallets(Ps.allWallets),OptionsController.setIncludeWalletIds(Ps.includeWalletIds),OptionsController.setExcludeWalletIds(Ps.excludeWalletIds),OptionsController.setFeaturedWalletIds(Ps.featuredWalletIds),OptionsController.setTokens(Ps.tokens),OptionsController.setTermsConditionsUrl(Ps.termsConditionsUrl),OptionsController.setPrivacyPolicyUrl(Ps.privacyPolicyUrl),OptionsController.setCustomWallets(Ps.customWallets),OptionsController.setFeatures(Ps.features),OptionsController.setAllowUnsupportedChain(Ps.allowUnsupportedChain),OptionsController.setUniversalProviderConfigOverride(Ps.universalProviderConfigOverride),OptionsController.setPreferUniversalLinks(Ps.experimental_preferUniversalLinks),OptionsController.setDefaultAccountTypes(Ps.defaultAccountTypes);const Ws=this.getDefaultMetaData();if(!Ps.metadata&&Ws&&(Ps.metadata=Ws),OptionsController.setMetadata(Ps.metadata),OptionsController.setDisableAppend(Ps.disableAppend),OptionsController.setEnableEmbedded(Ps.enableEmbedded),OptionsController.setSIWX(Ps.siwx),this.features=OptionsController.state.features??{},!Ps.projectId){AlertController.open(ErrorUtil.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(Ps.adapters?.find(Zs=>Zs.namespace===ConstantsUtil$3.CHAIN.EVM)&&Ps.siweConfig){if(Ps.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");OptionsController.setSIWX(Ps.siweConfig.mapToSIWX())}}getDefaultMetaData(){return CoreHelperUtil.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(Ps){const Ws=this.getActiveChainNamespace();if(Ws){const Hs=CaipNetworksUtil.getUnsupportedNetwork(`${Ws}:${Ps}`);ChainController.setActiveCaipNetwork(Hs)}}getDefaultNetwork(){return CaipNetworksUtil.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(Ps,Ws){return CaipNetworksUtil.extendCaipNetwork(Ps,{customNetworkImageUrls:Ws.chainImages,projectId:Ws.projectId})}extendCaipNetworks(Ps){return CaipNetworksUtil.extendCaipNetworks(Ps.networks,{customNetworkImageUrls:Ps.chainImages,customRpcUrls:Ps.customRpcUrls,projectId:Ps.projectId})}extendDefaultCaipNetwork(Ps){const Ws=Ps.networks.find(Zs=>Zs.id===Ps.defaultNetwork?.id);return Ws?CaipNetworksUtil.extendCaipNetwork(Ws,{customNetworkImageUrls:Ps.chainImages,customRpcUrls:Ps.customRpcUrls,projectId:Ps.projectId}):void 0}async disconnectConnector(Ps,Ws){try{this.setLoading(!0,Ps);let Hs={connections:[]};const Zs=this.getAdapter(Ps);return(ChainController.state.chains.get(Ps)?.accountState?.caipAddress||!OptionsController.state.enableReconnect)&&Zs?.disconnect&&(Hs=await Zs.disconnect({id:Ws})),this.setLoading(!1,Ps),Hs}catch(Hs){throw this.setLoading(!1,Ps),new Error(`Failed to disconnect chains: ${Hs.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const Ps=ChainController.state.activeChain,Ws=this.getAdapter(Ps),Hs=this.getCaipNetwork(Ps)?.id,Zs=ConnectionController.getConnections(Ps),zs=this.remoteFeatures.multiWallet,Xs=Zs.length>0;if(!Ws)throw new Error("Adapter not found");const Va=await Ws.connectWalletConnect(Hs);(!Xs||!zs)&&this.close(),this.setClientId(Va?.clientId||null),StorageUtil.setConnectedNamespaces([...ChainController.state.chains.keys()]),await this.syncWalletConnectAccount(),await SIWXUtil.initializeIfEnabled()},connectExternal:async Ps=>{const Ws=await this.onConnectExternal(Ps);return await this.connectInactiveNamespaces(Ps,Ws),Ws?{address:Ws.address}:void 0},reconnectExternal:async({id:Ps,info:Ws,type:Hs,provider:Zs})=>{const zs=ChainController.state.activeChain,Xs=this.getAdapter(zs);if(!zs)throw new Error("reconnectExternal: namespace not found");if(!Xs)throw new Error("reconnectExternal: adapter not found");Xs?.reconnect&&(await Xs?.reconnect({id:Ps,info:Ws,type:Hs,provider:Zs,chainId:this.getCaipNetwork()?.id}),StorageUtil.addConnectedNamespace(zs),this.syncConnectedWalletInfo(zs))},disconnectConnector:async Ps=>{await this.disconnectConnector(Ps.namespace,Ps.id)},disconnect:async Ps=>{const{id:Ws,chainNamespace:Hs,initialDisconnect:Zs}=Ps||{},zs=Hs||ChainController.state.activeChain,Xs=ConnectorController.getConnectorId(zs),Va=Ws===ConstantsUtil$3.CONNECTOR_ID.AUTH||Xs===ConstantsUtil$3.CONNECTOR_ID.AUTH,Js=Ws===ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT||Xs===ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT;try{const Ma=Array.from(ChainController.state.chains.keys());let qs=Hs?[Hs]:Ma;(Js||Va)&&(qs=Ma);const Ys=qs.map(async Vc=>{const Dc=ConnectorController.getConnectorId(Vc),al=Ws||Dc,dl=await this.disconnectConnector(Vc,al);dl&&(Va&&StorageUtil.deleteConnectedSocialProvider(),dl.connections.forEach(hl=>{StorageUtil.addDisconnectedConnectorId(hl.connectorId,Vc)})),Zs&&this.onDisconnectNamespace({chainNamespace:Vc,closeModal:!1})}),Hc=await Promise.allSettled(Ys);SendController.resetSend(),ConnectionController.resetWcConnection(),SIWXUtil.getSIWX()?.signOutOnDisconnect&&await SIWXUtil.clearSessions(),ConnectorController.setFilterByNamespace(void 0),ConnectionController.syncStorageConnections();const ol=Hc.filter(Vc=>Vc.status==="rejected");if(ol.length>0)throw new Error(ol.map(Vc=>Vc.reason.message).join(", "));EventsController.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:Hs||"all"}})}catch(Ma){throw new Error(`Failed to disconnect chains: ${Ma.message}`)}},checkInstalled:Ps=>Ps?Ps.some(Ws=>!!window.ethereum?.[String(Ws)]):!!window.ethereum,signMessage:async Ps=>{const Ws=ChainController.state.activeChain,Hs=this.getAdapter(ChainController.state.activeChain);if(!Ws)throw new Error("signMessage: namespace not found");if(!Hs)throw new Error("signMessage: adapter not found");const Zs=this.getAddress(Ws);if(!Zs)throw new Error("signMessage: address not found");return(await Hs?.signMessage({message:Ps,address:Zs,provider:ProviderController.getProvider(Ws)}))?.signature||""},sendTransaction:async Ps=>{const Ws=Ps.chainNamespace;if(!Ws)throw new Error("sendTransaction: namespace not found");if(ConstantsUtil$2.SEND_SUPPORTED_NAMESPACES.includes(Ws)){const Hs=this.getAdapter(Ws);if(!Hs)throw new Error("sendTransaction: adapter not found");const Zs=ProviderController.getProvider(Ws);return(await Hs?.sendTransaction({...Ps,caipNetwork:this.getCaipNetwork(),provider:Zs}))?.hash||""}return""},estimateGas:async Ps=>{const Ws=Ps.chainNamespace;if(Ws===ConstantsUtil$3.CHAIN.EVM){const Hs=this.getAdapter(Ws);if(!Hs)throw new Error("estimateGas: adapter is required but got undefined");const Zs=ProviderController.getProvider(Ws),zs=this.getCaipNetwork();if(!zs)throw new Error("estimateGas: caipNetwork is required but got undefined");return(await Hs?.estimateGas({...Ps,provider:Zs,caipNetwork:zs}))?.gas||0n}return 0n},getEnsAvatar:async()=>{const Ps=ChainController.state.activeChain;if(!Ps)throw new Error("getEnsAvatar: namespace is required but got undefined");const Ws=this.getAddress(Ps);if(!Ws)throw new Error("getEnsAvatar: address not found");return await this.syncIdentity({address:Ws,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:Ps}),ChainController.getAccountData()?.profileImage||!1},getEnsAddress:async Ps=>await WcHelpersUtil.resolveReownName(Ps),writeContract:async Ps=>{const Ws=ChainController.state.activeChain,Hs=this.getAdapter(Ws);if(!Ws)throw new Error("writeContract: namespace is required but got undefined");if(!Hs)throw new Error("writeContract: adapter is required but got undefined");const Zs=this.getCaipNetwork(),zs=this.getCaipAddress(),Xs=ProviderController.getProvider(Ws);if(!Zs||!zs)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");return(await Hs?.writeContract({...Ps,caipNetwork:Zs,provider:Xs,caipAddress:zs}))?.hash},parseUnits:(Ps,Ws)=>{const Hs=this.getAdapter(ChainController.state.activeChain);if(!Hs)throw new Error("parseUnits: adapter is required but got undefined");return Hs?.parseUnits({value:Ps,decimals:Ws})??0n},formatUnits:(Ps,Ws)=>{const Hs=this.getAdapter(ChainController.state.activeChain);if(!Hs)throw new Error("formatUnits: adapter is required but got undefined");return Hs?.formatUnits({value:Ps,decimals:Ws})??"0"},getCapabilities:async Ps=>{const Ws=this.getAdapter(ChainController.state.activeChain);if(!Ws)throw new Error("getCapabilities: adapter is required but got undefined");return await Ws?.getCapabilities(Ps)},grantPermissions:async Ps=>{const Ws=this.getAdapter(ChainController.state.activeChain);if(!Ws)throw new Error("grantPermissions: adapter is required but got undefined");return await Ws?.grantPermissions(Ps)},revokePermissions:async Ps=>{const Ws=this.getAdapter(ChainController.state.activeChain);if(!Ws)throw new Error("revokePermissions: adapter is required but got undefined");return Ws?.revokePermissions?await Ws.revokePermissions(Ps):"0x"},walletGetAssets:async Ps=>{const Ws=this.getAdapter(ChainController.state.activeChain);if(!Ws)throw new Error("walletGetAssets: adapter is required but got undefined");return await Ws?.walletGetAssets(Ps)??{}},updateBalance:Ps=>{const Ws=this.getAddress(Ps),Hs=this.getCaipNetwork(Ps);!Hs||!Ws||this.updateNativeBalance(Ws,Hs?.id,Ps)}},ConnectionController.setClient(this.connectionControllerClient)}async onConnectExternal(Ps){const Ws=ChainController.state.activeChain,Hs=Ps.chain||Ws,Zs=this.getAdapter(Hs);let zs=!0;if(Ps.type===ConstantsUtil$1.CONNECTOR_TYPE_AUTH&&ConstantsUtil$3.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(Ys=>ConnectorController.getConnectorId(Ys)===ConstantsUtil$3.CONNECTOR_ID.AUTH)&&Ps.chain!==Ws&&(zs=!1),Ps.chain&&Ps.chain!==Ws&&!Ps.caipNetwork){const Ma=this.getCaipNetworks().find(qs=>qs.chainNamespace===Ps.chain);Ma&&zs&&this.setCaipNetwork(Ma)}if(!Hs)throw new Error("connectExternal: namespace not found");if(!Zs)throw new Error("connectExternal: adapter not found");const Xs=this.getCaipNetwork(Hs),Va=Ps.caipNetwork||Xs,Js=await Zs.connect({id:Ps.id,address:Ps.address,info:Ps.info,type:Ps.type,provider:Ps.provider,socialUri:Ps.socialUri,chainId:Ps.caipNetwork?.id||Xs?.id,rpcUrl:Ps.caipNetwork?.rpcUrls?.default?.http?.[0]||Xs?.rpcUrls?.default?.http?.[0]});if(Js)return StorageUtil.addConnectedNamespace(Hs),this.syncProvider({...Js,chainNamespace:Hs}),this.setStatus("connected",Hs),this.syncConnectedWalletInfo(Hs),StorageUtil.removeDisconnectedConnectorId(Ps.id,Hs),{address:Js.address,connectedCaipNetwork:Va}}async connectInactiveNamespaces(Ps,Ws){const Hs=Ps.type===ConstantsUtil$1.CONNECTOR_TYPE_AUTH,Zs=HelpersUtil$1.getOtherAuthNamespaces(Ws?.connectedCaipNetwork?.chainNamespace),zs=ChainController.state.activeCaipNetwork,Xs=this.getAdapter(zs?.chainNamespace);Hs&&(await Promise.all(Zs.map(async Va=>{try{const Js=ProviderController.getProvider(Va),Ma=this.getCaipNetwork(Va);await this.getAdapter(Va)?.connect({...Ps,provider:Js,socialUri:void 0,chainId:Ma?.id,rpcUrl:Ma?.rpcUrls?.default?.http?.[0]})&&(StorageUtil.addConnectedNamespace(Va),StorageUtil.removeDisconnectedConnectorId(Ps.id,Va),this.setStatus("connected",Va),this.syncConnectedWalletInfo(Va))}catch(Js){AlertController.warn(ErrorUtil.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,ErrorUtil.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(Va,Js instanceof Error?Js.message:void 0),ErrorUtil.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}})),zs&&await Xs?.switchNetwork({caipNetwork:zs}))}getApprovedCaipNetworksData(){if(ProviderController.getProviderId(ChainController.state.activeChain)===ConstantsUtil$1.CONNECTOR_TYPE_WALLET_CONNECT){const Ws=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(Ws)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(Ps){const Ws=Ps.chainNamespace;if(this.getAddressByChainNamespace(Ps.chainNamespace)){const Zs=ProviderController.getProviderId(Ws);if(Ps.chainNamespace===ChainController.state.activeChain)await this.getAdapter(Ws)?.switchNetwork({caipNetwork:Ps});else if(this.setCaipNetwork(Ps),Zs===ConstantsUtil$1.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const zs=this.getAddressByChainNamespace(Ws);zs&&this.syncAccount({address:zs,chainId:Ps.id,chainNamespace:Ws})}}else this.setCaipNetwork(Ps)}getChainsFromNamespaces(Ps={}){return Object.values(Ps).flatMap(Ws=>{const Hs=Ws.chains||[],Zs=Ws.accounts.map(zs=>{const{chainId:Xs,chainNamespace:Va}=ParseUtil.parseCaipAddress(zs);return`${Va}:${Xs}`});return Array.from(new Set([...Hs,...Zs]))})}createAdapters(Ps){return this.createClients(),this.chainNamespaces.reduce((Ws,Hs)=>{const Zs=Ps?.find(zs=>zs.namespace===Hs);return Zs?(Zs.construct({namespace:Hs,projectId:this.options?.projectId,networks:this.caipNetworks?.filter(({chainNamespace:zs})=>zs===Hs)}),Ws[Hs]=Zs):Ws[Hs]=new UniversalAdapter({namespace:Hs,networks:this.getCaipNetworks()}),Ws},{})}async initChainAdapter(Ps){this.onConnectors(Ps),this.listenAdapter(Ps);const Ws=this.getAdapter(Ps);if(!Ws)throw new Error("adapter not found");await Ws.syncConnectors(),await this.createUniversalProviderForAdapter(Ps)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async Ps=>{await this.initChainAdapter(Ps)})),this.initAdapterController()}onConnectors(Ps){this.getAdapter(Ps)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(Ps){const Ws=this.getAdapter(Ps);if(!Ws)return;const Hs=StorageUtil.getConnectionStatus();OptionsController.state.enableReconnect===!1?this.setStatus("disconnected",Ps):Hs==="connected"?this.setStatus("connecting",Ps):Hs==="disconnected"?(StorageUtil.clearAddressCache(),this.setStatus(Hs,Ps)):this.setStatus(Hs,Ps),Ws.on("switchNetwork",({address:Zs,chainId:zs})=>{const Xs=this.getCaipNetworks().find(Ma=>Ma.id.toString()===zs.toString()||Ma.caipNetworkId.toString()===zs.toString()),Va=ChainController.state.activeChain===Ps,Js=ChainController.state.chains.get(Ps)?.accountState?.address;if(Xs){const Ma=Va&&Zs?Zs:Js;Ma&&this.syncAccount({address:Ma,chainId:Xs.id,chainNamespace:Ps})}else this.setUnsupportedNetwork(zs)}),Ws.on("disconnect",()=>{const Zs=this.remoteFeatures.multiWallet,zs=Array.from(ConnectionController.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:Ps,closeModal:!Zs||zs.length===0})}),Ws.on("connections",Zs=>{this.setConnections(Zs,Ps)}),Ws.on("pendingTransactions",()=>{const Zs=this.getAddress(Ps),zs=ChainController.state.activeCaipNetwork;!Zs||!zs?.id||this.updateNativeBalance(Zs,zs.id,zs.chainNamespace)}),Ws.on("accountChanged",({address:Zs,chainId:zs,connector:Xs})=>{this.handlePreviousConnectorConnection(Xs);const Va=ChainController.state.activeChain===Ps;Xs?.provider&&(this.syncProvider({id:Xs.id,type:Xs.type,provider:Xs?.provider,chainNamespace:Ps}),this.syncConnectedWalletInfo(Ps));const Js=ChainController.getNetworkData(Ps)?.caipNetwork?.id,Ma=zs||Js;Va&&Ma?this.syncAccount({address:Zs,chainId:Ma,chainNamespace:Ps}):!Va&&Ma?(this.syncAccountInfo(Zs,Ma,Ps),this.syncBalance({address:Zs,chainId:Ma,chainNamespace:Ps})):this.syncAccountInfo(Zs,zs,Ps),StorageUtil.addConnectedNamespace(Ps)})}async handlePreviousConnectorConnection(Ps){const Ws=Ps?.chain,Hs=Ps?.id,Zs=ConnectorController.getConnectorId(Ws),zs=OptionsController.state.remoteFeatures?.multiWallet,Va=Ws&&Hs&&Zs&&Zs!==Hs&&!zs;try{Va&&await ConnectionController.disconnect({id:Zs,namespace:Ws})}catch(Js){console.warn("Error disconnecting previous connector",Js)}}async createUniversalProviderForAdapter(Ps){await this.getUniversalProvider(),this.universalProvider&&await this.chainAdapters?.[Ps]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(Ps=>this.syncNamespaceConnection(Ps)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(Ps=>ConnectionController.disconnect({namespace:Ps,initialDisconnect:!0})))}catch(Ps){console.error("Error disconnecting existing connections:",Ps)}}async reconnectWalletConnect(){await this.syncWalletConnectAccount();const Ps=this.getAddress();this.getCaipAddress()||StorageUtil.deleteRecentWallet();const Ws=StorageUtil.getRecentWallet();EventsController.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:Ps,properties:{method:CoreHelperUtil.isMobile()?"mobile":"qrcode",name:Ws?.name||"Unknown",reconnect:!0,view:RouterController.state.view,walletRank:Ws?.order}})}async syncNamespaceConnection(Ps){try{Ps===ConstantsUtil$3.CHAIN.EVM&&CoreHelperUtil.isSafeApp()&&ConnectorController.setConnectorId(ConstantsUtil$3.CONNECTOR_ID.SAFE,Ps);const Ws=ConnectorController.getConnectorId(Ps);switch(this.setStatus("connecting",Ps),Ws){case ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case ConstantsUtil$3.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(Ps)}}catch(Ws){console.warn("AppKit couldn't sync existing connection",Ws),this.setStatus("disconnected",Ps)}}onDisconnectNamespace(Ps){const{chainNamespace:Ws,closeModal:Hs}=Ps||{};ChainController.resetAccount(Ws),ChainController.resetNetwork(Ws),StorageUtil.removeConnectedNamespace(Ws);const Zs=Array.from(ChainController.state.chains.keys());(Ws?[Ws]:Zs).forEach(Xs=>StorageUtil.addDisconnectedConnectorId(ConnectorController.getConnectorId(Xs)||"",Xs)),ConnectorController.removeConnectorId(Ws),ProviderController.resetChain(Ws),this.setUser(null,Ws),this.setStatus("disconnected",Ws),this.setConnectedWalletInfo(null,Ws),Hs!==!1&&ModalController.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map(Ps=>{const Ws=this.getAdapter(Ps),Hs=this.getCaipAddress(Ps),Zs=this.getCaipNetwork(Ps);return Ws?.syncConnections({connectToFirstConnector:!Hs,caipNetwork:Zs})}))}async syncAdapterConnection(Ps){const Ws=this.getAdapter(Ps),Hs=this.getCaipNetwork(Ps),Zs=ConnectorController.getConnectorId(Ps),Xs=ConnectorController.getConnectors(Ps).find(Va=>Va.id===Zs);try{if(!Ws||!Xs)throw new Error(`Adapter or connector not found for namespace ${Ps}`);if(!Hs?.id)throw new Error("CaipNetwork not found");const Va=await Ws?.syncConnection({namespace:Ps,id:Xs.id,chainId:Hs.id,rpcUrl:Hs?.rpcUrls?.default?.http?.[0]});Va?(this.syncProvider({...Va,chainNamespace:Ps}),await this.syncAccount({...Va,chainNamespace:Ps}),this.setStatus("connected",Ps),EventsController.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:Va.address,properties:{method:"browser",name:Xs.info?.name||Xs.name||"Unknown",reconnect:!0,view:RouterController.state.view,walletRank:void 0}})):this.setStatus("disconnected",Ps)}catch{this.onDisconnectNamespace({chainNamespace:Ps,closeModal:!1})}}async syncWalletConnectAccount(){const Ps=Object.keys(this.universalProvider?.session?.namespaces||{}),Ws=this.chainNamespaces.map(async Hs=>{const Zs=this.getAdapter(Hs);if(!Zs)return;const zs=this.universalProvider?.session?.namespaces?.[Hs]?.accounts||[],Xs=ChainController.state.activeCaipNetwork?.id,Va=zs.find(Ma=>{const{chainId:qs}=ParseUtil.parseCaipAddress(Ma);return qs===Xs?.toString()})||zs[0];if(Va){const Ma=ParseUtil.validateCaipAddress(Va),{chainId:qs,address:Ys}=ParseUtil.parseCaipAddress(Ma);if(ProviderController.setProviderId(Hs,ConstantsUtil$1.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&ChainController.state.activeCaipNetwork&&Zs.namespace!==ConstantsUtil$3.CHAIN.EVM){const Hc=Zs.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:ChainController.state.activeCaipNetwork});ProviderController.setProvider(Hs,Hc)}else ProviderController.setProvider(Hs,this.universalProvider);ConnectorController.setConnectorId(ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT,Hs),StorageUtil.addConnectedNamespace(Hs),await this.syncAccount({address:Ys,chainId:qs,chainNamespace:Hs})}else Ps.includes(Hs)&&this.setStatus("disconnected",Hs);const Js=this.getApprovedCaipNetworksData();this.syncConnectedWalletInfo(Hs),ChainController.setApprovedCaipNetworksData(Hs,{approvedCaipNetworkIds:Js.approvedCaipNetworkIds,supportsAllNetworks:Js.supportsAllNetworks})});await Promise.all(Ws)}syncProvider({type:Ps,provider:Ws,id:Hs,chainNamespace:Zs}){ProviderController.setProviderId(Zs,Ps),ProviderController.setProvider(Zs,Ws),ConnectorController.setConnectorId(Hs,Zs)}async syncAccount(Ps){const Ws=Ps.chainNamespace===ChainController.state.activeChain,Hs=ChainController.getCaipNetworkByNamespace(Ps.chainNamespace,Ps.chainId),{address:Zs,chainId:zs,chainNamespace:Xs}=Ps,{chainId:Va}=StorageUtil.getActiveNetworkProps(),Js=Hs?.id||Va,Ma=ChainController.state.activeCaipNetwork?.name===ConstantsUtil$3.UNSUPPORTED_NETWORK_NAME,qs=ChainController.getNetworkProp("supportsAllNetworks",Xs);if(this.setStatus("connected",Xs),!(Ma&&!qs)&&Js){let Ys=this.getCaipNetworks().find(Dc=>Dc.id.toString()===Js.toString()),Hc=this.getCaipNetworks().find(Dc=>Dc.chainNamespace===Xs);if(!qs&&!Ys&&!Hc){const Dc=this.getApprovedCaipNetworkIds()||[],al=Dc.find(hl=>ParseUtil.parseCaipNetworkId(hl)?.chainId===Js.toString()),dl=Dc.find(hl=>ParseUtil.parseCaipNetworkId(hl)?.chainNamespace===Xs);Ys=this.getCaipNetworks().find(hl=>hl.caipNetworkId===al),Hc=this.getCaipNetworks().find(hl=>hl.caipNetworkId===dl||"deprecatedCaipNetworkId"in hl&&hl.deprecatedCaipNetworkId===dl)}const ol=Ys||Hc;ol?.chainNamespace===ChainController.state.activeChain?OptionsController.state.enableNetworkSwitch&&!OptionsController.state.allowUnsupportedChain&&ChainController.state.activeCaipNetwork?.name===ConstantsUtil$3.UNSUPPORTED_NETWORK_NAME?ChainController.showUnsupportedChainUI():this.setCaipNetwork(ol):Ws||Hs&&this.setCaipNetworkOfNamespace(Hs,Xs),this.syncConnectedWalletInfo(Xs);const Vc=this.getAddress(Xs);HelpersUtil$1.isLowerCaseMatch(Zs,Vc)||this.syncAccountInfo(Zs,ol?.id,Xs),Ws?await this.syncBalance({address:Zs,chainId:ol?.id,chainNamespace:Xs}):await this.syncBalance({address:Zs,chainId:Hs?.id,chainNamespace:Xs}),this.syncIdentity({address:Zs,chainId:zs,chainNamespace:Xs})}}async syncAccountInfo(Ps,Ws,Hs){const Zs=this.getCaipAddress(Hs),zs=Ws||Zs?.split(":")[1];if(!zs)return;const Xs=`${Hs}:${zs}:${Ps}`;this.setCaipAddress(Xs,Hs,!0),await this.syncIdentity({address:Ps,chainId:zs,chainNamespace:Hs})}async syncReownName(Ps,Ws){try{const Hs=await this.getReownName(Ps);if(Hs[0]){const Zs=Hs[0];this.setProfileName(Zs.name,Ws)}else this.setProfileName(null,Ws)}catch{this.setProfileName(null,Ws)}}syncConnectedWalletInfo(Ps){const Ws=ConnectorController.getConnectorId(Ps),Hs=ProviderController.getProviderId(Ps);if(Hs===ConstantsUtil$1.CONNECTOR_TYPE_ANNOUNCED||Hs===ConstantsUtil$1.CONNECTOR_TYPE_INJECTED){if(Ws){const zs=this.getConnectors().find(Xs=>{const Va=Xs.id===Ws,Js=Xs.info?.rdns===Ws,Ma=Xs.connectors?.some(qs=>qs.id===Ws||qs.info?.rdns===Ws);return Va||Js||!!Ma});if(zs){const{info:Xs,name:Va,imageUrl:Js}=zs,Ma=Js||this.getConnectorImage(zs);this.setConnectedWalletInfo({name:Va,icon:Ma,...Xs},Ps)}}}else if(Hs===ConstantsUtil$1.CONNECTOR_TYPE_WALLET_CONNECT){const Zs=ProviderController.getProvider(Ps);Zs?.session&&this.setConnectedWalletInfo({...Zs.session.peer.metadata,name:Zs.session.peer.metadata.name,icon:Zs.session.peer.metadata.icons?.[0]},Ps)}else if(Ws&&(Ws===ConstantsUtil$3.CONNECTOR_ID.COINBASE_SDK||Ws===ConstantsUtil$3.CONNECTOR_ID.COINBASE)){const Zs=this.getConnectors().find(Js=>Js.id===Ws),zs=Zs?.name||"Coinbase Wallet",Xs=Zs?.imageUrl||this.getConnectorImage(Zs),Va=Zs?.info;this.setConnectedWalletInfo({...Va,name:zs,icon:Xs},Ps)}}async syncBalance(Ps){!NetworkUtil$1.getNetworksByNamespace(this.getCaipNetworks(),Ps.chainNamespace).find(Hs=>Hs.id.toString()===Ps.chainId?.toString())||!Ps.chainId||await this.updateNativeBalance(Ps.address,Ps.chainId,Ps.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(Ps,Ws,Hs){const Zs=this.getAdapter(Hs),zs=ChainController.getCaipNetworkByNamespace(Hs,Ws);if(Zs){const Xs=await Zs.getBalance({address:Ps,chainId:Ws,caipNetwork:zs,tokens:this.options.tokens});return this.setBalance(Xs.balance,Xs.symbol,Hs),Xs}}async initializeUniversalAdapter(){const Ps=LoggerUtil.createLogger((Hs,...Zs)=>{Hs&&this.handleAlertError(Hs),console.error(...Zs)}),Ws={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:Ps};OptionsController.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await N$4.init(Ws),OptionsController.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(Ps=>{WcHelpersUtil.listenWcProvider({universalProvider:this.universalProvider,namespace:Ps,onDisplayUri:Ws=>{ConnectionController.setUri(Ws)},onConnect:Ws=>{const{address:Hs}=CoreHelperUtil.getAccount(Ws[0]);ConnectionController.finalizeWcConnection(Hs)},onDisconnect:()=>{ChainController.state.noAdapters&&this.resetAccount(Ps),ConnectionController.resetWcConnection()},onChainChanged:Ws=>{const Hs=ChainController.state.activeChain,Zs=Hs&&ConnectorController.state.activeConnectorIds[Hs]===ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT;if(Hs===Ps&&(ChainController.state.noAdapters||Zs)){const zs=this.getCaipNetworks().find(Va=>Va.id.toString()===Ws.toString()||Va.caipNetworkId.toString()===Ws.toString()),Xs=this.getCaipNetwork();if(!zs){this.setUnsupportedNetwork(Ws);return}Xs?.id.toString()!==zs?.id.toString()&&Xs?.chainNamespace===zs?.chainNamespace&&this.setCaipNetwork(zs)}},onAccountsChanged:Ws=>{const Hs=ChainController.state.activeChain,Zs=Hs&&ConnectorController.state.activeConnectorIds[Hs]===ConstantsUtil$3.CONNECTOR_ID.WALLET_CONNECT;if(Hs===Ps&&(ChainController.state.noAdapters||Zs)){const zs=Ws?.[0];zs&&this.syncAccount({address:zs.address,chainId:zs.chainId,chainNamespace:zs.chainNamespace})}}})})}createUniversalProvider(){return!this.universalProviderInitPromise&&CoreHelperUtil.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(Ps){EventsController.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:Ps instanceof Error?Ps.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",Ps)}return this.universalProvider}getDisabledCaipNetworks(){const Ps=ChainController.getAllApprovedCaipNetworkIds(),Ws=ChainController.getAllRequestedCaipNetworks();return CoreHelperUtil.sortRequestedNetworks(Ps,Ws).filter(Zs=>ChainController.isCaipNetworkDisabled(Zs))}handleAlertError(Ps){const Ws=Object.entries(ErrorUtil.UniversalProviderErrors).find(([,{message:Va}])=>Ps.message.includes(Va)),[Hs,Zs]=Ws??[],{message:zs,alertErrorKey:Xs}=Zs??{};if(Hs&&zs&&!this.reportedAlertErrors[Hs]){const Va=ErrorUtil.ALERT_ERRORS[Xs];Va&&(AlertController.open(Va,"error"),this.reportedAlertErrors[Hs]=!0)}}getAdapter(Ps){if(Ps)return this.chainAdapters?.[Ps]}createAdapter(Ps){if(!Ps)return;const Ws=Ps.namespace;if(!Ws)return;this.createClients();const Hs=Ps;Hs.namespace=Ws,Hs.construct({namespace:Ws,projectId:this.options?.projectId,networks:this.caipNetworks?.filter(({chainNamespace:Zs})=>Zs===Ws)}),this.chainNamespaces.includes(Ws)||this.chainNamespaces.push(Ws),this.chainAdapters&&(this.chainAdapters[Ws]=Hs)}async open(Ps){await this.injectModalUi(),Ps?.uri&&ConnectionController.setUri(Ps.uri);const{isSwap:Ws,isSend:Hs}=this.toModalOptions();return Ws(Ps)?ModalController.open({...Ps,data:{swap:Ps.arguments}}):Hs(Ps)&&Ps.arguments?this.openSend(Ps.arguments):ModalController.open(Ps)}async close(){await this.injectModalUi(),ModalController.close()}setLoading(Ps,Ws){ModalController.setLoading(Ps,Ws)}async disconnect(Ps){await ConnectionController.disconnect({namespace:Ps})}getSIWX(){return OptionsController.state.siwx}getError(){return""}getChainId(){return ChainController.state.activeCaipNetwork?.id}async switchNetwork(Ps,{throwOnFailure:Ws=!1}={}){const Hs=this.getCaipNetworks().find(Zs=>Zs.id===Ps.id);if(!Hs){AlertController.open(ErrorUtil.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await ChainController.switchActiveNetwork(Hs,{throwOnFailure:Ws})}getWalletProvider(){return ChainController.state.activeChain?ProviderController.state.providers[ChainController.state.activeChain]:null}getWalletProviderType(){return ProviderController.getProviderId(ChainController.state.activeChain)}subscribeProviders(Ps){return ProviderController.subscribeProviders(Ps)}getThemeMode(){return ThemeController.state.themeMode}getThemeVariables(){return ThemeController.state.themeVariables}setThemeMode(Ps){ThemeController.setThemeMode(Ps),setColorTheme(ThemeController.state.themeMode)}setTermsConditionsUrl(Ps){OptionsController.setTermsConditionsUrl(Ps)}setPrivacyPolicyUrl(Ps){OptionsController.setPrivacyPolicyUrl(Ps)}setThemeVariables(Ps){ThemeController.setThemeVariables(Ps),setThemeVariables(ThemeController.state.themeVariables)}subscribeTheme(Ps){return ThemeController.subscribe(Ps)}subscribeConnections(Ps){return this.remoteFeatures.multiWallet?ConnectionController.subscribe(Ps):(AlertController.open(ConstantsUtil$3.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(Ps){return Ps?ChainController.state.chains.get(Ps)?.accountState?.connectedWalletInfo:ChainController.getAccountData()?.connectedWalletInfo}getAccount(Ps){const Ws=Ps||ChainController.state.activeChain,Hs=ConnectorController.getAuthConnector(Ws),Zs=ChainController.getAccountData(Ws),zs=StorageUtil.getConnectedConnectorId(ChainController.state.activeChain),Xs=ConnectionController.getConnections(Ws);if(!Ws)throw new Error("AppKit:getAccount - namespace is required");const Va=Xs.flatMap(Js=>Js.accounts.map(({address:Ma,type:qs,publicKey:Ys})=>CoreHelperUtil.createAccount(Ws,Ma,qs||"eoa",Ys)));if(Zs)return{allAccounts:Va,caipAddress:Zs.caipAddress,address:CoreHelperUtil.getPlainAddress(Zs.caipAddress),isConnected:!!Zs.caipAddress,status:Zs.status,embeddedWalletInfo:Hs&&zs===ConstantsUtil$3.CONNECTOR_ID.AUTH?{user:Zs.user?{...Zs.user,username:StorageUtil.getConnectedSocialUsername()}:void 0,authProvider:Zs.socialProvider||"email",accountType:getPreferredAccountType(Ws),isSmartAccountDeployed:!!Zs.smartAccountDeployed}:void 0}}subscribeAccount(Ps,Ws){const Hs=()=>{const Zs=this.getAccount(Ws);Zs&&Ps(Zs)};Ws?ChainController.subscribeChainProp("accountState",Hs,Ws):ChainController.subscribe(Hs),ConnectorController.subscribe(Hs)}subscribeNetwork(Ps){return ChainController.subscribe(({activeCaipNetwork:Ws})=>{Ps({caipNetwork:Ws,chainId:Ws?.id,caipNetworkId:Ws?.caipNetworkId})})}subscribeWalletInfo(Ps,Ws){return Ws?ChainController.subscribeChainProp("accountState",Hs=>Ps(Hs?.connectedWalletInfo),Ws):ChainController.subscribeChainProp("accountState",Hs=>Ps(Hs?.connectedWalletInfo))}subscribeShouldUpdateToAddress(Ps){ChainController.subscribeChainProp("accountState",Ws=>Ps(Ws?.shouldUpdateToAddress))}subscribeCaipNetworkChange(Ps){ChainController.subscribeKey("activeCaipNetwork",Ps)}getState(){return PublicStateController.state}getRemoteFeatures(){return OptionsController.state.remoteFeatures}subscribeState(Ps){return PublicStateController.subscribe(Ps)}subscribeRemoteFeatures(Ps){return OptionsController.subscribeKey("remoteFeatures",Ps)}showErrorMessage(Ps){SnackController.showError(Ps)}showSuccessMessage(Ps){SnackController.showSuccess(Ps)}getEvent(){return{...EventsController.state}}subscribeEvents(Ps){return EventsController.subscribe(Ps)}replace(Ps){RouterController.replace(Ps)}redirect(Ps){RouterController.push(Ps)}popTransactionStack(Ps){RouterController.popTransactionStack(Ps)}isOpen(){return ModalController.state.open}isTransactionStackEmpty(){return RouterController.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(Ps){OptionsController.setFeatures(Ps)}updateRemoteFeatures(Ps){OptionsController.setRemoteFeatures(Ps)}updateOptions(Ps){const Hs={...OptionsController.state||{},...Ps};OptionsController.setOptions(Hs)}setConnectMethodsOrder(Ps){OptionsController.setConnectMethodsOrder(Ps)}setWalletFeaturesOrder(Ps){OptionsController.setWalletFeaturesOrder(Ps)}setCollapseWallets(Ps){OptionsController.setCollapseWallets(Ps)}setSocialsOrder(Ps){OptionsController.setSocialsOrder(Ps)}getConnectMethodsOrder(){return WalletUtil.getConnectOrderMethod(OptionsController.state.features,ConnectorController.getConnectors())}addNetwork(Ps,Ws){if(this.chainAdapters&&!this.chainAdapters[Ps])throw new Error(`Adapter for namespace ${Ps} doesn't exist`);const Hs=this.extendCaipNetwork(Ws,this.options);this.getCaipNetworks().find(Zs=>Zs.id===Hs.id)||ChainController.addNetwork(Hs)}removeNetwork(Ps,Ws){if(this.chainAdapters&&!this.chainAdapters[Ps])throw new Error(`Adapter for namespace ${Ps} doesn't exist`);this.getCaipNetworks().find(Zs=>Zs.id===Ws)&&ChainController.removeNetwork(Ps,Ws)}}let isInitialized=!1;class AppKit extends AppKitBaseClient{async onAuthProviderConnected(Ps){const Ws=HelpersUtil$1.userChainIdToChainNamespace(Ps?.chainId);if(Ps.message&&Ps.signature&&Ps.siwxMessage&&await SIWXUtil.addEmbeddedWalletSession({chainId:Ps.siwxMessage.chainId,accountAddress:Ps.address,notBefore:Ps.siwxMessage.notBefore,statement:Ps.siwxMessage.statement,resources:Ps.siwxMessage.resources,requestId:Ps.siwxMessage.requestId,issuedAt:Ps.siwxMessage.issuedAt,domain:Ps.siwxMessage.domain,uri:Ps.siwxMessage.uri,version:Ps.siwxMessage.version,nonce:Ps.siwxMessage.nonce},Ps.message,Ps.signature),!Ws)throw new Error("AppKit:onAuthProviderConnected - namespace is required");const Hs=Ws===ConstantsUtil$3.CHAIN.EVM?`eip155:${Ps.chainId}:${Ps.address}`:`${Ps.chainId}:${Ps.address}`,Zs=OptionsController.state.defaultAccountTypes[Ws],zs=getPreferredAccountType(Ws),Xs=Ps.preferredAccountType||zs||Zs;this.setCaipAddress(Hs,Ws);const{signature:Va,siwxMessage:Js,message:Ma,...qs}=Ps,Ys=ChainController.getAccountData(Ws);this.setUser({...Ys?.user||{},...qs},Ws),this.setSmartAccountDeployed(!!Ps.smartAccountDeployed,Ws),this.setPreferredAccountType(Xs,Ws),await Promise.all([this.syncAuthConnectorTheme(this.authProvider),this.syncAccount({address:Ps.address,chainId:Ps.chainId,chainNamespace:Ws})]),this.setLoading(!1,Ws)}setupAuthConnectorListeners(Ps){Ps.onRpcRequest(Ws=>{W3mFrameHelpers.checkIfRequestExists(Ws)?W3mFrameHelpers.checkIfRequestIsSafe(Ws)||this.handleUnsafeRPCRequest():(this.open(),console.error(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_MESSAGE,{method:Ws.method}),setTimeout(()=>{this.showErrorMessage(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_UI_MESSAGE)},300),Ps.rejectRpcRequests())}),Ps.onRpcError(()=>{this.isOpen()&&(this.isTransactionStackEmpty()?this.close():this.popTransactionStack("error"))}),Ps.onRpcSuccess((Ws,Hs)=>{const Zs=W3mFrameHelpers.checkIfRequestIsSafe(Hs),zs=this.getAddress(),Xs=ChainController.state.activeCaipNetwork;Zs||(zs&&Xs?.id&&this.updateNativeBalance(zs,Xs.id,Xs.chainNamespace),this.isTransactionStackEmpty()?this.close():this.popTransactionStack("success"))}),Ps.onNotConnected(()=>{const Ws=ChainController.state.activeChain;if(!Ws)throw new Error("AppKit:onNotConnected - namespace is required");ConnectorController.getConnectorId(Ws)===ConstantsUtil$3.CONNECTOR_ID.AUTH&&(this.setCaipAddress(null,Ws),this.setLoading(!1,Ws))}),Ps.onConnect(this.onAuthProviderConnected.bind(this)),Ps.onSocialConnected(this.onAuthProviderConnected.bind(this)),Ps.onSetPreferredAccount(({address:Ws,type:Hs})=>{const Zs=ChainController.state.activeChain;if(!Zs)throw new Error("AppKit:onSetPreferredAccount - namespace is required");Ws&&this.setPreferredAccountType(Hs,Zs)})}async syncAuthConnectorTheme(Ps){if(!Ps)return;const Ws=ThemeController.getSnapshot();await Ps.syncTheme({themeMode:Ws.themeMode,themeVariables:Ws.themeVariables,w3mThemeVariables:getW3mThemeVariables(Ws.themeVariables,Ws.themeMode)})}async syncAuthConnector(Ps,Ws){const Hs=ConstantsUtil$3.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(Ws),Zs=Ws===ChainController.state.activeChain;if(!Hs)return;this.setLoading(!0,Ws);const zs=Ps.getLoginEmailUsed();this.setLoading(zs,Ws),zs&&this.setStatus("connecting",Ws);const Xs=Ps.getEmail(),Va=Ps.getUsername(),Js=ChainController.getAccountData(Ws)?.user||{};this.setUser({...Js,username:Va,email:Xs},Ws),this.setupAuthConnectorListeners(Ps);const{isConnected:Ma}=await Ps.isConnected();if(Ws&&Hs&&Zs)if(Ma&&this.connectionControllerClient?.connectExternal){await Ps.init(),await this.syncAuthConnectorTheme(Ps),await this.connectionControllerClient?.connectExternal({id:ConstantsUtil$3.CONNECTOR_ID.AUTH,info:{name:ConstantsUtil$3.CONNECTOR_ID.AUTH},type:ConstantsUtil$1.CONNECTOR_TYPE_AUTH,provider:Ps,chainId:ChainController.getNetworkData(Ws)?.caipNetwork?.id,chain:Ws}),this.setStatus("connected",Ws);const qs=StorageUtil.getConnectedSocialProvider();qs?EventsController.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",address:this.getAddress(),properties:{provider:qs,reconnect:!0}}):EventsController.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:this.getAddress(),properties:{method:"email",name:this.universalProvider?.session?.peer?.metadata?.name||"Unknown",reconnect:!0,view:RouterController.state.view,walletRank:void 0}})}else ConnectorController.getConnectorId(Ws)===ConstantsUtil$3.CONNECTOR_ID.AUTH&&(this.setStatus("disconnected",Ws),StorageUtil.removeConnectedNamespace(Ws));this.setLoading(!1,Ws)}async checkExistingTelegramSocialConnection(Ps){try{if(!CoreHelperUtil.isTelegram())return;const Ws=StorageUtil.getTelegramSocialProvider();if(!Ws||!CoreHelperUtil.isClient())return;const Zs=new URL(window.location.href).searchParams.get("result_uri");if(!Zs)return;Ws&&ChainController.setAccountProp("socialProvider",Ws,Ps),await this.authProvider?.init();const zs=ConnectorController.getAuthConnector();Ws&&zs&&(this.setLoading(!0,Ps),await ConnectionController.connectExternal({id:zs.id,type:zs.type,socialUri:Zs},zs.chain),StorageUtil.setConnectedSocialProvider(Ws),StorageUtil.removeTelegramSocialProvider(),EventsController.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:Ws}}))}catch(Ws){this.setLoading(!1,Ps),console.error("checkExistingSTelegramocialConnection error",Ws)}try{const Ws=new URL(window.location.href);Ws.searchParams.delete("result_uri"),window.history.replaceState({},document.title,Ws.toString())}catch(Ws){console.error("tma social login failed",Ws)}}createAuthProvider(Ps){if(!ConstantsUtil$3.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(Ps))return;const Hs=this.remoteFeatures?.email,Zs=Array.isArray(this.remoteFeatures?.socials)&&this.remoteFeatures.socials.length>0,zs=Hs||Zs,Va=HelpersUtil$1.getActiveNamespaceConnectedToAuth()||Ps;!this.authProvider&&this.options?.projectId&&zs&&(this.authProvider=W3mFrameProviderSingleton.getInstance({projectId:this.options.projectId,enableLogger:this.options.enableAuthLogger,chainId:this.getCaipNetwork(Va)?.caipNetworkId,abortController:ErrorUtil.EmbeddedWalletAbortController,onTimeout:Ma=>{Ma==="iframe_load_failed"?AlertController.open(ErrorUtil.ALERT_ERRORS.IFRAME_LOAD_FAILED,"error"):Ma==="iframe_request_timeout"?AlertController.open(ErrorUtil.ALERT_ERRORS.IFRAME_REQUEST_TIMEOUT,"error"):Ma==="unverified_domain"&&AlertController.open(ErrorUtil.ALERT_ERRORS.UNVERIFIED_DOMAIN,"error")},getActiveCaipNetwork:Ma=>getActiveCaipNetwork(Ma),getCaipNetworks:Ma=>ChainController.getCaipNetworks(Ma)}),PublicStateController.subscribeOpen(Ma=>{!Ma&&this.isTransactionStackEmpty()&&this.authProvider?.rejectRpcRequests()}));const Js=Ps===ChainController.state.activeChain&&OptionsController.state.enableReconnect;OptionsController.state.enableReconnect===!1?this.syncAuthConnectorTheme(this.authProvider):this.authProvider&&Js&&(this.syncAuthConnector(this.authProvider,Ps),this.checkExistingTelegramSocialConnection(Ps))}createAuthProviderForAdapter(Ps){this.createAuthProvider(Ps),this.authProvider&&this.chainAdapters?.[Ps]?.setAuthProvider?.(this.authProvider)}initControllers(Ps){super.initControllers(Ps),this.options.excludeWalletIds&&ApiController.initializeExcludedWallets({ids:this.options.excludeWalletIds})}async switchCaipNetwork(Ps){if(!Ps)return;const Ws=ChainController.state.activeChain,Hs=Ps.chainNamespace,Zs=this.getAddressByChainNamespace(Hs);if(Hs===Ws&&ChainController.getAccountData(Hs)?.caipAddress)await this.getAdapter(Hs)?.switchNetwork({caipNetwork:Ps}),this.setCaipNetwork(Ps);else{const Va=ProviderController.getProviderId(Ws)===ConstantsUtil$1.CONNECTOR_TYPE_AUTH,Js=ProviderController.getProviderId(Hs),Ma=Js===ConstantsUtil$1.CONNECTOR_TYPE_AUTH,qs=ConstantsUtil$3.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(Hs);if(!Hs)throw new Error("AppKit:switchCaipNetwork - networkNamespace is required");if((Va&&Js===void 0||Ma)&&qs)try{ChainController.state.activeChain=Ps.chainNamespace,Zs?await this.getAdapter(Hs)?.switchNetwork({caipNetwork:Ps}):await this.connectionControllerClient?.connectExternal?.({id:ConstantsUtil$3.CONNECTOR_ID.AUTH,provider:this.authProvider,chain:Hs,chainId:Ps.id,type:ConstantsUtil$1.CONNECTOR_TYPE_AUTH,caipNetwork:Ps}),this.setCaipNetwork(Ps)}catch{await this.getAdapter(Hs)?.switchNetwork({caipNetwork:Ps})}else Js===ConstantsUtil$1.CONNECTOR_TYPE_WALLET_CONNECT?(ChainController.state.noAdapters||await this.getAdapter(Hs)?.switchNetwork({caipNetwork:Ps}),this.setCaipNetwork(Ps),this.syncWalletConnectAccount()):(this.setCaipNetwork(Ps),Zs&&this.syncAccount({address:Zs,chainId:Ps.id,chainNamespace:Hs}))}}async initialize(Ps){await super.initialize(Ps),this.chainNamespaces?.forEach(Ws=>{this.createAuthProviderForAdapter(Ws)}),await this.injectModalUi(),PublicStateController.set({initialized:!0})}async syncIdentity({address:Ps,chainId:Ws,chainNamespace:Hs}){const Zs=`${Hs}:${Ws}`;if(this.caipNetworks?.find(Va=>Va.caipNetworkId===Zs)?.testnet){this.setProfileName(null,Hs),this.setProfileImage(null,Hs);return}const Xs=ConnectorController.getConnectorId(Hs)===ConstantsUtil$3.CONNECTOR_ID.AUTH;try{const{name:Va,avatar:Js}=await this.fetchIdentity({address:Ps});!Va&&Xs?await this.syncReownName(Ps,Hs):(this.setProfileName(Va,Hs),this.setProfileImage(Js,Hs))}catch{Ws!==1&&this.setProfileImage(null,Hs)}}syncConnectedWalletInfo(Ps){const Ws=ProviderController.getProviderId(Ps);if(Ws===ConstantsUtil$1.CONNECTOR_TYPE_AUTH){const Hs=this.authProvider;if(Hs){const Zs=StorageUtil.getConnectedSocialProvider()??"email",zs=Hs.getEmail()??Hs.getUsername();this.setConnectedWalletInfo({name:Ws,identifier:zs,social:Zs},Ps)}}else super.syncConnectedWalletInfo(Ps)}async injectModalUi(){if(CoreHelperUtil.isClient()&&!isInitialized)try{const Ps={...ConstantsUtil$2.DEFAULT_FEATURES,...this.options.features},Ws=this.remoteFeatures;if(await this.loadModalComponents(Ps,Ws),CoreHelperUtil.isClient()&&!document.querySelector("w3m-modal")){const Zs=document.createElement("w3m-modal");!OptionsController.state.disableAppend&&!OptionsController.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",Zs)}isInitialized=!0}catch(Ps){console.error("Error injecting modal UI:",Ps)}}async loadModalComponents(Ps,Ws){if(!CoreHelperUtil.isClient())return;const Hs=[];(Ws.email||Ws.socials&&Ws.socials.length>0)&&Hs.push(Promise.resolve().then(()=>embeddedWallet)),Ws.email&&Hs.push(Promise.resolve().then(()=>email)),Ws.socials&&Hs.push(Promise.resolve().then(()=>socials)),Ws.swaps&&Ws.swaps.length>0&&Hs.push(Promise.resolve().then(()=>swaps)),Ps.send&&Hs.push(Promise.resolve().then(()=>send)),Ps.receive&&Hs.push(Promise.resolve().then(()=>receive)),Ws.onramp&&Ws.onramp.length>0&&Hs.push(Promise.resolve().then(()=>onramp)),Ws.payWithExchange&&Hs.push(Promise.resolve().then(()=>payWithExchange)),Ws.activity&&Hs.push(Promise.resolve().then(()=>transactions)),(Ps.pay||Ws.payments)&&Hs.push(Promise.resolve().then(()=>index$2)),Ws.emailCapture&&Hs.push(Promise.resolve().then(()=>dataCapture)),await Promise.all([...Hs,Promise.resolve().then(()=>index$1),Promise.resolve().then(()=>w3mModal)])}}const PACKAGE_VERSION="1.8.9";function createAppKit(Fs){return new AppKit({...Fs,sdkVersion:CoreHelperUtil.generateSdkVersion(Fs.adapters??[],"html",PACKAGE_VERSION)})}var HederaChainId;(function(Fs){Fs.Mainnet="hedera:mainnet",Fs.Testnet="hedera:testnet",Fs.Previewnet="hedera:previewnet",Fs.Devnet="hedera:devnet"})(HederaChainId||(HederaChainId={}));var HederaSessionEvent;(function(Fs){Fs.AccountsChanged="accountsChanged",Fs.ChainChanged="chainChanged"})(HederaSessionEvent||(HederaSessionEvent={}));var HederaJsonRpcMethod;(function(Fs){Fs.GetNodeAddresses="hedera_getNodeAddresses",Fs.ExecuteTransaction="hedera_executeTransaction",Fs.SignMessage="hedera_signMessage",Fs.SignAndExecuteQuery="hedera_signAndExecuteQuery",Fs.SignAndExecuteTransaction="hedera_signAndExecuteTransaction",Fs.SignTransaction="hedera_signTransaction"})(HederaJsonRpcMethod||(HederaJsonRpcMethod={}));function transactionToBase64String(Fs){const Ps=Fs.toBytes();return Buffer$1.from(Ps).toString("base64")}function transactionToTransactionBody(Fs,Ps=null){return Fs._makeTransactionBody(Ps)}function transactionBodyToBase64String(Fs){return Uint8ArrayToBase64String(libExports.proto.TransactionBody.encode(Fs).finish())}function base64StringToSignatureMap(Fs){const Ps=Buffer$1.from(Fs,"base64");return libExports.proto.SignatureMap.decode(Ps)}function Uint8ArrayToBase64String(Fs){return Buffer$1.from(Fs).toString("base64")}function Uint8ArrayToString(Fs){return Buffer$1.from(Fs).toString("utf-8")}function base64StringToUint8Array(Fs){const Ps=Buffer$1.from(Fs,"base64");return new Uint8Array(Ps)}function queryToBase64String(Fs){const Ps=Fs.toBytes();return Buffer$1.from(Ps).toString("base64")}function prefixMessageToSign(Fs){return`Hedera Signed Message:
|
|
464
464
|
`+Fs.length+Fs}function verifyMessageSignature(Fs,Ps,Ws){const Hs=base64StringToSignatureMap(Ps),Zs=Hs.sigPair[0].ed25519||Hs.sigPair[0].ECDSASecp256k1;if(!Zs)throw new Error("Signature not found in signature map");return Ws.verify(Buffer$1.from(prefixMessageToSign(Fs)),Zs)}const LEDGER_ID_MAPPINGS=[[r$y.MAINNET,295,"hedera:mainnet"],[r$y.TESTNET,296,"hedera:testnet"],[r$y.PREVIEWNET,297,"hedera:previewnet"],[r$y.LOCAL_NODE,298,"hedera:devnet"]],DEFAULT_LEDGER_ID=r$y.LOCAL_NODE,DEFAULT_CAIP=LEDGER_ID_MAPPINGS[3][2];function CAIPChainIdToLedgerId(Fs){for(let Ps=0;Ps<LEDGER_ID_MAPPINGS.length;Ps++){const[Ws,Hs,Zs]=LEDGER_ID_MAPPINGS[Ps];if(Fs===Zs)return Ws}return DEFAULT_LEDGER_ID}function ledgerIdToCAIPChainId(Fs){for(let Ps=0;Ps<LEDGER_ID_MAPPINGS.length;Ps++){const[Ws,Hs,Zs]=LEDGER_ID_MAPPINGS[Ps];if(Fs.toString()===Ws.toString())return Zs}return DEFAULT_CAIP}const networkNamespaces=(Fs,Ps,Ws)=>({hedera:{chains:[ledgerIdToCAIPChainId(Fs)],methods:Ps,events:Ws}}),accountAndLedgerFromSession=Fs=>{const Ps=Fs.namespaces.hedera;if(!Ps)throw new Error("No hedera namespace found");return Ps.accounts.map(Ws=>{const[Hs,Zs,zs]=Ws.split(":");return{network:CAIPChainIdToLedgerId(Hs+":"+Zs),account:y$f.fromString(zs)}})};var EVENTS;(function(Fs){Fs.extensionQuery="hedera-extension-query",Fs.extensionConnect="hedera-extension-connect-",Fs.extensionOpen="hedera-extension-open-",Fs.extensionResponse="hedera-extension-response",Fs.iframeQuery="hedera-iframe-query",Fs.iframeQueryResponse="hedera-iframe-response",Fs.iframeConnect="hedera-iframe-connect"})(EVENTS||(EVENTS={}));const findExtensions=Fs=>{typeof window>"u"||(window.addEventListener("message",Ps=>{var Ws,Hs;((Ws=Ps?.data)===null||Ws===void 0?void 0:Ws.type)==EVENTS.extensionResponse&&Ps.data.metadata&&Fs(Ps.data.metadata,!1),((Hs=Ps?.data)===null||Hs===void 0?void 0:Hs.type)==EVENTS.iframeQueryResponse&&Ps.data.metadata&&Fs(Ps.data.metadata,!0)}),setTimeout(()=>{extensionQuery()},200))},extensionQuery=()=>{window.postMessage({type:EVENTS.extensionQuery},"*"),window.parent&&window.parent.postMessage({type:EVENTS.iframeQuery},"*")},extensionConnect=(Fs,Ps,Ws)=>{if(Ps){window.parent.postMessage({type:EVENTS.iframeConnect,pairingString:Ws},"*");return}window.postMessage({type:EVENTS.extensionConnect+Fs,pairingString:Ws},"*")},extensionOpen=Fs=>{window.postMessage({type:EVENTS.extensionOpen+Fs},"*")};var l$g={exports:{}},h$c=typeof Reflect=="object"?Reflect:null,y$6=h$c&&typeof h$c.apply=="function"?h$c.apply:function(Fs,Ps,Ws){return Function.prototype.apply.call(Fs,Ps,Ws)},f$k;h$c&&typeof h$c.ownKeys=="function"?f$k=h$c.ownKeys:Object.getOwnPropertySymbols?f$k=function(Fs){return Object.getOwnPropertyNames(Fs).concat(Object.getOwnPropertySymbols(Fs))}:f$k=function(Fs){return Object.getOwnPropertyNames(Fs)};function K$1(Fs){console&&console.warn&&console.warn(Fs)}var w$d=Number.isNaN||function(Fs){return Fs!==Fs};function o$v(){o$v.init.call(this)}l$g.exports=o$v,l$g.exports.once=F$1,o$v.EventEmitter=o$v,o$v.prototype._events=void 0,o$v.prototype._eventsCount=0,o$v.prototype._maxListeners=void 0;var L$2=10;function g$h(Fs){if(typeof Fs!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof Fs)}Object.defineProperty(o$v,"defaultMaxListeners",{enumerable:!0,get:function(){return L$2},set:function(Fs){if(typeof Fs!="number"||Fs<0||w$d(Fs))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+Fs+".");L$2=Fs}}),o$v.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o$v.prototype.setMaxListeners=function(Fs){if(typeof Fs!="number"||Fs<0||w$d(Fs))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+Fs+".");return this._maxListeners=Fs,this};function S$4(Fs){return Fs._maxListeners===void 0?o$v.defaultMaxListeners:Fs._maxListeners}o$v.prototype.getMaxListeners=function(){return S$4(this)},o$v.prototype.emit=function(Fs){for(var Ps=[],Ws=1;Ws<arguments.length;Ws++)Ps.push(arguments[Ws]);var Hs=Fs==="error",Zs=this._events;if(Zs!==void 0)Hs=Hs&&Zs.error===void 0;else if(!Hs)return!1;if(Hs){var zs;if(Ps.length>0&&(zs=Ps[0]),zs instanceof Error)throw zs;var Xs=new Error("Unhandled error."+(zs?" ("+zs.message+")":""));throw Xs.context=zs,Xs}var Va=Zs[Fs];if(Va===void 0)return!1;if(typeof Va=="function")y$6(Va,this,Ps);else for(var Js=Va.length,Ma=b$4(Va,Js),Ws=0;Ws<Js;++Ws)y$6(Ma[Ws],this,Ps);return!0};function _$2(Fs,Ps,Ws,Hs){var Zs,zs,Xs;if(g$h(Ws),zs=Fs._events,zs===void 0?(zs=Fs._events=Object.create(null),Fs._eventsCount=0):(zs.newListener!==void 0&&(Fs.emit("newListener",Ps,Ws.listener?Ws.listener:Ws),zs=Fs._events),Xs=zs[Ps]),Xs===void 0)Xs=zs[Ps]=Ws,++Fs._eventsCount;else if(typeof Xs=="function"?Xs=zs[Ps]=Hs?[Ws,Xs]:[Xs,Ws]:Hs?Xs.unshift(Ws):Xs.push(Ws),Zs=S$4(Fs),Zs>0&&Xs.length>Zs&&!Xs.warned){Xs.warned=!0;var Va=new Error("Possible EventEmitter memory leak detected. "+Xs.length+" "+String(Ps)+" listeners added. Use emitter.setMaxListeners() to increase limit");Va.name="MaxListenersExceededWarning",Va.emitter=Fs,Va.type=Ps,Va.count=Xs.length,K$1(Va)}return Fs}o$v.prototype.addListener=function(Fs,Ps){return _$2(this,Fs,Ps,!1)},o$v.prototype.on=o$v.prototype.addListener,o$v.prototype.prependListener=function(Fs,Ps){return _$2(this,Fs,Ps,!0)};function k$2(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function C$1(Fs,Ps,Ws){var Hs={fired:!1,wrapFn:void 0,target:Fs,type:Ps,listener:Ws},Zs=k$2.bind(Hs);return Zs.listener=Ws,Hs.wrapFn=Zs,Zs}o$v.prototype.once=function(Fs,Ps){return g$h(Ps),this.on(Fs,C$1(this,Fs,Ps)),this},o$v.prototype.prependOnceListener=function(Fs,Ps){return g$h(Ps),this.prependListener(Fs,C$1(this,Fs,Ps)),this},o$v.prototype.removeListener=function(Fs,Ps){var Ws,Hs,Zs,zs,Xs;if(g$h(Ps),Hs=this._events,Hs===void 0)return this;if(Ws=Hs[Fs],Ws===void 0)return this;if(Ws===Ps||Ws.listener===Ps)--this._eventsCount===0?this._events=Object.create(null):(delete Hs[Fs],Hs.removeListener&&this.emit("removeListener",Fs,Ws.listener||Ps));else if(typeof Ws!="function"){for(Zs=-1,zs=Ws.length-1;zs>=0;zs--)if(Ws[zs]===Ps||Ws[zs].listener===Ps){Xs=Ws[zs].listener,Zs=zs;break}if(Zs<0)return this;Zs===0?Ws.shift():W$1(Ws,Zs),Ws.length===1&&(Hs[Fs]=Ws[0]),Hs.removeListener!==void 0&&this.emit("removeListener",Fs,Xs||Ps)}return this},o$v.prototype.off=o$v.prototype.removeListener,o$v.prototype.removeAllListeners=function(Fs){var Ps,Ws,Hs;if(Ws=this._events,Ws===void 0)return this;if(Ws.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):Ws[Fs]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete Ws[Fs]),this;if(arguments.length===0){var Zs=Object.keys(Ws),zs;for(Hs=0;Hs<Zs.length;++Hs)zs=Zs[Hs],zs!=="removeListener"&&this.removeAllListeners(zs);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(Ps=Ws[Fs],typeof Ps=="function")this.removeListener(Fs,Ps);else if(Ps!==void 0)for(Hs=Ps.length-1;Hs>=0;Hs--)this.removeListener(Fs,Ps[Hs]);return this};function E$3(Fs,Ps,Ws){var Hs=Fs._events;if(Hs===void 0)return[];var Zs=Hs[Ps];return Zs===void 0?[]:typeof Zs=="function"?Ws?[Zs.listener||Zs]:[Zs]:Ws?D$2(Zs):b$4(Zs,Zs.length)}o$v.prototype.listeners=function(Fs){return E$3(this,Fs,!0)},o$v.prototype.rawListeners=function(Fs){return E$3(this,Fs,!1)},o$v.listenerCount=function(Fs,Ps){return typeof Fs.listenerCount=="function"?Fs.listenerCount(Ps):O$3.call(Fs,Ps)},o$v.prototype.listenerCount=O$3;function O$3(Fs){var Ps=this._events;if(Ps!==void 0){var Ws=Ps[Fs];if(typeof Ws=="function")return 1;if(Ws!==void 0)return Ws.length}return 0}o$v.prototype.eventNames=function(){return this._eventsCount>0?f$k(this._events):[]};function b$4(Fs,Ps){for(var Ws=new Array(Ps),Hs=0;Hs<Ps;++Hs)Ws[Hs]=Fs[Hs];return Ws}function W$1(Fs,Ps){for(;Ps+1<Fs.length;Ps++)Fs[Ps]=Fs[Ps+1];Fs.pop()}function D$2(Fs){for(var Ps=new Array(Fs.length),Ws=0;Ws<Ps.length;++Ws)Ps[Ws]=Fs[Ws].listener||Fs[Ws];return Ps}function F$1(Fs,Ps){return new Promise(function(Ws,Hs){function Zs(Xs){Fs.removeListener(Ps,zs),Hs(Xs)}function zs(){typeof Fs.removeListener=="function"&&Fs.removeListener("error",Zs),Ws([].slice.call(arguments))}x$2(Fs,Ps,zs,{once:!0}),Ps!=="error"&&z$2(Fs,Zs,{once:!0})})}function z$2(Fs,Ps,Ws){typeof Fs.on=="function"&&x$2(Fs,"error",Ps,Ws)}function x$2(Fs,Ps,Ws,Hs){if(typeof Fs.on=="function")Hs.once?Fs.once(Ps,Ws):Fs.on(Ps,Ws);else if(typeof Fs.addEventListener=="function")Fs.addEventListener(Ps,function Zs(zs){Hs.once&&Fs.removeEventListener(Ps,Zs),Ws(zs)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof Fs)}const t$I=Symbol(),s$m=Object.getPrototypeOf,c$j=new WeakMap,l$f=Fs=>Fs&&(c$j.has(Fs)?c$j.get(Fs):s$m(Fs)===Object.prototype||s$m(Fs)===Array.prototype),y$5=Fs=>l$f(Fs)&&Fs[t$I]||null,h$b=(Fs,Ps=!0)=>{c$j.set(Fs,Ps)},__vite_import_meta_env__$1={},isObject$1=Fs=>typeof Fs=="object"&&Fs!==null,proxyStateMap$1=new WeakMap,refSet$1=new WeakSet,buildProxyFunction=(Fs=Object.is,Ps=(Ma,qs)=>new Proxy(Ma,qs),Ws=Ma=>isObject$1(Ma)&&!refSet$1.has(Ma)&&(Array.isArray(Ma)||!(Symbol.iterator in Ma))&&!(Ma instanceof WeakMap)&&!(Ma instanceof WeakSet)&&!(Ma instanceof Error)&&!(Ma instanceof Number)&&!(Ma instanceof Date)&&!(Ma instanceof String)&&!(Ma instanceof RegExp)&&!(Ma instanceof ArrayBuffer),Hs=Ma=>{switch(Ma.status){case"fulfilled":return Ma.value;case"rejected":throw Ma.reason;default:throw Ma}},Zs=new WeakMap,zs=(Ma,qs,Ys=Hs)=>{const Hc=Zs.get(Ma);if(Hc?.[0]===qs)return Hc[1];const ol=Array.isArray(Ma)?[]:Object.create(Object.getPrototypeOf(Ma));return h$b(ol,!0),Zs.set(Ma,[qs,ol]),Reflect.ownKeys(Ma).forEach(Vc=>{if(Object.getOwnPropertyDescriptor(ol,Vc))return;const Dc=Reflect.get(Ma,Vc),al={value:Dc,enumerable:!0,configurable:!0};if(refSet$1.has(Dc))h$b(Dc,!1);else if(Dc instanceof Promise)delete al.value,al.get=()=>Ys(Dc);else if(proxyStateMap$1.has(Dc)){const[dl,hl]=proxyStateMap$1.get(Dc);al.value=zs(dl,hl(),Ys)}Object.defineProperty(ol,Vc,al)}),Object.preventExtensions(ol)},Xs=new WeakMap,Va=[1,1],Js=Ma=>{if(!isObject$1(Ma))throw new Error("object required");const qs=Xs.get(Ma);if(qs)return qs;let Ys=Va[0];const Hc=new Set,ol=(wl,Sl=++Va[0])=>{Ys!==Sl&&(Ys=Sl,Hc.forEach(fl=>fl(wl,Sl)))};let Vc=Va[1];const Dc=(wl=++Va[1])=>(Vc!==wl&&!Hc.size&&(Vc=wl,dl.forEach(([Sl])=>{const fl=Sl[1](wl);fl>Ys&&(Ys=fl)})),Ys),al=wl=>(Sl,fl)=>{const Mc=[...Sl];Mc[1]=[wl,...Mc[1]],ol(Mc,fl)},dl=new Map,hl=(wl,Sl)=>{if((__vite_import_meta_env__$1?"production":void 0)!=="production"&&dl.has(wl))throw new Error("prop listener already exists");if(Hc.size){const fl=Sl[3](al(wl));dl.set(wl,[Sl,fl])}else dl.set(wl,[Sl])},pl=wl=>{var Sl;const fl=dl.get(wl);fl&&(dl.delete(wl),(Sl=fl[1])==null||Sl.call(fl))},gl=wl=>(Hc.add(wl),Hc.size===1&&dl.forEach(([fl,Mc],tl)=>{if((__vite_import_meta_env__$1?"production":void 0)!=="production"&&Mc)throw new Error("remove already exists");const nl=fl[3](al(tl));dl.set(tl,[fl,nl])}),()=>{Hc.delete(wl),Hc.size===0&&dl.forEach(([fl,Mc],tl)=>{Mc&&(Mc(),dl.set(tl,[fl]))})}),yl=Array.isArray(Ma)?[]:Object.create(Object.getPrototypeOf(Ma)),Il=Ps(yl,{deleteProperty(wl,Sl){const fl=Reflect.get(wl,Sl);pl(Sl);const Mc=Reflect.deleteProperty(wl,Sl);return Mc&&ol(["delete",[Sl],fl]),Mc},set(wl,Sl,fl,Mc){const tl=Reflect.has(wl,Sl),nl=Reflect.get(wl,Sl,Mc);if(tl&&(Fs(nl,fl)||Xs.has(fl)&&Fs(nl,Xs.get(fl))))return!0;pl(Sl),isObject$1(fl)&&(fl=y$5(fl)||fl);let rl=fl;if(fl instanceof Promise)fl.then(il=>{fl.status="fulfilled",fl.value=il,ol(["resolve",[Sl],il])}).catch(il=>{fl.status="rejected",fl.reason=il,ol(["reject",[Sl],il])});else{!proxyStateMap$1.has(fl)&&Ws(fl)&&(rl=Js(fl));const il=!refSet$1.has(rl)&&proxyStateMap$1.get(rl);il&&hl(Sl,il)}return Reflect.set(wl,Sl,rl,Mc),ol(["set",[Sl],fl,nl]),!0}});Xs.set(Ma,Il);const El=[yl,Dc,zs,gl];return proxyStateMap$1.set(Il,El),Reflect.ownKeys(Ma).forEach(wl=>{const Sl=Object.getOwnPropertyDescriptor(Ma,wl);"value"in Sl&&(Il[wl]=Ma[wl],delete Sl.value,delete Sl.writable),Object.defineProperty(yl,wl,Sl)}),Il})=>[Js,proxyStateMap$1,refSet$1,Fs,Ps,Ws,Hs,Zs,zs,Xs,Va],[defaultProxyFunction]=buildProxyFunction();function proxy$1(Fs={}){return defaultProxyFunction(Fs)}function subscribe$1(Fs,Ps,Ws){const Hs=proxyStateMap$1.get(Fs);(__vite_import_meta_env__$1?"production":void 0)!=="production"&&!Hs&&console.warn("Please use proxy object");let Zs;const zs=[],Xs=Hs[3];let Va=!1;const Ma=Xs(qs=>{zs.push(qs),Zs||(Zs=Promise.resolve().then(()=>{Zs=void 0,Va&&Ps(zs.splice(0))}))});return Va=!0,()=>{Va=!1,Ma()}}function snapshot(Fs,Ps){const Ws=proxyStateMap$1.get(Fs);(__vite_import_meta_env__$1?"production":void 0)!=="production"&&!Ws&&console.warn("Please use proxy object");const[Hs,Zs,zs]=Ws;return zs(Hs,Zs(),Ps)}const state$7=proxy$1({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),RouterCtrl={state:state$7,subscribe(Fs){return subscribe$1(state$7,()=>Fs(state$7))},push(Fs,Ps){Fs!==state$7.view&&(state$7.view=Fs,Ps&&(state$7.data=Ps),state$7.history.push(Fs))},reset(Fs){state$7.view=Fs,state$7.history=[Fs]},replace(Fs){state$7.history.length>1&&(state$7.history[state$7.history.length-1]=Fs,state$7.view=Fs)},goBack(){if(state$7.history.length>1){state$7.history.pop();const[Fs]=state$7.history.slice(-1);state$7.view=Fs}},setData(Fs){state$7.data=Fs}},CoreUtil={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return CoreUtil.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const Fs=navigator.userAgent.toLowerCase();return CoreUtil.isMobile()&&(Fs.includes("iphone")||Fs.includes("ipad"))},isHttpUrl(Fs){return Fs.startsWith("http://")||Fs.startsWith("https://")},isArray(Fs){return Array.isArray(Fs)&&Fs.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(Fs,Ps,Ws){if(CoreUtil.isHttpUrl(Fs))return this.formatUniversalUrl(Fs,Ps,Ws);let Hs=Fs;Hs.includes("://")||(Hs=Fs.replaceAll("/","").replaceAll(":",""),Hs=`${Hs}://`),Hs.endsWith("/")||(Hs=`${Hs}/`),this.setWalletConnectDeepLink(Hs,Ws);const Zs=encodeURIComponent(Ps);return`${Hs}wc?uri=${Zs}`},formatUniversalUrl(Fs,Ps,Ws){if(!CoreUtil.isHttpUrl(Fs))return this.formatNativeUrl(Fs,Ps,Ws);let Hs=Fs;if(Hs.startsWith("https://t.me")){const zs=Buffer.from(Ps).toString("base64").replace(/[=]/g,"");Hs.endsWith("/")&&(Hs=Hs.slice(0,-1)),this.setWalletConnectDeepLink(Hs,Ws);const Xs=new URL(Hs);return Xs.searchParams.set("startapp",zs),Xs.toString()}Hs.endsWith("/")||(Hs=`${Hs}/`),this.setWalletConnectDeepLink(Hs,Ws);const Zs=encodeURIComponent(Ps);return`${Hs}wc?uri=${Zs}`},async wait(Fs){return new Promise(Ps=>{setTimeout(Ps,Fs)})},openHref(Fs,Ps){const Ws=this.isTelegram()?"_blank":Ps;window.open(Fs,Ws,"noreferrer noopener")},setWalletConnectDeepLink(Fs,Ps){try{localStorage.setItem(CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:Fs,name:Ps}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(Fs){try{const[Ps]=Fs.split("?");localStorage.setItem(CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:Ps,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(CoreUtil.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var Fs;const Ps=(Fs=RouterCtrl.state.data)==null?void 0:Fs.Wallet;if(!Ps)throw new Error('Missing "Wallet" view data');return Ps}},isEnabled=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),state$6=proxy$1({enabled:isEnabled,userSessionId:"",events:[],connectedWalletId:void 0}),EventsCtrl={state:state$6,subscribe(Fs){return subscribe$1(state$6.events,()=>Fs(snapshot(state$6.events[state$6.events.length-1])))},initialize(){state$6.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(state$6.userSessionId=crypto.randomUUID())},setConnectedWalletId(Fs){state$6.connectedWalletId=Fs},click(Fs){if(state$6.enabled){const Ps={type:"CLICK",name:Fs.name,userSessionId:state$6.userSessionId,timestamp:Date.now(),data:Fs};state$6.events.push(Ps)}},track(Fs){if(state$6.enabled){const Ps={type:"TRACK",name:Fs.name,userSessionId:state$6.userSessionId,timestamp:Date.now(),data:Fs};state$6.events.push(Ps)}},view(Fs){if(state$6.enabled){const Ps={type:"VIEW",name:Fs.name,userSessionId:state$6.userSessionId,timestamp:Date.now(),data:Fs};state$6.events.push(Ps)}}},state$5=proxy$1({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),OptionsCtrl={state:state$5,subscribe(Fs){return subscribe$1(state$5,()=>Fs(state$5))},setChains(Fs){state$5.chains=Fs},setWalletConnectUri(Fs){state$5.walletConnectUri=Fs},setIsCustomDesktop(Fs){state$5.isCustomDesktop=Fs},setIsCustomMobile(Fs){state$5.isCustomMobile=Fs},setIsDataLoaded(Fs){state$5.isDataLoaded=Fs},setIsUiLoaded(Fs){state$5.isUiLoaded=Fs},setIsAuth(Fs){state$5.isAuth=Fs}},state$4=proxy$1({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),ConfigCtrl={state:state$4,subscribe(Fs){return subscribe$1(state$4,()=>Fs(state$4))},setConfig(Fs){var Ps,Ws;EventsCtrl.initialize(),OptionsCtrl.setChains(Fs.chains),OptionsCtrl.setIsAuth(!!Fs.enableAuthMode),OptionsCtrl.setIsCustomMobile(!!((Ps=Fs.mobileWallets)!=null&&Ps.length)),OptionsCtrl.setIsCustomDesktop(!!((Ws=Fs.desktopWallets)!=null&&Ws.length)),CoreUtil.setModalVersionInStorage(),Object.assign(state$4,Fs)}};var __defProp$2=Object.defineProperty,__getOwnPropSymbols$2=Object.getOwnPropertySymbols,__hasOwnProp$2=Object.prototype.hasOwnProperty,__propIsEnum$2=Object.prototype.propertyIsEnumerable,__defNormalProp$2=(Fs,Ps,Ws)=>Ps in Fs?__defProp$2(Fs,Ps,{enumerable:!0,configurable:!0,writable:!0,value:Ws}):Fs[Ps]=Ws,__spreadValues$2=(Fs,Ps)=>{for(var Ws in Ps||(Ps={}))__hasOwnProp$2.call(Ps,Ws)&&__defNormalProp$2(Fs,Ws,Ps[Ws]);if(__getOwnPropSymbols$2)for(var Ws of __getOwnPropSymbols$2(Ps))__propIsEnum$2.call(Ps,Ws)&&__defNormalProp$2(Fs,Ws,Ps[Ws]);return Fs};const W3M_API="https://explorer-api.walletconnect.com",SDK_TYPE="wcm",SDK_VERSION="js-2.7.0";async function fetchListings(Fs,Ps){const Ws=__spreadValues$2({sdkType:SDK_TYPE,sdkVersion:SDK_VERSION},Ps),Hs=new URL(Fs,W3M_API);return Hs.searchParams.append("projectId",ConfigCtrl.state.projectId),Object.entries(Ws).forEach(([zs,Xs])=>{Xs&&Hs.searchParams.append(zs,String(Xs))}),(await fetch(Hs)).json()}const ExplorerUtil={async getDesktopListings(Fs){return fetchListings("/w3m/v1/getDesktopListings",Fs)},async getMobileListings(Fs){return fetchListings("/w3m/v1/getMobileListings",Fs)},async getInjectedListings(Fs){return fetchListings("/w3m/v1/getInjectedListings",Fs)},async getAllListings(Fs){return fetchListings("/w3m/v1/getAllListings",Fs)},getWalletImageUrl(Fs){return`${W3M_API}/w3m/v1/getWalletImage/${Fs}?projectId=${ConfigCtrl.state.projectId}&sdkType=${SDK_TYPE}&sdkVersion=${SDK_VERSION}`},getAssetImageUrl(Fs){return`${W3M_API}/w3m/v1/getAssetImage/${Fs}?projectId=${ConfigCtrl.state.projectId}&sdkType=${SDK_TYPE}&sdkVersion=${SDK_VERSION}`}};var __defProp$1$1=Object.defineProperty,__getOwnPropSymbols$1=Object.getOwnPropertySymbols,__hasOwnProp$1=Object.prototype.hasOwnProperty,__propIsEnum$1=Object.prototype.propertyIsEnumerable,__defNormalProp$1=(Fs,Ps,Ws)=>Ps in Fs?__defProp$1$1(Fs,Ps,{enumerable:!0,configurable:!0,writable:!0,value:Ws}):Fs[Ps]=Ws,__spreadValues$1=(Fs,Ps)=>{for(var Ws in Ps||(Ps={}))__hasOwnProp$1.call(Ps,Ws)&&__defNormalProp$1(Fs,Ws,Ps[Ws]);if(__getOwnPropSymbols$1)for(var Ws of __getOwnPropSymbols$1(Ps))__propIsEnum$1.call(Ps,Ws)&&__defNormalProp$1(Fs,Ws,Ps[Ws]);return Fs};const isMobile=CoreUtil.isMobile(),state$3=proxy$1({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),ExplorerCtrl={state:state$3,async getRecomendedWallets(){const{explorerRecommendedWalletIds:Fs,explorerExcludedWalletIds:Ps}=ConfigCtrl.state;if(Fs==="NONE"||Ps==="ALL"&&!Fs)return state$3.recomendedWallets;if(CoreUtil.isArray(Fs)){const Hs={recommendedIds:Fs.join(",")},{listings:Zs}=await ExplorerUtil.getAllListings(Hs),zs=Object.values(Zs);zs.sort((Xs,Va)=>{const Js=Fs.indexOf(Xs.id),Ma=Fs.indexOf(Va.id);return Js-Ma}),state$3.recomendedWallets=zs}else{const{chains:Ws,isAuth:Hs}=OptionsCtrl.state,Zs=Ws?.join(","),zs=CoreUtil.isArray(Ps),Xs={page:1,sdks:Hs?"auth_v1":void 0,entries:CoreUtil.RECOMMENDED_WALLET_AMOUNT,chains:Zs,version:2,excludedIds:zs?Ps.join(","):void 0},{listings:Va}=isMobile?await ExplorerUtil.getMobileListings(Xs):await ExplorerUtil.getDesktopListings(Xs);state$3.recomendedWallets=Object.values(Va)}return state$3.recomendedWallets},async getWallets(Fs){const Ps=__spreadValues$1({},Fs),{explorerRecommendedWalletIds:Ws,explorerExcludedWalletIds:Hs}=ConfigCtrl.state,{recomendedWallets:Zs}=state$3;if(Hs==="ALL")return state$3.wallets;Zs.length?Ps.excludedIds=Zs.map(Ys=>Ys.id).join(","):CoreUtil.isArray(Ws)&&(Ps.excludedIds=Ws.join(",")),CoreUtil.isArray(Hs)&&(Ps.excludedIds=[Ps.excludedIds,Hs].filter(Boolean).join(",")),OptionsCtrl.state.isAuth&&(Ps.sdks="auth_v1");const{page:zs,search:Xs}=Fs,{listings:Va,total:Js}=isMobile?await ExplorerUtil.getMobileListings(Ps):await ExplorerUtil.getDesktopListings(Ps),Ma=Object.values(Va),qs=Xs?"search":"wallets";return state$3[qs]={listings:[...state$3[qs].listings,...Ma],total:Js,page:zs??1},{listings:Ma,total:Js}},getWalletImageUrl(Fs){return ExplorerUtil.getWalletImageUrl(Fs)},getAssetImageUrl(Fs){return ExplorerUtil.getAssetImageUrl(Fs)},resetSearch(){state$3.search={listings:[],total:0,page:1}}},state$2=proxy$1({open:!1}),ModalCtrl={state:state$2,subscribe(Fs){return subscribe$1(state$2,()=>Fs(state$2))},async open(Fs){return new Promise(Ps=>{const{isUiLoaded:Ws,isDataLoaded:Hs}=OptionsCtrl.state;if(CoreUtil.removeWalletConnectDeepLink(),OptionsCtrl.setWalletConnectUri(Fs?.uri),OptionsCtrl.setChains(Fs?.chains),RouterCtrl.reset("ConnectWallet"),Ws&&Hs)state$2.open=!0,Ps();else{const Zs=setInterval(()=>{const zs=OptionsCtrl.state;zs.isUiLoaded&&zs.isDataLoaded&&(clearInterval(Zs),state$2.open=!0,Ps())},200)}})},close(){state$2.open=!1}};var __defProp$3=Object.defineProperty,__getOwnPropSymbols$3=Object.getOwnPropertySymbols,__hasOwnProp$3=Object.prototype.hasOwnProperty,__propIsEnum$3=Object.prototype.propertyIsEnumerable,__defNormalProp$3=(Fs,Ps,Ws)=>Ps in Fs?__defProp$3(Fs,Ps,{enumerable:!0,configurable:!0,writable:!0,value:Ws}):Fs[Ps]=Ws,__spreadValues$3=(Fs,Ps)=>{for(var Ws in Ps||(Ps={}))__hasOwnProp$3.call(Ps,Ws)&&__defNormalProp$3(Fs,Ws,Ps[Ws]);if(__getOwnPropSymbols$3)for(var Ws of __getOwnPropSymbols$3(Ps))__propIsEnum$3.call(Ps,Ws)&&__defNormalProp$3(Fs,Ws,Ps[Ws]);return Fs};function isDarkMode(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const state$1=proxy$1({themeMode:isDarkMode()?"dark":"light"}),ThemeCtrl={state:state$1,subscribe(Fs){return subscribe$1(state$1,()=>Fs(state$1))},setThemeConfig(Fs){const{themeMode:Ps,themeVariables:Ws}=Fs;Ps&&(state$1.themeMode=Ps),Ws&&(state$1.themeVariables=__spreadValues$3({},Ws))}},state$8=proxy$1({open:!1,message:"",variant:"success"}),ToastCtrl={state:state$8,subscribe(Fs){return subscribe$1(state$8,()=>Fs(state$8))},openToast(Fs,Ps){state$8.open=!0,state$8.message=Fs,state$8.variant=Ps},closeToast(){state$8.open=!1}};class WalletConnectModal{constructor(Ps){this.openModal=ModalCtrl.open,this.closeModal=ModalCtrl.close,this.subscribeModal=ModalCtrl.subscribe,this.setTheme=ThemeCtrl.setThemeConfig,ThemeCtrl.setThemeConfig(Ps),ConfigCtrl.setConfig(Ps),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(()=>index);const Ps=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",Ps),OptionsCtrl.setIsUiLoaded(!0)}}}var _a;class DefaultLogger{constructor(Ps="info",Ws){this.logLevel="info",this.logLevel=Ps,this.name=Ws||"Logger"}setLogLevel(Ps){this.logLevel=Ps}getLogLevel(){return this.logLevel}error(Ps,...Ws){["error","warn","info","debug"].includes(this.logLevel)&&console.error(`[ERROR - ${this.name}] ${Ps}`,...Ws)}warn(Ps,...Ws){["warn","info","debug"].includes(this.logLevel)&&console.warn(`[WARN - ${this.name}] ${Ps}`,...Ws)}info(Ps,...Ws){["info","debug"].includes(this.logLevel)&&console.info(`[INFO - ${this.name}] ${Ps}`,...Ws)}debug(Ps,...Ws){this.logLevel==="debug"&&console.debug(`[DEBUG - ${this.name}] ${Ps}`,...Ws)}}typeof process$1<"u"&&(!((_a=process$1.env)===null||_a===void 0)&&_a.HWC_LOG_LEVEL)&&process$1.env.HWC_LOG_LEVEL.toLowerCase(),typeof localStorage<"u"&&localStorage.getItem("hwc_log_level");class SessionNotFoundError extends Error{constructor(Ps){super(Ps),this.name="SessionNotFoundError"}}const clients={};class DAppSigner{constructor(Ps,Ws,Hs,Zs=r$y.MAINNET,zs,Xs="debug"){this.accountId=Ps,this.signClient=Ws,this.topic=Hs,this.ledgerId=Zs,this.extensionId=zs,this.logger=new DefaultLogger(Xs)}setLogLevel(Ps){this.logger instanceof DefaultLogger&&this.logger.setLogLevel(Ps)}_getHederaClient(){const Ps=this.ledgerId.toString();return clients[Ps]||(clients[Ps]=a$u.forName(Ps)),clients[Ps]}get _signerAccountId(){return`${ledgerIdToCAIPChainId(this.ledgerId)}:${this.accountId.toString()}`}request(Ps){var Ws,Hs;if(!(!((Hs=(Ws=this===null||this===void 0?void 0:this.signClient)===null||Ws===void 0?void 0:Ws.session)===null||Hs===void 0)&&Hs.get(this.topic)))throw this.logger.error("Session no longer exists, signer will be removed. Please reconnect to the wallet."),this.signClient.emit({topic:this.topic,event:{name:"session_delete",data:{topic:this.topic}},chainId:ledgerIdToCAIPChainId(this.ledgerId)}),new SessionNotFoundError("Session no longer exists. Please reconnect to the wallet.");return this.extensionId&&extensionOpen(this.extensionId),this.signClient.request({topic:this.topic,request:Ps,chainId:ledgerIdToCAIPChainId(this.ledgerId)})}getAccountId(){return this.accountId}getAccountKey(){throw new Error("Method not implemented.")}getLedgerId(){return this.ledgerId}getNetwork(){return this._getHederaClient().network}getMirrorNetwork(){return this._getHederaClient().mirrorNetwork}getAccountBalance(){return this.call(new e$x().setAccountId(this.accountId))}getAccountInfo(){return this.call(new c$A().setAccountId(this.accountId))}getAccountRecords(){return this.call(new e$w().setAccountId(this.accountId))}getMetadata(){return this.signClient.metadata}async sign(Ps,Ws={encoding:"utf-8"}){try{const Hs=Ws.encoding==="base64"?Uint8ArrayToBase64String(Ps[0]):Uint8ArrayToString(Ps[0]),{signatureMap:Zs}=await this.request({method:HederaJsonRpcMethod.SignMessage,params:{signerAccountId:this._signerAccountId,message:Hs}}),zs=base64StringToSignatureMap(Zs),Xs=new t$M({accountId:this.getAccountId(),publicKey:i$v.fromBytes(zs.sigPair[0].pubKeyPrefix),signature:zs.sigPair[0].ed25519||zs.sigPair[0].ECDSASecp256k1});return this.logger.debug("Data signed successfully"),[Xs]}catch(Hs){throw this.logger.error("Error signing data:",Hs),Hs}}async checkTransaction(Ps){throw new Error("Method not implemented.")}async populateTransaction(Ps){return Ps.setTransactionId(i$s.generate(this.getAccountId()))}async signTransaction(Ps){var Ws,Hs;Ps.isFrozen()||Ps.freezeWith(this._getHederaClient());const Zs=(Hs=(Ws=Ps.nodeAccountIds)===null||Ws===void 0?void 0:Ws[0])!==null&&Hs!==void 0?Hs:null,zs=transactionToTransactionBody(Ps,Zs);if(!zs)throw new Error("Failed to serialize transaction body");const Xs=transactionBodyToBase64String(zs),{signatureMap:Va}=await this.request({method:HederaJsonRpcMethod.SignTransaction,params:{signerAccountId:this._signerAccountId,transactionBody:Xs}}),Js=base64StringToSignatureMap(Va),Ma=Ps.toBytes(),Ys=libExports.proto.TransactionList.decode(Ma).transactionList.map(ol=>{if(ol.signedTransactionBytes){const Vc=libExports.proto.SignedTransaction.decode(ol.signedTransactionBytes),al=[...(Vc.sigMap||libExports.proto.SignatureMap.create({})).sigPair||[],...Js.sigPair||[]];return{signedTransactionBytes:libExports.proto.SignedTransaction.encode({bodyBytes:Vc.bodyBytes,sigMap:libExports.proto.SignatureMap.create({sigPair:al})}).finish()}}else{const Vc=ol.sigMap||libExports.proto.SignatureMap.create({}),Dc=[...Vc.sigPair||[],...Js.sigPair||[]];return Object.assign(Object.assign({},ol),{sigMap:Object.assign(Object.assign({},Vc),{sigPair:Dc})})}}),Hc=libExports.proto.TransactionList.encode({transactionList:Ys}).finish();return L$a.fromBytes(Hc)}async _tryExecuteTransactionRequest(Ps){try{const Ws=Ps.toBytes();this.logger.debug("Creating transaction from bytes",Ws,Ps);const Hs=L$a.fromBytes(Ws);this.logger.debug("Executing transaction request",Hs);const Zs=await this.request({method:HederaJsonRpcMethod.SignAndExecuteTransaction,params:{signerAccountId:this._signerAccountId,transactionList:transactionToBase64String(Hs)}});return this.logger.debug("Transaction request completed successfully"),{result:h$n.fromJSON(Zs)}}catch(Ws){return this.logger.error("Error executing transaction request:",Ws),{error:Ws}}}async _parseQueryResponse(Ps,Ws){if(Ps instanceof e$w)return Ws.split(",").map(Xs=>base64StringToUint8Array(Xs)).map(Xs=>b$e.fromBytes(Xs));const Hs=base64StringToUint8Array(Ws);if(Ps instanceof e$x)return a$D.fromBytes(Hs);if(Ps instanceof c$A)return d$p.fromBytes(Hs);if(Ps instanceof l$C)return d$r.fromBytes(Hs);if(Ps instanceof h$o)return b$e.fromBytes(Hs);throw new Error("Unsupported query type")}async executeReceiptQueryFromRequest(Ps){try{const Hs=this.ledgerId===r$y.MAINNET?a$u.forMainnet():a$u.forTestnet();return{result:await l$C.fromBytes(Ps.toBytes()).execute(Hs)}}catch(Ws){return{error:Ws}}}async _tryExecuteQueryRequest(Ps){try{const Ws=Ps instanceof l$C;if(Ws){this.logger.debug("Attempting to execute free receipt query",Ps);const zs=await this.executeReceiptQueryFromRequest(Ps);if(!zs?.error)return{result:zs.result};this.logger.error("Error executing free receipt query. Sending to wallet.",zs.error)}const Hs=Ws?l$C.fromBytes(Ps.toBytes()):h$p.fromBytes(Ps.toBytes());this.logger.debug("Executing query request",Hs,queryToBase64String(Hs),Ws);const Zs=await this.request({method:HederaJsonRpcMethod.SignAndExecuteQuery,params:{signerAccountId:this._signerAccountId,query:queryToBase64String(Hs)}});return this.logger.debug("Query request completed successfully",Zs),{result:this._parseQueryResponse(Hs,Zs.response)}}catch(Ws){return this.logger.error("Error executing query request:",Ws),{error:Ws}}}async call(Ps){var Ws,Hs,Zs,zs,Xs,Va,Js,Ma,qs;const Ys=Ps instanceof l$C;let Hc;if(!Ys&&(Hc=await this._tryExecuteTransactionRequest(Ps),Hc.result))return Hc.result;const ol=await this._tryExecuteQueryRequest(Ps);if(ol.result)return ol.result;throw Ys?new Error(`Error executing receipt query:
|
|
465
465
|
`+JSON.stringify({queryError:{name:(Ws=ol.error)===null||Ws===void 0?void 0:Ws.name,message:(Hs=ol.error)===null||Hs===void 0?void 0:Hs.message,stack:(Zs=ol.error)===null||Zs===void 0?void 0:Zs.stack}})):new Error(`Error executing transaction or query:
|
|
466
|
-
`+JSON.stringify({txError:{name:(zs=Hc?.error)===null||zs===void 0?void 0:zs.name,message:(Xs=Hc?.error)===null||Xs===void 0?void 0:Xs.message,stack:(Va=Hc?.error)===null||Va===void 0?void 0:Va.stack},queryError:{name:(Js=ol.error)===null||Js===void 0?void 0:Js.name,message:(Ma=ol.error)===null||Ma===void 0?void 0:Ma.message,stack:(qs=ol.error)===null||qs===void 0?void 0:qs.stack}},null,2))}}class DAppConnector{constructor(Ps,Ws,Hs,Zs,zs,Xs,Va="debug"){this.network=r$y.TESTNET,this.supportedMethods=[],this.supportedEvents=[],this.supportedChains=[],this.extensions=[],this.onSessionIframeCreated=null,this.signers=[],this.isInitializing=!1,this.abortableConnect=async Js=>new Promise(async(Ma,qs)=>{const Hc=setTimeout(()=>{this.walletConnectModal.closeModal(),qs(new Error("Connect timed out after 480000(ms)"))},48e4);try{return Ma(await Js())}catch(ol){qs(ol)}finally{clearTimeout(Hc)}}),this.logger=new DefaultLogger(Va),this.dAppMetadata=Ps,this.network=Ws,this.projectId=Hs,this.supportedMethods=Zs??Object.values(HederaJsonRpcMethod),this.supportedEvents=zs??[],this.supportedChains=Xs??[],this.extensions=[],this.walletConnectModal=new WalletConnectModal({projectId:Hs,chains:Xs}),findExtensions((Js,Ma)=>{this.extensions.push(Object.assign(Object.assign({},Js),{available:!0,availableInIframe:Ma}))})}setLogLevel(Ps){this.logger instanceof DefaultLogger&&this.logger.setLogLevel(Ps)}async init({logger:Ps}={}){try{if(this.isInitializing=!0,!this.projectId)throw new Error("Project ID is not defined");this.walletConnectClient=await fe$1.init({logger:Ps,relayUrl:"wss://relay.walletconnect.com",projectId:this.projectId,metadata:this.dAppMetadata});const Ws=this.walletConnectClient.session.getAll();Ws.length>0?this.signers=Ws.flatMap(Hs=>this.createSigners(Hs)):this.checkIframeConnect(),this.walletConnectClient.on("session_event",this.handleSessionEvent.bind(this)),this.walletConnectClient.on("session_update",this.handleSessionUpdate.bind(this)),this.walletConnectClient.on("session_delete",this.handleSessionDelete.bind(this)),this.walletConnectClient.core.events.on("session_delete",this.handleSessionDelete.bind(this)),this.walletConnectClient.core.pairing.events.on("pairing_delete",this.handlePairingDelete.bind(this))}catch(Ws){this.logger.error("Error initializing DAppConnector:",Ws)}finally{this.isInitializing=!1}}getSigner(Ps){if(this.isInitializing)throw new Error("DAppConnector is not initialized yet. Try again later.");const Ws=this.signers.find(Hs=>Hs.getAccountId().equals(Ps));if(!Ws)throw new Error("Signer is not found for this accountId");return Ws}async openModal(Ps,Ws=!1){try{const{uri:Hs,approval:Zs}=await this.connectURI(Ps);return this.walletConnectModal.openModal({uri:Hs}),await new Promise(async(Xs,Va)=>{Ws&&this.walletConnectModal.subscribeModal(Js=>{Js.open||Va(new Error("User rejected pairing"))});try{const Js=await Zs();await this.onSessionConnected(Js),Xs(Js)}catch(Js){Va(Js)}})}finally{this.walletConnectModal.closeModal()}}async connect(Ps,Ws,Hs){return this.abortableConnect(async()=>{var Zs;const{uri:zs,approval:Xs}=await this.connectURI(Ws);if(!zs)throw new Error("URI is not defined");Ps(zs);const Va=await Xs();if(Hs){const Js=Object.assign(Object.assign({},Va.sessionProperties),{extensionId:Hs});Va.sessionProperties=Js,await((Zs=this.walletConnectClient)===null||Zs===void 0?void 0:Zs.session.update(Va.topic,{sessionProperties:Js}))}return await this.onSessionConnected(Va),Va})}async connectExtension(Ps,Ws){const Hs=this.extensions.find(Zs=>Zs.id===Ps);if(!Hs||!Hs.available)throw new Error("Extension is not available");return this.connect(Zs=>{extensionConnect(Hs.id,Hs.availableInIframe,Zs)},Ws,Hs.availableInIframe?void 0:Ps)}validateSession(Ps){try{if(!this.walletConnectClient)return!1;const Ws=this.walletConnectClient.session.get(Ps),Hs=this.signers.some(Zs=>Zs.topic===Ps);return Ws?Hs?!0:(this.logger.warn(`Session exists but no signer found for topic: ${Ps}`),!1):(Hs&&(this.logger.warn(`Signer exists but no session found for topic: ${Ps}`),this.handleSessionDelete({topic:Ps})),!1)}catch(Ws){return this.logger.error("Error validating session:",Ws),!1}}validateAndRefreshSigners(){this.signers=this.signers.filter(Ps=>this.validateSession(Ps.topic))}async checkIframeConnect(){const Ps=this.extensions.find(Ws=>Ws.availableInIframe);if(Ps){const Ws=await this.connectExtension(Ps.id);this.onSessionIframeCreated&&this.onSessionIframeCreated(Ws)}}async disconnect(Ps){try{if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");return await this.walletConnectClient.disconnect({topic:Ps,reason:zt$2("USER_DISCONNECTED")}),!0}catch(Ws){return this.logger.error("Either the session was already disconnected or the topic is invalid",Ws),!1}}async disconnectAll(){if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");const Ps=this.walletConnectClient.session.getAll(),Ws=this.walletConnectClient.core.pairing.getPairings();if(!Ps?.length&&!Ws?.length)throw new Error("There is no active session/pairing. Connect to the wallet at first.");const Hs=[];for(const Zs of this.walletConnectClient.session.getAll()){this.logger.info(`Disconnecting from session: ${Zs}`);const zs=this.disconnect(Zs.topic);Hs.push(zs)}for(const Zs of Ws){const zs=this.disconnect(Zs.topic);Hs.push(zs)}await Promise.all(Hs),this.signers=[]}createSigners(Ps){return accountAndLedgerFromSession(Ps).map(({account:Hs,network:Zs})=>{var zs;return new DAppSigner(Hs,this.walletConnectClient,Ps.topic,Zs,(zs=Ps.sessionProperties)===null||zs===void 0?void 0:zs.extensionId,this.logger instanceof DefaultLogger?this.logger.getLogLevel():"debug")})}async onSessionConnected(Ps){const Ws=this.createSigners(Ps);for(const Hs of Ws){const Zs=this.signers.filter(zs=>{var Xs,Va;const Js=((Xs=zs?.getAccountId())===null||Xs===void 0?void 0:Xs.toString())===((Va=Hs?.getAccountId())===null||Va===void 0?void 0:Va.toString()),Ma=Hs.extensionId===zs.extensionId,qs=Hs.getMetadata(),Ys=zs.getMetadata(),Hc=qs?.name===Ys?.name;return zs.topic===Hs.topic&&this.logger.error("The topic was already connected. This is a weird error. Please report it.",Hs.getAccountId().toString()),Js&&Ma&&Hc});for(const zs of Zs)this.logger.debug(`Disconnecting duplicate signer for account ${zs.getAccountId().toString()}`),await this.disconnect(zs.topic),this.signers=this.signers.filter(Xs=>Xs.topic!==zs.topic)}this.signers.push(...Ws),this.logger.debug(`Current signers after connection: ${this.signers.map(Hs=>`${Hs.getAccountId().toString()}:${Hs.topic}`).join(", ")}`)}async connectURI(Ps){if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");const Ws=networkNamespaces(this.network,this.supportedMethods,this.supportedEvents);return this.logger.debug("V1 DAppConnector: Connecting with params:",{network:this.network.toString(),pairingTopic:Ps,requiredNamespaces:Ws,supportedMethods:this.supportedMethods,supportedEvents:this.supportedEvents}),this.walletConnectClient.connect({pairingTopic:Ps,requiredNamespaces:Ws})}async request({method:Ps,params:Ws}){var Hs,Zs,zs;let Xs;if(this.logger.debug(`Requesting method: ${Ps} with params: ${JSON.stringify(Ws)}`),Ws?.signerAccountId){const Va=(Zs=(Hs=Ws?.signerAccountId)===null||Hs===void 0?void 0:Hs.split(":"))===null||Zs===void 0?void 0:Zs.pop();if(Xs=this.signers.find(Js=>{var Ma;return((Ma=Js?.getAccountId())===null||Ma===void 0?void 0:Ma.toString())===Va}),this.logger.debug(`Found signer: ${(zs=Xs?.getAccountId())===null||zs===void 0?void 0:zs.toString()}`),!Xs)throw new Error(`Signer not found for account ID: ${Ws?.signerAccountId}. Did you use the correct format? e.g hedera:<network>:<address> `)}else Xs=this.signers[this.signers.length-1];if(!Xs)throw new Error("There is no active session. Connect to the wallet at first.");return this.logger.debug(`Using signer: ${Xs.getAccountId().toString()}: ${Xs.topic} - about to request.`),await Xs.request({method:Ps,params:Ws})}async getNodeAddresses(){return await this.request({method:HederaJsonRpcMethod.GetNodeAddresses,params:void 0})}async executeTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.ExecuteTransaction,params:Ps})}async signMessage(Ps){return await this.request({method:HederaJsonRpcMethod.SignMessage,params:Ps})}async signAndExecuteQuery(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteQuery,params:Ps})}async signAndExecuteTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteTransaction,params:Ps})}async signTransaction(Ps){var Ws,Hs;if(typeof Ps?.transactionBody=="string")return this.logger.warn("Transaction body is a string. This is not recommended, please migrate to passing a transaction object directly."),await this.request({method:HederaJsonRpcMethod.SignTransaction,params:Ps});if(Ps?.transactionBody instanceof L$a){const Zs=(Hs=(Ws=Ps?.signerAccountId)===null||Ws===void 0?void 0:Ws.split(":"))===null||Hs===void 0?void 0:Hs.pop(),zs=this.signers.find(Xs=>{var Va;return((Va=Xs?.getAccountId())===null||Va===void 0?void 0:Va.toString())===Zs});if(!zs)throw new Error(`No signer found for account ${Zs}`);if(!Ps?.transactionBody)throw new Error("No transaction provided");return await zs.signTransaction(Ps.transactionBody)}throw new Error("Transaction sent in incorrect format. Ensure transaction body is either a base64 transaction body or Transaction object.")}handleSessionEvent(Ps){this.logger.debug("Session event received:",Ps),this.validateAndRefreshSigners()}handleSessionUpdate({topic:Ps,params:Ws}){const{namespaces:Hs}=Ws,Zs=this.walletConnectClient.session.get(Ps),zs=Object.assign(Object.assign({},Zs),{namespaces:Hs});this.logger.info("Session updated:",zs),this.signers=this.signers.filter(Xs=>Xs.topic!==Ps),this.signers.push(...this.createSigners(zs))}handleSessionDelete(Ps){this.logger.info("Session deleted:",Ps);let Ws=!1;if(this.signers=this.signers.filter(Hs=>Hs.topic!==Ps.topic?!0:(Ws=!0,!1)),Ws){try{this.disconnect(Ps.topic)}catch(Hs){this.logger.error("Error disconnecting session:",Hs)}this.logger.info("Session deleted and signer removed")}}handlePairingDelete(Ps){this.logger.info("Pairing deleted:",Ps),this.signers=this.signers.filter(Ws=>Ws.topic!==Ps.topic);try{this.disconnect(Ps.topic)}catch(Ws){this.logger.error("Error disconnecting pairing:",Ws)}this.logger.info("Pairing deleted by wallet")}}function defineChain(Fs){return{formatters:void 0,fees:void 0,serializers:void 0,...Fs}}defineChain({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"}),defineChain({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"}),defineChain({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"}),defineChain({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}}),defineChain({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}),defineChain({id:"00000008819873e925422c1ff0f99f7c",caipNetworkId:"bip122:00000008819873e925422c1ff0f99f7c",chainNamespace:"bip122",name:"Bitcoin Signet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const hederaNamespace="hedera",HederaChainDefinition={Native:{Mainnet:defineChain({id:"mainnet",chainNamespace:hederaNamespace,caipNetworkId:"hedera:mainnet",name:"Hedera Mainnet",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:8},rpcUrls:{default:{http:["https://mainnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/mainnet"}},testnet:!1}),Testnet:defineChain({id:"testnet",chainNamespace:hederaNamespace,caipNetworkId:"hedera:testnet",name:"Hedera Testnet",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:8},rpcUrls:{default:{http:["https://testnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!0})},EVM:{Mainnet:defineChain({id:295,name:"Hedera Mainnet EVM",chainNamespace:"eip155",caipNetworkId:"eip155:295",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:18},rpcUrls:{default:{http:["https://mainnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!1}),Testnet:defineChain({id:296,name:"Hedera Testnet EVM",chainNamespace:"eip155",caipNetworkId:"eip155:296",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:18},rpcUrls:{default:{http:["https://testnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!0})}};var Eip155JsonRpcMethod;(function(Fs){Fs.PersonalSign="personal_sign",Fs.Sign="eth_sign",Fs.SignTransaction="eth_signTransaction",Fs.SignTypedData="eth_signTypedData",Fs.SignTypedDataV3="eth_signTypedData_v3",Fs.SignTypedDataV4="eth_signTypedData_v4",Fs.SendRawTransaction="eth_sendRawTransaction",Fs.SendTransaction="eth_sendTransaction"})(Eip155JsonRpcMethod||(Eip155JsonRpcMethod={}));const LEVEL_ORDER={error:0,warn:1,info:2,debug:3};class Logger{constructor(){this.level="info"}setLogLevel(Ps){this.level=Ps}error(Ps,...Ws){this.shouldLog("error")&&console.error(Ps,...Ws)}warn(Ps,...Ws){this.shouldLog("warn")&&console.warn(Ps,...Ws)}info(Ps,...Ws){this.shouldLog("info")&&console.info(Ps,...Ws)}debug(Ps,...Ws){this.shouldLog("debug")&&console.debug(Ps,...Ws)}shouldLog(Ps){return LEVEL_ORDER[Ps]<=LEVEL_ORDER[this.level]}}var fetchRetry_umd$1={exports:{}},fetchRetry_umd=fetchRetry_umd$1.exports,hasRequiredFetchRetry_umd;function requireFetchRetry_umd(){return hasRequiredFetchRetry_umd||(hasRequiredFetchRetry_umd=1,(function(Fs,Ps){(function(Ws,Hs){Fs.exports=Hs()})(fetchRetry_umd,(function(){var Ws=function(zs,Xs){if(Xs=Xs||{},typeof zs!="function")throw new Zs("fetch must be a function");if(typeof Xs!="object")throw new Zs("defaults must be an object");if(Xs.retries!==void 0&&!Hs(Xs.retries))throw new Zs("retries must be a positive integer");if(Xs.retryDelay!==void 0&&!Hs(Xs.retryDelay)&&typeof Xs.retryDelay!="function")throw new Zs("retryDelay must be a positive integer or a function returning a positive integer");if(Xs.retryOn!==void 0&&!Array.isArray(Xs.retryOn)&&typeof Xs.retryOn!="function")throw new Zs("retryOn property expects an array or function");var Va={retries:3,retryDelay:1e3,retryOn:[]};return Xs=Object.assign(Va,Xs),function(Ma,qs){var Ys=Xs.retries,Hc=Xs.retryDelay,ol=Xs.retryOn;if(qs&&qs.retries!==void 0)if(Hs(qs.retries))Ys=qs.retries;else throw new Zs("retries must be a positive integer");if(qs&&qs.retryDelay!==void 0)if(Hs(qs.retryDelay)||typeof qs.retryDelay=="function")Hc=qs.retryDelay;else throw new Zs("retryDelay must be a positive integer or a function returning a positive integer");if(qs&&qs.retryOn)if(Array.isArray(qs.retryOn)||typeof qs.retryOn=="function")ol=qs.retryOn;else throw new Zs("retryOn property expects an array or function");return new Promise(function(Vc,Dc){var al=function(hl){var pl=typeof Request<"u"&&Ma instanceof Request?Ma.clone():Ma;zs(pl,qs).then(function(gl){if(Array.isArray(ol)&&ol.indexOf(gl.status)===-1)Vc(gl);else if(typeof ol=="function")try{return Promise.resolve(ol(hl,null,gl)).then(function(yl){yl?dl(hl,null,gl):Vc(gl)}).catch(Dc)}catch(yl){Dc(yl)}else hl<Ys?dl(hl,null,gl):Vc(gl)}).catch(function(gl){if(typeof ol=="function")try{Promise.resolve(ol(hl,gl,null)).then(function(yl){yl?dl(hl,gl,null):Dc(gl)}).catch(function(yl){Dc(yl)})}catch(yl){Dc(yl)}else hl<Ys?dl(hl,gl,null):Dc(gl)})};function dl(hl,pl,gl){var yl=typeof Hc=="function"?Hc(hl,pl,gl):Hc;setTimeout(function(){al(++hl)},yl)}al(0)})}};function Hs(zs){return Number.isInteger(zs)&&zs>=0}function Zs(zs){this.name="ArgumentError",this.message=zs}return Ws}))})(fetchRetry_umd$1)),fetchRetry_umd$1.exports}var fetchRetry_umdExports=requireFetchRetry_umd();const retryFetch=getDefaultExportFromCjs$1(fetchRetry_umdExports),fetchWithRetry=()=>retryFetch(fetch,{retries:3});var Name=(Fs=>(Fs.Contractcall="CONTRACTCALL",Fs.Cryptotransfer="CRYPTOTRANSFER",Fs))(Name||{}),Result=(Fs=>(Fs.Success="SUCCESS",Fs))(Result||{});function ensureGlobalHTMLElement(){typeof globalThis>"u"||typeof globalThis.HTMLElement>"u"&&(globalThis.HTMLElement=class{})}ensureGlobalHTMLElement();const Pd=class Pd{constructor(Ps,Ws){this.reownAppKit=null,this.reownAppKitKey=null,this.extensionCheckInterval=null,this.hasCalledExtensionCallback=!1,this.logger=Ps||new Logger,this.network=Ws||r$y.MAINNET}get dAppConnector(){return Pd.dAppConnectorInstance}static getInstance(Ps,Ws){let Hs=Pd?.instance;return Hs||(Pd.instance=new Pd(Ps,Ws),Hs=Pd.instance,Pd.proxyInstance=null),Ws&&Hs.setNetwork(Ws),Pd.proxyInstance||(Pd.proxyInstance=new Proxy(Hs,{get(Zs,zs,Xs){const Va=Reflect.get(Zs,zs,Xs);return typeof Va=="function"?Va.bind(Zs):Va}})),Pd.proxyInstance}setLogger(Ps){this.logger=Ps}setNetwork(Ps){this.network=Ps}getNetwork(){return this.network}setReownAppKit(Ps){this.reownAppKit=Ps}async ensureReownAppKit(Ps,Ws,Hs){if(typeof window>"u")return;const Zs=`${Ps}:${Hs.toString()}`;if(!(this.reownAppKit&&this.reownAppKitKey===Zs))try{let zs=HederaChainDefinition.Native.Mainnet;Hs.toString()==="testnet"&&(zs=HederaChainDefinition.Native.Testnet),this.reownAppKit=createAppKit({projectId:Ps,metadata:Ws,networks:[HederaChainDefinition.Native.Mainnet,HederaChainDefinition.Native.Testnet],defaultNetwork:zs}),this.reownAppKitKey=Zs}catch(zs){this.logger.warn("Failed to initialize Reown AppKit",zs),this.reownAppKit=null,this.reownAppKitKey=null}}setLogLevel(Ps){this.logger instanceof Logger&&this.logger.setLogLevel(Ps)}async init(Ps,Ws,Hs,Zs){const zs=Hs||this.network,Xs=zs.toString()==="mainnet";return Pd.dAppConnectorInstance||(Pd.dAppConnectorInstance=new DAppConnector(Ws,zs,Ps,Object.values(HederaJsonRpcMethod),[HederaSessionEvent.ChainChanged,HederaSessionEvent.AccountsChanged],[Xs?HederaChainId.Mainnet:HederaChainId.Testnet],"debug"),await Pd.dAppConnectorInstance.init({logger:"error"}),await this.ensureReownAppKit(Ps,Ws,zs),Pd.dAppConnectorInstance.onSessionIframeCreated=Va=>{this.logger.info("new session from from iframe",Va),this.handleNewSession(Va),Zs&&Zs(Va)},this.logger.info(`Hedera Wallet Connect SDK initialized on ${zs}`)),Pd.dAppConnectorInstance}async connect(Ps){this.ensureInitialized();const Ws=Ps?.pairingTopic,Hs=this.reownAppKit;if(Hs){const zs=await this.connectUsingReownAppKit(Hs,Ws);return this.handleNewSession(zs),zs}const Zs=await this.dAppConnector.openModal(Ws);return this.handleNewSession(Zs),Zs}async connectUsingReownAppKit(Ps,Ws){if(this.ensureInitialized(),!Ps)throw new Error("AppKit instance is required.");try{return await this.dAppConnector.connect(Hs=>{Ps.open({view:"ConnectingWalletConnectBasic",uri:Hs}).catch(Zs=>{this.logger.error("Failed to open Reown AppKit modal",Zs)})},Ws)}finally{try{await Ps.close()}catch(Hs){this.logger.warn("Failed to close Reown AppKit modal",Hs)}}}async disconnect(){try{this.ensureInitialized();const Ps=this.getAccountInfo(),Ws=Ps?.accountId,Hs=Ps?.network,Zs=this?.dAppConnector?.signers.find(zs=>zs.getAccountId().toString()===Ws);return await this.dAppConnector?.disconnect(Zs?.topic),this.logger.info(`Disconnected from ${Ws} on ${Hs}`),!0}catch(Ps){return this.logger.error("Failed to disconnect",Ps),!1}}async disconnectAll(){try{return this.ensureInitialized(),await this.dAppConnector?.disconnectAll(),this.logger.info("Disconnected from all wallets"),!0}catch(Ps){return this.logger.error("Failed to disconnect",Ps),!1}}async executeTransaction(Ps,Ws=!1){this.ensureInitialized();const Zs=this.getAccountInfo()?.accountId,zs=this.dAppConnector.signers.find(Xs=>Xs.getAccountId().toString()===Zs);if(!zs)throw new Error("No signer available. Please ensure wallet is connected.");try{return Ws?await(await Ps.executeWithSigner(zs)).getReceiptWithSigner(zs):await(await(await Ps.freezeWithSigner(zs)).executeWithSigner(zs)).getReceiptWithSigner(zs)}catch(Xs){throw(Xs.message??"").toLowerCase().includes("nodeaccountid")?new Error("Transaction execution failed because nodeAccountId is not set. Set node account IDs on the transaction before calling executeTransaction."):Xs}}async executeTransactionWithErrorHandling(Ps,Ws){try{return{result:await this.executeTransaction(Ps,Ws),error:void 0}}catch(Hs){const zs=Hs.message?.toLowerCase();if(this.logger.error("Failed to execute transaction",Hs),this.logger.error("Failure reason for transaction is",zs),zs.includes("insufficient payer balance"))return{result:void 0,error:"Insufficient balance to complete the transaction."};if(zs.includes("reject"))return{result:void 0,error:"You rejected the transaction"};if(zs.includes("invalid signature"))return{result:void 0,error:"Invalid signature. Please check your account and try again."};if(zs.includes("transaction expired"))return{result:void 0,error:"Transaction expired. Please try again."};if(zs.includes("account not found"))return{result:void 0,error:"Account not found. Please check the account ID and try again."};if(zs.includes("unauthorized"))return{result:void 0,error:"Unauthorized. You may not have the necessary permissions for this action."};if(zs.includes("busy"))return{result:void 0,error:"The network is busy. Please try again later."};if(zs.includes("invalid transaction"))return{result:void 0,error:"Invalid transaction. Please check your inputs and try again."}}}async submitMessageToTopic(Ps,Ws,Hs){this.ensureInitialized();let Zs=new u$u().setTopicId(d$s.fromString(Ps)).setMessage(Ws);return Hs&&(Zs=await Zs.sign(Hs)),this.executeTransaction(Zs)}async transferHbar(Ps,Ws,Hs){this.ensureInitialized();const Zs=new T$a().setTransactionId(i$s.generate(Ps)).addHbarTransfer(y$f.fromString(Ps),new e$F(-Hs)).addHbarTransfer(y$f.fromString(Ws),new e$F(Hs));return this.executeTransaction(Zs)}async executeSmartContract(Ps,Ws,Hs,Zs=1e5){this.ensureInitialized();const zs=new i$o().setContractId(g$p.fromString(Ps)).setGas(Zs).setFunction(Ws,Hs);return this.executeTransaction(zs)}handleNewSession(Ps){const Hs=Ps.namespaces?.hedera?.accounts?.[0]?.split(":"),Zs=Hs.pop(),zs=Hs.pop();if(this.logger.info("sessionAccount is",Zs,zs),Zs)this.saveConnectionInfo(Zs,zs);else{this.logger.error("No account id found in the session");return}}getNetworkPrefix(){const Ws=this.getAccountInfo()?.network;if(!Ws){this.logger.warn("Network is not set on SDK, defaulting.");const Hs=localStorage.getItem("connectedNetwork");return Hs||"mainnet-public"}return Ws!==this.network&&(this.logger.warn("Detected network mismatch, reverting to signer network",Ws),this.network=Ws),Ws.isMainnet()?"mainnet-public":"testnet"}async requestAccount(Ps){try{const Hs=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/accounts/${Ps}`,Zs=await fetchWithRetry()(Hs);if(!Zs.ok)throw new Error(`Failed to make request to mirror node for account: ${Zs.status}`);return await Zs.json()}catch(Ws){throw this.logger.error("Failed to fetch account",Ws),Ws}}async getAccountBalance(){this.ensureInitialized();const Ws=this.getAccountInfo()?.accountId;if(!Ws)return null;const Hs=await this.requestAccount(Ws);if(!Hs)throw new Error("Failed to fetch account. Try again or check if the Account ID is valid.");const Zs=Hs.balance.balance/10**8;return Number(Zs).toLocaleString("en-US")}getAccountInfo(){const{accountId:Ps}=this.loadConnectionInfo();if(!Ps||!this?.dAppConnector?.signers?.length)return null;const Hs=this.dAppConnector.signers.find(Xs=>Xs.getAccountId().toString()===Ps);if(!Hs)return null;const Zs=Hs?.getAccountId()?.toString();if(!Zs)return null;const zs=Hs.getLedgerId();return{accountId:Zs,network:zs}}async createTopic(Ps,Ws,Hs){this.ensureInitialized();let Zs=new c$w().setTopicMemo(Ps||"");if(Ws){const Xs=g$q.fromString(Ws);Zs.setAdminKey(Xs.publicKey),Zs=await Zs.sign(Xs)}return Hs&&Zs.setSubmitKey(g$q.fromString(Hs).publicKey),(await this.executeTransaction(Zs)).topicId.toString()}async createToken(Ps,Ws,Hs,Zs,zs,Xs,Va){this.ensureInitialized();let Js=new c$x().setTokenName(Ps).setTokenSymbol(Ws).setDecimals(Zs).setInitialSupply(Hs).setTreasuryAccountId(y$f.fromString(zs)).setTokenType(e$l.NonFungibleUnique).setSupplyType(e$k.Finite);return Va&&(Js=Js.setSupplyKey(g$q.fromString(Va))),Xs&&(Js=Js.setAdminKey(g$q.fromString(Xs)),Js=await Js.sign(g$q.fromString(Xs))),(await this.executeTransaction(Js)).tokenId.toString()}async mintNFT(Ps,Ws,Hs){this.ensureInitialized();let Zs=await new r$n().setTokenId(Ps).setMetadata([Buffer$1.from(Ws,"utf-8")]).sign(Hs);return this.executeTransaction(Zs)}async getMessages(Ps,Ws,Hs=!1,Zs){const Xs=`https://${Zs||this.getNetworkPrefix()}.mirrornode.hedera.com`,Va=Number(Ws)>0&&!Hs?`×tamp=gt:${Ws}`:"",Js=`${Xs}/api/v1/topics/${Ps}/messages?limit=200${Va}`;try{const Ma=await fetchWithRetry()(Js);if(!Ma.ok)throw new Error(`Failed to make request to mirror node: ${Ma.status}`);const qs=await Ma.json(),Ys=qs?.messages||[],Hc=qs?.links?.next,ol=Ys.map(Vc=>({...JSON.parse(atob(Vc.message)),payer:Vc.payer_account_id,created:new Date(Number(Vc.consensus_timestamp)*1e3),consensus_timestamp:Vc.consensus_timestamp,sequence_number:Vc.sequence_number}));if(Hc){const Vc=await this.getMessages(Ps,Number(ol[ol.length-1]?.consensus_timestamp),Hs);ol.push(...Vc.messages)}return{messages:ol.sort((Vc,Dc)=>Vc.sequence_number-Dc.sequence_number),error:""}}catch(Ma){return this.logger.error("Error fetching topic data:",Ma),{messages:[],error:Ma.toString()}}}async signMessage(Ps){const Ws=this.dAppConnector;if(!Ws)throw new Error("No active connection or signer");const Zs=this.getAccountInfo()?.accountId,zs={signerAccountId:`hedera:${this.network}:${Zs}`,message:Ps};return{userSignature:(await Ws.signMessage(zs)).signatureMap}}saveConnectionInfo(Ps,Ws){if(!Ps)localStorage.removeItem("connectedAccountId"),localStorage.removeItem("connectedNetwork");else{const Hs=Ws?.replace(/['"]+/g,"");localStorage.setItem("connectedNetwork",Hs),localStorage.setItem("connectedAccountId",Ps)}}loadConnectionInfo(){return{accountId:localStorage.getItem("connectedAccountId"),network:localStorage.getItem("connectedNetwork")}}async connectWallet(Ps,Ws,Hs){try{await this.init(Ps,Ws,Hs);const Zs=await this.connect(),Xs=this.getAccountInfo()?.accountId,Va=await this.getAccountBalance(),Js=this.getNetworkPrefix();return this.saveConnectionInfo(Xs,Js),{accountId:Xs,balance:Va,session:Zs}}catch(Zs){throw this.logger.error("Failed to connect wallet:",Zs),Zs}}async disconnectWallet(Ps=!0){try{const Ws=await this.disconnect();return Ws&&Ps&&localStorage.clear(),this.saveConnectionInfo(void 0),Ws}catch(Ws){return this.logger.error("Failed to disconnect wallet:",Ws),!1}}async initAccount(Ps,Ws,Hs,Zs=()=>{}){const{accountId:zs,network:Xs}=this.loadConnectionInfo();if(zs&&Xs)try{const Va=Xs==="mainnet"?r$y.MAINNET:r$y.TESTNET,Js=Hs||Va;await this.init(Ps,Ws,Js,Zs);const Ma=await this.getAccountBalance();return{accountId:zs,balance:Ma}}catch(Va){return this.logger.error("Failed to reconnect:",Va),this.saveConnectionInfo(void 0,void 0),null}else if(Hs)try{this.logger.info("initializing normally through override.",Hs),await this.init(Ps,Ws,Hs,Zs),this.logger.info("initialized",Hs),await this.connectViaDappBrowser(),this.logger.info("connected via dapp browser")}catch(Va){return this.logger.error("Failed to fallback connect:",Va),this.saveConnectionInfo(void 0,void 0),null}return null}subscribeToExtensions(Ps){return this.extensionCheckInterval&&clearInterval(this.extensionCheckInterval),this.hasCalledExtensionCallback=!1,this.extensionCheckInterval=setInterval(()=>{const Hs=(this.dAppConnector?.extensions||[]).find(Zs=>Zs.availableInIframe);Hs&&!this.hasCalledExtensionCallback&&(this.hasCalledExtensionCallback=!0,Ps(Hs),this.extensionCheckInterval&&(clearInterval(this.extensionCheckInterval),this.extensionCheckInterval=null))},1e3),()=>{this.extensionCheckInterval&&(clearInterval(this.extensionCheckInterval),this.extensionCheckInterval=null),this.hasCalledExtensionCallback=!1}}async connectViaDappBrowser(){const Ps=this.dAppConnector.extensions||[],Ws=Ps.find(Hs=>(this.logger.info("Checking extension",Hs),Hs.availableInIframe));this.logger.info("extensions are",Ps,Ws),Ws?await this.connectToExtension(Ws):this.subscribeToExtensions(async Hs=>{await this.connectToExtension(Hs)})}async connectToExtension(Ps){this.logger.info("found extension, connecting to iframe.",Ps);const Ws=await this.dAppConnector.connectExtension(Ps.id),Hs=this.dAppConnector.onSessionIframeCreated;Hs&&Hs(Ws)}ensureInitialized(){if(!this.dAppConnector)throw new Error("SDK not initialized. Call init() first.")}static run(){try{typeof window<"u"&&(window.HashinalsWalletConnectSDK=Pd.getInstance(),window.HashgraphSDK=HashgraphSDK)}catch{console.error("[ERROR]: failed setting sdk on window")}}async transferToken(Ps,Ws,Hs,Zs){this.ensureInitialized();const zs=new T$a().setTransactionId(i$s.generate(Ws)).addTokenTransfer(c$E.fromString(Ps),y$f.fromString(Ws),-Zs).addTokenTransfer(c$E.fromString(Ps),y$f.fromString(Hs),Zs);return this.executeTransaction(zs)}async createAccount(Ps){this.ensureInitialized();const Ws=new h$m().setInitialBalance(new e$F(Ps));return this.executeTransaction(Ws)}async associateTokenToAccount(Ps,Ws){this.ensureInitialized();const Hs=new r$t().setAccountId(y$f.fromString(Ps)).setTokenIds([c$E.fromString(Ws)]);return this.executeTransaction(Hs)}async dissociateTokenFromAccount(Ps,Ws){this.ensureInitialized();const Hs=new r$s().setAccountId(y$f.fromString(Ps)).setTokenIds([c$E.fromString(Ws)]);return this.executeTransaction(Hs)}async updateAccount(Ps,Ws){this.ensureInitialized();const Hs=new s$G().setAccountId(y$f.fromString(Ps)).setMaxAutomaticTokenAssociations(Ws);return this.executeTransaction(Hs)}async approveAllowance(Ps,Ws,Hs,Zs){this.ensureInitialized();const zs=new A$c().approveTokenAllowance(c$E.fromString(Ws),y$f.fromString(Zs),y$f.fromString(Ps),Hs);return this.executeTransaction(zs)}async getAccountTokens(Ps){this.ensureInitialized();const Hs=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com`,Zs=`${Hs}/api/v1/accounts/${Ps}/tokens?limit=200`;try{const zs=await fetchWithRetry()(Zs);if(!zs.ok)throw new Error(`Failed to make request to mirror node for account tokens: ${zs.status}`);const Xs=await zs.json(),Va=[];for(const Ma of Xs.tokens)Ma.token_id&&Va.push({tokenId:Ma.token_id,balance:Ma.balance,decimals:Ma.decimals,formatted_balance:(Ma.balance/10**Ma.decimals).toLocaleString("en-US"),created_timestamp:new Date(Number(Ma.created_timestamp)*1e3)});let Js=Xs.links?.next;for(;Js;){const Ma=`${Hs}${Js}`,qs=await fetchWithRetry()(Ma);if(!qs.ok)throw new Error(`Failed to make request to mirror node for account tokens: ${qs.status}, page: ${Ma}`);const Ys=await qs.json();for(const Hc of Ys.tokens)Hc.token_id&&Va.push({tokenId:Hc.token_id,balance:Hc.balance,decimals:Hc.decimals,formatted_balance:(Hc.balance/10**Hc.decimals).toLocaleString("en-US"),created_timestamp:new Date(Number(Hc.created_timestamp)*1e3)});Js=Ys.links?.next}return{tokens:Va}}catch(zs){throw this.logger.error("Error fetching account tokens:",zs),zs}}async getTransaction(Ps){try{const Hs=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/transactions/${Ps}`;this.logger.debug("Fetching transaction",Hs);const Zs=await fetchWithRetry()(Hs);if(!Zs.ok)throw new Error(`Failed to fetch transaction: ${Zs.status}`);return await Zs.json()}catch(Ws){return this.logger.error("Failed to get transaction",Ws),null}}async getTransactionByTimestamp(Ps){try{const Hs=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/transactions?timestamp=${Ps}`;this.logger.debug("Fetching transaction by timestamp",Hs);const Zs=await fetchWithRetry()(Hs);if(!Zs.ok)throw new Error(`Failed to fetch transaction by timestamp: ${Zs.status}`);const Xs=(await Zs.json())?.transactions?.[0];return Xs?await this.getTransaction(Xs.transaction_id):null}catch(Ws){return this.logger.error("Failed to get transaction by timestamp",Ws),null}}async getAccountNFTs(Ps,Ws){try{const Hs=this.getNetworkPrefix(),Zs=Ws?`&token.id=${Ws}`:"",zs=`https://${Hs}.mirrornode.hedera.com/api/v1/accounts/${Ps}/nfts?limit=200${Zs}`,Xs=await fetchWithRetry()(zs);if(!Xs.ok)throw new Error(`Failed to fetch NFTs for account: ${Xs.status}`);const Va=await Xs.json();let Js=Va?.links?.next||null,Ma=Va.nfts||[];for(;Js;)try{const qs=await fetchWithRetry()(`https://${Hs}.mirrornode.hedera.com${Js}`);if(!qs.ok)throw new Error(`Failed to fetch next page of NFTs: ${qs.status}`);const Ys=await qs.json(),Hc=Ys?.nfts||[];Ma=[...Ma,...Hc],Js=Ys?.links?.next&&Js!==Ys?.links?.next?Ys.links.next:null}catch(qs){this.logger.error("Failed to fetch next page of NFTs",qs);break}return Ma.map(qs=>{try{qs.token_uri=Buffer$1.from(qs.metadata,"base64").toString("ascii")}catch(Ys){this.logger.error("Failed to decode NFT metadata",Ys)}return qs})}catch(Hs){return this.logger.error("Failed to get account NFTs",Hs),[]}}async validateNFTOwnership(Ps,Ws,Hs){return(await this.getAccountNFTs(Ws,Hs)).find(zs=>zs.token_id===Hs&&zs.serial_number.toString()===Ps)||null}async readSmartContract(Ps,Ws,Hs,Zs=!0,zs=0){try{const Xs=this.getNetworkPrefix(),Va={block:"latest",data:Ps,estimate:Zs,from:Ws.toSolidityAddress(),to:Hs.toSolidityAddress(),value:zs};Zs||(Va.gas=3e5,Va.gasPrice=1e8);const Js=`https://${Xs}.mirrornode.hedera.com/api/v1/contracts/call`,Ma=await fetchWithRetry()(Js,{method:"POST",body:JSON.stringify(Va),headers:{"Content-Type":"application/json"}});if(!Ma.ok)throw new Error(`Failed to make contract call: ${Ma.status}`);return await Ma.json()}catch(Xs){return this.logger.error("Failed to make contract call",Xs),null}}};Pd.proxyInstance=null;let HashinalsWalletConnectSDK=Pd;HashinalsWalletConnectSDK.run();class ReownAuthenticationMessenger{constructor(Ps){this.getNonce=Ps.getNonce}async createMessage(Ps){const Ws={accountAddress:Ps.accountAddress,chainId:Ps.chainId,version:"1",domain:typeof document>"u"?"Unknown Domain":document.location.host,uri:typeof document>"u"?"Unknown URI":document.location.href,resources:this.resources,nonce:await this.getNonce(Ps),issuedAt:this.stringifyDate(new Date),statement:void 0,expirationTime:void 0,notBefore:void 0};return Object.assign(Ws,{toString:()=>this.stringify(Ws)})}stringify(Ps){const Ws=this.getNetworkName(Ps.chainId);return[`${Ps.domain} wants you to sign in with your ${Ws} account:`,Ps.accountAddress,Ps.statement?`
|
|
466
|
+
`+JSON.stringify({txError:{name:(zs=Hc?.error)===null||zs===void 0?void 0:zs.name,message:(Xs=Hc?.error)===null||Xs===void 0?void 0:Xs.message,stack:(Va=Hc?.error)===null||Va===void 0?void 0:Va.stack},queryError:{name:(Js=ol.error)===null||Js===void 0?void 0:Js.name,message:(Ma=ol.error)===null||Ma===void 0?void 0:Ma.message,stack:(qs=ol.error)===null||qs===void 0?void 0:qs.stack}},null,2))}}class DAppConnector{constructor(Ps,Ws,Hs,Zs,zs,Xs,Va="debug"){this.network=r$y.TESTNET,this.supportedMethods=[],this.supportedEvents=[],this.supportedChains=[],this.extensions=[],this.onSessionIframeCreated=null,this.signers=[],this.isInitializing=!1,this.abortableConnect=async Js=>new Promise(async(Ma,qs)=>{const Hc=setTimeout(()=>{this.walletConnectModal.closeModal(),qs(new Error("Connect timed out after 480000(ms)"))},48e4);try{return Ma(await Js())}catch(ol){qs(ol)}finally{clearTimeout(Hc)}}),this.logger=new DefaultLogger(Va),this.dAppMetadata=Ps,this.network=Ws,this.projectId=Hs,this.supportedMethods=Zs??Object.values(HederaJsonRpcMethod),this.supportedEvents=zs??[],this.supportedChains=Xs??[],this.extensions=[],this.walletConnectModal=new WalletConnectModal({projectId:Hs,chains:Xs}),findExtensions((Js,Ma)=>{this.extensions.push(Object.assign(Object.assign({},Js),{available:!0,availableInIframe:Ma}))})}setLogLevel(Ps){this.logger instanceof DefaultLogger&&this.logger.setLogLevel(Ps)}async init({logger:Ps}={}){try{if(this.isInitializing=!0,!this.projectId)throw new Error("Project ID is not defined");this.walletConnectClient=await fe$1.init({logger:Ps,relayUrl:"wss://relay.walletconnect.com",projectId:this.projectId,metadata:this.dAppMetadata});const Ws=this.walletConnectClient.session.getAll();Ws.length>0?this.signers=Ws.flatMap(Hs=>this.createSigners(Hs)):this.checkIframeConnect(),this.walletConnectClient.on("session_event",this.handleSessionEvent.bind(this)),this.walletConnectClient.on("session_update",this.handleSessionUpdate.bind(this)),this.walletConnectClient.on("session_delete",this.handleSessionDelete.bind(this)),this.walletConnectClient.core.events.on("session_delete",this.handleSessionDelete.bind(this)),this.walletConnectClient.core.pairing.events.on("pairing_delete",this.handlePairingDelete.bind(this))}catch(Ws){this.logger.error("Error initializing DAppConnector:",Ws)}finally{this.isInitializing=!1}}getSigner(Ps){if(this.isInitializing)throw new Error("DAppConnector is not initialized yet. Try again later.");const Ws=this.signers.find(Hs=>Hs.getAccountId().equals(Ps));if(!Ws)throw new Error("Signer is not found for this accountId");return Ws}async openModal(Ps,Ws=!1){try{const{uri:Hs,approval:Zs}=await this.connectURI(Ps);return this.walletConnectModal.openModal({uri:Hs}),await new Promise(async(Xs,Va)=>{Ws&&this.walletConnectModal.subscribeModal(Js=>{Js.open||Va(new Error("User rejected pairing"))});try{const Js=await Zs();await this.onSessionConnected(Js),Xs(Js)}catch(Js){Va(Js)}})}finally{this.walletConnectModal.closeModal()}}async connect(Ps,Ws,Hs){return this.abortableConnect(async()=>{var Zs;const{uri:zs,approval:Xs}=await this.connectURI(Ws);if(!zs)throw new Error("URI is not defined");Ps(zs);const Va=await Xs();if(Hs){const Js=Object.assign(Object.assign({},Va.sessionProperties),{extensionId:Hs});Va.sessionProperties=Js,await((Zs=this.walletConnectClient)===null||Zs===void 0?void 0:Zs.session.update(Va.topic,{sessionProperties:Js}))}return await this.onSessionConnected(Va),Va})}async connectExtension(Ps,Ws){const Hs=this.extensions.find(Zs=>Zs.id===Ps);if(!Hs||!Hs.available)throw new Error("Extension is not available");return this.connect(Zs=>{extensionConnect(Hs.id,Hs.availableInIframe,Zs)},Ws,Hs.availableInIframe?void 0:Ps)}validateSession(Ps){try{if(!this.walletConnectClient)return!1;const Ws=this.walletConnectClient.session.get(Ps),Hs=this.signers.some(Zs=>Zs.topic===Ps);return Ws?Hs?!0:(this.logger.warn(`Session exists but no signer found for topic: ${Ps}`),!1):(Hs&&(this.logger.warn(`Signer exists but no session found for topic: ${Ps}`),this.handleSessionDelete({topic:Ps})),!1)}catch(Ws){return this.logger.error("Error validating session:",Ws),!1}}validateAndRefreshSigners(){this.signers=this.signers.filter(Ps=>this.validateSession(Ps.topic))}async checkIframeConnect(){const Ps=this.extensions.find(Ws=>Ws.availableInIframe);if(Ps){const Ws=await this.connectExtension(Ps.id);this.onSessionIframeCreated&&this.onSessionIframeCreated(Ws)}}async disconnect(Ps){try{if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");return await this.walletConnectClient.disconnect({topic:Ps,reason:zt$2("USER_DISCONNECTED")}),!0}catch(Ws){return this.logger.error("Either the session was already disconnected or the topic is invalid",Ws),!1}}async disconnectAll(){if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");const Ps=this.walletConnectClient.session.getAll(),Ws=this.walletConnectClient.core.pairing.getPairings();if(!Ps?.length&&!Ws?.length)throw new Error("There is no active session/pairing. Connect to the wallet at first.");const Hs=[];for(const Zs of this.walletConnectClient.session.getAll()){this.logger.info(`Disconnecting from session: ${Zs}`);const zs=this.disconnect(Zs.topic);Hs.push(zs)}for(const Zs of Ws){const zs=this.disconnect(Zs.topic);Hs.push(zs)}await Promise.all(Hs),this.signers=[]}createSigners(Ps){return accountAndLedgerFromSession(Ps).map(({account:Hs,network:Zs})=>{var zs;return new DAppSigner(Hs,this.walletConnectClient,Ps.topic,Zs,(zs=Ps.sessionProperties)===null||zs===void 0?void 0:zs.extensionId,this.logger instanceof DefaultLogger?this.logger.getLogLevel():"debug")})}async onSessionConnected(Ps){const Ws=this.createSigners(Ps);for(const Hs of Ws){const Zs=this.signers.filter(zs=>{var Xs,Va;const Js=((Xs=zs?.getAccountId())===null||Xs===void 0?void 0:Xs.toString())===((Va=Hs?.getAccountId())===null||Va===void 0?void 0:Va.toString()),Ma=Hs.extensionId===zs.extensionId,qs=Hs.getMetadata(),Ys=zs.getMetadata(),Hc=qs?.name===Ys?.name;return zs.topic===Hs.topic&&this.logger.error("The topic was already connected. This is a weird error. Please report it.",Hs.getAccountId().toString()),Js&&Ma&&Hc});for(const zs of Zs)this.logger.debug(`Disconnecting duplicate signer for account ${zs.getAccountId().toString()}`),await this.disconnect(zs.topic),this.signers=this.signers.filter(Xs=>Xs.topic!==zs.topic)}this.signers.push(...Ws),this.logger.debug(`Current signers after connection: ${this.signers.map(Hs=>`${Hs.getAccountId().toString()}:${Hs.topic}`).join(", ")}`)}async connectURI(Ps){if(!this.walletConnectClient)throw new Error("WalletConnect is not initialized");const Ws=networkNamespaces(this.network,this.supportedMethods,this.supportedEvents);return this.logger.debug("V1 DAppConnector: Connecting with params:",{network:this.network.toString(),pairingTopic:Ps,requiredNamespaces:Ws,supportedMethods:this.supportedMethods,supportedEvents:this.supportedEvents}),this.walletConnectClient.connect({pairingTopic:Ps,requiredNamespaces:Ws})}async request({method:Ps,params:Ws}){var Hs,Zs,zs;let Xs;if(this.logger.debug(`Requesting method: ${Ps} with params: ${JSON.stringify(Ws)}`),Ws?.signerAccountId){const Va=(Zs=(Hs=Ws?.signerAccountId)===null||Hs===void 0?void 0:Hs.split(":"))===null||Zs===void 0?void 0:Zs.pop();if(Xs=this.signers.find(Js=>{var Ma;return((Ma=Js?.getAccountId())===null||Ma===void 0?void 0:Ma.toString())===Va}),this.logger.debug(`Found signer: ${(zs=Xs?.getAccountId())===null||zs===void 0?void 0:zs.toString()}`),!Xs)throw new Error(`Signer not found for account ID: ${Ws?.signerAccountId}. Did you use the correct format? e.g hedera:<network>:<address> `)}else Xs=this.signers[this.signers.length-1];if(!Xs)throw new Error("There is no active session. Connect to the wallet at first.");return this.logger.debug(`Using signer: ${Xs.getAccountId().toString()}: ${Xs.topic} - about to request.`),await Xs.request({method:Ps,params:Ws})}async getNodeAddresses(){return await this.request({method:HederaJsonRpcMethod.GetNodeAddresses,params:void 0})}async executeTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.ExecuteTransaction,params:Ps})}async signMessage(Ps){return await this.request({method:HederaJsonRpcMethod.SignMessage,params:Ps})}async signAndExecuteQuery(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteQuery,params:Ps})}async signAndExecuteTransaction(Ps){return await this.request({method:HederaJsonRpcMethod.SignAndExecuteTransaction,params:Ps})}async signTransaction(Ps){var Ws,Hs;if(typeof Ps?.transactionBody=="string")return this.logger.warn("Transaction body is a string. This is not recommended, please migrate to passing a transaction object directly."),await this.request({method:HederaJsonRpcMethod.SignTransaction,params:Ps});if(Ps?.transactionBody instanceof L$a){const Zs=(Hs=(Ws=Ps?.signerAccountId)===null||Ws===void 0?void 0:Ws.split(":"))===null||Hs===void 0?void 0:Hs.pop(),zs=this.signers.find(Xs=>{var Va;return((Va=Xs?.getAccountId())===null||Va===void 0?void 0:Va.toString())===Zs});if(!zs)throw new Error(`No signer found for account ${Zs}`);if(!Ps?.transactionBody)throw new Error("No transaction provided");return await zs.signTransaction(Ps.transactionBody)}throw new Error("Transaction sent in incorrect format. Ensure transaction body is either a base64 transaction body or Transaction object.")}handleSessionEvent(Ps){this.logger.debug("Session event received:",Ps),this.validateAndRefreshSigners()}handleSessionUpdate({topic:Ps,params:Ws}){const{namespaces:Hs}=Ws,Zs=this.walletConnectClient.session.get(Ps),zs=Object.assign(Object.assign({},Zs),{namespaces:Hs});this.logger.info("Session updated:",zs),this.signers=this.signers.filter(Xs=>Xs.topic!==Ps),this.signers.push(...this.createSigners(zs))}handleSessionDelete(Ps){this.logger.info("Session deleted:",Ps);let Ws=!1;if(this.signers=this.signers.filter(Hs=>Hs.topic!==Ps.topic?!0:(Ws=!0,!1)),Ws){try{this.disconnect(Ps.topic)}catch(Hs){this.logger.error("Error disconnecting session:",Hs)}this.logger.info("Session deleted and signer removed")}}handlePairingDelete(Ps){this.logger.info("Pairing deleted:",Ps),this.signers=this.signers.filter(Ws=>Ws.topic!==Ps.topic);try{this.disconnect(Ps.topic)}catch(Ws){this.logger.error("Error disconnecting pairing:",Ws)}this.logger.info("Pairing deleted by wallet")}}function defineChain(Fs){return{formatters:void 0,fees:void 0,serializers:void 0,...Fs}}defineChain({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"}),defineChain({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"}),defineChain({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"}),defineChain({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}}),defineChain({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}),defineChain({id:"00000008819873e925422c1ff0f99f7c",caipNetworkId:"bip122:00000008819873e925422c1ff0f99f7c",chainNamespace:"bip122",name:"Bitcoin Signet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const hederaNamespace="hedera",HederaChainDefinition={Native:{Mainnet:defineChain({id:"mainnet",chainNamespace:hederaNamespace,caipNetworkId:"hedera:mainnet",name:"Hedera Mainnet",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:8},rpcUrls:{default:{http:["https://mainnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/mainnet"}},testnet:!1}),Testnet:defineChain({id:"testnet",chainNamespace:hederaNamespace,caipNetworkId:"hedera:testnet",name:"Hedera Testnet",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:8},rpcUrls:{default:{http:["https://testnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!0})},EVM:{Mainnet:defineChain({id:295,name:"Hedera Mainnet EVM",chainNamespace:"eip155",caipNetworkId:"eip155:295",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:18},rpcUrls:{default:{http:["https://mainnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!1}),Testnet:defineChain({id:296,name:"Hedera Testnet EVM",chainNamespace:"eip155",caipNetworkId:"eip155:296",nativeCurrency:{symbol:"ℏ",name:"HBAR",decimals:18},rpcUrls:{default:{http:["https://testnet.hashio.io/api"]}},blockExplorers:{default:{name:"Hashscan",url:"https://hashscan.io/testnet"}},testnet:!0})}};var Eip155JsonRpcMethod;(function(Fs){Fs.PersonalSign="personal_sign",Fs.Sign="eth_sign",Fs.SignTransaction="eth_signTransaction",Fs.SignTypedData="eth_signTypedData",Fs.SignTypedDataV3="eth_signTypedData_v3",Fs.SignTypedDataV4="eth_signTypedData_v4",Fs.SendRawTransaction="eth_sendRawTransaction",Fs.SendTransaction="eth_sendTransaction"})(Eip155JsonRpcMethod||(Eip155JsonRpcMethod={}));const LEVEL_ORDER={error:0,warn:1,info:2,debug:3};class Logger{constructor(){this.level="info"}setLogLevel(Ps){this.level=Ps}error(Ps,...Ws){this.shouldLog("error")&&console.error(Ps,...Ws)}warn(Ps,...Ws){this.shouldLog("warn")&&console.warn(Ps,...Ws)}info(Ps,...Ws){this.shouldLog("info")&&console.info(Ps,...Ws)}debug(Ps,...Ws){this.shouldLog("debug")&&console.debug(Ps,...Ws)}shouldLog(Ps){return LEVEL_ORDER[Ps]<=LEVEL_ORDER[this.level]}}var fetchRetry_umd$1={exports:{}},fetchRetry_umd=fetchRetry_umd$1.exports,hasRequiredFetchRetry_umd;function requireFetchRetry_umd(){return hasRequiredFetchRetry_umd||(hasRequiredFetchRetry_umd=1,(function(Fs,Ps){(function(Ws,Hs){Fs.exports=Hs()})(fetchRetry_umd,(function(){var Ws=function(zs,Xs){if(Xs=Xs||{},typeof zs!="function")throw new Zs("fetch must be a function");if(typeof Xs!="object")throw new Zs("defaults must be an object");if(Xs.retries!==void 0&&!Hs(Xs.retries))throw new Zs("retries must be a positive integer");if(Xs.retryDelay!==void 0&&!Hs(Xs.retryDelay)&&typeof Xs.retryDelay!="function")throw new Zs("retryDelay must be a positive integer or a function returning a positive integer");if(Xs.retryOn!==void 0&&!Array.isArray(Xs.retryOn)&&typeof Xs.retryOn!="function")throw new Zs("retryOn property expects an array or function");var Va={retries:3,retryDelay:1e3,retryOn:[]};return Xs=Object.assign(Va,Xs),function(Ma,qs){var Ys=Xs.retries,Hc=Xs.retryDelay,ol=Xs.retryOn;if(qs&&qs.retries!==void 0)if(Hs(qs.retries))Ys=qs.retries;else throw new Zs("retries must be a positive integer");if(qs&&qs.retryDelay!==void 0)if(Hs(qs.retryDelay)||typeof qs.retryDelay=="function")Hc=qs.retryDelay;else throw new Zs("retryDelay must be a positive integer or a function returning a positive integer");if(qs&&qs.retryOn)if(Array.isArray(qs.retryOn)||typeof qs.retryOn=="function")ol=qs.retryOn;else throw new Zs("retryOn property expects an array or function");return new Promise(function(Vc,Dc){var al=function(hl){var pl=typeof Request<"u"&&Ma instanceof Request?Ma.clone():Ma;zs(pl,qs).then(function(gl){if(Array.isArray(ol)&&ol.indexOf(gl.status)===-1)Vc(gl);else if(typeof ol=="function")try{return Promise.resolve(ol(hl,null,gl)).then(function(yl){yl?dl(hl,null,gl):Vc(gl)}).catch(Dc)}catch(yl){Dc(yl)}else hl<Ys?dl(hl,null,gl):Vc(gl)}).catch(function(gl){if(typeof ol=="function")try{Promise.resolve(ol(hl,gl,null)).then(function(yl){yl?dl(hl,gl,null):Dc(gl)}).catch(function(yl){Dc(yl)})}catch(yl){Dc(yl)}else hl<Ys?dl(hl,gl,null):Dc(gl)})};function dl(hl,pl,gl){var yl=typeof Hc=="function"?Hc(hl,pl,gl):Hc;setTimeout(function(){al(++hl)},yl)}al(0)})}};function Hs(zs){return Number.isInteger(zs)&&zs>=0}function Zs(zs){this.name="ArgumentError",this.message=zs}return Ws}))})(fetchRetry_umd$1)),fetchRetry_umd$1.exports}var fetchRetry_umdExports=requireFetchRetry_umd();const retryFetch=getDefaultExportFromCjs$1(fetchRetry_umdExports),fetchWithRetry=()=>retryFetch(fetch,{retries:3});var Name=(Fs=>(Fs.Contractcall="CONTRACTCALL",Fs.Cryptotransfer="CRYPTOTRANSFER",Fs))(Name||{}),Result=(Fs=>(Fs.Success="SUCCESS",Fs))(Result||{});function ensureGlobalHTMLElement(){typeof globalThis>"u"||typeof globalThis.HTMLElement>"u"&&(globalThis.HTMLElement=class{})}ensureGlobalHTMLElement();const HASH_PACK_WALLET_ID="a29498d225fa4b13468ff4d6cf4ae0ea4adcbd95f07ce8a843a1dee10b632f3f",Pd=class Pd{constructor(Ps,Ws){this.reownAppKit=null,this.reownAppKitKey=null,this.extensionCheckInterval=null,this.hasCalledExtensionCallback=!1,this.logger=Ps||new Logger,this.network=Ws||r$y.MAINNET}get dAppConnector(){return Pd.dAppConnectorInstance}static getInstance(Ps,Ws){let Hs=Pd?.instance;return Hs||(Pd.instance=new Pd(Ps,Ws),Hs=Pd.instance,Pd.proxyInstance=null),Ws&&Hs.setNetwork(Ws),Pd.proxyInstance||(Pd.proxyInstance=new Proxy(Hs,{get(Zs,zs,Xs){const Va=Reflect.get(Zs,zs,Xs);return typeof Va=="function"?Va.bind(Zs):Va}})),Pd.proxyInstance}setLogger(Ps){this.logger=Ps}setNetwork(Ps){this.network=Ps}getNetwork(){return this.network}setReownAppKit(Ps){this.reownAppKit=Ps}async ensureReownAppKit(Ps,Ws,Hs){if(typeof window>"u")return;const Zs=`${Ps}:${Hs.toString()}`;if(!(this.reownAppKit&&this.reownAppKitKey===Zs))try{let zs=HederaChainDefinition.Native.Mainnet;Hs.toString()==="testnet"&&(zs=HederaChainDefinition.Native.Testnet),this.reownAppKit=createAppKit({projectId:Ps,metadata:Ws,networks:[HederaChainDefinition.Native.Mainnet,HederaChainDefinition.Native.Testnet],defaultNetwork:zs,featuredWalletIds:[HASH_PACK_WALLET_ID]}),this.reownAppKitKey=Zs}catch(zs){this.logger.warn("Failed to initialize Reown AppKit",zs),this.reownAppKit=null,this.reownAppKitKey=null}}setLogLevel(Ps){this.logger instanceof Logger&&this.logger.setLogLevel(Ps)}async init(Ps,Ws,Hs,Zs){const zs=Hs||this.network,Xs=zs.toString()==="mainnet";return Pd.dAppConnectorInstance||(Pd.dAppConnectorInstance=new DAppConnector(Ws,zs,Ps,Object.values(HederaJsonRpcMethod),[HederaSessionEvent.ChainChanged,HederaSessionEvent.AccountsChanged],[Xs?HederaChainId.Mainnet:HederaChainId.Testnet],"debug"),await Pd.dAppConnectorInstance.init({logger:"error"}),await this.ensureReownAppKit(Ps,Ws,zs),Pd.dAppConnectorInstance.onSessionIframeCreated=Va=>{this.logger.info("new session from from iframe",Va),this.handleNewSession(Va),Zs&&Zs(Va)},this.logger.info(`Hedera Wallet Connect SDK initialized on ${zs}`)),Pd.dAppConnectorInstance}async connect(Ps){this.ensureInitialized();const Ws=Ps?.pairingTopic,Hs=this.reownAppKit;if(Hs){const zs=await this.connectUsingReownAppKit(Hs,Ws);return this.handleNewSession(zs),zs}const Zs=await this.dAppConnector.openModal(Ws);return this.handleNewSession(Zs),Zs}async connectUsingReownAppKit(Ps,Ws){if(this.ensureInitialized(),!Ps)throw new Error("AppKit instance is required.");try{return await this.dAppConnector.connect(Hs=>{Ps.open({view:"ConnectingWalletConnectBasic",uri:Hs}).catch(Zs=>{this.logger.error("Failed to open Reown AppKit modal",Zs)})},Ws)}finally{try{await Ps.close()}catch(Hs){this.logger.warn("Failed to close Reown AppKit modal",Hs)}}}async disconnect(){try{this.ensureInitialized();const Ps=this.getAccountInfo(),Ws=Ps?.accountId,Hs=Ps?.network,Zs=this?.dAppConnector?.signers.find(zs=>zs.getAccountId().toString()===Ws);return await this.dAppConnector?.disconnect(Zs?.topic),this.logger.info(`Disconnected from ${Ws} on ${Hs}`),!0}catch(Ps){return this.logger.error("Failed to disconnect",Ps),!1}}async disconnectAll(){try{return this.ensureInitialized(),await this.dAppConnector?.disconnectAll(),this.logger.info("Disconnected from all wallets"),!0}catch(Ps){return this.logger.error("Failed to disconnect",Ps),!1}}async executeTransaction(Ps,Ws=!1){this.ensureInitialized();const Zs=this.getAccountInfo()?.accountId,zs=this.dAppConnector.signers.find(Xs=>Xs.getAccountId().toString()===Zs);if(!zs)throw new Error("No signer available. Please ensure wallet is connected.");try{return Ws?await(await Ps.executeWithSigner(zs)).getReceiptWithSigner(zs):await(await(await Ps.freezeWithSigner(zs)).executeWithSigner(zs)).getReceiptWithSigner(zs)}catch(Xs){throw(Xs.message??"").toLowerCase().includes("nodeaccountid")?new Error("Transaction execution failed because nodeAccountId is not set. Set node account IDs on the transaction before calling executeTransaction."):Xs}}async executeTransactionWithErrorHandling(Ps,Ws){try{return{result:await this.executeTransaction(Ps,Ws),error:void 0}}catch(Hs){const zs=Hs.message?.toLowerCase();if(this.logger.error("Failed to execute transaction",Hs),this.logger.error("Failure reason for transaction is",zs),zs.includes("insufficient payer balance"))return{result:void 0,error:"Insufficient balance to complete the transaction."};if(zs.includes("reject"))return{result:void 0,error:"You rejected the transaction"};if(zs.includes("invalid signature"))return{result:void 0,error:"Invalid signature. Please check your account and try again."};if(zs.includes("transaction expired"))return{result:void 0,error:"Transaction expired. Please try again."};if(zs.includes("account not found"))return{result:void 0,error:"Account not found. Please check the account ID and try again."};if(zs.includes("unauthorized"))return{result:void 0,error:"Unauthorized. You may not have the necessary permissions for this action."};if(zs.includes("busy"))return{result:void 0,error:"The network is busy. Please try again later."};if(zs.includes("invalid transaction"))return{result:void 0,error:"Invalid transaction. Please check your inputs and try again."}}}async submitMessageToTopic(Ps,Ws,Hs){this.ensureInitialized();let Zs=new u$u().setTopicId(d$s.fromString(Ps)).setMessage(Ws);return Hs&&(Zs=await Zs.sign(Hs)),this.executeTransaction(Zs)}async transferHbar(Ps,Ws,Hs){this.ensureInitialized();const Zs=new T$a().setTransactionId(i$s.generate(Ps)).addHbarTransfer(y$f.fromString(Ps),new e$F(-Hs)).addHbarTransfer(y$f.fromString(Ws),new e$F(Hs));return this.executeTransaction(Zs)}async executeSmartContract(Ps,Ws,Hs,Zs=1e5){this.ensureInitialized();const zs=new i$o().setContractId(g$p.fromString(Ps)).setGas(Zs).setFunction(Ws,Hs);return this.executeTransaction(zs)}handleNewSession(Ps){const Hs=Ps.namespaces?.hedera?.accounts?.[0]?.split(":"),Zs=Hs.pop(),zs=Hs.pop();if(this.logger.info("sessionAccount is",Zs,zs),Zs)this.saveConnectionInfo(Zs,zs);else{this.logger.error("No account id found in the session");return}}getNetworkPrefix(){const Ws=this.getAccountInfo()?.network;if(!Ws){this.logger.warn("Network is not set on SDK, defaulting.");const Hs=localStorage.getItem("connectedNetwork");return Hs||"mainnet-public"}return Ws!==this.network&&(this.logger.warn("Detected network mismatch, reverting to signer network",Ws),this.network=Ws),Ws.isMainnet()?"mainnet-public":"testnet"}async requestAccount(Ps){try{const Hs=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/accounts/${Ps}`,Zs=await fetchWithRetry()(Hs);if(!Zs.ok)throw new Error(`Failed to make request to mirror node for account: ${Zs.status}`);return await Zs.json()}catch(Ws){throw this.logger.error("Failed to fetch account",Ws),Ws}}async getAccountBalance(){this.ensureInitialized();const Ws=this.getAccountInfo()?.accountId;if(!Ws)return null;const Hs=await this.requestAccount(Ws);if(!Hs)throw new Error("Failed to fetch account. Try again or check if the Account ID is valid.");const Zs=Hs.balance.balance/10**8;return Number(Zs).toLocaleString("en-US")}getAccountInfo(){const{accountId:Ps}=this.loadConnectionInfo();if(!Ps||!this?.dAppConnector?.signers?.length)return null;const Hs=this.dAppConnector.signers.find(Xs=>Xs.getAccountId().toString()===Ps);if(!Hs)return null;const Zs=Hs?.getAccountId()?.toString();if(!Zs)return null;const zs=Hs.getLedgerId();return{accountId:Zs,network:zs}}async createTopic(Ps,Ws,Hs){this.ensureInitialized();let Zs=new c$w().setTopicMemo(Ps||"");if(Ws){const Xs=g$q.fromString(Ws);Zs.setAdminKey(Xs.publicKey),Zs=await Zs.sign(Xs)}return Hs&&Zs.setSubmitKey(g$q.fromString(Hs).publicKey),(await this.executeTransaction(Zs)).topicId.toString()}async createToken(Ps,Ws,Hs,Zs,zs,Xs,Va){this.ensureInitialized();let Js=new c$x().setTokenName(Ps).setTokenSymbol(Ws).setDecimals(Zs).setInitialSupply(Hs).setTreasuryAccountId(y$f.fromString(zs)).setTokenType(e$l.NonFungibleUnique).setSupplyType(e$k.Finite);return Va&&(Js=Js.setSupplyKey(g$q.fromString(Va))),Xs&&(Js=Js.setAdminKey(g$q.fromString(Xs)),Js=await Js.sign(g$q.fromString(Xs))),(await this.executeTransaction(Js)).tokenId.toString()}async mintNFT(Ps,Ws,Hs){this.ensureInitialized();let Zs=await new r$n().setTokenId(Ps).setMetadata([Buffer$1.from(Ws,"utf-8")]).sign(Hs);return this.executeTransaction(Zs)}async getMessages(Ps,Ws,Hs=!1,Zs){const Xs=`https://${Zs||this.getNetworkPrefix()}.mirrornode.hedera.com`,Va=Number(Ws)>0&&!Hs?`×tamp=gt:${Ws}`:"",Js=`${Xs}/api/v1/topics/${Ps}/messages?limit=200${Va}`;try{const Ma=await fetchWithRetry()(Js);if(!Ma.ok)throw new Error(`Failed to make request to mirror node: ${Ma.status}`);const qs=await Ma.json(),Ys=qs?.messages||[],Hc=qs?.links?.next,ol=Ys.map(Vc=>({...JSON.parse(atob(Vc.message)),payer:Vc.payer_account_id,created:new Date(Number(Vc.consensus_timestamp)*1e3),consensus_timestamp:Vc.consensus_timestamp,sequence_number:Vc.sequence_number}));if(Hc){const Vc=await this.getMessages(Ps,Number(ol[ol.length-1]?.consensus_timestamp),Hs);ol.push(...Vc.messages)}return{messages:ol.sort((Vc,Dc)=>Vc.sequence_number-Dc.sequence_number),error:""}}catch(Ma){return this.logger.error("Error fetching topic data:",Ma),{messages:[],error:Ma.toString()}}}async signMessage(Ps){const Ws=this.dAppConnector;if(!Ws)throw new Error("No active connection or signer");const Zs=this.getAccountInfo()?.accountId,zs={signerAccountId:`hedera:${this.network}:${Zs}`,message:Ps};return{userSignature:(await Ws.signMessage(zs)).signatureMap}}saveConnectionInfo(Ps,Ws){if(!Ps)localStorage.removeItem("connectedAccountId"),localStorage.removeItem("connectedNetwork");else{const Hs=Ws?.replace(/['"]+/g,"");localStorage.setItem("connectedNetwork",Hs),localStorage.setItem("connectedAccountId",Ps)}}loadConnectionInfo(){return{accountId:localStorage.getItem("connectedAccountId"),network:localStorage.getItem("connectedNetwork")}}async connectWallet(Ps,Ws,Hs){try{await this.init(Ps,Ws,Hs);const Zs=await this.connect(),Xs=this.getAccountInfo()?.accountId,Va=await this.getAccountBalance(),Js=this.getNetworkPrefix();return this.saveConnectionInfo(Xs,Js),{accountId:Xs,balance:Va,session:Zs}}catch(Zs){throw this.logger.error("Failed to connect wallet:",Zs),Zs}}async disconnectWallet(Ps=!0){try{const Ws=await this.disconnect();return Ws&&Ps&&localStorage.clear(),this.saveConnectionInfo(void 0),Ws}catch(Ws){return this.logger.error("Failed to disconnect wallet:",Ws),!1}}async initAccount(Ps,Ws,Hs,Zs=()=>{}){const{accountId:zs,network:Xs}=this.loadConnectionInfo();if(zs&&Xs)try{const Va=Xs==="mainnet"?r$y.MAINNET:r$y.TESTNET,Js=Hs||Va;await this.init(Ps,Ws,Js,Zs);const Ma=await this.getAccountBalance();return{accountId:zs,balance:Ma}}catch(Va){return this.logger.error("Failed to reconnect:",Va),this.saveConnectionInfo(void 0,void 0),null}else if(Hs)try{this.logger.info("initializing normally through override.",Hs),await this.init(Ps,Ws,Hs,Zs),this.logger.info("initialized",Hs),await this.connectViaDappBrowser(),this.logger.info("connected via dapp browser")}catch(Va){return this.logger.error("Failed to fallback connect:",Va),this.saveConnectionInfo(void 0,void 0),null}return null}subscribeToExtensions(Ps){return this.extensionCheckInterval&&clearInterval(this.extensionCheckInterval),this.hasCalledExtensionCallback=!1,this.extensionCheckInterval=setInterval(()=>{const Hs=(this.dAppConnector?.extensions||[]).find(Zs=>Zs.availableInIframe);Hs&&!this.hasCalledExtensionCallback&&(this.hasCalledExtensionCallback=!0,Ps(Hs),this.extensionCheckInterval&&(clearInterval(this.extensionCheckInterval),this.extensionCheckInterval=null))},1e3),()=>{this.extensionCheckInterval&&(clearInterval(this.extensionCheckInterval),this.extensionCheckInterval=null),this.hasCalledExtensionCallback=!1}}async connectViaDappBrowser(){const Ps=this.dAppConnector.extensions||[],Ws=Ps.find(Hs=>(this.logger.info("Checking extension",Hs),Hs.availableInIframe));this.logger.info("extensions are",Ps,Ws),Ws?await this.connectToExtension(Ws):this.subscribeToExtensions(async Hs=>{await this.connectToExtension(Hs)})}async connectToExtension(Ps){this.logger.info("found extension, connecting to iframe.",Ps);const Ws=await this.dAppConnector.connectExtension(Ps.id),Hs=this.dAppConnector.onSessionIframeCreated;Hs&&Hs(Ws)}ensureInitialized(){if(!this.dAppConnector)throw new Error("SDK not initialized. Call init() first.")}static run(){try{typeof window<"u"&&(window.HashinalsWalletConnectSDK=Pd.getInstance(),window.HashgraphSDK=HashgraphSDK)}catch{console.error("[ERROR]: failed setting sdk on window")}}async transferToken(Ps,Ws,Hs,Zs){this.ensureInitialized();const zs=new T$a().setTransactionId(i$s.generate(Ws)).addTokenTransfer(c$E.fromString(Ps),y$f.fromString(Ws),-Zs).addTokenTransfer(c$E.fromString(Ps),y$f.fromString(Hs),Zs);return this.executeTransaction(zs)}async createAccount(Ps){this.ensureInitialized();const Ws=new h$m().setInitialBalance(new e$F(Ps));return this.executeTransaction(Ws)}async associateTokenToAccount(Ps,Ws){this.ensureInitialized();const Hs=new r$t().setAccountId(y$f.fromString(Ps)).setTokenIds([c$E.fromString(Ws)]);return this.executeTransaction(Hs)}async dissociateTokenFromAccount(Ps,Ws){this.ensureInitialized();const Hs=new r$s().setAccountId(y$f.fromString(Ps)).setTokenIds([c$E.fromString(Ws)]);return this.executeTransaction(Hs)}async updateAccount(Ps,Ws){this.ensureInitialized();const Hs=new s$G().setAccountId(y$f.fromString(Ps)).setMaxAutomaticTokenAssociations(Ws);return this.executeTransaction(Hs)}async approveAllowance(Ps,Ws,Hs,Zs){this.ensureInitialized();const zs=new A$c().approveTokenAllowance(c$E.fromString(Ws),y$f.fromString(Zs),y$f.fromString(Ps),Hs);return this.executeTransaction(zs)}async getAccountTokens(Ps){this.ensureInitialized();const Hs=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com`,Zs=`${Hs}/api/v1/accounts/${Ps}/tokens?limit=200`;try{const zs=await fetchWithRetry()(Zs);if(!zs.ok)throw new Error(`Failed to make request to mirror node for account tokens: ${zs.status}`);const Xs=await zs.json(),Va=[];for(const Ma of Xs.tokens)Ma.token_id&&Va.push({tokenId:Ma.token_id,balance:Ma.balance,decimals:Ma.decimals,formatted_balance:(Ma.balance/10**Ma.decimals).toLocaleString("en-US"),created_timestamp:new Date(Number(Ma.created_timestamp)*1e3)});let Js=Xs.links?.next;for(;Js;){const Ma=`${Hs}${Js}`,qs=await fetchWithRetry()(Ma);if(!qs.ok)throw new Error(`Failed to make request to mirror node for account tokens: ${qs.status}, page: ${Ma}`);const Ys=await qs.json();for(const Hc of Ys.tokens)Hc.token_id&&Va.push({tokenId:Hc.token_id,balance:Hc.balance,decimals:Hc.decimals,formatted_balance:(Hc.balance/10**Hc.decimals).toLocaleString("en-US"),created_timestamp:new Date(Number(Hc.created_timestamp)*1e3)});Js=Ys.links?.next}return{tokens:Va}}catch(zs){throw this.logger.error("Error fetching account tokens:",zs),zs}}async getTransaction(Ps){try{const Hs=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/transactions/${Ps}`;this.logger.debug("Fetching transaction",Hs);const Zs=await fetchWithRetry()(Hs);if(!Zs.ok)throw new Error(`Failed to fetch transaction: ${Zs.status}`);return await Zs.json()}catch(Ws){return this.logger.error("Failed to get transaction",Ws),null}}async getTransactionByTimestamp(Ps){try{const Hs=`https://${this.getNetworkPrefix()}.mirrornode.hedera.com/api/v1/transactions?timestamp=${Ps}`;this.logger.debug("Fetching transaction by timestamp",Hs);const Zs=await fetchWithRetry()(Hs);if(!Zs.ok)throw new Error(`Failed to fetch transaction by timestamp: ${Zs.status}`);const Xs=(await Zs.json())?.transactions?.[0];return Xs?await this.getTransaction(Xs.transaction_id):null}catch(Ws){return this.logger.error("Failed to get transaction by timestamp",Ws),null}}async getAccountNFTs(Ps,Ws){try{const Hs=this.getNetworkPrefix(),Zs=Ws?`&token.id=${Ws}`:"",zs=`https://${Hs}.mirrornode.hedera.com/api/v1/accounts/${Ps}/nfts?limit=200${Zs}`,Xs=await fetchWithRetry()(zs);if(!Xs.ok)throw new Error(`Failed to fetch NFTs for account: ${Xs.status}`);const Va=await Xs.json();let Js=Va?.links?.next||null,Ma=Va.nfts||[];for(;Js;)try{const qs=await fetchWithRetry()(`https://${Hs}.mirrornode.hedera.com${Js}`);if(!qs.ok)throw new Error(`Failed to fetch next page of NFTs: ${qs.status}`);const Ys=await qs.json(),Hc=Ys?.nfts||[];Ma=[...Ma,...Hc],Js=Ys?.links?.next&&Js!==Ys?.links?.next?Ys.links.next:null}catch(qs){this.logger.error("Failed to fetch next page of NFTs",qs);break}return Ma.map(qs=>{try{qs.token_uri=Buffer$1.from(qs.metadata,"base64").toString("ascii")}catch(Ys){this.logger.error("Failed to decode NFT metadata",Ys)}return qs})}catch(Hs){return this.logger.error("Failed to get account NFTs",Hs),[]}}async validateNFTOwnership(Ps,Ws,Hs){return(await this.getAccountNFTs(Ws,Hs)).find(zs=>zs.token_id===Hs&&zs.serial_number.toString()===Ps)||null}async readSmartContract(Ps,Ws,Hs,Zs=!0,zs=0){try{const Xs=this.getNetworkPrefix(),Va={block:"latest",data:Ps,estimate:Zs,from:Ws.toSolidityAddress(),to:Hs.toSolidityAddress(),value:zs};Zs||(Va.gas=3e5,Va.gasPrice=1e8);const Js=`https://${Xs}.mirrornode.hedera.com/api/v1/contracts/call`,Ma=await fetchWithRetry()(Js,{method:"POST",body:JSON.stringify(Va),headers:{"Content-Type":"application/json"}});if(!Ma.ok)throw new Error(`Failed to make contract call: ${Ma.status}`);return await Ma.json()}catch(Xs){return this.logger.error("Failed to make contract call",Xs),null}}};Pd.proxyInstance=null;let HashinalsWalletConnectSDK=Pd;HashinalsWalletConnectSDK.run();class ReownAuthenticationMessenger{constructor(Ps){this.getNonce=Ps.getNonce}async createMessage(Ps){const Ws={accountAddress:Ps.accountAddress,chainId:Ps.chainId,version:"1",domain:typeof document>"u"?"Unknown Domain":document.location.host,uri:typeof document>"u"?"Unknown URI":document.location.href,resources:this.resources,nonce:await this.getNonce(Ps),issuedAt:this.stringifyDate(new Date),statement:void 0,expirationTime:void 0,notBefore:void 0};return Object.assign(Ws,{toString:()=>this.stringify(Ws)})}stringify(Ps){const Ws=this.getNetworkName(Ps.chainId);return[`${Ps.domain} wants you to sign in with your ${Ws} account:`,Ps.accountAddress,Ps.statement?`
|
|
467
467
|
${Ps.statement}
|
|
468
468
|
`:"",`URI: ${Ps.uri}`,`Version: ${Ps.version}`,`Chain ID: ${Ps.chainId}`,`Nonce: ${Ps.nonce}`,Ps.issuedAt&&`Issued At: ${Ps.issuedAt}`,Ps.expirationTime&&`Expiration Time: ${Ps.expirationTime}`,Ps.notBefore&&`Not Before: ${Ps.notBefore}`,Ps.requestId&&`Request ID: ${Ps.requestId}`,Ps.resources?.length&&Ps.resources.reduce((Hs,Zs)=>`${Hs}
|
|
469
469
|
- ${Zs}`,"Resources:")].filter(Hs=>typeof Hs=="string").join(`
|