graz 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +201 -74
- package/dist/index.d.ts +201 -74
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{create as e}from"zustand";import{createJSONStorage as n,subscribeWithSelector as t,persist as o}from"zustand/middleware";import{Cosmiframe as r,isInIframe as i}from"@dao-dao/cosmiframe";import{isSnapInstalled as a,installSnap as s,CosmosSnap as c}from"@cosmsnap/snapper";import{encodeEd25519Pubkey as l,encodeSecp256k1Pubkey as d,pubkeyType as u,rawEd25519PubkeyToRawAddress as g,rawSecp256k1PubkeyToRawAddress as w}from"@cosmjs/amino";import f from"long";import{fromBech32 as h}from"@cosmjs/encoding";import{WalletConnectModal as m}from"@walletconnect/modal";import{SignClient as p}from"@walletconnect/sign-client";import{getSdkError as y}from"@walletconnect/utils";import{useQuery as S,useMutation as C}from"@tanstack/react-query";import{useMemo as I,useEffect as b,useState as E}from"react";import A from"p-map";import{CosmWasmClient as _,SigningCosmWasmClient as v}from"@cosmjs/cosmwasm-stargate";import{StargateClient as O,SigningStargateClient as k,GasPrice as N}from"@cosmjs/stargate";import{useShallow as B}from"zustand/shallow";import{jsxs as T,jsx as P,Fragment as D}from"react/jsx-runtime";var F="graz-reconnect-session",L=(e=>(e.KEPLR="keplr",e.LEAP="leap",e.VECTIS="vectis",e.COSMOSTATION="cosmostation",e.WALLETCONNECT="walletconnect",e.WC_KEPLR_MOBILE="wc_keplr_mobile",e.WC_LEAP_MOBILE="wc_leap_mobile",e.WC_COSMOSTATION_MOBILE="wc_cosmostation_mobile",e.WC_CLOT_MOBILE="wc_clot_mobile",e.METAMASK_SNAP_LEAP="metamask_snap_leap",e.METAMASK_SNAP_COSMOS="metamask_snap_cosmos",e.STATION="station",e.XDEFI="xdefi",e.COSMIFRAME="cosmiframe",e.COMPASS="compass",e.INITIA="initia",e.OKX="okx",e.PARA="para",e.CACTUSCOSMOS="cactuscosmos",e))(L||{}),K=["keplr","leap","vectis","cosmostation","walletconnect","wc_keplr_mobile","wc_leap_mobile","wc_cosmostation_mobile","wc_clot_mobile","metamask_snap_leap","station","xdefi","metamask_snap_cosmos","cosmiframe","compass","initia","okx","para","cactuscosmos"],M={iframeOptions:null,recentChainIds:null,chains:null,chainsConfig:null,paraConfig:null,multiChainFetchConcurrency:3,walletType:"keplr",walletConnect:{options:null,walletConnectModal:null},walletDefaultOptions:null,pingInterval:36e5,_notFoundFn:()=>null,_onReconnectFailed:()=>null,_reconnect:!1,_reconnectConnector:null},U={accounts:null,activeChainIds:null,status:"disconnected",lastPing:null,wcSignClients:new Map,paraConnector:null},q=e(t(o(()=>U,{name:"graz-session",version:2,partialize:e=>({accounts:e.accounts,activeChainIds:e.activeChainIds,lastPing:e.lastPing,status:e.status}),storage:n(()=>sessionStorage)}))),$=e(t(o(()=>M,{name:"graz-internal",partialize:e=>({recentChainIds:e.recentChainIds,_reconnect:e._reconnect,_reconnectConnector:e._reconnectConnector,walletType:e.walletType,chains:e.chains}),version:3}))),x=()=>{if(void 0!==window.cactuslink_cosmos){const e=window.cactuslink_cosmos,n=e=>{const n=()=>{de(),e()};return window.addEventListener("accountsChanged",n),()=>{window.removeEventListener("accountsChanged",n)}};return{...Object.assign(e,{subscription:n}),getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSigner(n),experimentalSuggestChain:async()=>{throw new Error("Cactus Cosmos does not support experimentalSuggestChain")}}}throw $.getState()._notFoundFn(),new Error("window.cactuslink_cosmos is not defined")},j=()=>{if(void 0!==window.compass){const e=window.compass,n=e=>{const n=()=>{de(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.leap is not defined")},W=()=>{const e=$.getState();if(!e.iframeOptions)throw e._notFoundFn(),new Error("no iframe options set");if(!i())throw e._notFoundFn(),new Error("not in iframe");if(!e.iframeOptions.allowedIframeParentOrigins.length)throw e._notFoundFn(),new Error("no iframe allowed origins");const n=new r(e.iframeOptions.allowedIframeParentOrigins).getKeplrClient();return{enable:n.enable.bind(n),getKey:n.getKey.bind(n),getOfflineSigner:n.getOfflineSigner.bind(n),getOfflineSignerAuto:n.getOfflineSignerAuto.bind(n),getOfflineSignerOnlyAmino:n.getOfflineSignerOnlyAmino.bind(n),experimentalSuggestChain:n.experimentalSuggestChain.bind(n),signDirect:n.signDirect.bind(n),signAmino:n.signAmino.bind(n)}},R={},z=()=>{if(void 0!==window.cosmostation?.providers.keplr){const e=window.cosmostation.providers.keplr,n=e=>{const n=()=>{de(),e()};return window.addEventListener("cosmostation_keystorechange",n),()=>{window.removeEventListener("cosmostation_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.cosmostation.providers.keplr is not defined")},G=()=>{if(void 0!==window.initia){const e=window.initia;return{enable:async()=>{await e.getAddress()},getKey:async n=>{const t=e.getOfflineSigner(n),[o]=await t.getAccounts();if(!o)throw new Error("Wallet connection failed");const r=(()=>{switch(o.algo){case"secp256k1":return w(o.pubkey);case"ed25519":return g(o.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{name:(i=o.address,`${i.slice(0,6)}...${i.slice(-6)}`),algo:o.algo,pubKey:o.pubkey,bech32Address:o.address,address:r,isNanoLedger:!1,isKeystone:!1};var i},getOfflineSigner:n=>{const t=e.getOfflineSigner(n),o=e.getOfflineSignerOnlyAmino(n);return{getAccounts:t.getAccounts.bind(t),signDirect:t.signDirect.bind(t),signAmino:o.signAmino.bind(o)}},getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),experimentalSuggestChain:n=>e.requestAddInitiaLayer({chain_id:n.chainId,chain_name:n.chainName,bech32_prefix:"init",bech32_config:n.bech32Config,slip44:n.bip44.coinType,logo_URIs:{png:n.chainSymbolImageUrl},fees:{fee_tokens:n.feeCurrencies.map(e=>({denom:e.coinDenom,amount:e.coinMinimalDenom,low_gas_price:e.gasPriceStep?.low,average_gas_price:e.gasPriceStep?.average,high_gas_price:e.gasPriceStep?.high}))},apis:{rpc:[{address:n.rpc}],rest:[{address:n.rest}]}}),signDirect:(...n)=>{const[t,o,r]=n;return e.getOfflineSigner(t).signDirect(o,(e=>{const{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}=e;if(!(n&&t&&o&&r))throw new Error("Invalid sign doc");return{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}})(r))},signAmino:(...n)=>{const[t,o,r]=n;return e.getOfflineSignerOnlyAmino(t).signAmino(o,r)},signArbitrary:async(n,t,o)=>{const r=e.getOfflineSigner(n),i=(await r.getAccounts()).find(e=>e.address===t);if(!i)throw new Error(`Wallet not connected to account ${t}`);const a=(()=>{switch(i.algo){case"secp256k1":return d(i.pubkey);case"ed25519":return l(i.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{signature:await e.signArbitrary(o),pub_key:{type:"secp256k1"===i.algo?u.secp256k1:u.ed25519,value:a.value}}},subscription:e=>{const n=()=>{de(),e()};return window.addEventListener("initia_keystorechange",n),()=>{window.removeEventListener("initia_keystorechange",n)}}}}throw $.getState()._notFoundFn(),new Error("window.initia is not defined")},V=()=>{if(void 0!==window.keplr){const e=window.keplr,n=e=>{const n=()=>{de(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.keplr is not defined")},H=()=>{if(void 0!==window.leap){const e=window.leap,n=e=>{const n=()=>{de(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.leap is not defined")},X={},Y=()=>(e=>{const n=window.ethereum;if(n&&e){const t=async()=>await n.request({method:"wallet_getSnaps"}),o=async n=>{try{const o=await t();return Object.values(o).find(t=>t.id===e.id&&(!n||t.version===n))}catch(e){return}},r=async()=>{await n.request({method:"wallet_requestSnaps",params:{[e.id]:e.params||{}}})},i=async()=>{const e=await n.request({method:"web3_clientVersion"});if(!e.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const t=e.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(t)>=11))throw new Error("Metamask Snap is not supported in this version");return await o()||await r(),!0},a=async(t,o,r)=>{const i=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signDirect",params:{chainId:t,signerAddress:o,signDoc:r}}}}),a=r.accountNumber,s=new f(a.low,a.high,a.unsigned);return{signature:i.signature,signed:{...i.signed,accountNumber:s.toString(),authInfoBytes:new Uint8Array(Object.values(i.signed.authInfoBytes)),bodyBytes:new Uint8Array(Object.values(i.signed.bodyBytes))}}},s=async(t,o,r)=>await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signAmino",params:{chainId:t,signerAddress:o,signDoc:r}}}}),c=async t=>{if(void 0!==X[t])return X[t];const o=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"getKey",params:{chainId:t}}}});if(!o)throw new Error("No response from Metamask");return o.pubKey=Uint8Array.from(Object.values(o.pubkey)),delete o.pubkey,X[t]=o,X[t]},l=async e=>{const n=await c(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async(...e)=>{const[n,t,o,r]=e;return await s(n,t,o)},u=async(...e)=>{const[n,t,o]=e,r={...o,accountNumber:f.fromString(o.accountNumber?.toString()||"0"),authInfoBytes:o.authInfoBytes,bodyBytes:o.bodyBytes};return await a(n,t,r)},g=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>d(e,n,t)});return{enable:async e=>{await o()||await r()},experimentalSuggestChain:async(...t)=>{await i(),await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"suggestChain",params:{chainInfo:t[0]}}}})},getKey:c,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>d(e,n,t)}),getOfflineSignerAuto:async e=>g(e),getOfflineSignerOnlyAmino:g,init:i,signAmino:d,signDirect:u}}throw $.getState()._notFoundFn(),new Error("window.ethereum is not defined")})({id:"npm:@leapwallet/metamask-cosmos-snap"}),Q=()=>{if(void 0!==window.okxwallet?.keplr){const e=window.okxwallet.keplr,n=e=>{const n=()=>{de(),e()};return window.okxwallet?.on("accountsChanged",n),()=>{window.okxwallet?.removeListener("accountsChanged",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.okxwallet.keplr is not defined")},J=null,Z=()=>{const e=()=>{const e=q.getState().paraConnector;if(!e)throw new Error("Para connector not initialized. Call connect() first or check paraConfig in GrazProvider.");return e},n=$.getState().paraConfig;if(!n?.paraWeb)throw new Error("Missing Para config. Provide paraConfig with 'paraWeb' to GrazProvider.");return{enable:async e=>{const t=Array.isArray(e)?e:[e];try{const e=await(J||(J=(async()=>{const e=q.getState().paraConnector;if(e)return e;try{let e;if(n.connectorClass)e=n.connectorClass;else{if("undefined"==typeof window)throw new Error("Para connector requires client-side execution (SSR is unsupported).");const n=new Function("specifier","return import(specifier)"),t=await n("@getpara/graz-integration"),o=t?.ParaGrazConnector;if("function"!=typeof o)throw new Error("Invalid ParaGrazConnector in @getpara/graz-integration. Check the package/export.");e=o}const t=$.getState().chains,o=new e(n,t);if(q.setState(e=>({...e,paraConnector:o})),!o)throw new Error("Para connector initialization failed. Check config and dependencies.");return o}catch(e){if(J=null,"MODULE_NOT_FOUND"===e?.code||e?.message?.includes("Cannot find module")||e?.message?.includes("Failed to resolve"))throw new Error("Para integration package not found. Install @getpara/graz-integration to use Para wallet: npm install @getpara/graz-integration");throw new Error(`Para connector init failed: ${e?.message||"Unknown error"}. Check @getpara/graz-integration and ParaConfig.`)}})()));q.setState({paraConnector:e,status:"connecting"}),await e.enable(t);const o=Object.fromEntries(await Promise.all(t.map(async n=>[n,await e.getKey(n)])));q.setState(e=>({accounts:{...e.accounts||{},...o},activeChainIds:Array.from(new Set([...e.activeChainIds||[],...t])),status:"connected"})),$.setState(e=>({recentChainIds:Array.from(new Set([...e.recentChainIds||[],...t])),walletType:"para",_reconnect:!1,_reconnectConnector:"para"}))}catch(e){q.setState({paraConnector:null,status:"disconnected"});if(e?.message?.includes("not found")||e?.message?.includes("Cannot find"))throw new Error("Para wallet connection failed: Required packages not installed. Install @getpara/graz-integration to enable Para wallet.");throw new Error("Para enable failed"+(e instanceof Error?`: ${e.message}`:""))}},disable:async()=>{const e=q.getState().paraConnector;if(e)try{await e.disconnect(),await e.getParaWebClient().logout()}catch(e){throw new Error("Para disconnect failed"+(e?.message?`: ${e.message}`:". Wallet may already be disconnected."))}finally{q.setState({paraConnector:null,status:"disconnected"})}else q.setState({paraConnector:null,status:"disconnected"})},getKey:async n=>{try{return await e().getKey(n)}catch(e){throw new Error(`Failed to get key${e?.message?`: ${e.message}`:""}. Check chain connection and Cosmos API key settings at developer.getpara.com.`)}},getOfflineSigner:n=>{try{return e().getOfflineSigner(n)}catch(e){throw new Error(`Failed to get offline signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerOnlyAmino:n=>{try{return e().getOfflineSignerOnlyAmino(n)}catch(e){throw new Error(`Failed to get Amino signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerAuto:n=>{try{return e().getOfflineSignerAuto(n)}catch(e){throw new Error(`Failed to get auto signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},signAmino:async(n,t,o,r)=>{try{return await e().signAmino(n,t,o,r)}catch(e){throw new Error(`Amino signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signDirect:async(n,t,o,r)=>{try{return await e().signDirect(n,t,o,r)}catch(e){throw new Error(`Direct signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signArbitrary:async(n,t,o)=>{try{return await e().signArbitrary(n,t,o)}catch(e){throw new Error(`Arbitrary signing failed${e?.message?`: ${e.message}`:""}. User rejected or feature not supported.`)}},experimentalSuggestChain:async()=>{throw new Error("Chain suggestion not supported. Configure chains in Para wallet settings.")}}},ee=()=>{if(void 0!==window.station?.keplr){const e=window.station.keplr;return{subscription:e=>{const n=()=>{de(),e()};return window.addEventListener("station_wallet_change",n),()=>{window.removeEventListener("station_wallet_change",n)}},getKey:async n=>({isKeystone:!1,...await e.getKey(n)}),getOfflineSigner:n=>{try{const t=e.getOfflineSignerOnlyAmino(n),o=(e,n)=>{throw new Error("signDirect not supported by Station")};return Object.assign(t,{signDirect:o})}catch(e){throw console.error(e),e}},experimentalSuggestChain:async n=>{try{if(!n.bech32Config)throw new Error("Bech32Config is required");if(!n.stakeCurrency)throw new Error("StakeCurrency is required");const t=Object.assign(n,{bech32Config:n.bech32Config,chainSymbolImageUrl:n.chainSymbolImageUrl||"",stakeCurrency:{coinDecimals:n.stakeCurrency.coinDecimals,coinDenom:n.stakeCurrency.coinDenom,coinImageUrl:n.stakeCurrency.coinImageUrl||"",coinMinimalDenom:n.stakeCurrency.coinMinimalDenom},currencies:n.currencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom})),feeCurrencies:n.feeCurrencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom,gasPriceStep:{average:e.gasPriceStep?.average||0,high:e.gasPriceStep?.high||0,low:e.gasPriceStep?.low||0}}))});await e.experimentalSuggestChain(t)}catch(e){throw console.error(e),e}},enable:n=>e.enable(n),disable:n=>e.disable(n),getOfflineSignerAuto:n=>e.getOfflineSignerAuto(n),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),signDirect:e.signDirect,signAmino:(n,t,o,r)=>e.signAmino(n,t,o)}}throw $.getState()._notFoundFn(),new Error("window.station is not defined")},ne=()=>{if(void 0!==window.vectis){const e=window.vectis.cosmos;return{enable:n=>e.enable(n),getOfflineSigner:n=>{const t=e.getOfflineSigner(n);return{getAccounts:t.getAccounts,signAmino:t.signAmino,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:f.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}},getOfflineSignerAuto:async n=>{const t=await e.getOfflineSignerAuto(n);return"signAmino"in t?t:"signDirect"in t?{getAccounts:t.getAccounts,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:f.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}:t},getKey:async n=>{const t=await e.getKey(n);return{address:h(t.address).data,algo:t.algo,bech32Address:t.address,name:t.name,pubKey:t.pubKey,isKeystone:!1,isNanoLedger:t.isNanoLedger}},subscription:e=>{const n=()=>{de(),e()};return window.addEventListener("vectis_accountChanged",n),()=>{window.removeEventListener("vectis_accountChanged",n)}},getOfflineSignerOnlyAmino:(...n)=>{const t=n[0];return e.getOfflineSignerAmino(t)},experimentalSuggestChain:async(...n)=>{const[t]=n;if(!t.bech32Config)throw new Error("Bech32Config is required");if(!t.stakeCurrency)throw new Error("StakeCurrency is required");const o={rpcUrl:t.rpc,restUrl:t.rest,prettyName:t.chainName.replace(" ",""),bech32Prefix:t.bech32Config.bech32PrefixAccAddr,currencies:t.currencies,feeCurrencies:t.feeCurrencies,chainId:t.chainId,chainName:t.chainName,bip44:t.bip44,stakeCurrency:t.stakeCurrency,features:t.features};return e.suggestChains([o])},signDirect:async(...n)=>{const{1:t,2:o}=n,r=await e.signDirect(t,{bodyBytes:o.bodyBytes||Uint8Array.from([]),authInfoBytes:o.authInfoBytes||Uint8Array.from([]),accountNumber:f.fromString(o.accountNumber?.toString()||"",!1),chainId:o.chainId||""});return{signature:r.signature,signed:{authInfoBytes:r.signed.authInfoBytes,bodyBytes:r.signed.bodyBytes,chainId:r.signed.chainId,accountNumber:BigInt(r.signed.accountNumber.toString())}}},signAmino:async(...n)=>{const{1:t,2:o}=n;return e.signAmino(t,o)}}}throw $.getState()._notFoundFn(),new Error("window.vectis is not defined")},te=()=>{if("undefined"!=typeof window){const e=navigator.userAgent;return!!/android/i.test(e)||!!/iPad|iPhone|iPod/.test(e)}return!1},oe=(e,n,t=new Error("Promise timed out"))=>{const o=new Promise((e,o)=>{setTimeout(()=>{o(t)},n)});return Promise.race([e,o])},re=e=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");const n=e?.walletType||"walletconnect",t=e?.encoding||"base64",o=n=>{if(!e)return;const{appUrl:t,formatNativeUrl:o}=e;if(te()){if(te()&&navigator.userAgent.toLowerCase().includes("android")){const e=o(t.mobile.android,n,"android");window.open(e,"_self","noreferrer noopener")}if(te()&&(navigator.userAgent.toLowerCase().includes("iphone")||navigator.userAgent.toLowerCase().includes("ipad"))){const e=o(t.mobile.ios,n,"ios");window.open(e,"_self","noreferrer noopener")}}},r=()=>{const{wcSignClients:e}=q.getState();if(!e.get(n))throw new Error("walletConnect.signClient is not defined");e.delete(n),q.setState({wcSignClients:e}),$.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})},i=async e=>{const{wcSignClients:t}=q.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");if(!e)throw new Error("No wallet connect session");await o.disconnect({topic:e,reason:y("USER_DISCONNECTED")}),await s(o)},a=e=>{try{const{wcSignClients:t}=q.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");const r=o.session.getAll(),a=r.at(-1);if(!a)return;if(!(1e3*a.expiry>Date.now()+1e3))throw i(a.topic),new Error("invalid session");try{const n=r.find(n=>n.requiredNamespaces.cosmos?.chains?.includes(`cosmos:${e}`));if(!n)throw new Error("no session");return n}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}return a}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},s=async e=>{try{const n=e.core.pairing.pairings.getAll({active:!1});if(!n.length)return;await Promise.all(n.map(async n=>{await e.core.pairing.pairings.delete(n.topic,{code:7001,message:"clear pairing"})}))}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},c=async t=>{const r="string"==typeof t?[t]:t,{wcSignClients:s,activeChainIds:c}=q.getState(),l=s.get(n);if(!l)throw new Error("enable walletConnect.signClient is not defined");const{walletConnect:u}=$.getState();if(!u?.options?.projectId)throw new Error("walletConnect.options.projectId is not defined");const g=new m({projectId:u.options.projectId,enableExplorer:!1,explorerRecommendedWalletIds:"NONE",...u.walletConnectModal}),w=(e=>{try{return a(e)}catch(e){return}})(r);if(!w){const{uri:n,approval:t}=await oe(l.connect({requiredNamespaces:{cosmos:{methods:["cosmos_getAccounts","cosmos_signAmino","cosmos_signDirect"],chains:r.map(e=>`cosmos:${e}`),events:["chainChanged","accountsChanged"]}}}),15e3,new Error("Connection timeout"));if(!n)throw new Error("No wallet connect uri");e?o(n):await g.openModal({uri:n});const i=async e=>e.aborted?Promise.reject(new Error("User closed wallet connect")):new Promise((n,o)=>{t().then(e=>{const t=e.sessionProperties;if(!t)return o(new Error("No session properties"));const r=JSON.parse(String(t.keys));if(0===r.length)return o(new Error("No accounts"));if(!r[0])return o(new Error("No accounts"));const i={};return r.forEach(e=>{i[e.chainId]={address:e.address,algo:e.algo,bech32Address:e.bech32Address,isNanoLedger:e.isNanoLedger,isKeystone:e.isKeystone,name:e.name,pubKey:e.pubKey}}),q.setState(e=>({accounts:{...e.accounts||{},...i}})),n(e)}).catch(o),e.addEventListener("abort",()=>{o(new Error("User closed wallet connect"))},{once:!0})});try{const e=new AbortController,n=e.signal;g.subscribeModal(n=>{n.open||e.abort()}),await i(n)}catch(e){if(g.closeModal(),!e.message.toLowerCase().includes("no matching key"))return Promise.reject(e)}return e||g.closeModal(),Promise.resolve()}try{await oe((async()=>{const e=Object.fromEntries(await Promise.all((c||r).map(async e=>[e,await d(e)])));q.setState({accounts:e})})(),15e3,new Error("Connection timeout"))}catch(e){if(i(w.topic),!e.message.toLowerCase().includes("no matching key"))throw e}},l=async e=>{const n=await d(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async e=>{const n=a([e]);if(!n?.topic)throw new Error("No wallet connect session");const o=n.sessionProperties&&JSON.parse(String(n.sessionProperties.keys));if(!o)throw new Error("No wallet connect key");if(0===o.length)throw new Error("No wallet connect session");const r=o.find(n=>n.chainId===e);if(!r)throw new Error(`No wallet connect key for chainId ${e}`);return{...r,pubKey:Buffer.from(String(r.pubKey),t)}},u=async(...e)=>{const[r,i,s]=e,{signature:c,signed:l}=await(async(...e)=>{const[r,i,s]=e,{accounts:c,wcSignClients:l}=q.getState(),d=l.get(n);if(!d)throw new Error("walletConnect.signClient is not defined");if(!c)throw new Error("account is not defined");const u=a([r])?.topic;if(!u)throw new Error("No wallet connect session");if(!s.bodyBytes)throw new Error("No bodyBytes");if(!s.authInfoBytes)throw new Error("No authInfoBytes");return o(),await d.request({topic:u,chainId:`cosmos:${r}`,request:{method:"cosmos_signDirect",params:{signerAddress:i,signDoc:{chainId:s.chainId,accountNumber:s.accountNumber?.toString(),bodyBytes:s.bodyBytes?Buffer.from(s.bodyBytes).toString(t):null,authInfoBytes:s.authInfoBytes?Buffer.from(s.authInfoBytes).toString(t):null}}}})})(r,i,s);return{signed:{chainId:l.chainId??"",accountNumber:l.accountNumber?BigInt(l.accountNumber):BigInt(0),authInfoBytes:l.authInfoBytes?new Uint8Array(Buffer.from(l.authInfoBytes,t)):new Uint8Array([]),bodyBytes:l.bodyBytes?new Uint8Array(Buffer.from(l.bodyBytes,t)):new Uint8Array([])},signature:c}},g=async(...e)=>{const[t,r,i,s]=e,c=await(async(...e)=>{const[t,r,i,s]=e,{wcSignClients:c}=q.getState(),l=c.get(n),{accounts:d}=q.getState();if(!l)throw new Error("walletConnect.signClient is not defined");if(!d)throw new Error("account is not defined");const u=a([t])?.topic;if(!u)throw new Error("No wallet connect session");return o(),await l.request({topic:u,chainId:`cosmos:${t}`,request:{method:"cosmos_signDirect",params:{signerAddress:r,signDoc:i}}})})(t,r,i);return c},w=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>g(e,n,t)});return{enable:c,disable:async e=>{const{wcSignClients:t}=q.getState(),o=t.get(n);if(void 0===e){const e=o?.session.getAll();void 0!==e&&await Promise.all(e.map(e=>i(e.topic)))}else"string"==typeof e?await i(a([e])?.topic):await Promise.all(e.map(e=>i(a([e])?.topic)));0===o?.session.getAll().length&&r()},experimentalSuggestChain:async(...e)=>{await Promise.reject(new Error("WalletConnect does not support experimentalSuggestChain"))},getKey:d,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>g(e,n,t)}),getOfflineSignerAuto:async e=>(await d(e)).isNanoLedger?w(e):(e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t)}))(e),getOfflineSignerOnlyAmino:w,signAmino:g,signDirect:u,subscription:e=>{const{wcSignClients:t}=q.getState(),o=t.get(n);if(!o)return()=>{};const i=n=>{const t=q.getState().accounts;if("accountsChanged"===n.params.event.name&&t&&!Object.values(t).map(e=>e.bech32Address).includes(n.params.event.data[0])){const e=n.params.chainId.split(":")[1];e&&c([e])}else e()};return o.events.on("session_delete",r),o.events.on("session_expire",r),o.events.on("session_event",i),()=>{o.events.off("session_delete",r),o.events.off("session_expire",r),o.events.off("session_event",i)}},init:async()=>{const{walletConnect:e}=$.getState();if(!e?.options)throw new Error("walletConnect.options is not defined");const{wcSignClients:t}=q.getState(),o=t.get(n);if(o)return o;const r=await p.init(e.options);return t.set(n,r),q.setState({wcSignClients:t}),r}}},ie=()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Cosmostation mobile is only supported in mobile");return re({encoding:"hex",appUrl:{mobile:{ios:"cosmostation://",android:"cosmostation://"}},walletType:"wc_cosmostation_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,"");return n?`${o}://wc?${n}`:`${o}://wc`}})},ae=()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Keplr mobile is only supported in mobile");return re({encoding:"base64",appUrl:{mobile:{ios:"keplrwallet://",android:"intent://"}},walletType:"wc_keplr_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`:`${o}://wcV2#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},se=()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Leap mobile is only supported in mobile");return re({encoding:"base64",appUrl:{mobile:{ios:"leapcosmos://",android:"intent://"}},walletType:"wc_leap_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`:`${o}://wcV2#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},ce=()=>{if(void 0!==window.xfi?.keplr){const e=window.xfi.keplr,n=e=>{const n=()=>{de(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}};return Object.assign(e,{subscription:n})}throw $.getState()._notFoundFn(),new Error("window.xfi.keplr is not defined")},le=(e=$.getState().walletType)=>{try{return ue(e),!0}catch(e){return!1}},de=()=>{window.sessionStorage.removeItem(F),q.setState(U)},ue=(e=$.getState().walletType)=>{const n=(()=>{switch(e){case"keplr":return V();case"leap":return H();case"cosmostation":return z();case"vectis":return ne();case"walletconnect":return re();case"wc_keplr_mobile":return ae();case"wc_leap_mobile":return se();case"wc_cosmostation_mobile":return ie();case"wc_clot_mobile":return(()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Clot mobile is only supported in mobile");return re({encoding:"base64",appUrl:{mobile:{android:"clot://",ios:"clot://"}},walletType:"wc_clot_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);return"ios"===t?r?`${o}://wcV2?${r}`:`${o}://wcV2`:r?`${o}://wc?uri=${r}`:`${o}://wc`}})})();case"metamask_snap_leap":return Y();case"metamask_snap_cosmos":return(()=>{const e=window.ethereum;let n=window.cosmos;if(e)return{init:async()=>{const t=await e.request({method:"web3_clientVersion"});if(!t.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const o=t.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(o)>=11))throw new Error("Metamask Snap is not supported in this version");return await a()||await s(),window.cosmos=new c,n=window.cosmos,!0},enable:async e=>{await a()||await s()},getOfflineSigner:e=>n.getOfflineSigner(e),experimentalSuggestChain:async e=>{if(!e.bech32Config)throw new Error("Bech32Config is required");if(!e.stakeCurrency)throw new Error("StakeCurrency is required");await n.experimentalSuggestChain({...e,stakeCurrency:e.stakeCurrency,bech32Config:e.bech32Config})},signAmino:async(e,t,o)=>n.signAmino(e,t,o),getKey:async e=>void 0!==R[e]?R[e]:n.getKey(e),getOfflineSignerAuto:async e=>(await n.getKey(e)).isNanoLedger?n.getOfflineSignerOnlyAmino(e):n.getOfflineSigner(e),getOfflineSignerOnlyAmino:e=>n.getOfflineSignerOnlyAmino(e),signDirect:async(e,t,o)=>n.signDirect(e,t,o),signArbitrary:async(e,t,o)=>n.signArbitrary(e,t,o),disable:async e=>{e&&await n.deleteChain(e)}};throw $.getState()._notFoundFn(),new Error("window.ethereum is not defined")})();case"station":return ee();case"xdefi":return ce();case"cosmiframe":return W();case"compass":return j();case"initia":return G();case"okx":return Q();case"para":return Z();case"cactuscosmos":return x();default:throw new Error("Unknown wallet type")}})(),t=$.getState().walletDefaultOptions;return t&&n.setDefaultOptions?.(t),n},ge=()=>Object.fromEntries(K.map(e=>[e,le(e)])),we=e=>"metamask_snap_leap"===e,fe=()=>Boolean(navigator?.userAgent)&&/LeapCosmos/i.test(navigator.userAgent),he=e=>"walletconnect"===e||"wc_keplr_mobile"===e||"wc_leap_mobile"===e||"wc_cosmostation_mobile"===e,me=e=>"para"===e,pe=async e=>{try{const{recentChainIds:n,chains:t,walletType:o}=$.getState(),r=e?.walletType||o;if(he(r)){const e=ue("walletconnect"),{disable:n}=e;n&&n()}if(!le(r))throw new Error(`${r} is not available`);const i=ue(r),a="string"==typeof e?.chainId?[e.chainId]:e?.chainId||n;if(!a)throw new Error("No last known connected chain, connect action requires chain ids");const s=t?.map(e=>e.chainId);a.forEach(e=>{if(!s?.includes(e))throw new Error(`Chain ${e} is not provided in GrazProvider`)}),q.setState(e=>{const n=$.getState()._reconnect||Boolean($.getState()._reconnectConnector)||Boolean(a);return e.activeChainIds&&a.filter(n=>!e.activeChainIds?.includes(n)).length>0?{status:"connecting"}:n?{status:"reconnecting"}:{status:"connecting"}});const{accounts:c}=q.getState();if(await(i.init?.()),await i.enable(a),!he(r)){let e={};if(we(r)){const n={};for await(const e of a)n[e]=await i.getKey(e);e=n}else if(fe()&&i.getKeys){const n=await i.getKeys(a);a.forEach((t,o)=>{const r=n[o];r&&(e[t]=r)})}else e=Object.fromEntries(await Promise.all(a.map(async e=>[e,await i.getKey(e)])));q.setState(n=>({accounts:{...n.accounts||{},...e}}))}$.setState(e=>({recentChainIds:[...e.recentChainIds||[],...a].filter((e,n,t)=>t.indexOf(e)===n)})),q.setState(e=>({activeChainIds:[...e.activeChainIds||[],...a].filter((e,n,t)=>t.indexOf(e)===n)})),$.setState({walletType:r,_reconnect:Boolean(e?.autoReconnect),_reconnectConnector:r}),q.setState({status:"connected"}),"undefined"!=typeof window&&window.sessionStorage.setItem(F,"Active");const l=a.map(e=>t.find(n=>n.chainId===e));return{accounts:q.getState().accounts,walletType:r,chains:l}}catch(e){throw console.error("connect ",e),null===q.getState().accounts&&q.setState({status:"disconnected"}),q.getState().accounts&&q.getState().activeChainIds&&q.setState({status:"connected"}),e}},ye=e=>{"undefined"!=typeof window&&window.sessionStorage.removeItem(F);const n="string"==typeof e?.chainId?[e.chainId]:e?.chainId,t=()=>{if(he($.getState().walletType)){const e=ue("walletconnect"),{disable:n}=e;n&&n()}if(me($.getState().walletType)){const e=ue("para"),{disable:n}=e;n&&n()}};if(n){const e=q.getState().accounts;n.forEach(n=>{delete e?.[n]});0===Object.values(e||{}).length?(t(),q.setState(U),$.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})):(q.setState(t=>({activeChainIds:t.activeChainIds?.filter(e=>!n.includes(e)),accounts:e})),$.setState(e=>({recentChainIds:e.recentChainIds?.filter(e=>!n.includes(e))})))}else t(),q.setState(U),$.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null});return Promise.resolve()},Se=async e=>{const{recentChainIds:n,_reconnectConnector:t,_reconnect:o}=$.getState();try{const e=le(t||void 0);if(n&&e&&t){if(he(t))return;return await pe({chainId:n,walletType:t,autoReconnect:o})}}catch(n){e?.onError?.(n),ye()}},Ce=async e=>{if(!e?.chainId)throw new Error("chainId is required");const{walletType:n}=$.getState(),t=e.walletType||n;if(!le(t))throw new Error(`${t} is not available`);const o=ue(t);return{offlineSigner:o.getOfflineSigner(e.chainId),offlineSignerAmino:o.getOfflineSignerOnlyAmino(e.chainId),offlineSignerAuto:await o.getOfflineSignerAuto(e.chainId)}},Ie=()=>{$.setState({recentChainIds:null})},be=()=>$.getState().recentChainIds,Ee=()=>{const{recentChainIds:e,chains:n}=$.getState();return e?.map(e=>n.find(n=>n.chainId===e))??null},Ae=({chainId:e}={})=>$.getState().chains?.find(n=>n.chainId===e),_e=({chainId:e}={})=>{const n=$.getState().chains;return e?n?.filter(n=>e.includes(n.chainId)):n??void 0},ve=async({chainInfo:e})=>{const{chains:n}=$.getState(),t=n?.find(n=>n.chainId===e.chainId);if(t)throw new Error(`Chain with chainId "${e.chainId}" already exists in the store`);return $.setState(n=>({chains:[...n.chains||[],e]})),e},Oe=async({chainInfo:e,walletType:n})=>{const t=ue(n);await t.experimentalSuggestChain(e);const{chains:o}=$.getState(),r=o?.find(n=>n.chainId===e.chainId);return r||$.setState(n=>({chains:[...n.chains||[],e]})),e},ke=async e=>{const n=$.getState().walletType;await Oe({chainInfo:e.chainInfo,walletType:e.walletType??n});return await pe({chainId:e.chainInfo.chainId,walletType:e.walletType,autoReconnect:e.autoReconnect})},Ne=e=>($.setState(n=>{const t=n.chains??[],o=e.chains,r=new Map;o.forEach(e=>r.set(e.chainId,e)),t.forEach(e=>{r.has(e.chainId)||r.set(e.chainId,e)});const i=Array.from(r.values());return{iframeOptions:e.iframeOptions||n.iframeOptions,walletConnect:e.walletConnect||n.walletConnect,walletType:e.defaultWallet||n.walletType,paraConfig:e.paraConfig||n.paraConfig,walletDefaultOptions:e.walletDefaultOptions||n.walletDefaultOptions,chains:i,chainsConfig:e.chainsConfig||n.chainsConfig,multiChainFetchConcurrency:e.multiChainFetchConcurrency||n.multiChainFetchConcurrency,pingInterval:e.pingInteval||n.pingInterval,_notFoundFn:e.onNotFound||n._notFoundFn,_onReconnectFailed:e.onReconnectFailed||n._onReconnectFailed,_reconnect:void 0===e.autoReconnect||(e.autoReconnect||n._reconnect)}}),e),Be=async({signingClient:e,senderAddress:n,recipientAddress:t,amount:o,fee:r,memo:i})=>{if(!e)throw new Error("No connected account detected");if(!n)throw new Error("senderAddress is not defined");return e.sendTokens(n,t,o,r,i)},Te=async({signingClient:e,senderAddress:n,recipientAddress:t,transferAmount:o,sourcePort:r,sourceChannel:i,timeoutHeight:a,timeoutTimestamp:s,fee:c,memo:l})=>{if(!e)throw new Error("Stargate signing client is not ready");if(!n)throw new Error("senderAddress is not defined");return e.sendIbcTokens(n,t,o,r,i,a,s,c,l)},Pe=async({signingClient:e,senderAddress:n,msg:t,fee:o,options:r,label:i,codeId:a})=>{if(!e)throw new Error("CosmWasm signing client is not ready");return e.instantiate(n,a,t,i,o,r)},De=async({signingClient:e,senderAddress:n,msg:t,fee:o,contractAddress:r,funds:i,memo:a})=>{if(!e)throw new Error("CosmWasm signing client is not ready");return e.execute(n,r,t,o,a,i)},Fe=async(e,n,t)=>{if(!t)throw new Error("CosmWasm client is not ready");return await t.queryContractSmart(e,n)},Le=(e,n,t)=>{if(!t)throw new Error("CosmWasm client is not ready");const o=(new TextEncoder).encode(n);return t.queryContractRaw(e,o)},Ke=e=>e,Me=e=>e,Ue=({chainId:e})=>{const n=$(e=>e.chains);if(!n)throw new Error("No chains found in GrazProvider");return e&&e.length>0?e.map(e=>n.find(n=>n.chainId===e)).filter(Boolean):n},qe=async(e,n)=>{const t=$.getState().multiChainFetchConcurrency,o=await A(e,n,{concurrency:t});return Object.fromEntries(o.map((n,t)=>[e[t].chainId,n]))};function $e(e){const n=Ue({chainId:e?.chainId}),t=I(()=>["USE_STARGATE_CLIENT",n],[n]);return S({queryKey:t,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");return await qe(n,async e=>{const n=$.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await O.connect(t)})},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}function xe(e){const n=Ue({chainId:e?.chainId}),t=I(()=>["USE_COSMWASM_CLIENT",n],[n]);return S({queryKey:t,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");return await qe(n,async e=>{const n=$.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await _.connect(t)})},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}var je=()=>$(B(e=>({walletType:e.walletType,isCosmostation:"cosmostation"===e.walletType,isCosmostationMobile:"wc_cosmostation_mobile"===e.walletType,isKeplr:"keplr"===e.walletType,isKeplrMobile:"wc_keplr_mobile"===e.walletType,isLeap:"leap"===e.walletType,isLeapMobile:"wc_leap_mobile"===e.walletType,isVectis:"vectis"===e.walletType,isWalletConnect:"walletconnect"===e.walletType,isMetamaskSnapLeap:"metamask_snap_leap"===e.walletType,isStation:"station"===e.walletType,isCosmiframe:"cosmiframe"===e.walletType}))),We=e=>{const n=$(n=>e||n.walletType);return S({queryKey:["USE_CHECK_WALLET",n],queryFn:()=>!!n&&le(n)})};function Re(e){const n=$(e=>e.walletType),t=q(e=>e.activeChainIds),o=Ue({chainId:e?.chainId?e.chainId:t||void 0}),r=q(e=>e.accounts),i=q(e=>e.status);b(()=>q.subscribe(e=>e.status,(n,t)=>{if("connected"===n){const{accounts:n,activeChainIds:o}=q.getState(),{chains:r}=$.getState(),{walletType:i}=$.getState();if(!n||!o||!r)return e?.onDisconnect?.();e?.onConnect?.({accounts:n,chains:o.map(e=>r.find(n=>n.chainId===e)),walletType:i,isReconnect:"reconnecting"===t})}"disconnected"===n&&e?.onDisconnect?.()}),[e]);return{data:I(()=>r?((e,n)=>{const t=e.map(n);return Object.fromEntries(t.map((n,t)=>[e[t].chainId,n]))})(o,e=>r[e.chainId]):void 0,[r,o]),isConnected:"connected"===i,isConnecting:"connecting"===i,isDisconnected:"disconnected"===i,isReconnecting:"reconnecting"===i,isLoading:"connecting"===i||"reconnecting"===i,walletType:"connected"===i?n:void 0,reconnect:Se,status:i}}var ze=e=>{const n=Ue({chainId:[e.chainId]})[0],{data:t}=$e({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=I(()=>["USE_ALL_BALANCES",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return S({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getAllBalances(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},Ge=e=>{const n=Ue({chainId:[e.chainId]})[0],{data:t}=$e({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=I(()=>["USE_BALANCE",o,e.chainId,e.bech32Address,e.denom],[e.bech32Address,e.chainId,e.denom,o]);return S({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);const t=await o.getBalance(e.bech32Address,e.denom);return"0"===t.amount?void 0:t},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},Ve=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_CONNECT",e,n,t],mutationFn:pe,onError:(n,t)=>e?.(n,t),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))}),{data:r}=We();return{connect:e=>o.mutate(e),connectAsync:e=>o.mutateAsync(e),error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,isSupported:Boolean(r),status:o.status}},He=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_DISCONNECT",e,n,t],mutationFn:ye,onError:n=>Promise.resolve(e?.(n,void 0)),onMutate:n,onSuccess:()=>Promise.resolve(t?.(void 0))});return{disconnect:e=>o.mutate(e),disconnectAsync:e=>o.mutateAsync(e),error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,status:o.status}};function Xe(e){const n=Ue({chainId:e?.chainId}),t=$(e=>e.walletType),o="connected"===q.getState().status&&q.getState().accounts&&$.getState()._reconnectConnector===t,r=I(()=>["USE_OFFLINE_SIGNERS",n,t],[n,t]);return S({queryKey:r,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chain found");if(!t)throw new Error("Wallet is not defined");if(!le(t))throw new Error(`${t} is not available`);return await qe(n,async e=>await Ce({chainId:e.chainId,walletType:t}))},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&Boolean(o),refetchOnWindowFocus:!1})}var Ye=e=>{const n=Ue({chainId:[e.chainId]})[0],{data:t}=$e({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=I(()=>["USE_BALANCE_STAKED",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return S({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getBalanceStaked(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},Qe=()=>q(e=>e.activeChainIds),Je=()=>{const e=q(e=>e.activeChainIds),n=$(e=>e.chains);return e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean)},Ze=({chainId:e}={})=>$(e=>e.chains)?.find(n=>n.chainId===e),en=({chainId:e}={})=>{const n=$(e=>e.chains);return e?n?.filter(n=>e.includes(n.chainId)):n},nn=({denom:e})=>{const n=Je();return S({queryKey:["USE_ACTIVE_CHAIN_CURRENCY",e],queryFn:({queryKey:[,e]})=>n?.find(n=>n.currencies.find(n=>n.coinMinimalDenom===e))?.currencies.find(e=>e)})},tn=e=>{const n=e.status??"BOND_STATUS_BONDED",t=["USE_ACTIVE_CHAIN_VALIDATORS",e.queryClient,n];return S({queryKey:t,queryFn:async()=>{if(!e.queryClient)throw new Error("Query client is not defined");return await e.queryClient.staking.validators(n)},enabled:void 0!==e.queryClient})},on=()=>({data:$(e=>e.recentChainIds),clear:Ie}),rn=()=>{const e=$(e=>e.recentChainIds),n=$(e=>e.chains),t=e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean);return{data:t,clear:Ie}},an=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_ADD_CHAIN",e,n,t],mutationFn:ve,onError:(n,t)=>Promise.resolve(e?.(n,t.chainInfo)),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>Promise.resolve(t?.(e))});return{addChain:o.mutate,addChainAsync:o.mutateAsync,error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,status:o.status}},sn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_SUGGEST_CHAIN",e,n,t],mutationFn:Oe,onError:(n,t)=>Promise.resolve(e?.(n,t.chainInfo)),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>Promise.resolve(t?.(e))});return{error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,suggest:o.mutate,suggestAsync:o.mutateAsync,status:o.status}},cn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_SUGGEST_CHAIN_AND_CONNECT",e,n,t],mutationFn:ke,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:e=>n?.(e),onSuccess:e=>Promise.resolve(t?.(e))}),{data:r}=We();return{error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,isSupported:Boolean(r),status:o.status,suggestAndConnect:o.mutate,suggestAndConnectAsync:o.mutateAsync}},ln=({onError:e,onLoading:n,onSuccess:t}={})=>{const{mutate:o,mutateAsync:r,...i}=C({mutationKey:["USE_SEND_TOKENS",e,n,t],mutationFn:Be,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))});return{...i,sendTokens:o,sendTokensAsync:r}},dn=({onError:e,onLoading:n,onSuccess:t}={})=>{const{mutate:o,mutateAsync:r,...i}=C({mutationKey:["USE_SEND_IBC_TOKENS",e,n,t],mutationFn:Te,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))});return{...i,sendIbcTokens:o,sendIbcTokensAsync:r}},un=({codeId:e,onError:n,onLoading:t,onSuccess:o})=>{const{mutate:r,mutateAsync:i,...a}=C({mutationKey:["USE_INSTANTIATE_CONTRACT",n,t,o,e],mutationFn:n=>Pe({...n,fee:n.fee??"auto",codeId:e}),onError:(e,t)=>Promise.resolve(n?.(e,t)),onMutate:t,onSuccess:e=>Promise.resolve(o?.(e))});return{...a,instantiateContract:r,instantiateContractAsync:i}},gn=({contractAddress:e,onError:n,onLoading:t,onSuccess:o})=>{const{mutate:r,mutateAsync:i,...a}=C({mutationKey:["USE_EXECUTE_CONTRACT",n,t,o,e],mutationFn:n=>De({...n,fee:n.fee??"auto",contractAddress:e,memo:n.memo??"",funds:n.funds??[]}),onError:(e,t)=>Promise.resolve(n?.(e,t)),onMutate:t,onSuccess:e=>Promise.resolve(o?.(e))});return{...a,executeContract:r,executeContractAsync:i}},wn=e=>{const{data:n}=xe(),t=n&&Object.values(n)[0];return S({queryKey:["USE_QUERY_SMART",e?.address,e?.queryMsg,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.queryMsg)throw new Error("address or queryMsg undefined");return Fe(e.address,e.queryMsg,t)},enabled:Boolean(e?.address)&&Boolean(e?.queryMsg)&&Boolean(t)})},fn=e=>{const{data:n}=xe(),t=n&&Object.values(n)[0];return S({queryKey:["USE_QUERY_RAW",e?.key,e?.address,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.key)throw new Error("address or key undefined");return Le(e.address,e.key,t)},enabled:Boolean(e?.address)&&Boolean(e?.key)&&Boolean(t)})};function hn(e){const n=Ue({chainId:e?.chainId}),t=$(e=>e.walletType),o=q(e=>e.activeChainIds),r="connected"===q.getState().status&&q.getState().accounts&&$.getState()._reconnectConnector===t,i=I(()=>["USE_STARGATE_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return S({queryKey:i,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");return await qe(n,async n=>{if(!o?.includes(n.chainId))return null;if(!le(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return ue(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return ue(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return ue(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=$.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}};return await k.connectWithSigner(a,r,e?.opts?.[n.chainId])})},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})}function mn(e){const n=Ue({chainId:e?.chainId}),t=$(e=>e.walletType),o=q(e=>e.activeChainIds),r="connected"===q.getState().status&&q.getState().accounts&&$.getState()._reconnectConnector===t,i=I(()=>["USE_COSMWASM_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return S({queryKey:i,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");return await qe(n,async n=>{if(!o?.includes(n.chainId))return null;if(!le(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return ue(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return ue(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return ue(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=$.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}},s=i?.gas?N.fromString(`${i.gas.price}${i.gas.denom}`):void 0;return await v.connectWithSigner(a,r,{gasPrice:s,...e?.opts?.[n.chainId]||{}})})},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})}var pn=({children:e})=>{const[n,t]=E(!1);return b(()=>{t(!0)},[]),P(D,{children:n?e:null})},yn=()=>{const e="undefined"!=typeof window&&"Active"===window.sessionStorage.getItem(F),{_reconnect:n,_onReconnectFailed:t,_reconnectConnector:o,iframeOptions:i,chains:a,pingInterval:s}=$(),{activeChainIds:c,wcSignClients:l}=q(),d=le(o||void 0);return b(()=>{const n=async()=>{if(e&&d&&o&&c?.[0]){const e=q.getState().lastPing;if(e&&Date.now()-e<s)return;const n=ue(o);try{if(!await n.getKey(c[0]))throw new Error("No account found");q.setState({lastPing:Date.now()})}catch(e){Se({onError:t})}}};return window.addEventListener("focus",n),()=>{window.removeEventListener("focus",n)}},[e,d,o,a,c,s]),b(()=>{if(!i||!1===i.autoConnect||!i.allowedIframeParentOrigins.length||!a)return;new r(i.allowedIframeParentOrigins).isReady().then(e=>{if(e)return pe({chainId:a.map(e=>e.chainId),walletType:"cosmiframe"})})},[i]),b(()=>{if(o){if(!d)return;(e&&Boolean(c)||!e&&n)&&Se({onError:t})}},[d]),b(()=>{if(o){if(!d)return;"cosmostation"===o&&z().subscription?.(()=>{Se({onError:t})}),"keplr"===o&&V().subscription?.(()=>{Se({onError:t})}),"leap"===o&&H().subscription?.(()=>{Se({onError:t})}),"compass"===o&&j().subscription?.(()=>{Se({onError:t})}),"vectis"===o&&ne().subscription?.(()=>{Se({onError:t})}),"walletconnect"===o&&l.has("walletconnect")&&re().subscription?.(()=>{Se({onError:t})}),"station"===o&&ee().subscription?.(()=>{Se({onError:t})}),"xdefi"===o&&ce().subscription?.(()=>{Se({onError:t})}),"cosmiframe"===o&&W().subscription?.(()=>{Se({onError:t})}),"okx"===o&&Q().subscription?.(()=>{Se({onError:t})})}},[o,l,d]),null},Sn=()=>(yn(),null),Cn=({children:e,grazOptions:n})=>(b(()=>{Ne(n)},[n]),T(pn,{children:[e,P(Sn,{})]}));export{Sn as GrazEvents,Cn as GrazProvider,K as WALLET_TYPES,L as WalletType,ve as addChain,le as checkWallet,Ie as clearRecentChain,de as clearSession,Ne as configureGraz,pe as connect,Me as defineChainInfo,Ke as defineChains,ye as disconnect,De as executeContract,ge as getAvailableWallets,x as getCactusCosmos,Ae as getChainInfo,_e as getChainInfos,z as getCosmostation,V as getKeplr,H as getLeap,Y as getMetamaskSnapLeap,Ce as getOfflineSigners,Q as getOkx,Z as getPara,Le as getQueryRaw,Fe as getQuerySmart,be as getRecentChainIds,Ee as getRecentChains,ne as getVectis,ie as getWCCosmostation,ae as getWCKeplr,se as getWCLeap,ue as getWallet,re as getWalletConnect,Pe as instantiateContract,fe as isLeapDappBrowser,we as isLeapSnaps,me as isPara,he as isWalletConnect,Se as reconnect,Te as sendIbcTokens,Be as sendTokens,Oe as suggestChain,ke as suggestChainAndConnect,Re as useAccount,nn as useActiveChainCurrency,Qe as useActiveChainIds,Je as useActiveChains,je as useActiveWalletType,an as useAddChain,Ge as useBalance,Ye as useBalanceStaked,ze as useBalances,Ze as useChainInfo,en as useChainInfos,We as useCheckWallet,Ve as useConnect,xe as useCosmWasmClient,mn as useCosmWasmSigningClient,He as useDisconnect,gn as useExecuteContract,yn as useGrazEvents,un as useInstantiateContract,Xe as useOfflineSigners,tn as useQueryClientValidators,fn as useQueryRaw,wn as useQuerySmart,on as useRecentChainIds,rn as useRecentChains,dn as useSendIbcTokens,ln as useSendTokens,$e as useStargateClient,hn as useStargateSigningClient,sn as useSuggestChain,cn as useSuggestChainAndConnect};
|
|
1
|
+
import{create as e}from"zustand";import{createJSONStorage as n,subscribeWithSelector as t,persist as o}from"zustand/middleware";import{Cosmiframe as r,isInIframe as i}from"@dao-dao/cosmiframe";import{isSnapInstalled as a,installSnap as s,CosmosSnap as c}from"@cosmsnap/snapper";import{encodeEd25519Pubkey as l,encodeSecp256k1Pubkey as d,pubkeyType as u,rawEd25519PubkeyToRawAddress as g,rawSecp256k1PubkeyToRawAddress as h}from"@cosmjs/amino";import f from"long";import{fromBech32 as w}from"@cosmjs/encoding";import{WalletConnectModal as m}from"@walletconnect/modal";import{SignClient as p}from"@walletconnect/sign-client";import{getSdkError as C}from"@walletconnect/utils";import{useQuery as y,useMutation as S}from"@tanstack/react-query";import{useMemo as b,useEffect as I,useState as E}from"react";import A from"p-map";import{CosmWasmClient as _,SigningCosmWasmClient as v}from"@cosmjs/cosmwasm-stargate";import{StargateClient as O,SigningStargateClient as T,GasPrice as k}from"@cosmjs/stargate";import{useShallow as N}from"zustand/shallow";import{jsxs as B,jsx as D,Fragment as L}from"react/jsx-runtime";var R,F=Object.defineProperty,U=(e,n,t)=>((e,n,t)=>n in e?F(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t)(e,"symbol"!=typeof n?n+"":n,t),P="connect-graz",q={WALLET:"wallet",TRANSACTION:"transaction",QUERY:"query",STORE:"store",MULTICHAIN:"multichain",EVENT:"event",PERFORMANCE:"performance"},M={CONNECT:"connect",DISCONNECT:"disconnect",RECONNECT:"reconnect",GET_WALLET:"getWallet",CLEAR_RECENT_CHAIN:"clearRecentChain",GET_RECENT_CHAIN_IDS:"getRecentChainIds",GET_RECENT_CHAINS:"getRecentChains",GET_CHAIN_INFO:"getChainInfo",GET_CHAIN_INFOS:"getChainInfos",ADD_CHAIN:"addChain",SUGGEST_CHAIN:"suggestChain",SUGGEST_CHAIN_AND_CONNECT:"suggestChainAndConnect",SEND_TOKENS:"sendTokens",SEND_IBC_TOKENS:"sendIbcTokens",INSTANTIATE_CONTRACT:"instantiateContract",EXECUTE_CONTRACT:"executeContract",GET_QUERY_SMART:"getQuerySmart",GET_QUERY_RAW:"getQueryRaw",CREATE_MULTI_CHAIN_ASYNC_FUNCTION:"createMultiChainAsyncFunction",HANDLE_FOCUS:"handleFocus",AUTO_CONNECT_IFRAME:"autoConnectIframe",RECONNECT_EFFECT:"reconnectEffect",SUBSCRIPTION:"subscription"},W={USE_CONNECT:"useConnect",USE_DISCONNECT:"useDisconnect",USE_CHECK_WALLET:"useCheckWallet",USE_ADD_CHAIN:"useAddChain",USE_SUGGEST_CHAIN:"useSuggestChain",USE_SUGGEST_CHAIN_AND_CONNECT:"useSuggestChainAndConnect",USE_STARGATE_CLIENT:"useStargateClient",USE_COSMWASM_CLIENT:"useCosmWasmClient",USE_STARGATE_SIGNING_CLIENT:"useStargateSigningClient",USE_COSMWASM_SIGNING_CLIENT:"useCosmWasmSigningClient",USE_SEND_TOKENS:"useSendTokens",USE_SEND_IBC_TOKENS:"useSendIbcTokens",USE_INSTANTIATE_CONTRACT:"useInstantiateContract",USE_EXECUTE_CONTRACT:"useExecuteContract"},x=(e=>(e.KEPLR="keplr",e.LEAP="leap",e.VECTIS="vectis",e.COSMOSTATION="cosmostation",e.WALLETCONNECT="walletconnect",e.WC_KEPLR_MOBILE="wc_keplr_mobile",e.WC_LEAP_MOBILE="wc_leap_mobile",e.WC_COSMOSTATION_MOBILE="wc_cosmostation_mobile",e.WC_CLOT_MOBILE="wc_clot_mobile",e.METAMASK_SNAP_LEAP="metamask_snap_leap",e.METAMASK_SNAP_COSMOS="metamask_snap_cosmos",e.STATION="station",e.XDEFI="xdefi",e.COSMIFRAME="cosmiframe",e.COMPASS="compass",e.INITIA="initia",e.OKX="okx",e.PARA="para",e.CACTUSCOSMOS="cactuscosmos",e))(x||{}),K=["keplr","leap","vectis","cosmostation","walletconnect","wc_keplr_mobile","wc_leap_mobile","wc_cosmostation_mobile","wc_clot_mobile","metamask_snap_leap","station","xdefi","metamask_snap_cosmos","cosmiframe","compass","initia","okx","para","cactuscosmos"],$={iframeOptions:null,recentChainIds:null,chains:null,chainsConfig:null,paraConfig:null,multiChainFetchConcurrency:3,walletType:"keplr",walletConnect:{options:null,walletConnectModal:null},walletDefaultOptions:null,pingInterval:36e5,loggerConfig:null,_notFoundFn:()=>null,_onReconnectFailed:()=>null,_reconnect:!1,_reconnectConnector:null},j={accounts:null,activeChainIds:null,status:"disconnected",lastPing:null,wcSignClients:new Map,paraConnector:null},G=e(t(o(()=>j,{name:"graz-session",version:2,partialize:e=>({accounts:e.accounts,activeChainIds:e.activeChainIds,lastPing:e.lastPing,status:e.status}),storage:n(()=>sessionStorage)}))),H=e(t(o(()=>$,{name:"graz-internal",partialize:e=>({recentChainIds:e.recentChainIds,_reconnect:e._reconnect,_reconnectConnector:e._reconnectConnector,walletType:e.walletType,chains:e.chains}),version:3}))),z=(e=>(e[e.ERROR=0]="ERROR",e[e.WARN=1]="WARN",e[e.INFO=2]="INFO",e[e.DEBUG=3]="DEBUG",e[e.TRACE=4]="TRACE",e))(z||{}),Q=(e=>(e.WALLET="wallet",e.TRANSACTION="transaction",e.QUERY="query",e.STORE="store",e.MULTICHAIN="multichain",e.EVENT="event",e.PERFORMANCE="performance",e))(Q||{}),V=class{constructor(e){U(this,"level"),U(this,"categories"),U(this,"enabled"),U(this,"timers"),U(this,"errorReporter"),U(this,"levelColors",{error:"color: #ff4444; font-weight: bold;",warn:"color: #ff9800; font-weight: bold;",info:"color: #2196f3; font-weight: bold;",debug:"color: #4caf50; font-weight: bold;",trace:"color: #9e9e9e; font-weight: bold;",reset:"color: inherit; font-weight: normal;"}),U(this,"categoryColors",{wallet:"color: #9c27b0; font-weight: bold;",transaction:"color: #e91e63; font-weight: bold;",query:"color: #00bcd4; font-weight: bold;",store:"color: #ff5722; font-weight: bold;",multichain:"color: #3f51b5; font-weight: bold;",event:"color: #ffc107; font-weight: bold;",performance:"color: #4caf50; font-weight: bold;"}),U(this,"functionColors",{connect:"color: #00e5ff; font-weight: bold;",disconnect:"color: #00e676; font-weight: bold;",reconnect:"color: #ff6d00; font-weight: bold;",getWallet:"color: #d500f9; font-weight: bold;",clearRecentChain:"color: #ff1744; font-weight: bold;",getRecentChainIds:"color: #f50057; font-weight: bold;",getRecentChains:"color: #ff4081; font-weight: bold;",getChainInfo:"color: #e040fb; font-weight: bold;",getChainInfos:"color: #b388ff; font-weight: bold;",addChain:"color: #8c9eff; font-weight: bold;",suggestChain:"color: #536dfe; font-weight: bold;",suggestChainAndConnect:"color: #448aff; font-weight: bold;",sendTokens:"color: #18ffff; font-weight: bold;",sendIbcTokens:"color: #40c4ff; font-weight: bold;",instantiateContract:"color: #69f0ae; font-weight: bold;",executeContract:"color: #b2ff59; font-weight: bold;",getQuerySmart:"color: #eeff41; font-weight: bold;",getQueryRaw:"color: #ffea00; font-weight: bold;",createMultiChainAsyncFunction:"color: #7c4dff; font-weight: bold;",handleFocus:"color: #ff9100; font-weight: bold;",autoConnectIframe:"color: #ff6e40; font-weight: bold;",reconnectEffect:"color: #a1887f; font-weight: bold;",subscription:"color: #90caf9; font-weight: bold;"}),U(this,"hookColors",{useConnect:"color: #00e5ff; font-weight: bold;",useDisconnect:"color: #1de9b6; font-weight: bold;",useCheckWallet:"color: #d500f9; font-weight: bold;",useAddChain:"color: #aa00ff; font-weight: bold;",useSuggestChain:"color: #6200ea; font-weight: bold;",useSuggestChainAndConnect:"color: #651fff; font-weight: bold;",useStargateClient:"color: #2979ff; font-weight: bold;",useCosmWasmClient:"color: #2962ff; font-weight: bold;",useStargateSigningClient:"color: #448aff; font-weight: bold;",useCosmWasmSigningClient:"color: #536dfe; font-weight: bold;",useSendTokens:"color: #00e676; font-weight: bold;",useSendIbcTokens:"color: #76ff03; font-weight: bold;",useInstantiateContract:"color: #c6ff00; font-weight: bold;",useExecuteContract:"color: #aeea00; font-weight: bold;"});const n="undefined"!=typeof window&&window.__GRAZ_DEBUG__;this.level=e?.level,this.categories=new Set(e?.categories??[]),this.enabled=e?.enabled??n??!1,this.timers=new Map,this.errorReporter=e?.errorReporter}formatLog(e,n,t,o){const r=o?`%c[${o}]%c `:"";let i="color: #00e5ff; font-weight: bold;";o&&(i=this.hookColors[o]||this.functionColors[o]||i);const a=o?[i,this.levelColors.reset]:[];return[`%c[graz]%c %c${e.toUpperCase()}%c %c[${n}]%c ${r}${t}`,"color: #673ab7; font-weight: bold;",this.levelColors.reset,this.levelColors[e]||this.levelColors.reset,this.levelColors.reset,this.categoryColors[n]||this.levelColors.reset,this.levelColors.reset,...a]}error(e,n,t){if(!this.shouldLog(0,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("error",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.error(r,...i,Object.keys(a||{}).length>0?a:"");const s=this.errorReporter||"undefined"!=typeof window&&window.grazErrorReporter;if(s){const o=new Error(n);s.captureException(o,{category:e,context:t})}}warn(e,n,t){if(!this.shouldLog(1,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("warn",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.warn(r,...i,Object.keys(a||{}).length>0?a:"")}info(e,n,t){if(!this.shouldLog(2,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("info",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.info(r,...i,Object.keys(a||{}).length>0?a:"")}debug(e,n,t){if(!this.shouldLog(3,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("debug",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.debug(r,...i,Object.keys(a||{}).length>0?a:"")}trace(e,n,t){if(!this.shouldLog(4,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("trace",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.trace(r,...i,Object.keys(a||{}).length>0?a:"")}time(e){this.enabled&&"undefined"!=typeof performance&&this.timers.set(e,performance.now())}timeEnd(e){if(!this.enabled)return;if("undefined"==typeof performance)return;const n=this.timers.get(e);if(void 0!==n){const t=performance.now()-n,[o,...r]=this.formatLog("debug","performance",`⏱️ ${e}: ${t.toFixed(2)}ms`);console.debug(o,...r),this.timers.delete(e)}}group(e){this.enabled&&void 0!==console.group&&console.group(`[graz] ${e}`)}groupEnd(){this.enabled&&void 0!==console.groupEnd&&console.groupEnd()}shouldLog(e,n){if(!this.enabled)return!1;if(void 0!==this.level)if(Array.isArray(this.level)){if(!this.level.includes(e))return!1}else if(e>this.level)return!1;return!(this.categories.size>0&&!this.categories.has(n))}setLevel(e){this.level=e}setCategories(e){this.categories=new Set(e??[])}enable(){this.enabled=!0}disable(){this.enabled=!1}},Y=()=>(R||(R=new V),R),X=e=>{R=new V(e)},J=()=>{if(void 0!==window.cactuslink_cosmos){const e=window.cactuslink_cosmos,n=e=>{const n=()=>{be(),e()};return window.addEventListener("accountsChanged",n),()=>{window.removeEventListener("accountsChanged",n)}};return{...Object.assign(e,{subscription:n}),getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSigner(n),experimentalSuggestChain:async()=>{throw new Error("Cactus Cosmos does not support experimentalSuggestChain")}}}throw H.getState()._notFoundFn(),new Error("window.cactuslink_cosmos is not defined")},Z=()=>{if(void 0!==window.compass){const e=window.compass,n=e=>{const n=()=>{be(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw H.getState()._notFoundFn(),new Error("window.leap is not defined")},ee=()=>{const e=H.getState();if(!e.iframeOptions)throw e._notFoundFn(),new Error("no iframe options set");if(!i())throw e._notFoundFn(),new Error("not in iframe");if(!e.iframeOptions.allowedIframeParentOrigins.length)throw e._notFoundFn(),new Error("no iframe allowed origins");const n=new r(e.iframeOptions.allowedIframeParentOrigins).getKeplrClient();return{enable:n.enable.bind(n),getKey:n.getKey.bind(n),getOfflineSigner:n.getOfflineSigner.bind(n),getOfflineSignerAuto:n.getOfflineSignerAuto.bind(n),getOfflineSignerOnlyAmino:n.getOfflineSignerOnlyAmino.bind(n),experimentalSuggestChain:n.experimentalSuggestChain.bind(n),signDirect:n.signDirect.bind(n),signAmino:n.signAmino.bind(n)}},ne={},te=()=>{if(void 0!==window.cosmostation?.providers.keplr){const e=window.cosmostation.providers.keplr,n=e=>{const n=()=>{be(),e()};return window.addEventListener("cosmostation_keystorechange",n),()=>{window.removeEventListener("cosmostation_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw H.getState()._notFoundFn(),new Error("window.cosmostation.providers.keplr is not defined")},oe=()=>{if(void 0!==window.initia){const e=window.initia;return{enable:async()=>{await e.getAddress()},getKey:async n=>{const t=e.getOfflineSigner(n),[o]=await t.getAccounts();if(!o)throw new Error("Wallet connection failed");const r=(()=>{switch(o.algo){case"secp256k1":return h(o.pubkey);case"ed25519":return g(o.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{name:(i=o.address,`${i.slice(0,6)}...${i.slice(-6)}`),algo:o.algo,pubKey:o.pubkey,bech32Address:o.address,address:r,isNanoLedger:!1,isKeystone:!1};var i},getOfflineSigner:n=>{const t=e.getOfflineSigner(n),o=e.getOfflineSignerOnlyAmino(n);return{getAccounts:t.getAccounts.bind(t),signDirect:t.signDirect.bind(t),signAmino:o.signAmino.bind(o)}},getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),experimentalSuggestChain:n=>e.requestAddInitiaLayer({chain_id:n.chainId,chain_name:n.chainName,bech32_prefix:"init",bech32_config:n.bech32Config,slip44:n.bip44.coinType,logo_URIs:{png:n.chainSymbolImageUrl},fees:{fee_tokens:n.feeCurrencies.map(e=>({denom:e.coinDenom,amount:e.coinMinimalDenom,low_gas_price:e.gasPriceStep?.low,average_gas_price:e.gasPriceStep?.average,high_gas_price:e.gasPriceStep?.high}))},apis:{rpc:[{address:n.rpc}],rest:[{address:n.rest}]}}),signDirect:(...n)=>{const[t,o,r]=n;return e.getOfflineSigner(t).signDirect(o,(e=>{const{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}=e;if(!(n&&t&&o&&r))throw new Error("Invalid sign doc");return{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}})(r))},signAmino:(...n)=>{const[t,o,r]=n;return e.getOfflineSignerOnlyAmino(t).signAmino(o,r)},signArbitrary:async(n,t,o)=>{const r=e.getOfflineSigner(n),i=(await r.getAccounts()).find(e=>e.address===t);if(!i)throw new Error(`Wallet not connected to account ${t}`);const a=(()=>{switch(i.algo){case"secp256k1":return d(i.pubkey);case"ed25519":return l(i.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{signature:await e.signArbitrary(o),pub_key:{type:"secp256k1"===i.algo?u.secp256k1:u.ed25519,value:a.value}}},subscription:e=>{const n=()=>{be(),e()};return window.addEventListener("initia_keystorechange",n),()=>{window.removeEventListener("initia_keystorechange",n)}}}}throw H.getState()._notFoundFn(),new Error("window.initia is not defined")},re=()=>{if(void 0!==window.keplr){const e=window.keplr,n=e=>{const n=()=>{be(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw H.getState()._notFoundFn(),new Error("window.keplr is not defined")},ie=()=>{if(void 0!==window.leap){const e=window.leap,n=e=>{const n=()=>{be(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw H.getState()._notFoundFn(),new Error("window.leap is not defined")},ae={},se=()=>(e=>{const n=window.ethereum;if(n&&e){const t=async()=>await n.request({method:"wallet_getSnaps"}),o=async n=>{try{const o=await t();return Object.values(o).find(t=>t.id===e.id&&(!n||t.version===n))}catch(e){return}},r=async()=>{await n.request({method:"wallet_requestSnaps",params:{[e.id]:e.params||{}}})},i=async()=>{const e=await n.request({method:"web3_clientVersion"});if(!e.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const t=e.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(t)>=11))throw new Error("Metamask Snap is not supported in this version");return await o()||await r(),!0},a=async(t,o,r)=>{const i=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signDirect",params:{chainId:t,signerAddress:o,signDoc:r}}}}),a=r.accountNumber,s=new f(a.low,a.high,a.unsigned);return{signature:i.signature,signed:{...i.signed,accountNumber:s.toString(),authInfoBytes:new Uint8Array(Object.values(i.signed.authInfoBytes)),bodyBytes:new Uint8Array(Object.values(i.signed.bodyBytes))}}},s=async(t,o,r)=>await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signAmino",params:{chainId:t,signerAddress:o,signDoc:r}}}}),c=async t=>{if(void 0!==ae[t])return ae[t];const o=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"getKey",params:{chainId:t}}}});if(!o)throw new Error("No response from Metamask");return o.pubKey=Uint8Array.from(Object.values(o.pubkey)),delete o.pubkey,ae[t]=o,ae[t]},l=async e=>{const n=await c(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async(...e)=>{const[n,t,o,r]=e;return await s(n,t,o)},u=async(...e)=>{const[n,t,o]=e,r={...o,accountNumber:f.fromString(o.accountNumber?.toString()||"0"),authInfoBytes:o.authInfoBytes,bodyBytes:o.bodyBytes};return await a(n,t,r)},g=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>d(e,n,t)});return{enable:async e=>{await o()||await r()},experimentalSuggestChain:async(...t)=>{await i(),await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"suggestChain",params:{chainInfo:t[0]}}}})},getKey:c,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>d(e,n,t)}),getOfflineSignerAuto:async e=>g(e),getOfflineSignerOnlyAmino:g,init:i,signAmino:d,signDirect:u}}throw H.getState()._notFoundFn(),new Error("window.ethereum is not defined")})({id:"npm:@leapwallet/metamask-cosmos-snap"}),ce=()=>{if(void 0!==window.okxwallet?.keplr){const e=window.okxwallet.keplr,n=e=>{const n=()=>{be(),e()};return window.okxwallet?.on("accountsChanged",n),()=>{window.okxwallet?.removeListener("accountsChanged",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw H.getState()._notFoundFn(),new Error("window.okxwallet.keplr is not defined")},le=null,de=()=>{const e=()=>{const e=G.getState().paraConnector;if(!e)throw new Error("Para connector not initialized. Call connect() first or check paraConfig in GrazProvider.");return e},n=H.getState().paraConfig;if(!n?.paraWeb)throw new Error("Missing Para config. Provide paraConfig with 'paraWeb' to GrazProvider.");return{enable:async e=>{const t=Array.isArray(e)?e:[e];try{const e=await(le||(le=(async()=>{const e=G.getState().paraConnector;if(e)return e;if(!n.connectorClass)throw new Error("Para connector class not provided. Provide 'connectorClass' in paraConfig to use Para wallet.");try{const e=H.getState().chains,t=new n.connectorClass(n,e);if(!t)throw new Error("Para connector initialization failed. Check config and dependencies.");return G.setState(e=>({...e,paraConnector:t})),t}catch(e){throw le=null,new Error(`Para connector init failed: ${e?.message||"Unknown error"}. Check ParaConfig and connectorClass.`)}})()));G.setState({paraConnector:e,status:"connecting"}),await e.enable(t);const o=Object.fromEntries(await Promise.all(t.map(async n=>[n,await e.getKey(n)])));G.setState(e=>({accounts:{...e.accounts||{},...o},activeChainIds:Array.from(new Set([...e.activeChainIds||[],...t])),status:"connected"})),H.setState(e=>({recentChainIds:Array.from(new Set([...e.recentChainIds||[],...t])),walletType:"para",_reconnect:!1,_reconnectConnector:"para"}))}catch(e){throw G.setState({paraConnector:null,status:"disconnected"}),new Error("Para enable failed"+(e instanceof Error?`: ${e.message}`:""))}},disable:async()=>{const e=G.getState().paraConnector;if(e)try{await e.disconnect(),await e.getParaWebClient().logout()}catch(e){throw new Error("Para disconnect failed"+(e?.message?`: ${e.message}`:". Wallet may already be disconnected."))}finally{G.setState({paraConnector:null,status:"disconnected"})}else G.setState({paraConnector:null,status:"disconnected"})},getKey:async n=>{try{return await e().getKey(n)}catch(e){throw new Error(`Failed to get key${e?.message?`: ${e.message}`:""}. Check chain connection and Cosmos API key settings at developer.getpara.com.`)}},getOfflineSigner:n=>{try{return e().getOfflineSigner(n)}catch(e){throw new Error(`Failed to get offline signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerOnlyAmino:n=>{try{return e().getOfflineSignerOnlyAmino(n)}catch(e){throw new Error(`Failed to get Amino signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerAuto:n=>{try{return e().getOfflineSignerAuto(n)}catch(e){throw new Error(`Failed to get auto signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},signAmino:async(n,t,o,r)=>{try{return await e().signAmino(n,t,o,r)}catch(e){throw new Error(`Amino signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signDirect:async(n,t,o,r)=>{try{return await e().signDirect(n,t,o,r)}catch(e){throw new Error(`Direct signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signArbitrary:async(n,t,o)=>{try{return await e().signArbitrary(n,t,o)}catch(e){throw new Error(`Arbitrary signing failed${e?.message?`: ${e.message}`:""}. User rejected or feature not supported.`)}},experimentalSuggestChain:async()=>{throw new Error("Chain suggestion not supported. Configure chains in Para wallet settings.")}}},ue=()=>{if(void 0!==window.station?.keplr){const e=window.station.keplr;return{subscription:e=>{const n=()=>{be(),e()};return window.addEventListener("station_wallet_change",n),()=>{window.removeEventListener("station_wallet_change",n)}},getKey:async n=>({isKeystone:!1,...await e.getKey(n)}),getOfflineSigner:n=>{try{const t=e.getOfflineSignerOnlyAmino(n),o=(e,n)=>{throw new Error("signDirect not supported by Station")};return Object.assign(t,{signDirect:o})}catch(e){throw console.error(e),e}},experimentalSuggestChain:async n=>{try{if(!n.bech32Config)throw new Error("Bech32Config is required");if(!n.stakeCurrency)throw new Error("StakeCurrency is required");const t=Object.assign(n,{bech32Config:n.bech32Config,chainSymbolImageUrl:n.chainSymbolImageUrl||"",stakeCurrency:{coinDecimals:n.stakeCurrency.coinDecimals,coinDenom:n.stakeCurrency.coinDenom,coinImageUrl:n.stakeCurrency.coinImageUrl||"",coinMinimalDenom:n.stakeCurrency.coinMinimalDenom},currencies:n.currencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom})),feeCurrencies:n.feeCurrencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom,gasPriceStep:{average:e.gasPriceStep?.average||0,high:e.gasPriceStep?.high||0,low:e.gasPriceStep?.low||0}}))});await e.experimentalSuggestChain(t)}catch(e){throw console.error(e),e}},enable:n=>e.enable(n),disable:n=>e.disable(n),getOfflineSignerAuto:n=>e.getOfflineSignerAuto(n),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),signDirect:e.signDirect,signAmino:(n,t,o,r)=>e.signAmino(n,t,o)}}throw H.getState()._notFoundFn(),new Error("window.station is not defined")},ge=()=>{if(void 0!==window.vectis){const e=window.vectis.cosmos;return{enable:n=>e.enable(n),getOfflineSigner:n=>{const t=e.getOfflineSigner(n);return{getAccounts:t.getAccounts,signAmino:t.signAmino,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:f.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}},getOfflineSignerAuto:async n=>{const t=await e.getOfflineSignerAuto(n);return"signAmino"in t?t:"signDirect"in t?{getAccounts:t.getAccounts,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:f.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}:t},getKey:async n=>{const t=await e.getKey(n);return{address:w(t.address).data,algo:t.algo,bech32Address:t.address,name:t.name,pubKey:t.pubKey,isKeystone:!1,isNanoLedger:t.isNanoLedger}},subscription:e=>{const n=()=>{be(),e()};return window.addEventListener("vectis_accountChanged",n),()=>{window.removeEventListener("vectis_accountChanged",n)}},getOfflineSignerOnlyAmino:(...n)=>{const t=n[0];return e.getOfflineSignerAmino(t)},experimentalSuggestChain:async(...n)=>{const[t]=n;if(!t.bech32Config)throw new Error("Bech32Config is required");if(!t.stakeCurrency)throw new Error("StakeCurrency is required");const o={rpcUrl:t.rpc,restUrl:t.rest,prettyName:t.chainName.replace(" ",""),bech32Prefix:t.bech32Config.bech32PrefixAccAddr,currencies:t.currencies,feeCurrencies:t.feeCurrencies,chainId:t.chainId,chainName:t.chainName,bip44:t.bip44,stakeCurrency:t.stakeCurrency,features:t.features};return e.suggestChains([o])},signDirect:async(...n)=>{const{1:t,2:o}=n,r=await e.signDirect(t,{bodyBytes:o.bodyBytes||Uint8Array.from([]),authInfoBytes:o.authInfoBytes||Uint8Array.from([]),accountNumber:f.fromString(o.accountNumber?.toString()||"",!1),chainId:o.chainId||""});return{signature:r.signature,signed:{authInfoBytes:r.signed.authInfoBytes,bodyBytes:r.signed.bodyBytes,chainId:r.signed.chainId,accountNumber:BigInt(r.signed.accountNumber.toString())}}},signAmino:async(...n)=>{const{1:t,2:o}=n;return e.signAmino(t,o)}}}throw H.getState()._notFoundFn(),new Error("window.vectis is not defined")},he=()=>{if("undefined"!=typeof window){const e=navigator.userAgent;return!!/android/i.test(e)||!!/iPad|iPhone|iPod/.test(e)}return!1},fe=(e,n,t=new Error("Promise timed out"))=>{const o=new Promise((e,o)=>{setTimeout(()=>{o(t)},n)});return Promise.race([e,o])},we=e=>{if(!H.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");const n=e?.walletType||"walletconnect",t=e?.encoding||"base64",o=n=>{if(!e)return;const{appUrl:t,formatNativeUrl:o}=e;if(he()){if(he()&&navigator.userAgent.toLowerCase().includes("android")){const e=o(t.mobile.android,n,"android");window.open(e,"_self","noreferrer noopener")}if(he()&&(navigator.userAgent.toLowerCase().includes("iphone")||navigator.userAgent.toLowerCase().includes("ipad"))){const e=o(t.mobile.ios,n,"ios");window.open(e,"_self","noreferrer noopener")}}},r=()=>{const{wcSignClients:e}=G.getState();if(!e.get(n))throw new Error("walletConnect.signClient is not defined");e.delete(n),G.setState({wcSignClients:e}),H.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})},i=async e=>{const{wcSignClients:t}=G.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");if(!e)throw new Error("No wallet connect session");await o.disconnect({topic:e,reason:C("USER_DISCONNECTED")}),await s(o)},a=e=>{try{const{wcSignClients:t}=G.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");const r=o.session.getAll(),a=r.at(-1);if(!a)return;if(!(1e3*a.expiry>Date.now()+1e3))throw i(a.topic),new Error("invalid session");try{const n=r.find(n=>n.requiredNamespaces.cosmos?.chains?.includes(`cosmos:${e}`));if(!n)throw new Error("no session");return n}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}return a}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},s=async e=>{try{const n=e.core.pairing.pairings.getAll({active:!1});if(!n.length)return;await Promise.all(n.map(async n=>{await e.core.pairing.pairings.delete(n.topic,{code:7001,message:"clear pairing"})}))}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},c=async t=>{const r="string"==typeof t?[t]:t,{wcSignClients:s,activeChainIds:c}=G.getState(),l=s.get(n);if(!l)throw new Error("enable walletConnect.signClient is not defined");const{walletConnect:u}=H.getState();if(!u?.options?.projectId)throw new Error("walletConnect.options.projectId is not defined");const g=new m({projectId:u.options.projectId,enableExplorer:!1,explorerRecommendedWalletIds:"NONE",...u.walletConnectModal}),h=(e=>{try{return a(e)}catch(e){return}})(r);if(!h){const{uri:n,approval:t}=await fe(l.connect({requiredNamespaces:{cosmos:{methods:["cosmos_getAccounts","cosmos_signAmino","cosmos_signDirect"],chains:r.map(e=>`cosmos:${e}`),events:["chainChanged","accountsChanged"]}}}),15e3,new Error("Connection timeout"));if(!n)throw new Error("No wallet connect uri");e?o(n):await g.openModal({uri:n});const i=async e=>e.aborted?Promise.reject(new Error("User closed wallet connect")):new Promise((n,o)=>{t().then(e=>{const t=e.sessionProperties;if(!t)return o(new Error("No session properties"));const r=JSON.parse(String(t.keys));if(0===r.length)return o(new Error("No accounts"));if(!r[0])return o(new Error("No accounts"));const i={};return r.forEach(e=>{i[e.chainId]={address:e.address,algo:e.algo,bech32Address:e.bech32Address,isNanoLedger:e.isNanoLedger,isKeystone:e.isKeystone,name:e.name,pubKey:e.pubKey}}),G.setState(e=>({accounts:{...e.accounts||{},...i}})),n(e)}).catch(o),e.addEventListener("abort",()=>{o(new Error("User closed wallet connect"))},{once:!0})});try{const e=new AbortController,n=e.signal;g.subscribeModal(n=>{n.open||e.abort()}),await i(n)}catch(e){if(g.closeModal(),!e.message.toLowerCase().includes("no matching key"))return Promise.reject(e)}return e||g.closeModal(),Promise.resolve()}try{await fe((async()=>{const e=Object.fromEntries(await Promise.all((c||r).map(async e=>[e,await d(e)])));G.setState({accounts:e})})(),15e3,new Error("Connection timeout"))}catch(e){if(i(h.topic),!e.message.toLowerCase().includes("no matching key"))throw e}},l=async e=>{const n=await d(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async e=>{const n=a([e]);if(!n?.topic)throw new Error("No wallet connect session");const o=n.sessionProperties&&JSON.parse(String(n.sessionProperties.keys));if(!o)throw new Error("No wallet connect key");if(0===o.length)throw new Error("No wallet connect session");const r=o.find(n=>n.chainId===e);if(!r)throw new Error(`No wallet connect key for chainId ${e}`);return{...r,pubKey:Buffer.from(String(r.pubKey),t)}},u=async(...e)=>{const[r,i,s]=e,{signature:c,signed:l}=await(async(...e)=>{const[r,i,s]=e,{accounts:c,wcSignClients:l}=G.getState(),d=l.get(n);if(!d)throw new Error("walletConnect.signClient is not defined");if(!c)throw new Error("account is not defined");const u=a([r])?.topic;if(!u)throw new Error("No wallet connect session");if(!s.bodyBytes)throw new Error("No bodyBytes");if(!s.authInfoBytes)throw new Error("No authInfoBytes");return o(),await d.request({topic:u,chainId:`cosmos:${r}`,request:{method:"cosmos_signDirect",params:{signerAddress:i,signDoc:{chainId:s.chainId,accountNumber:s.accountNumber?.toString(),bodyBytes:s.bodyBytes?Buffer.from(s.bodyBytes).toString(t):null,authInfoBytes:s.authInfoBytes?Buffer.from(s.authInfoBytes).toString(t):null}}}})})(r,i,s);return{signed:{chainId:l.chainId??"",accountNumber:l.accountNumber?BigInt(l.accountNumber):BigInt(0),authInfoBytes:l.authInfoBytes?new Uint8Array(Buffer.from(l.authInfoBytes,t)):new Uint8Array([]),bodyBytes:l.bodyBytes?new Uint8Array(Buffer.from(l.bodyBytes,t)):new Uint8Array([])},signature:c}},g=async(...e)=>{const[t,r,i,s]=e,c=await(async(...e)=>{const[t,r,i,s]=e,{wcSignClients:c}=G.getState(),l=c.get(n),{accounts:d}=G.getState();if(!l)throw new Error("walletConnect.signClient is not defined");if(!d)throw new Error("account is not defined");const u=a([t])?.topic;if(!u)throw new Error("No wallet connect session");return o(),await l.request({topic:u,chainId:`cosmos:${t}`,request:{method:"cosmos_signDirect",params:{signerAddress:r,signDoc:i}}})})(t,r,i);return c},h=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>g(e,n,t)});return{enable:c,disable:async e=>{const{wcSignClients:t}=G.getState(),o=t.get(n);if(void 0===e){const e=o?.session.getAll();void 0!==e&&await Promise.all(e.map(e=>i(e.topic)))}else"string"==typeof e?await i(a([e])?.topic):await Promise.all(e.map(e=>i(a([e])?.topic)));0===o?.session.getAll().length&&r()},experimentalSuggestChain:async(...e)=>{await Promise.reject(new Error("WalletConnect does not support experimentalSuggestChain"))},getKey:d,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>g(e,n,t)}),getOfflineSignerAuto:async e=>(await d(e)).isNanoLedger?h(e):(e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t)}))(e),getOfflineSignerOnlyAmino:h,signAmino:g,signDirect:u,subscription:e=>{const{wcSignClients:t}=G.getState(),o=t.get(n);if(!o)return()=>{};const i=n=>{const t=G.getState().accounts;if("accountsChanged"===n.params.event.name&&t&&!Object.values(t).map(e=>e.bech32Address).includes(n.params.event.data[0])){const e=n.params.chainId.split(":")[1];e&&c([e])}else e()};return o.events.on("session_delete",r),o.events.on("session_expire",r),o.events.on("session_event",i),()=>{o.events.off("session_delete",r),o.events.off("session_expire",r),o.events.off("session_event",i)}},init:async()=>{const{walletConnect:e}=H.getState();if(!e?.options)throw new Error("walletConnect.options is not defined");const{wcSignClients:t}=G.getState(),o=t.get(n);if(o)return o;const r=await p.init(e.options);return t.set(n,r),G.setState({wcSignClients:t}),r}}},me=()=>{if(!H.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!he())throw new Error("WalletConnect Cosmostation mobile is only supported in mobile");return we({encoding:"hex",appUrl:{mobile:{ios:"cosmostation://",android:"cosmostation://"}},walletType:"wc_cosmostation_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,"");return n?`${o}://wc?${n}`:`${o}://wc`}})},pe=()=>{if(!H.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!he())throw new Error("WalletConnect Keplr mobile is only supported in mobile");return we({encoding:"base64",appUrl:{mobile:{ios:"keplrwallet://",android:"intent://"}},walletType:"wc_keplr_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`:`${o}://wcV2#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},Ce=()=>{if(!H.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!he())throw new Error("WalletConnect Leap mobile is only supported in mobile");return we({encoding:"base64",appUrl:{mobile:{ios:"leapcosmos://",android:"intent://"}},walletType:"wc_leap_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`:`${o}://wcV2#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},ye=()=>{if(void 0!==window.xfi?.keplr){const e=window.xfi.keplr,n=e=>{const n=()=>{be(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}};return Object.assign(e,{subscription:n})}throw H.getState()._notFoundFn(),new Error("window.xfi.keplr is not defined")},Se=(e=H.getState().walletType)=>{try{return Ie(e),!0}catch(e){return!1}},be=()=>{window.sessionStorage.removeItem(P),G.setState(j)},Ie=(e=H.getState().walletType)=>{const n=Y();n.debug("wallet","Getting wallet adapter",{function:"getWallet",walletType:e});const t=(()=>{switch(e){case"keplr":return re();case"leap":return ie();case"cosmostation":return te();case"vectis":return ge();case"walletconnect":return we();case"wc_keplr_mobile":return pe();case"wc_leap_mobile":return Ce();case"wc_cosmostation_mobile":return me();case"wc_clot_mobile":return(()=>{if(!H.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!he())throw new Error("WalletConnect Clot mobile is only supported in mobile");return we({encoding:"base64",appUrl:{mobile:{android:"clot://",ios:"clot://"}},walletType:"wc_clot_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);return"ios"===t?r?`${o}://wcV2?${r}`:`${o}://wcV2`:r?`${o}://wc?uri=${r}`:`${o}://wc`}})})();case"metamask_snap_leap":return se();case"metamask_snap_cosmos":return(()=>{const e=window.ethereum;let n=window.cosmos;if(e)return{init:async()=>{const t=await e.request({method:"web3_clientVersion"});if(!t.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const o=t.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(o)>=11))throw new Error("Metamask Snap is not supported in this version");return await a()||await s(),window.cosmos=new c,n=window.cosmos,!0},enable:async e=>{await a()||await s()},getOfflineSigner:e=>n.getOfflineSigner(e),experimentalSuggestChain:async e=>{if(!e.bech32Config)throw new Error("Bech32Config is required");if(!e.stakeCurrency)throw new Error("StakeCurrency is required");await n.experimentalSuggestChain({...e,stakeCurrency:e.stakeCurrency,bech32Config:e.bech32Config})},signAmino:async(e,t,o)=>n.signAmino(e,t,o),getKey:async e=>void 0!==ne[e]?ne[e]:n.getKey(e),getOfflineSignerAuto:async e=>(await n.getKey(e)).isNanoLedger?n.getOfflineSignerOnlyAmino(e):n.getOfflineSigner(e),getOfflineSignerOnlyAmino:e=>n.getOfflineSignerOnlyAmino(e),signDirect:async(e,t,o)=>n.signDirect(e,t,o),signArbitrary:async(e,t,o)=>n.signArbitrary(e,t,o),disable:async e=>{e&&await n.deleteChain(e)}};throw H.getState()._notFoundFn(),new Error("window.ethereum is not defined")})();case"station":return ue();case"xdefi":return ye();case"cosmiframe":return ee();case"compass":return Z();case"initia":return oe();case"okx":return ce();case"para":return de();case"cactuscosmos":return J();default:throw n.warn("wallet","Unknown wallet type",{function:"getWallet",walletType:e}),new Error("Unknown wallet type")}})(),o=H.getState().walletDefaultOptions;return o&&t.setDefaultOptions?.(o),t},Ee=()=>Object.fromEntries(K.map(e=>[e,Se(e)])),Ae=e=>"metamask_snap_leap"===e,_e=()=>Boolean(navigator?.userAgent)&&/LeapCosmos/i.test(navigator.userAgent),ve=e=>"walletconnect"===e||"wc_keplr_mobile"===e||"wc_leap_mobile"===e||"wc_cosmostation_mobile"===e,Oe=e=>"para"===e,Te=async e=>{const n=Y();n.time("connect"),n.group("Connect Wallet");try{const{recentChainIds:t,chains:o,walletType:r}=H.getState(),i=e?.walletType||r;if(n.debug("wallet","Starting connection",{function:"connect",walletType:i,chainId:e?.chainId,timestamp:Date.now()}),ve(i)){const e=Ie("walletconnect"),{disable:n}=e;n&&n()}if(!Se(i))throw n.warn("wallet","Wallet not available",{function:M.CONNECT,walletType:i}),new Error(`${i} is not available`);n.debug("wallet","Wallet adapter retrieved",{function:M.CONNECT,walletType:i});const a=Ie(i),s="string"==typeof e?.chainId?[e.chainId]:e?.chainId||t;if(!s)throw new Error("No last known connected chain, connect action requires chain ids");const c=o?.map(e=>e.chainId);if(s.forEach(e=>{if(!c?.includes(e))throw new Error(`Chain ${e} is not provided in GrazProvider`)}),G.setState(e=>{const n=H.getState()._reconnect||Boolean(H.getState()._reconnectConnector)||Boolean(s);return e.activeChainIds&&s.filter(n=>!e.activeChainIds?.includes(n)).length>0?{status:"connecting"}:n?{status:"reconnecting"}:{status:"connecting"}}),n.debug("wallet","Initializing wallet",{function:M.CONNECT}),await(a.init?.()),n.debug("wallet","Enabling chains",{function:M.CONNECT,chainIds:s,chainCount:s.length}),await a.enable(s),n.debug("wallet","Fetching accounts",{function:M.CONNECT}),!ve(i)){let e={};if(Ae(i)){const n={};for await(const e of s)n[e]=await a.getKey(e);e=n}else if(_e()&&a.getKeys){const n=await a.getKeys(s);s.forEach((t,o)=>{const r=n[o];r&&(e[t]=r)})}else e=Object.fromEntries(await Promise.all(s.map(async e=>[e,await a.getKey(e)])));G.setState(n=>({accounts:{...n.accounts||{},...e}}))}H.setState(e=>({recentChainIds:[...e.recentChainIds||[],...s].filter((e,n,t)=>t.indexOf(e)===n)})),G.setState(e=>({activeChainIds:[...e.activeChainIds||[],...s].filter((e,n,t)=>t.indexOf(e)===n)})),H.setState({walletType:i,_reconnect:Boolean(e?.autoReconnect),_reconnectConnector:i}),G.setState({status:"connected"}),"undefined"!=typeof window&&window.sessionStorage.setItem(P,"Active");const l=s.map(e=>o.find(n=>n.chainId===e)),d=G.getState().accounts;return n.info("wallet","Connection successful",{function:M.CONNECT,walletType:i,chainCount:s.length,chainIds:s,addresses:d?Object.values(d).map(e=>e.bech32Address):[]}),n.debug("store","Session store updated",{function:M.CONNECT,accountCount:Object.keys(d||{}).length}),n.timeEnd("connect"),n.groupEnd(),{accounts:d,walletType:i,chains:l}}catch(t){throw n.error("wallet","Connection failed",{function:M.CONNECT,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,walletType:e?.walletType,chainId:e?.chainId}),null===G.getState().accounts&&G.setState({status:"disconnected"}),G.getState().accounts&&G.getState().activeChainIds&&G.setState({status:"connected"}),n.timeEnd("connect"),n.groupEnd(),t}},ke=e=>{const n=Y(),t="string"==typeof e?.chainId?[e.chainId]:e?.chainId;n.info("wallet","Disconnecting",{function:M.DISCONNECT,chainId:t||"all chains"}),"undefined"!=typeof window&&window.sessionStorage.removeItem(P);const o=()=>{if(ve(H.getState().walletType)){const e=Ie("walletconnect"),{disable:n}=e;n&&n()}if(Oe(H.getState().walletType)){const e=Ie("para"),{disable:n}=e;n&&n()}};if(t){const e=G.getState().accounts;t.forEach(n=>{delete e?.[n]});0===Object.values(e||{}).length?(o(),G.setState(j),H.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null}),n.debug("store","Session cleared - all chains disconnected",{function:M.DISCONNECT})):(G.setState(n=>({activeChainIds:n.activeChainIds?.filter(e=>!t.includes(e)),accounts:e})),H.setState(e=>({recentChainIds:e.recentChainIds?.filter(e=>!t.includes(e))})),n.debug("store","Partial disconnect - some chains remain connected",{function:M.DISCONNECT}))}else o(),G.setState(j),H.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null}),n.debug("store","Session cleared - disconnected from all chains",{function:M.DISCONNECT});return n.info("wallet","Disconnected successfully",{function:M.DISCONNECT,chainId:t||"all chains"}),Promise.resolve()},Ne=async e=>{const n=Y(),{recentChainIds:t,_reconnectConnector:o,_reconnect:r}=H.getState();n.debug("wallet","Attempting reconnection",{function:M.RECONNECT,recentChains:t,walletType:o});try{const e=Se(o||void 0);if(t&&e&&o){if(ve(o))return;const e=await Te({chainId:t,walletType:o,autoReconnect:r});return n.info("wallet","Reconnection successful",{function:M.RECONNECT}),e}n.warn("wallet","Reconnection skipped",{function:M.RECONNECT,hasRecentChains:Boolean(t),isWalletReady:e,hasConnector:Boolean(o)})}catch(t){n.warn("wallet","Reconnection failed",{function:M.RECONNECT,error:t instanceof Error?t.message:String(t)}),e?.onError?.(t),ke()}},Be=async e=>{if(!e?.chainId)throw new Error("chainId is required");const{walletType:n}=H.getState(),t=e.walletType||n;if(!Se(t))throw new Error(`${t} is not available`);const o=Ie(t);return{offlineSigner:o.getOfflineSigner(e.chainId),offlineSignerAmino:o.getOfflineSignerOnlyAmino(e.chainId),offlineSignerAuto:await o.getOfflineSignerAuto(e.chainId)}},De=()=>{Y().debug("store","Clearing recent chains",{function:"clearRecentChain"}),H.setState({recentChainIds:null})},Le=()=>{const e=Y(),n=H.getState().recentChainIds;return e.debug("store","Getting recent chain IDs",{function:"getRecentChainIds",chainIds:n}),n},Re=()=>{const e=Y(),{recentChainIds:n,chains:t}=H.getState(),o=n?.map(e=>t.find(n=>n.chainId===e))??null;return e.debug("store","Getting recent chains",{function:"getRecentChains",chainIds:n,chainCount:o?.length??0}),o},Fe=({chainId:e}={})=>{const n=Y(),t=H.getState().chains?.find(n=>n.chainId===e);return n.debug("store","Getting chain info",{function:"getChainInfo",chainId:e,found:Boolean(t)}),t},Ue=({chainId:e}={})=>{const n=Y(),t=H.getState().chains,o=e?t?.filter(n=>e.includes(n.chainId)):t??void 0;return n.debug("store","Getting chain infos",{function:"getChainInfos",requestedChainIds:e,resultCount:o?.length??0}),o},Pe=async({chainInfo:e})=>{const n=Y();n.debug("store","Adding chain",{function:"addChain",chainId:e.chainId,chainName:e.chainName});const{chains:t}=H.getState(),o=t?.find(n=>n.chainId===e.chainId);if(o)throw n.warn("store","Chain already exists",{function:"addChain",chainId:e.chainId}),new Error(`Chain with chainId "${e.chainId}" already exists in the store`);return H.setState(n=>({chains:[...n.chains||[],e]})),n.info("store","Chain added successfully",{function:"addChain",chainId:e.chainId,chainName:e.chainName}),e},qe=async({chainInfo:e,walletType:n})=>{const t=Y();t.debug("wallet","Suggesting chain to wallet",{function:"suggestChain",chainId:e.chainId,chainName:e.chainName,walletType:n});try{const o=Ie(n);await o.experimentalSuggestChain(e);const{chains:r}=H.getState(),i=r?.find(n=>n.chainId===e.chainId);return i||(H.setState(n=>({chains:[...n.chains||[],e]})),t.debug("store","Chain added to store after suggestion",{function:"suggestChain",chainId:e.chainId})),t.info("wallet","Chain suggested successfully",{function:"suggestChain",chainId:e.chainId,chainName:e.chainName,walletType:n}),e}catch(o){throw t.error("wallet","Failed to suggest chain",{function:"suggestChain",error:o instanceof Error?o.message:String(o),chainId:e.chainId,walletType:n}),o}},Me=async e=>{const n=Y(),t=H.getState().walletType,o=e.walletType??t;n.info("wallet","Suggesting chain and connecting",{function:"suggestChainAndConnect",chainId:e.chainInfo.chainId,chainName:e.chainInfo.chainName,walletType:o}),n.time("suggest-chain-and-connect");try{await qe({chainInfo:e.chainInfo,walletType:o});const t=await Te({chainId:e.chainInfo.chainId,walletType:e.walletType,autoReconnect:e.autoReconnect});return n.timeEnd("suggest-chain-and-connect"),n.info("wallet","Chain suggested and connected successfully",{function:"suggestChainAndConnect",chainId:e.chainInfo.chainId,walletType:t.walletType}),t}catch(t){throw n.timeEnd("suggest-chain-and-connect"),n.error("wallet","Failed to suggest chain and connect",{function:"suggestChainAndConnect",error:t instanceof Error?t.message:String(t),chainId:e.chainInfo.chainId}),t}},We=e=>(X({enabled:e.logger?.enabled??!1,level:e.logger?.level,categories:e.logger?.categories}),H.setState(n=>{const t=n.chains??[],o=e.chains,r=new Map;o.forEach(e=>r.set(e.chainId,e)),t.forEach(e=>{r.has(e.chainId)||r.set(e.chainId,e)});const i=Array.from(r.values());return{iframeOptions:e.iframeOptions||n.iframeOptions,walletConnect:e.walletConnect||n.walletConnect,walletType:e.defaultWallet||n.walletType,paraConfig:e.paraConfig||n.paraConfig,walletDefaultOptions:e.walletDefaultOptions||n.walletDefaultOptions,chains:i,chainsConfig:e.chainsConfig||n.chainsConfig,multiChainFetchConcurrency:e.multiChainFetchConcurrency||n.multiChainFetchConcurrency,pingInterval:e.pingInteval||n.pingInterval,loggerConfig:e.logger?{enabled:e.logger.enabled??n.loggerConfig?.enabled??!1,level:e.logger.level??n.loggerConfig?.level??1,categories:e.logger.categories??n.loggerConfig?.categories??[]}:n.loggerConfig,_notFoundFn:e.onNotFound||n._notFoundFn,_onReconnectFailed:e.onReconnectFailed||n._onReconnectFailed,_reconnect:void 0===e.autoReconnect||(e.autoReconnect||n._reconnect)}}),e),xe=async({signingClient:e,senderAddress:n,recipientAddress:t,amount:o,fee:r,memo:i})=>{const a=Y();if(!e)throw new Error("No connected account detected");if(!n)throw new Error("senderAddress is not defined");a.debug("transaction","Signing transaction",{function:"sendTokens",senderAddress:n,recipientAddress:t,amount:o});try{const s=await e.sendTokens(n,t,o,r,i);return a.info("transaction","Transaction broadcasted",{function:"sendTokens",txHash:s.transactionHash,height:s.height}),s}catch(e){throw a.error("transaction","Transaction failed",{function:"sendTokens",error:e instanceof Error?e.message:String(e),senderAddress:n,recipientAddress:t}),e}},Ke=async({signingClient:e,senderAddress:n,recipientAddress:t,transferAmount:o,sourcePort:r,sourceChannel:i,timeoutHeight:a,timeoutTimestamp:s,fee:c,memo:l})=>{const d=Y();if(!e)throw new Error("Stargate signing client is not ready");if(!n)throw new Error("senderAddress is not defined");d.debug("transaction","Signing IBC transfer",{function:"sendIbcTokens",senderAddress:n,recipientAddress:t,transferAmount:o,sourceChannel:i,sourcePort:r});try{const u=await e.sendIbcTokens(n,t,o,r,i,a,s,c,l);return d.info("transaction","IBC transfer successful",{function:"sendIbcTokens",txHash:u.transactionHash,height:u.height}),u}catch(e){throw d.error("transaction","IBC transfer failed",{function:"sendIbcTokens",error:e instanceof Error?e.message:String(e),senderAddress:n,recipientAddress:t,sourceChannel:i}),e}},$e=async({signingClient:e,senderAddress:n,msg:t,fee:o,options:r,label:i,codeId:a})=>{const s=Y();if(!e)throw new Error("CosmWasm signing client is not ready");s.debug("transaction","Instantiating contract",{function:"instantiateContract",senderAddress:n,codeId:a,label:i});try{const c=await e.instantiate(n,a,t,i,o,r);return s.info("transaction","Contract instantiated",{function:"instantiateContract",contractAddress:c.contractAddress,txHash:c.transactionHash}),c}catch(e){throw s.error("transaction","Contract instantiation failed",{function:"instantiateContract",error:e instanceof Error?e.message:String(e),codeId:a,senderAddress:n}),e}},je=async({signingClient:e,senderAddress:n,msg:t,fee:o,contractAddress:r,funds:i,memo:a})=>{const s=Y();if(!e)throw new Error("CosmWasm signing client is not ready");s.debug("transaction","Executing contract",{function:"executeContract",senderAddress:n,contractAddress:r,msg:t});try{const c=await e.execute(n,r,t,o,a,i);return s.info("transaction","Contract execution successful",{function:"executeContract",txHash:c.transactionHash,events:c.events.length}),c}catch(e){throw s.error("transaction","Contract execution failed",{function:"executeContract",error:e instanceof Error?e.message:String(e),contractAddress:r,senderAddress:n}),e}},Ge=async(e,n,t)=>{const o=Y();if(!t)throw new Error("CosmWasm client is not ready");o.debug("query","Querying smart contract",{function:"getQuerySmart",address:e,queryMsg:n});try{const r=await t.queryContractSmart(e,n);return o.debug("query","Smart query successful",{function:"getQuerySmart",address:e}),r}catch(n){throw o.error("query","Smart query failed",{function:"getQuerySmart",error:n instanceof Error?n.message:String(n),address:e}),n}},He=async(e,n,t)=>{const o=Y();if(!t)throw new Error("CosmWasm client is not ready");o.debug("query","Querying raw contract data",{function:"getQueryRaw",address:e,key:n});try{const r=(new TextEncoder).encode(n),i=await t.queryContractRaw(e,r);return o.debug("query","Raw query successful",{function:"getQueryRaw",address:e}),i}catch(n){throw o.error("query","Raw query failed",{function:"getQueryRaw",error:n instanceof Error?n.message:String(n),address:e}),n}},ze=e=>e,Qe=e=>e,Ve=({chainId:e})=>{const n=H(e=>e.chains);if(!n)throw new Error("No chains found in GrazProvider");return e&&e.length>0?e.map(e=>n.find(n=>n.chainId===e)).filter(Boolean):n},Ye=async(e,n,t)=>{const o=Y(),r=H.getState().multiChainFetchConcurrency,i=t?{hook:t}:{function:"createMultiChainAsyncFunction"};o.debug("multichain","Starting parallel operations",{...i,chainCount:e.length,concurrency:r,chainIds:e.map(e=>e.chainId)}),o.time("multichain-operation");try{const t=await A(e,n,{concurrency:r}),a=Object.fromEntries(t.map((n,t)=>[e[t].chainId,n]));return o.timeEnd("multichain-operation"),o.info("multichain","All chains completed",{...i,chainCount:e.length,chainIds:e.map(e=>e.chainId),successCount:Object.keys(a).length}),a}catch(n){throw o.timeEnd("multichain-operation"),o.error("multichain","Multi-chain operation failed",{...i,error:n instanceof Error?n.message:String(n),chainCount:e.length,chainIds:e.map(e=>e.chainId)}),n}};function Xe(e){const n=Ve({chainId:e?.chainId}),t=b(()=>["USE_STARGATE_CLIENT",n],[n]);return y({queryKey:t,queryFn:async()=>{const e=Y();if(e.debug("query","Creating Stargate clients",{hook:"useStargateClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId)}),!n||n.length<1)throw new Error("No chains found");try{const t=await Ye(n,async e=>{const n=H.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await O.connect(t)},"useStargateClient");return e.debug("query","Stargate clients created successfully",{hook:"useStargateClient",clientCount:Object.keys(t).length}),t}catch(n){throw e.error("query","Failed to create Stargate clients",{hook:"useStargateClient",error:n instanceof Error?n.message:String(n)}),n}},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}function Je(e){const n=Ve({chainId:e?.chainId}),t=b(()=>["USE_COSMWASM_CLIENT",n],[n]);return y({queryKey:t,queryFn:async()=>{const e=Y();if(e.debug("query","Creating CosmWasm clients",{hook:"useCosmWasmClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId)}),!n||n.length<1)throw new Error("No chains found");try{const t=await Ye(n,async e=>{const n=H.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await _.connect(t)},"useCosmWasmClient");return e.debug("query","CosmWasm clients created successfully",{hook:"useCosmWasmClient",clientCount:Object.keys(t).length}),t}catch(n){throw e.error("query","Failed to create CosmWasm clients",{hook:"useCosmWasmClient",error:n instanceof Error?n.message:String(n)}),n}},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}var Ze=()=>H(N(e=>({walletType:e.walletType,isCosmostation:"cosmostation"===e.walletType,isCosmostationMobile:"wc_cosmostation_mobile"===e.walletType,isKeplr:"keplr"===e.walletType,isKeplrMobile:"wc_keplr_mobile"===e.walletType,isLeap:"leap"===e.walletType,isLeapMobile:"wc_leap_mobile"===e.walletType,isVectis:"vectis"===e.walletType,isWalletConnect:"walletconnect"===e.walletType,isMetamaskSnapLeap:"metamask_snap_leap"===e.walletType,isStation:"station"===e.walletType,isCosmiframe:"cosmiframe"===e.walletType}))),en=e=>{const n=H(n=>e||n.walletType);return y({queryKey:["USE_CHECK_WALLET",n],queryFn:()=>{const e=Y();if(e.debug("wallet","Checking wallet availability",{hook:"useCheckWallet",walletType:n}),!n)return e.debug("wallet","No wallet type provided",{hook:"useCheckWallet"}),!1;const t=Se(n);return e.debug("wallet","Wallet check completed",{hook:"useCheckWallet",walletType:n,isAvailable:t}),t}})};function nn(e){const n=H(e=>e.walletType),t=G(e=>e.activeChainIds),o=Ve({chainId:e?.chainId?e.chainId:t||void 0}),r=G(e=>e.accounts),i=G(e=>e.status);I(()=>G.subscribe(e=>e.status,(n,t)=>{if("connected"===n){const{accounts:n,activeChainIds:o}=G.getState(),{chains:r}=H.getState(),{walletType:i}=H.getState();if(!n||!o||!r)return e?.onDisconnect?.();e?.onConnect?.({accounts:n,chains:o.map(e=>r.find(n=>n.chainId===e)),walletType:i,isReconnect:"reconnecting"===t})}"disconnected"===n&&e?.onDisconnect?.()}),[e]);return{data:b(()=>r?((e,n)=>{const t=e.map(n);return Object.fromEntries(t.map((n,t)=>[e[t].chainId,n]))})(o,e=>r[e.chainId]):void 0,[r,o]),isConnected:"connected"===i,isConnecting:"connecting"===i,isDisconnected:"disconnected"===i,isReconnecting:"reconnecting"===i,isLoading:"connecting"===i||"reconnecting"===i,walletType:"connected"===i?n:void 0,reconnect:Ne,status:i}}var tn=e=>{const n=Ve({chainId:[e.chainId]})[0],{data:t}=Xe({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=b(()=>["USE_ALL_BALANCES",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return y({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getAllBalances(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},on=e=>{const n=Ve({chainId:[e.chainId]})[0],{data:t}=Xe({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=b(()=>["USE_BALANCE",o,e.chainId,e.bech32Address,e.denom],[e.bech32Address,e.chainId,e.denom,o]);return y({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);const t=await o.getBalance(e.bech32Address,e.denom);return"0"===t.amount?void 0:t},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},rn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),r=S({mutationKey:["USE_CONNECT",e,n,t],mutationFn:Te,onError:(n,t)=>{o.error("wallet","useConnect mutation failed",{error:n instanceof Error?n.message:String(n),chainId:t?.chainId}),e?.(n,t)},onMutate:n,onSuccess:e=>(o.info("wallet","useConnect mutation successful",{hook:"useConnect",walletType:e.walletType,chainCount:e.chains.length}),Promise.resolve(t?.(e)))}),{data:i}=en();return{connect:e=>r.mutate(e),connectAsync:e=>r.mutateAsync(e),error:r.error,isLoading:r.isPending,isSuccess:r.isSuccess,isSupported:Boolean(i),status:r.status}},an=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),r=S({mutationKey:["USE_DISCONNECT",e,n,t],mutationFn:ke,onError:n=>(o.error("wallet","useDisconnect mutation failed",{hook:"useDisconnect",error:n instanceof Error?n.message:String(n)}),Promise.resolve(e?.(n,void 0))),onMutate:n,onSuccess:()=>(o.info("wallet","useDisconnect mutation successful",{hook:"useDisconnect"}),Promise.resolve(t?.(void 0)))});return{disconnect:e=>r.mutate(e),disconnectAsync:e=>r.mutateAsync(e),error:r.error,isLoading:r.isPending,isSuccess:r.isSuccess,status:r.status}};function sn(e){const n=Ve({chainId:e?.chainId}),t=H(e=>e.walletType),o="connected"===G.getState().status&&G.getState().accounts&&H.getState()._reconnectConnector===t,r=b(()=>["USE_OFFLINE_SIGNERS",n,t],[n,t]);return y({queryKey:r,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chain found");if(!t)throw new Error("Wallet is not defined");if(!Se(t))throw new Error(`${t} is not available`);return await Ye(n,async e=>await Be({chainId:e.chainId,walletType:t}),"useOfflineSigners")},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&Boolean(o),refetchOnWindowFocus:!1})}var cn=e=>{const n=Ve({chainId:[e.chainId]})[0],{data:t}=Xe({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=b(()=>["USE_BALANCE_STAKED",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return y({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getBalanceStaked(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},ln=()=>G(e=>e.activeChainIds),dn=()=>{const e=G(e=>e.activeChainIds),n=H(e=>e.chains);return e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean)},un=({chainId:e}={})=>H(e=>e.chains)?.find(n=>n.chainId===e),gn=({chainId:e}={})=>{const n=H(e=>e.chains);return e?n?.filter(n=>e.includes(n.chainId)):n},hn=({denom:e})=>{const n=dn();return y({queryKey:["USE_ACTIVE_CHAIN_CURRENCY",e],queryFn:({queryKey:[,e]})=>n?.find(n=>n.currencies.find(n=>n.coinMinimalDenom===e))?.currencies.find(e=>e)})},fn=e=>{const n=e.status??"BOND_STATUS_BONDED",t=["USE_ACTIVE_CHAIN_VALIDATORS",e.queryClient,n];return y({queryKey:t,queryFn:async()=>{if(!e.queryClient)throw new Error("Query client is not defined");return await e.queryClient.staking.validators(n)},enabled:void 0!==e.queryClient})},wn=()=>({data:H(e=>e.recentChainIds),clear:De}),mn=()=>{const e=H(e=>e.recentChainIds),n=H(e=>e.chains),t=e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean);return{data:t,clear:De}},pn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),r=S({mutationKey:["USE_ADD_CHAIN",e,n,t],mutationFn:Pe,onError:(n,t)=>(o.error("store","useAddChain mutation failed",{hook:"useAddChain",error:n instanceof Error?n.message:String(n),chainId:t.chainInfo.chainId}),Promise.resolve(e?.(n,t.chainInfo))),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>(o.info("store","useAddChain mutation successful",{hook:"useAddChain",chainId:e.chainId,chainName:e.chainName}),Promise.resolve(t?.(e)))});return{addChain:r.mutate,addChainAsync:r.mutateAsync,error:r.error,isLoading:r.isPending,isSuccess:r.isSuccess,status:r.status}},Cn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),r=S({mutationKey:["USE_SUGGEST_CHAIN",e,n,t],mutationFn:qe,onError:(n,t)=>(o.error("wallet","useSuggestChain mutation failed",{hook:"useSuggestChain",error:n instanceof Error?n.message:String(n),chainId:t.chainInfo.chainId,walletType:t.walletType}),Promise.resolve(e?.(n,t.chainInfo))),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>(o.info("wallet","useSuggestChain mutation successful",{hook:"useSuggestChain",chainId:e.chainId,chainName:e.chainName}),Promise.resolve(t?.(e)))});return{error:r.error,isLoading:r.isPending,isSuccess:r.isSuccess,suggest:r.mutate,suggestAsync:r.mutateAsync,status:r.status}},yn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),r=S({mutationKey:["USE_SUGGEST_CHAIN_AND_CONNECT",e,n,t],mutationFn:Me,onError:(n,t)=>(o.error("wallet","useSuggestChainAndConnect mutation failed",{error:n instanceof Error?n.message:String(n),chainId:t.chainInfo.chainId}),Promise.resolve(e?.(n,t))),onMutate:e=>n?.(e),onSuccess:e=>(o.info("wallet","useSuggestChainAndConnect mutation successful",{hook:"useSuggestChainAndConnect",walletType:e.walletType,chainCount:e.chains.length}),Promise.resolve(t?.(e)))}),{data:i}=en();return{error:r.error,isLoading:r.isPending,isSuccess:r.isSuccess,isSupported:Boolean(i),status:r.status,suggestAndConnect:r.mutate,suggestAndConnectAsync:r.mutateAsync}},Sn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),{mutate:r,mutateAsync:i,...a}=S({mutationKey:["USE_SEND_TOKENS",e,n,t],mutationFn:xe,onError:(n,t)=>(o.error("transaction","useSendTokens mutation failed",{hook:"useSendTokens",error:n instanceof Error?n.message:String(n),recipientAddress:t.recipientAddress}),Promise.resolve(e?.(n,t))),onMutate:n,onSuccess:e=>(o.info("transaction","useSendTokens mutation successful",{hook:"useSendTokens",txHash:e.transactionHash}),Promise.resolve(t?.(e)))});return{...a,sendTokens:r,sendTokensAsync:i}},bn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),{mutate:r,mutateAsync:i,...a}=S({mutationKey:["USE_SEND_IBC_TOKENS",e,n,t],mutationFn:Ke,onError:(n,t)=>(o.error("transaction","useSendIbcTokens mutation failed",{error:n instanceof Error?n.message:String(n),sourceChannel:t.sourceChannel}),Promise.resolve(e?.(n,t))),onMutate:n,onSuccess:e=>(o.info("transaction","useSendIbcTokens mutation successful",{hook:"useSendIbcTokens",txHash:e.transactionHash}),Promise.resolve(t?.(e)))});return{...a,sendIbcTokens:r,sendIbcTokensAsync:i}},In=({codeId:e,onError:n,onLoading:t,onSuccess:o})=>{const r=Y(),{mutate:i,mutateAsync:a,...s}=S({mutationKey:["USE_INSTANTIATE_CONTRACT",n,t,o,e],mutationFn:n=>$e({...n,fee:n.fee??"auto",codeId:e}),onError:(t,o)=>(r.error("transaction","useInstantiateContract mutation failed",{error:t instanceof Error?t.message:String(t),codeId:e}),Promise.resolve(n?.(t,o))),onMutate:t,onSuccess:e=>(r.info("transaction","useInstantiateContract mutation successful",{hook:"useInstantiateContract",contractAddress:e.contractAddress,txHash:e.transactionHash}),Promise.resolve(o?.(e)))});return{...s,instantiateContract:i,instantiateContractAsync:a}},En=({contractAddress:e,onError:n,onLoading:t,onSuccess:o})=>{const r=Y(),{mutate:i,mutateAsync:a,...s}=S({mutationKey:["USE_EXECUTE_CONTRACT",n,t,o,e],mutationFn:n=>je({...n,fee:n.fee??"auto",contractAddress:e,memo:n.memo??"",funds:n.funds??[]}),onError:(t,o)=>(r.error("transaction","useExecuteContract mutation failed",{hook:"useExecuteContract",error:t instanceof Error?t.message:String(t),contractAddress:e}),Promise.resolve(n?.(t,o))),onMutate:t,onSuccess:n=>(r.info("transaction","useExecuteContract mutation successful",{hook:"useExecuteContract",txHash:n.transactionHash,contractAddress:e}),Promise.resolve(o?.(n)))});return{...s,executeContract:i,executeContractAsync:a}},An=e=>{const{data:n}=Je(),t=n&&Object.values(n)[0];return y({queryKey:["USE_QUERY_SMART",e?.address,e?.queryMsg,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.queryMsg)throw new Error("address or queryMsg undefined");return Ge(e.address,e.queryMsg,t)},enabled:Boolean(e?.address)&&Boolean(e?.queryMsg)&&Boolean(t)})},_n=e=>{const{data:n}=Je(),t=n&&Object.values(n)[0];return y({queryKey:["USE_QUERY_RAW",e?.key,e?.address,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.key)throw new Error("address or key undefined");return He(e.address,e.key,t)},enabled:Boolean(e?.address)&&Boolean(e?.key)&&Boolean(t)})};function vn(e){const n=Ve({chainId:e?.chainId}),t=H(e=>e.walletType),o=G(e=>e.activeChainIds),r="connected"===G.getState().status&&G.getState().accounts&&H.getState()._reconnectConnector===t,i=b(()=>["USE_STARGATE_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return y({queryKey:i,queryFn:async()=>{const r=Y();if(r.debug("query","Creating Stargate signing clients",{hook:"useStargateSigningClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId),walletType:t}),!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");try{const i=await Ye(n,async n=>{if(!o?.includes(n.chainId))return null;if(!Se(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return Ie(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return Ie(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return Ie(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=H.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}};return await T.connectWithSigner(a,r,e?.opts?.[n.chainId])},"useStargateSigningClient");return r.debug("query","Stargate signing clients created successfully",{hook:"useStargateSigningClient",clientCount:Object.keys(i).length}),i}catch(e){throw r.error("query","Failed to create Stargate signing clients",{hook:"useStargateSigningClient",error:e instanceof Error?e.message:String(e),walletType:t}),e}},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})}function On(e){const n=Ve({chainId:e?.chainId}),t=H(e=>e.walletType),o=G(e=>e.activeChainIds),r="connected"===G.getState().status&&G.getState().accounts&&H.getState()._reconnectConnector===t,i=b(()=>["USE_COSMWASM_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return y({queryKey:i,queryFn:async()=>{const r=Y();if(r.debug("query","Creating CosmWasm signing clients",{hook:"useCosmWasmSigningClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId),walletType:t}),!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");try{const i=await Ye(n,async n=>{if(!o?.includes(n.chainId))return null;if(!Se(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return Ie(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return Ie(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return Ie(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=H.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}},s=i?.gas?k.fromString(`${i.gas.price}${i.gas.denom}`):void 0;return await v.connectWithSigner(a,r,{gasPrice:s,...e?.opts?.[n.chainId]||{}})},"useCosmWasmSigningClient");return r.debug("query","CosmWasm signing clients created successfully",{hook:"useCosmWasmSigningClient",clientCount:Object.keys(i).length}),i}catch(e){throw r.error("query","Failed to create CosmWasm signing clients",{hook:"useCosmWasmSigningClient",error:e instanceof Error?e.message:String(e),walletType:t}),e}},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})}var Tn=({children:e})=>{const[n,t]=E(!1);return I(()=>{t(!0)},[]),D(L,{children:n?e:null})},kn=()=>{const e=Y(),n="undefined"!=typeof window&&"Active"===window.sessionStorage.getItem(P),{_reconnect:t,_onReconnectFailed:o,_reconnectConnector:i,iframeOptions:a,chains:s,pingInterval:c}=H(),{activeChainIds:l,wcSignClients:d}=G(),u=Se(i||void 0);return I(()=>{const t=async()=>{if(n&&u&&i&&l?.[0]){const n=G.getState().lastPing;if(n&&Date.now()-n<c)return;const t=Ie(i);try{if(!await t.getKey(l[0]))throw new Error("No account found");G.setState({lastPing:Date.now()}),e.debug("event","Wallet ping successful",{function:"handleFocus"})}catch(n){e.debug("event","Wallet ping failed, triggering reconnect",{function:"handleFocus",error:n instanceof Error?n.message:String(n),walletType:i}),Ne({onError:o})}}};return window.addEventListener("focus",t),()=>{window.removeEventListener("focus",t)}},[n,u,i,s,l,c]),I(()=>{if(!a||!1===a.autoConnect||!a.allowedIframeParentOrigins.length||!s)return;new r(a.allowedIframeParentOrigins).isReady().then(n=>{if(n)return e.info("event","Auto-connecting to iframe wallet",{function:"autoConnectIframe"}),Te({chainId:s.map(e=>e.chainId),walletType:"cosmiframe"})})},[a]),I(()=>{if(i){if(!u)return;n&&Boolean(l)?(e.info("event","Reconnection triggered",{function:"reconnectEffect",reason:"session active"}),Ne({onError:o})):!n&&t&&(e.info("event","Reconnection triggered",{function:"reconnectEffect",reason:"auto-reconnect enabled"}),Ne({onError:o}))}},[u]),I(()=>{if(i){if(!u)return;"cosmostation"===i&&te().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"cosmostation"}),Ne({onError:o})}),"keplr"===i&&re().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"keplr"}),Ne({onError:o})}),"leap"===i&&ie().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"leap"}),Ne({onError:o})}),"compass"===i&&Z().subscription?.(()=>{Ne({onError:o})}),"vectis"===i&&ge().subscription?.(()=>{Ne({onError:o})}),"walletconnect"===i&&d.has("walletconnect")&&we().subscription?.(()=>{Ne({onError:o})}),"station"===i&&ue().subscription?.(()=>{Ne({onError:o})}),"xdefi"===i&&ye().subscription?.(()=>{Ne({onError:o})}),"cosmiframe"===i&&ee().subscription?.(()=>{Ne({onError:o})}),"okx"===i&&ce().subscription?.(()=>{Ne({onError:o})})}},[i,d,u]),null},Nn=()=>(kn(),null),Bn=({children:e,grazOptions:n})=>(I(()=>{We(n)},[n]),B(Tn,{children:[e,D(Nn,{})]}));export{Nn as GrazEvents,Bn as GrazProvider,q as LOG_CATEGORIES,M as LOG_FUNCTIONS,W as LOG_HOOKS,Q as LogCategory,z as LogLevel,K as WALLET_TYPES,x as WalletType,Pe as addChain,Se as checkWallet,De as clearRecentChain,be as clearSession,We as configureGraz,X as configureLogger,Te as connect,Qe as defineChainInfo,ze as defineChains,ke as disconnect,je as executeContract,Ee as getAvailableWallets,J as getCactusCosmos,Fe as getChainInfo,Ue as getChainInfos,te as getCosmostation,re as getKeplr,ie as getLeap,Y as getLogger,se as getMetamaskSnapLeap,Be as getOfflineSigners,ce as getOkx,de as getPara,He as getQueryRaw,Ge as getQuerySmart,Le as getRecentChainIds,Re as getRecentChains,ge as getVectis,me as getWCCosmostation,pe as getWCKeplr,Ce as getWCLeap,Ie as getWallet,we as getWalletConnect,$e as instantiateContract,_e as isLeapDappBrowser,Ae as isLeapSnaps,Oe as isPara,ve as isWalletConnect,Ne as reconnect,Ke as sendIbcTokens,xe as sendTokens,qe as suggestChain,Me as suggestChainAndConnect,nn as useAccount,hn as useActiveChainCurrency,ln as useActiveChainIds,dn as useActiveChains,Ze as useActiveWalletType,pn as useAddChain,on as useBalance,cn as useBalanceStaked,tn as useBalances,un as useChainInfo,gn as useChainInfos,en as useCheckWallet,rn as useConnect,Je as useCosmWasmClient,On as useCosmWasmSigningClient,an as useDisconnect,En as useExecuteContract,kn as useGrazEvents,In as useInstantiateContract,sn as useOfflineSigners,fn as useQueryClientValidators,_n as useQueryRaw,An as useQuerySmart,wn as useRecentChainIds,mn as useRecentChains,bn as useSendIbcTokens,Sn as useSendTokens,Xe as useStargateClient,vn as useStargateSigningClient,Cn as useSuggestChain,yn as useSuggestChainAndConnect};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "graz",
|
|
3
3
|
"description": "React hooks for Cosmos",
|
|
4
|
-
"version": "0.4.
|
|
4
|
+
"version": "0.4.2",
|
|
5
5
|
"author": "Nur Fikri <kikiding.space@gmail.com>",
|
|
6
6
|
"repository": "https://github.com/graz-sh/graz.git",
|
|
7
7
|
"homepage": "https://github.com/graz-sh/graz",
|
|
@@ -67,11 +67,11 @@
|
|
|
67
67
|
"@getpara/graz-connector": "2.0.0-alpha.51",
|
|
68
68
|
"@getpara/web-sdk": "2.0.0-alpha.51",
|
|
69
69
|
"@types/node": "^18.17.15",
|
|
70
|
-
"@types/react": "^
|
|
70
|
+
"@types/react": "^19.0.0",
|
|
71
71
|
"@vitest/ui": "^2.1.9",
|
|
72
72
|
"arg": "^5.0.2",
|
|
73
73
|
"jsdom": "^23.0.0",
|
|
74
|
-
"react": "^
|
|
74
|
+
"react": "^19.0.0",
|
|
75
75
|
"typescript": "^5.4.0",
|
|
76
76
|
"vite": "^5.4.20",
|
|
77
77
|
"vitest": "^2.1.9"
|