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.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("zustand"),n=require("zustand/middleware"),t=require("@dao-dao/cosmiframe"),r=require("@cosmsnap/snapper"),o=require("@cosmjs/amino"),i=require("long"),a=require("@cosmjs/encoding"),s=require("@walletconnect/modal"),c=require("@walletconnect/sign-client"),l=require("@walletconnect/utils"),d=require("@tanstack/react-query"),u=require("react"),g=require("p-map"),w=require("@cosmjs/cosmwasm-stargate"),f=require("@cosmjs/stargate"),h=require("zustand/shallow"),p=require("react/jsx-runtime");function m(e){return e&&e.__esModule?e:{default:e}}var y=m(i),S=m(g),C="graz-reconnect-session",I=(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))(I||{}),b=["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"],E={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},A={accounts:null,activeChainIds:null,status:"disconnected",lastPing:null,wcSignClients:new Map,paraConnector:null},_={name:"graz-session",version:2,partialize:e=>({accounts:e.accounts,activeChainIds:e.activeChainIds,lastPing:e.lastPing,status:e.status}),storage:n.createJSONStorage(()=>sessionStorage)},v=e.create(n.subscribeWithSelector(n.persist(()=>A,_))),O=e.create(n.subscribeWithSelector(n.persist(()=>E,{name:"graz-internal",partialize:e=>({recentChainIds:e.recentChainIds,_reconnect:e._reconnect,_reconnectConnector:e._reconnectConnector,walletType:e.walletType,chains:e.chains}),version:3}))),k=()=>{if(void 0!==window.cactuslink_cosmos){const e=window.cactuslink_cosmos,n=e=>{const n=()=>{X(),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 O.getState()._notFoundFn(),new Error("window.cactuslink_cosmos is not defined")},x=()=>{if(void 0!==window.compass){const e=window.compass,n=e=>{const n=()=>{X(),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 O.getState()._notFoundFn(),new Error("window.leap is not defined")},B=()=>{const e=O.getState();if(!e.iframeOptions)throw e._notFoundFn(),new Error("no iframe options set");if(!t.isInIframe())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 t.Cosmiframe(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)}},N={},T=()=>{if(void 0!==window.cosmostation?.providers.keplr){const e=window.cosmostation.providers.keplr,n=e=>{const n=()=>{X(),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 O.getState()._notFoundFn(),new Error("window.cosmostation.providers.keplr is not defined")},P=()=>{if(void 0!==window.initia){const e=window.initia;return{enable:async()=>{await e.getAddress()},getKey:async n=>{const t=e.getOfflineSigner(n),[r]=await t.getAccounts();if(!r)throw new Error("Wallet connection failed");const i=(()=>{switch(r.algo){case"secp256k1":return o.rawSecp256k1PubkeyToRawAddress(r.pubkey);case"ed25519":return o.rawEd25519PubkeyToRawAddress(r.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{name:(a=r.address,`${a.slice(0,6)}...${a.slice(-6)}`),algo:r.algo,pubKey:r.pubkey,bech32Address:r.address,address:i,isNanoLedger:!1,isKeystone:!1};var a},getOfflineSigner:n=>{const t=e.getOfflineSigner(n),r=e.getOfflineSignerOnlyAmino(n);return{getAccounts:t.getAccounts.bind(t),signDirect:t.signDirect.bind(t),signAmino:r.signAmino.bind(r)}},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,r,o]=n;return e.getOfflineSigner(t).signDirect(r,(e=>{const{bodyBytes:n,authInfoBytes:t,chainId:r,accountNumber:o}=e;if(!(n&&t&&r&&o))throw new Error("Invalid sign doc");return{bodyBytes:n,authInfoBytes:t,chainId:r,accountNumber:o}})(o))},signAmino:(...n)=>{const[t,r,o]=n;return e.getOfflineSignerOnlyAmino(t).signAmino(r,o)},signArbitrary:async(n,t,r)=>{const i=e.getOfflineSigner(n),a=(await i.getAccounts()).find(e=>e.address===t);if(!a)throw new Error(`Wallet not connected to account ${t}`);const s=(()=>{switch(a.algo){case"secp256k1":return o.encodeSecp256k1Pubkey(a.pubkey);case"ed25519":return o.encodeEd25519Pubkey(a.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{signature:await e.signArbitrary(r),pub_key:{type:"secp256k1"===a.algo?o.pubkeyType.secp256k1:o.pubkeyType.ed25519,value:s.value}}},subscription:e=>{const n=()=>{X(),e()};return window.addEventListener("initia_keystorechange",n),()=>{window.removeEventListener("initia_keystorechange",n)}}}}throw O.getState()._notFoundFn(),new Error("window.initia is not defined")},M=()=>{if(void 0!==window.keplr){const e=window.keplr,n=e=>{const n=()=>{X(),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 O.getState()._notFoundFn(),new Error("window.keplr is not defined")},D=()=>{if(void 0!==window.leap){const e=window.leap,n=e=>{const n=()=>{X(),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 O.getState()._notFoundFn(),new Error("window.leap is not defined")},L={},F=()=>(e=>{const n=window.ethereum;if(n&&e){const t=async()=>await n.request({method:"wallet_getSnaps"}),r=async n=>{try{const r=await t();return Object.values(r).find(t=>t.id===e.id&&(!n||t.version===n))}catch(e){return}},o=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 r()||await o(),!0},a=async(t,r,o)=>{const i=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signDirect",params:{chainId:t,signerAddress:r,signDoc:o}}}}),a=o.accountNumber,s=new y.default(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,r,o)=>await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signAmino",params:{chainId:t,signerAddress:r,signDoc:o}}}}),c=async t=>{if(void 0!==L[t])return L[t];const r=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"getKey",params:{chainId:t}}}});if(!r)throw new Error("No response from Metamask");return r.pubKey=Uint8Array.from(Object.values(r.pubkey)),delete r.pubkey,L[t]=r,L[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,r,o]=e;return await s(n,t,r)},u=async(...e)=>{const[n,t,r]=e,o={...r,accountNumber:y.default.fromString(r.accountNumber?.toString()||"0"),authInfoBytes:r.authInfoBytes,bodyBytes:r.bodyBytes};return await a(n,t,o)},g=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>d(e,n,t)});return{enable:async e=>{await r()||await o()},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 O.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=()=>{X(),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 O.getState()._notFoundFn(),new Error("window.okxwallet.keplr is not defined")},K=null,U=()=>{const e=()=>{const e=v.getState().paraConnector;if(!e)throw new Error("Para connector not initialized. Call connect() first or check paraConfig in GrazProvider.");return e},n=O.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(K||(K=(async()=>{const e=v.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"),r=t?.ParaGrazConnector;if("function"!=typeof r)throw new Error("Invalid ParaGrazConnector in @getpara/graz-integration. Check the package/export.");e=r}const t=O.getState().chains,r=new e(n,t);if(v.setState(e=>({...e,paraConnector:r})),!r)throw new Error("Para connector initialization failed. Check config and dependencies.");return r}catch(e){if(K=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.`)}})()));v.setState({paraConnector:e,status:"connecting"}),await e.enable(t);const r=Object.fromEntries(await Promise.all(t.map(async n=>[n,await e.getKey(n)])));v.setState(e=>({accounts:{...e.accounts||{},...r},activeChainIds:Array.from(new Set([...e.activeChainIds||[],...t])),status:"connected"})),O.setState(e=>({recentChainIds:Array.from(new Set([...e.recentChainIds||[],...t])),walletType:"para",_reconnect:!1,_reconnectConnector:"para"}))}catch(e){v.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=v.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{v.setState({paraConnector:null,status:"disconnected"})}else v.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,r,o)=>{try{return await e().signAmino(n,t,r,o)}catch(e){throw new Error(`Amino signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signDirect:async(n,t,r,o)=>{try{return await e().signDirect(n,t,r,o)}catch(e){throw new Error(`Direct signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signArbitrary:async(n,t,r)=>{try{return await e().signArbitrary(n,t,r)}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.")}}},$=()=>{if(void 0!==window.station?.keplr){const e=window.station.keplr;return{subscription:e=>{const n=()=>{X(),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),r=(e,n)=>{throw new Error("signDirect not supported by Station")};return Object.assign(t,{signDirect:r})}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,r,o)=>e.signAmino(n,t,r)}}throw O.getState()._notFoundFn(),new Error("window.station is not defined")},W=()=>{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 r=await t.signDirect(e,{accountNumber:y.default.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:r.signature,signed:{authInfoBytes:r.signed.authInfoBytes,bodyBytes:r.signed.bodyBytes,chainId:r.signed.chainId,accountNumber:BigInt(r.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 r=await t.signDirect(e,{accountNumber:y.default.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:r.signature,signed:{authInfoBytes:r.signed.authInfoBytes,bodyBytes:r.signed.bodyBytes,chainId:r.signed.chainId,accountNumber:BigInt(r.signed.accountNumber.toString())}}}}:t},getKey:async n=>{const t=await e.getKey(n);return{address:a.fromBech32(t.address).data,algo:t.algo,bech32Address:t.address,name:t.name,pubKey:t.pubKey,isKeystone:!1,isNanoLedger:t.isNanoLedger}},subscription:e=>{const n=()=>{X(),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 r={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([r])},signDirect:async(...n)=>{const{1:t,2:r}=n,o=await e.signDirect(t,{bodyBytes:r.bodyBytes||Uint8Array.from([]),authInfoBytes:r.authInfoBytes||Uint8Array.from([]),accountNumber:y.default.fromString(r.accountNumber?.toString()||"",!1),chainId:r.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}},signAmino:async(...n)=>{const{1:t,2:r}=n;return e.signAmino(t,r)}}}throw O.getState()._notFoundFn(),new Error("window.vectis is not defined")},j=()=>{if("undefined"!=typeof window){const e=navigator.userAgent;return!!/android/i.test(e)||!!/iPad|iPhone|iPod/.test(e)}return!1},R=(e,n,t=new Error("Promise timed out"))=>{const r=new Promise((e,r)=>{setTimeout(()=>{r(t)},n)});return Promise.race([e,r])},z=e=>{if(!O.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");const n=e?.walletType||"walletconnect",t=e?.encoding||"base64",r=n=>{if(!e)return;const{appUrl:t,formatNativeUrl:r}=e;if(j()){if(j()&&navigator.userAgent.toLowerCase().includes("android")){const e=r(t.mobile.android,n,"android");window.open(e,"_self","noreferrer noopener")}if(j()&&(navigator.userAgent.toLowerCase().includes("iphone")||navigator.userAgent.toLowerCase().includes("ipad"))){const e=r(t.mobile.ios,n,"ios");window.open(e,"_self","noreferrer noopener")}}},o=()=>{const{wcSignClients:e}=v.getState();if(!e.get(n))throw new Error("walletConnect.signClient is not defined");e.delete(n),v.setState({wcSignClients:e}),O.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})},i=async e=>{const{wcSignClients:t}=v.getState(),r=t.get(n);if(!r)throw new Error("walletConnect.signClient is not defined");if(!e)throw new Error("No wallet connect session");await r.disconnect({topic:e,reason:l.getSdkError("USER_DISCONNECTED")}),await d(r)},a=e=>{try{const{wcSignClients:t}=v.getState(),r=t.get(n);if(!r)throw new Error("walletConnect.signClient is not defined");const o=r.session.getAll(),a=o.at(-1);if(!a)return;if(!(1e3*a.expiry>Date.now()+1e3))throw i(a.topic),new Error("invalid session");try{const n=o.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}},d=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}},u=async t=>{const o="string"==typeof t?[t]:t,{wcSignClients:c,activeChainIds:l}=v.getState(),d=c.get(n);if(!d)throw new Error("enable walletConnect.signClient is not defined");const{walletConnect:u}=O.getState();if(!u?.options?.projectId)throw new Error("walletConnect.options.projectId is not defined");const g=new s.WalletConnectModal({projectId:u.options.projectId,enableExplorer:!1,explorerRecommendedWalletIds:"NONE",...u.walletConnectModal}),f=(e=>{try{return a(e)}catch(e){return}})(o);if(!f){const{uri:n,approval:t}=await R(d.connect({requiredNamespaces:{cosmos:{methods:["cosmos_getAccounts","cosmos_signAmino","cosmos_signDirect"],chains:o.map(e=>`cosmos:${e}`),events:["chainChanged","accountsChanged"]}}}),15e3,new Error("Connection timeout"));if(!n)throw new Error("No wallet connect uri");e?r(n):await g.openModal({uri:n});const i=async e=>e.aborted?Promise.reject(new Error("User closed wallet connect")):new Promise((n,r)=>{t().then(e=>{const t=e.sessionProperties;if(!t)return r(new Error("No session properties"));const o=JSON.parse(String(t.keys));if(0===o.length)return r(new Error("No accounts"));if(!o[0])return r(new Error("No accounts"));const i={};return o.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}}),v.setState(e=>({accounts:{...e.accounts||{},...i}})),n(e)}).catch(r),e.addEventListener("abort",()=>{r(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 R((async()=>{const e=Object.fromEntries(await Promise.all((l||o).map(async e=>[e,await w(e)])));v.setState({accounts:e})})(),15e3,new Error("Connection timeout"))}catch(e){if(i(f.topic),!e.message.toLowerCase().includes("no matching key"))throw e}},g=async e=>{const n=await w(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},w=async e=>{const n=a([e]);if(!n?.topic)throw new Error("No wallet connect session");const r=n.sessionProperties&&JSON.parse(String(n.sessionProperties.keys));if(!r)throw new Error("No wallet connect key");if(0===r.length)throw new Error("No wallet connect session");const o=r.find(n=>n.chainId===e);if(!o)throw new Error(`No wallet connect key for chainId ${e}`);return{...o,pubKey:Buffer.from(String(o.pubKey),t)}},f=async(...e)=>{const[o,i,s]=e,{signature:c,signed:l}=await(async(...e)=>{const[o,i,s]=e,{accounts:c,wcSignClients:l}=v.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([o])?.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 r(),await d.request({topic:u,chainId:`cosmos:${o}`,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}}}})})(o,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}},h=async(...e)=>{const[t,o,i,s]=e,c=await(async(...e)=>{const[t,o,i,s]=e,{wcSignClients:c}=v.getState(),l=c.get(n),{accounts:d}=v.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 r(),await l.request({topic:u,chainId:`cosmos:${t}`,request:{method:"cosmos_signDirect",params:{signerAddress:o,signDoc:i}}})})(t,o,i);return c},p=e=>({getAccounts:async()=>[await g(e)],signAmino:(n,t)=>h(e,n,t)});return{enable:u,disable:async e=>{const{wcSignClients:t}=v.getState(),r=t.get(n);if(void 0===e){const e=r?.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===r?.session.getAll().length&&o()},experimentalSuggestChain:async(...e)=>{await Promise.reject(new Error("WalletConnect does not support experimentalSuggestChain"))},getKey:w,getOfflineSigner:e=>({getAccounts:async()=>[await g(e)],signDirect:(n,t)=>f(e,n,t),signAmino:(n,t)=>h(e,n,t)}),getOfflineSignerAuto:async e=>(await w(e)).isNanoLedger?p(e):(e=>({getAccounts:async()=>[await g(e)],signDirect:(n,t)=>f(e,n,t)}))(e),getOfflineSignerOnlyAmino:p,signAmino:h,signDirect:f,subscription:e=>{const{wcSignClients:t}=v.getState(),r=t.get(n);if(!r)return()=>{};const i=n=>{const t=v.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&&u([e])}else e()};return r.events.on("session_delete",o),r.events.on("session_expire",o),r.events.on("session_event",i),()=>{r.events.off("session_delete",o),r.events.off("session_expire",o),r.events.off("session_event",i)}},init:async()=>{const{walletConnect:e}=O.getState();if(!e?.options)throw new Error("walletConnect.options is not defined");const{wcSignClients:t}=v.getState(),r=t.get(n);if(r)return r;const o=await c.SignClient.init(e.options);return t.set(n,o),v.setState({wcSignClients:t}),o}}},G=()=>{if(!O.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!j())throw new Error("WalletConnect Cosmostation mobile is only supported in mobile");return z({encoding:"hex",appUrl:{mobile:{ios:"cosmostation://",android:"cosmostation://"}},walletType:"wc_cosmostation_mobile",formatNativeUrl:(e,n,t)=>{const r=e.replace(/\//g,"").replace(/:/g,"");return n?`${r}://wc?${n}`:`${r}://wc`}})},Q=()=>{if(!O.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!j())throw new Error("WalletConnect Keplr mobile is only supported in mobile");return z({encoding:"base64",appUrl:{mobile:{ios:"keplrwallet://",android:"intent://"}},walletType:"wc_keplr_mobile",formatNativeUrl:(e,n,t)=>{const r=e.replace(/\//g,"").replace(/:/g,""),o=n&&encodeURIComponent(n);switch(t){case"ios":return o?`${r}://wcV2?${o}`:`${r}://wcV2`;case"android":return o?`${r}://wcV2?${o}#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`:`${r}://wcV2#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`;default:return o?`${r}://wc?uri=${o}`:`${r}://wc`}}})},V=()=>{if(!O.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!j())throw new Error("WalletConnect Leap mobile is only supported in mobile");return z({encoding:"base64",appUrl:{mobile:{ios:"leapcosmos://",android:"intent://"}},walletType:"wc_leap_mobile",formatNativeUrl:(e,n,t)=>{const r=e.replace(/\//g,"").replace(/:/g,""),o=n&&encodeURIComponent(n);switch(t){case"ios":return o?`${r}://wcV2?${o}`:`${r}://wcV2`;case"android":return o?`${r}://wcV2?${o}#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`:`${r}://wcV2#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`;default:return o?`${r}://wc?uri=${o}`:`${r}://wc`}}})},H=()=>{if(void 0!==window.xfi?.keplr){const e=window.xfi.keplr,n=e=>{const n=()=>{X(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}};return Object.assign(e,{subscription:n})}throw O.getState()._notFoundFn(),new Error("window.xfi.keplr is not defined")},Y=(e=O.getState().walletType)=>{try{return J(e),!0}catch(e){return!1}},X=()=>{window.sessionStorage.removeItem(C),v.setState(A)},J=(e=O.getState().walletType)=>{const n=(()=>{switch(e){case"keplr":return M();case"leap":return D();case"cosmostation":return T();case"vectis":return W();case"walletconnect":return z();case"wc_keplr_mobile":return Q();case"wc_leap_mobile":return V();case"wc_cosmostation_mobile":return G();case"wc_clot_mobile":return(()=>{if(!O.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!j())throw new Error("WalletConnect Clot mobile is only supported in mobile");return z({encoding:"base64",appUrl:{mobile:{android:"clot://",ios:"clot://"}},walletType:"wc_clot_mobile",formatNativeUrl:(e,n,t)=>{const r=e.replace(/\//g,"").replace(/:/g,""),o=n&&encodeURIComponent(n);return"ios"===t?o?`${r}://wcV2?${o}`:`${r}://wcV2`:o?`${r}://wc?uri=${o}`:`${r}://wc`}})})();case"metamask_snap_leap":return F();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 r.isSnapInstalled()||await r.installSnap(),window.cosmos=new r.CosmosSnap,n=window.cosmos,!0},enable:async e=>{await r.isSnapInstalled()||await r.installSnap()},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,r)=>n.signAmino(e,t,r),getKey:async e=>void 0!==N[e]?N[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,r)=>n.signDirect(e,t,r),signArbitrary:async(e,t,r)=>n.signArbitrary(e,t,r),disable:async e=>{e&&await n.deleteChain(e)}};throw O.getState()._notFoundFn(),new Error("window.ethereum is not defined")})();case"station":return $();case"xdefi":return H();case"cosmiframe":return B();case"compass":return x();case"initia":return P();case"okx":return q();case"para":return U();case"cactuscosmos":return k();default:throw new Error("Unknown wallet type")}})(),t=O.getState().walletDefaultOptions;return t&&n.setDefaultOptions?.(t),n},Z=e=>"metamask_snap_leap"===e,ee=()=>Boolean(navigator?.userAgent)&&/LeapCosmos/i.test(navigator.userAgent),ne=e=>"walletconnect"===e||"wc_keplr_mobile"===e||"wc_leap_mobile"===e||"wc_cosmostation_mobile"===e,te=e=>"para"===e,re=async e=>{try{const{recentChainIds:n,chains:t,walletType:r}=O.getState(),o=e?.walletType||r;if(ne(o)){const e=J("walletconnect"),{disable:n}=e;n&&n()}if(!Y(o))throw new Error(`${o} is not available`);const i=J(o),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`)}),v.setState(e=>{const n=O.getState()._reconnect||Boolean(O.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}=v.getState();if(await(i.init?.()),await i.enable(a),!ne(o)){let e={};if(Z(o)){const n={};for await(const e of a)n[e]=await i.getKey(e);e=n}else if(ee()&&i.getKeys){const n=await i.getKeys(a);a.forEach((t,r)=>{const o=n[r];o&&(e[t]=o)})}else e=Object.fromEntries(await Promise.all(a.map(async e=>[e,await i.getKey(e)])));v.setState(n=>({accounts:{...n.accounts||{},...e}}))}O.setState(e=>({recentChainIds:[...e.recentChainIds||[],...a].filter((e,n,t)=>t.indexOf(e)===n)})),v.setState(e=>({activeChainIds:[...e.activeChainIds||[],...a].filter((e,n,t)=>t.indexOf(e)===n)})),O.setState({walletType:o,_reconnect:Boolean(e?.autoReconnect),_reconnectConnector:o}),v.setState({status:"connected"}),"undefined"!=typeof window&&window.sessionStorage.setItem(C,"Active");const l=a.map(e=>t.find(n=>n.chainId===e));return{accounts:v.getState().accounts,walletType:o,chains:l}}catch(e){throw console.error("connect ",e),null===v.getState().accounts&&v.setState({status:"disconnected"}),v.getState().accounts&&v.getState().activeChainIds&&v.setState({status:"connected"}),e}},oe=e=>{"undefined"!=typeof window&&window.sessionStorage.removeItem(C);const n="string"==typeof e?.chainId?[e.chainId]:e?.chainId,t=()=>{if(ne(O.getState().walletType)){const e=J("walletconnect"),{disable:n}=e;n&&n()}if(te(O.getState().walletType)){const e=J("para"),{disable:n}=e;n&&n()}};if(n){const e=v.getState().accounts;n.forEach(n=>{delete e?.[n]});0===Object.values(e||{}).length?(t(),v.setState(A),O.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})):(v.setState(t=>({activeChainIds:t.activeChainIds?.filter(e=>!n.includes(e)),accounts:e})),O.setState(e=>({recentChainIds:e.recentChainIds?.filter(e=>!n.includes(e))})))}else t(),v.setState(A),O.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null});return Promise.resolve()},ie=async e=>{const{recentChainIds:n,_reconnectConnector:t,_reconnect:r}=O.getState();try{const e=Y(t||void 0);if(n&&e&&t){if(ne(t))return;return await re({chainId:n,walletType:t,autoReconnect:r})}}catch(n){e?.onError?.(n),oe()}},ae=async e=>{if(!e?.chainId)throw new Error("chainId is required");const{walletType:n}=O.getState(),t=e.walletType||n;if(!Y(t))throw new Error(`${t} is not available`);const r=J(t);return{offlineSigner:r.getOfflineSigner(e.chainId),offlineSignerAmino:r.getOfflineSignerOnlyAmino(e.chainId),offlineSignerAuto:await r.getOfflineSignerAuto(e.chainId)}},se=()=>{O.setState({recentChainIds:null})},ce=async({chainInfo:e})=>{const{chains:n}=O.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 O.setState(n=>({chains:[...n.chains||[],e]})),e},le=async({chainInfo:e,walletType:n})=>{const t=J(n);await t.experimentalSuggestChain(e);const{chains:r}=O.getState(),o=r?.find(n=>n.chainId===e.chainId);return o||O.setState(n=>({chains:[...n.chains||[],e]})),e},de=async e=>{const n=O.getState().walletType;await le({chainInfo:e.chainInfo,walletType:e.walletType??n});return await re({chainId:e.chainInfo.chainId,walletType:e.walletType,autoReconnect:e.autoReconnect})},ue=e=>(O.setState(n=>{const t=n.chains??[],r=e.chains,o=new Map;r.forEach(e=>o.set(e.chainId,e)),t.forEach(e=>{o.has(e.chainId)||o.set(e.chainId,e)});const i=Array.from(o.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),ge=async({signingClient:e,senderAddress:n,recipientAddress:t,amount:r,fee:o,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,r,o,i)},we=async({signingClient:e,senderAddress:n,recipientAddress:t,transferAmount:r,sourcePort:o,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,r,o,i,a,s,c,l)},fe=async({signingClient:e,senderAddress:n,msg:t,fee:r,options:o,label:i,codeId:a})=>{if(!e)throw new Error("CosmWasm signing client is not ready");return e.instantiate(n,a,t,i,r,o)},he=async({signingClient:e,senderAddress:n,msg:t,fee:r,contractAddress:o,funds:i,memo:a})=>{if(!e)throw new Error("CosmWasm signing client is not ready");return e.execute(n,o,t,r,a,i)},pe=async(e,n,t)=>{if(!t)throw new Error("CosmWasm client is not ready");return await t.queryContractSmart(e,n)},me=(e,n,t)=>{if(!t)throw new Error("CosmWasm client is not ready");const r=(new TextEncoder).encode(n);return t.queryContractRaw(e,r)},ye=({chainId:e})=>{const n=O(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},Se=async(e,n)=>{const t=O.getState().multiChainFetchConcurrency,r=await S.default(e,n,{concurrency:t});return Object.fromEntries(r.map((n,t)=>[e[t].chainId,n]))};function Ce(e){const n=ye({chainId:e?.chainId}),t=u.useMemo(()=>["USE_STARGATE_CLIENT",n],[n]);return d.useQuery({queryKey:t,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");return await Se(n,async e=>{const n=O.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await f.StargateClient.connect(t)})},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}function Ie(e){const n=ye({chainId:e?.chainId}),t=u.useMemo(()=>["USE_COSMWASM_CLIENT",n],[n]);return d.useQuery({queryKey:t,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");return await Se(n,async e=>{const n=O.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await w.CosmWasmClient.connect(t)})},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}var be=e=>{const n=O(n=>e||n.walletType),t=["USE_CHECK_WALLET",n];return d.useQuery({queryKey:t,queryFn:()=>!!n&&Y(n)})};var Ee=()=>{const e=v(e=>e.activeChainIds),n=O(e=>e.chains);return e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean)};var Ae=({children:e})=>{const[n,t]=u.useState(!1);return u.useEffect(()=>{t(!0)},[]),p.jsx(p.Fragment,{children:n?e:null})},_e=()=>{const e="undefined"!=typeof window&&"Active"===window.sessionStorage.getItem(C),{_reconnect:n,_onReconnectFailed:r,_reconnectConnector:o,iframeOptions:i,chains:a,pingInterval:s}=O(),{activeChainIds:c,wcSignClients:l}=v(),d=Y(o||void 0);return u.useEffect(()=>{const n=async()=>{if(e&&d&&o&&c?.[0]){const e=v.getState().lastPing;if(e&&Date.now()-e<s)return;const n=J(o);try{if(!await n.getKey(c[0]))throw new Error("No account found");v.setState({lastPing:Date.now()})}catch(e){ie({onError:r})}}};return window.addEventListener("focus",n),()=>{window.removeEventListener("focus",n)}},[e,d,o,a,c,s]),u.useEffect(()=>{if(!i||!1===i.autoConnect||!i.allowedIframeParentOrigins.length||!a)return;new t.Cosmiframe(i.allowedIframeParentOrigins).isReady().then(e=>{if(e)return re({chainId:a.map(e=>e.chainId),walletType:"cosmiframe"})})},[i]),u.useEffect(()=>{if(o){if(!d)return;(e&&Boolean(c)||!e&&n)&&ie({onError:r})}},[d]),u.useEffect(()=>{if(o){if(!d)return;"cosmostation"===o&&T().subscription?.(()=>{ie({onError:r})}),"keplr"===o&&M().subscription?.(()=>{ie({onError:r})}),"leap"===o&&D().subscription?.(()=>{ie({onError:r})}),"compass"===o&&x().subscription?.(()=>{ie({onError:r})}),"vectis"===o&&W().subscription?.(()=>{ie({onError:r})}),"walletconnect"===o&&l.has("walletconnect")&&z().subscription?.(()=>{ie({onError:r})}),"station"===o&&$().subscription?.(()=>{ie({onError:r})}),"xdefi"===o&&H().subscription?.(()=>{ie({onError:r})}),"cosmiframe"===o&&B().subscription?.(()=>{ie({onError:r})}),"okx"===o&&q().subscription?.(()=>{ie({onError:r})})}},[o,l,d]),null},ve=()=>(_e(),null);exports.GrazEvents=ve,exports.GrazProvider=({children:e,grazOptions:n})=>(u.useEffect(()=>{ue(n)},[n]),p.jsxs(Ae,{children:[e,p.jsx(ve,{})]})),exports.WALLET_TYPES=b,exports.WalletType=I,exports.addChain=ce,exports.checkWallet=Y,exports.clearRecentChain=se,exports.clearSession=X,exports.configureGraz=ue,exports.connect=re,exports.defineChainInfo=e=>e,exports.defineChains=e=>e,exports.disconnect=oe,exports.executeContract=he,exports.getAvailableWallets=()=>Object.fromEntries(b.map(e=>[e,Y(e)])),exports.getCactusCosmos=k,exports.getChainInfo=({chainId:e}={})=>O.getState().chains?.find(n=>n.chainId===e),exports.getChainInfos=({chainId:e}={})=>{const n=O.getState().chains;return e?n?.filter(n=>e.includes(n.chainId)):n??void 0},exports.getCosmostation=T,exports.getKeplr=M,exports.getLeap=D,exports.getMetamaskSnapLeap=F,exports.getOfflineSigners=ae,exports.getOkx=q,exports.getPara=U,exports.getQueryRaw=me,exports.getQuerySmart=pe,exports.getRecentChainIds=()=>O.getState().recentChainIds,exports.getRecentChains=()=>{const{recentChainIds:e,chains:n}=O.getState();return e?.map(e=>n.find(n=>n.chainId===e))??null},exports.getVectis=W,exports.getWCCosmostation=G,exports.getWCKeplr=Q,exports.getWCLeap=V,exports.getWallet=J,exports.getWalletConnect=z,exports.instantiateContract=fe,exports.isLeapDappBrowser=ee,exports.isLeapSnaps=Z,exports.isPara=te,exports.isWalletConnect=ne,exports.reconnect=ie,exports.sendIbcTokens=we,exports.sendTokens=ge,exports.suggestChain=le,exports.suggestChainAndConnect=de,exports.useAccount=function(e){const n=O(e=>e.walletType),t=v(e=>e.activeChainIds),r=ye({chainId:e?.chainId?e.chainId:t||void 0}),o=v(e=>e.accounts),i=v(e=>e.status);return u.useEffect(()=>v.subscribe(e=>e.status,(n,t)=>{if("connected"===n){const{accounts:n,activeChainIds:r}=v.getState(),{chains:o}=O.getState(),{walletType:i}=O.getState();if(!n||!r||!o)return e?.onDisconnect?.();e?.onConnect?.({accounts:n,chains:r.map(e=>o.find(n=>n.chainId===e)),walletType:i,isReconnect:"reconnecting"===t})}"disconnected"===n&&e?.onDisconnect?.()}),[e]),{data:u.useMemo(()=>o?((e,n)=>{const t=e.map(n);return Object.fromEntries(t.map((n,t)=>[e[t].chainId,n]))})(r,e=>o[e.chainId]):void 0,[o,r]),isConnected:"connected"===i,isConnecting:"connecting"===i,isDisconnected:"disconnected"===i,isReconnecting:"reconnecting"===i,isLoading:"connecting"===i||"reconnecting"===i,walletType:"connected"===i?n:void 0,reconnect:ie,status:i}},exports.useActiveChainCurrency=({denom:e})=>{const n=Ee(),t=["USE_ACTIVE_CHAIN_CURRENCY",e];return d.useQuery({queryKey:t,queryFn:({queryKey:[,e]})=>n?.find(n=>n.currencies.find(n=>n.coinMinimalDenom===e))?.currencies.find(e=>e)})},exports.useActiveChainIds=()=>v(e=>e.activeChainIds),exports.useActiveChains=Ee,exports.useActiveWalletType=()=>O(h.useShallow(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}))),exports.useAddChain=({onError:e,onLoading:n,onSuccess:t}={})=>{const r=["USE_ADD_CHAIN",e,n,t],o=d.useMutation({mutationKey:r,mutationFn:ce,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}},exports.useBalance=e=>{const n=ye({chainId:[e.chainId]})[0],{data:t}=Ce({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),r=t?.[e.chainId],o=u.useMemo(()=>["USE_BALANCE",r,e.chainId,e.bech32Address,e.denom],[e.bech32Address,e.chainId,e.denom,r]);return d.useQuery({queryKey:o,queryFn:async()=>{if(!r)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 r.getBalance(e.bech32Address,e.denom);return"0"===t.amount?void 0:t},enabled:Boolean(r)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},exports.useBalanceStaked=e=>{const n=ye({chainId:[e.chainId]})[0],{data:t}=Ce({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),r=t?.[e.chainId],o=u.useMemo(()=>["USE_BALANCE_STAKED",r,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,r]);return d.useQuery({queryKey:o,queryFn:async()=>{if(!r)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 r.getBalanceStaked(e.bech32Address)},enabled:Boolean(r)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},exports.useBalances=e=>{const n=ye({chainId:[e.chainId]})[0],{data:t}=Ce({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),r=t?.[e.chainId],o=u.useMemo(()=>["USE_ALL_BALANCES",r,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,r]);return d.useQuery({queryKey:o,queryFn:async()=>{if(!r)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 r.getAllBalances(e.bech32Address)},enabled:Boolean(r)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},exports.useChainInfo=({chainId:e}={})=>O(e=>e.chains)?.find(n=>n.chainId===e),exports.useChainInfos=({chainId:e}={})=>{const n=O(e=>e.chains);return e?n?.filter(n=>e.includes(n.chainId)):n},exports.useCheckWallet=be,exports.useConnect=({onError:e,onLoading:n,onSuccess:t}={})=>{const r=["USE_CONNECT",e,n,t],o=d.useMutation({mutationKey:r,mutationFn:re,onError:(n,t)=>e?.(n,t),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))}),{data:i}=be();return{connect:e=>o.mutate(e),connectAsync:e=>o.mutateAsync(e),error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,isSupported:Boolean(i),status:o.status}},exports.useCosmWasmClient=Ie,exports.useCosmWasmSigningClient=function(e){const n=ye({chainId:e?.chainId}),t=O(e=>e.walletType),r=v(e=>e.activeChainIds),o="connected"===v.getState().status&&v.getState().accounts&&O.getState()._reconnectConnector===t,i=u.useMemo(()=>["USE_COSMWASM_SIGNING_CLIENT",n,t,e,r],[r,e,n,t]);return d.useQuery({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 Se(n,async n=>{if(!r?.includes(n.chainId))return null;if(!Y(t))throw new Error(`${t} is not available`);const o=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return J(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return J(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return J(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=O.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}},s=i?.gas?f.GasPrice.fromString(`${i.gas.price}${i.gas.denom}`):void 0;return await w.SigningCosmWasmClient.connectWithSigner(a,o,{gasPrice:s,...e?.opts?.[n.chainId]||{}})})},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(o),refetchOnWindowFocus:!1})},exports.useDisconnect=({onError:e,onLoading:n,onSuccess:t}={})=>{const r=["USE_DISCONNECT",e,n,t],o=d.useMutation({mutationKey:r,mutationFn:oe,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}},exports.useExecuteContract=({contractAddress:e,onError:n,onLoading:t,onSuccess:r})=>{const{mutate:o,mutateAsync:i,...a}=d.useMutation({mutationKey:["USE_EXECUTE_CONTRACT",n,t,r,e],mutationFn:n=>he({...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(r?.(e))});return{...a,executeContract:o,executeContractAsync:i}},exports.useGrazEvents=_e,exports.useInstantiateContract=({codeId:e,onError:n,onLoading:t,onSuccess:r})=>{const{mutate:o,mutateAsync:i,...a}=d.useMutation({mutationKey:["USE_INSTANTIATE_CONTRACT",n,t,r,e],mutationFn:n=>fe({...n,fee:n.fee??"auto",codeId:e}),onError:(e,t)=>Promise.resolve(n?.(e,t)),onMutate:t,onSuccess:e=>Promise.resolve(r?.(e))});return{...a,instantiateContract:o,instantiateContractAsync:i}},exports.useOfflineSigners=function(e){const n=ye({chainId:e?.chainId}),t=O(e=>e.walletType),r="connected"===v.getState().status&&v.getState().accounts&&O.getState()._reconnectConnector===t,o=u.useMemo(()=>["USE_OFFLINE_SIGNERS",n,t],[n,t]);return d.useQuery({queryKey:o,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chain found");if(!t)throw new Error("Wallet is not defined");if(!Y(t))throw new Error(`${t} is not available`);return await Se(n,async e=>await ae({chainId:e.chainId,walletType:t}))},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&Boolean(r),refetchOnWindowFocus:!1})},exports.useQueryClientValidators=e=>{const n=e.status??"BOND_STATUS_BONDED",t=["USE_ACTIVE_CHAIN_VALIDATORS",e.queryClient,n];return d.useQuery({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})},exports.useQueryRaw=e=>{const{data:n}=Ie(),t=n&&Object.values(n)[0],r=["USE_QUERY_RAW",e?.key,e?.address,t];return d.useQuery({queryKey:r,queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.key)throw new Error("address or key undefined");return me(e.address,e.key,t)},enabled:Boolean(e?.address)&&Boolean(e?.key)&&Boolean(t)})},exports.useQuerySmart=e=>{const{data:n}=Ie(),t=n&&Object.values(n)[0];return d.useQuery({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 pe(e.address,e.queryMsg,t)},enabled:Boolean(e?.address)&&Boolean(e?.queryMsg)&&Boolean(t)})},exports.useRecentChainIds=()=>({data:O(e=>e.recentChainIds),clear:se}),exports.useRecentChains=()=>{const e=O(e=>e.recentChainIds),n=O(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:se}},exports.useSendIbcTokens=({onError:e,onLoading:n,onSuccess:t}={})=>{const{mutate:r,mutateAsync:o,...i}=d.useMutation({mutationKey:["USE_SEND_IBC_TOKENS",e,n,t],mutationFn:we,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))});return{...i,sendIbcTokens:r,sendIbcTokensAsync:o}},exports.useSendTokens=({onError:e,onLoading:n,onSuccess:t}={})=>{const{mutate:r,mutateAsync:o,...i}=d.useMutation({mutationKey:["USE_SEND_TOKENS",e,n,t],mutationFn:ge,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))});return{...i,sendTokens:r,sendTokensAsync:o}},exports.useStargateClient=Ce,exports.useStargateSigningClient=function(e){const n=ye({chainId:e?.chainId}),t=O(e=>e.walletType),r=v(e=>e.activeChainIds),o="connected"===v.getState().status&&v.getState().accounts&&O.getState()._reconnectConnector===t,i=u.useMemo(()=>["USE_STARGATE_SIGNING_CLIENT",n,t,e,r],[r,e,n,t]);return d.useQuery({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 Se(n,async n=>{if(!r?.includes(n.chainId))return null;if(!Y(t))throw new Error(`${t} is not available`);const o=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return J(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return J(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return J(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=O.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}};return await f.SigningStargateClient.connectWithSigner(a,o,e?.opts?.[n.chainId])})},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(o),refetchOnWindowFocus:!1})},exports.useSuggestChain=({onError:e,onLoading:n,onSuccess:t}={})=>{const r=["USE_SUGGEST_CHAIN",e,n,t],o=d.useMutation({mutationKey:r,mutationFn:le,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}},exports.useSuggestChainAndConnect=({onError:e,onLoading:n,onSuccess:t}={})=>{const r=["USE_SUGGEST_CHAIN_AND_CONNECT",e,n,t],o=d.useMutation({mutationKey:r,mutationFn:de,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:e=>n?.(e),onSuccess:e=>Promise.resolve(t?.(e))}),{data:i}=be();return{error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,isSupported:Boolean(i),status:o.status,suggestAndConnect:o.mutate,suggestAndConnectAsync:o.mutateAsync}};
|
|
1
|
+
"use strict";var e=require("zustand"),n=require("zustand/middleware"),t=require("@dao-dao/cosmiframe"),o=require("@cosmsnap/snapper"),r=require("@cosmjs/amino"),i=require("long"),a=require("@cosmjs/encoding"),s=require("@walletconnect/modal"),c=require("@walletconnect/sign-client"),l=require("@walletconnect/utils"),d=require("@tanstack/react-query"),u=require("react"),g=require("p-map"),h=require("@cosmjs/cosmwasm-stargate"),f=require("@cosmjs/stargate"),w=require("zustand/shallow"),m=require("react/jsx-runtime");function p(e){return e&&e.__esModule?e:{default:e}}var C,y=p(i),S=p(g),b=Object.defineProperty,I=(e,n,t)=>((e,n,t)=>n in e?b(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t)(e,"symbol"!=typeof n?n+"":n,t),E="connect-graz",A={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"},_=(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))(_||{}),v=["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"],O={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},k={accounts:null,activeChainIds:null,status:"disconnected",lastPing:null,wcSignClients:new Map,paraConnector:null},T={name:"graz-session",version:2,partialize:e=>({accounts:e.accounts,activeChainIds:e.activeChainIds,lastPing:e.lastPing,status:e.status}),storage:n.createJSONStorage(()=>sessionStorage)},N=e.create(n.subscribeWithSelector(n.persist(()=>k,T))),x=e.create(n.subscribeWithSelector(n.persist(()=>O,{name:"graz-internal",partialize:e=>({recentChainIds:e.recentChainIds,_reconnect:e._reconnect,_reconnectConnector:e._reconnectConnector,walletType:e.walletType,chains:e.chains}),version:3}))),B=(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))(B||{}),L=(e=>(e.WALLET="wallet",e.TRANSACTION="transaction",e.QUERY="query",e.STORE="store",e.MULTICHAIN="multichain",e.EVENT="event",e.PERFORMANCE="performance",e))(L||{}),R=class{constructor(e){I(this,"level"),I(this,"categories"),I(this,"enabled"),I(this,"timers"),I(this,"errorReporter"),I(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;"}),I(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;"}),I(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;"}),I(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}},D=()=>(C||(C=new R),C),P=e=>{C=new R(e)},q=()=>{if(void 0!==window.cactuslink_cosmos){const e=window.cactuslink_cosmos,n=e=>{const n=()=>{ae(),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 x.getState()._notFoundFn(),new Error("window.cactuslink_cosmos is not defined")},F=()=>{if(void 0!==window.compass){const e=window.compass,n=e=>{const n=()=>{ae(),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 x.getState()._notFoundFn(),new Error("window.leap is not defined")},M=()=>{const e=x.getState();if(!e.iframeOptions)throw e._notFoundFn(),new Error("no iframe options set");if(!t.isInIframe())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 t.Cosmiframe(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)}},U={},W=()=>{if(void 0!==window.cosmostation?.providers.keplr){const e=window.cosmostation.providers.keplr,n=e=>{const n=()=>{ae(),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 x.getState()._notFoundFn(),new Error("window.cosmostation.providers.keplr is not defined")},K=()=>{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 i=(()=>{switch(o.algo){case"secp256k1":return r.rawSecp256k1PubkeyToRawAddress(o.pubkey);case"ed25519":return r.rawEd25519PubkeyToRawAddress(o.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{name:(a=o.address,`${a.slice(0,6)}...${a.slice(-6)}`),algo:o.algo,pubKey:o.pubkey,bech32Address:o.address,address:i,isNanoLedger:!1,isKeystone:!1};var a},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 i=e.getOfflineSigner(n),a=(await i.getAccounts()).find(e=>e.address===t);if(!a)throw new Error(`Wallet not connected to account ${t}`);const s=(()=>{switch(a.algo){case"secp256k1":return r.encodeSecp256k1Pubkey(a.pubkey);case"ed25519":return r.encodeEd25519Pubkey(a.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{signature:await e.signArbitrary(o),pub_key:{type:"secp256k1"===a.algo?r.pubkeyType.secp256k1:r.pubkeyType.ed25519,value:s.value}}},subscription:e=>{const n=()=>{ae(),e()};return window.addEventListener("initia_keystorechange",n),()=>{window.removeEventListener("initia_keystorechange",n)}}}}throw x.getState()._notFoundFn(),new Error("window.initia is not defined")},$=()=>{if(void 0!==window.keplr){const e=window.keplr,n=e=>{const n=()=>{ae(),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 x.getState()._notFoundFn(),new Error("window.keplr is not defined")},j=()=>{if(void 0!==window.leap){const e=window.leap,n=e=>{const n=()=>{ae(),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 x.getState()._notFoundFn(),new Error("window.leap is not defined")},G={},H=()=>(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 y.default(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!==G[t])return G[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,G[t]=o,G[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:y.default.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 x.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=()=>{ae(),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 x.getState()._notFoundFn(),new Error("window.okxwallet.keplr is not defined")},z=null,V=()=>{const e=()=>{const e=N.getState().paraConnector;if(!e)throw new Error("Para connector not initialized. Call connect() first or check paraConfig in GrazProvider.");return e},n=x.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(z||(z=(async()=>{const e=N.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=x.getState().chains,t=new n.connectorClass(n,e);if(!t)throw new Error("Para connector initialization failed. Check config and dependencies.");return N.setState(e=>({...e,paraConnector:t})),t}catch(e){throw z=null,new Error(`Para connector init failed: ${e?.message||"Unknown error"}. Check ParaConfig and connectorClass.`)}})()));N.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)])));N.setState(e=>({accounts:{...e.accounts||{},...o},activeChainIds:Array.from(new Set([...e.activeChainIds||[],...t])),status:"connected"})),x.setState(e=>({recentChainIds:Array.from(new Set([...e.recentChainIds||[],...t])),walletType:"para",_reconnect:!1,_reconnectConnector:"para"}))}catch(e){throw N.setState({paraConnector:null,status:"disconnected"}),new Error("Para enable failed"+(e instanceof Error?`: ${e.message}`:""))}},disable:async()=>{const e=N.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{N.setState({paraConnector:null,status:"disconnected"})}else N.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.")}}},Y=()=>{if(void 0!==window.station?.keplr){const e=window.station.keplr;return{subscription:e=>{const n=()=>{ae(),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 x.getState()._notFoundFn(),new Error("window.station is not defined")},X=()=>{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:y.default.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:y.default.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:a.fromBech32(t.address).data,algo:t.algo,bech32Address:t.address,name:t.name,pubKey:t.pubKey,isKeystone:!1,isNanoLedger:t.isNanoLedger}},subscription:e=>{const n=()=>{ae(),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:y.default.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 x.getState()._notFoundFn(),new Error("window.vectis is not defined")},J=()=>{if("undefined"!=typeof window){const e=navigator.userAgent;return!!/android/i.test(e)||!!/iPad|iPhone|iPod/.test(e)}return!1},Z=(e,n,t=new Error("Promise timed out"))=>{const o=new Promise((e,o)=>{setTimeout(()=>{o(t)},n)});return Promise.race([e,o])},ee=e=>{if(!x.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(J()){if(J()&&navigator.userAgent.toLowerCase().includes("android")){const e=o(t.mobile.android,n,"android");window.open(e,"_self","noreferrer noopener")}if(J()&&(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}=N.getState();if(!e.get(n))throw new Error("walletConnect.signClient is not defined");e.delete(n),N.setState({wcSignClients:e}),x.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})},i=async e=>{const{wcSignClients:t}=N.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:l.getSdkError("USER_DISCONNECTED")}),await d(o)},a=e=>{try{const{wcSignClients:t}=N.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}},d=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}},u=async t=>{const r="string"==typeof t?[t]:t,{wcSignClients:c,activeChainIds:l}=N.getState(),d=c.get(n);if(!d)throw new Error("enable walletConnect.signClient is not defined");const{walletConnect:u}=x.getState();if(!u?.options?.projectId)throw new Error("walletConnect.options.projectId is not defined");const g=new s.WalletConnectModal({projectId:u.options.projectId,enableExplorer:!1,explorerRecommendedWalletIds:"NONE",...u.walletConnectModal}),f=(e=>{try{return a(e)}catch(e){return}})(r);if(!f){const{uri:n,approval:t}=await Z(d.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}}),N.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 Z((async()=>{const e=Object.fromEntries(await Promise.all((l||r).map(async e=>[e,await h(e)])));N.setState({accounts:e})})(),15e3,new Error("Connection timeout"))}catch(e){if(i(f.topic),!e.message.toLowerCase().includes("no matching key"))throw e}},g=async e=>{const n=await h(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},h=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)}},f=async(...e)=>{const[r,i,s]=e,{signature:c,signed:l}=await(async(...e)=>{const[r,i,s]=e,{accounts:c,wcSignClients:l}=N.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}},w=async(...e)=>{const[t,r,i,s]=e,c=await(async(...e)=>{const[t,r,i,s]=e,{wcSignClients:c}=N.getState(),l=c.get(n),{accounts:d}=N.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},m=e=>({getAccounts:async()=>[await g(e)],signAmino:(n,t)=>w(e,n,t)});return{enable:u,disable:async e=>{const{wcSignClients:t}=N.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:h,getOfflineSigner:e=>({getAccounts:async()=>[await g(e)],signDirect:(n,t)=>f(e,n,t),signAmino:(n,t)=>w(e,n,t)}),getOfflineSignerAuto:async e=>(await h(e)).isNanoLedger?m(e):(e=>({getAccounts:async()=>[await g(e)],signDirect:(n,t)=>f(e,n,t)}))(e),getOfflineSignerOnlyAmino:m,signAmino:w,signDirect:f,subscription:e=>{const{wcSignClients:t}=N.getState(),o=t.get(n);if(!o)return()=>{};const i=n=>{const t=N.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&&u([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}=x.getState();if(!e?.options)throw new Error("walletConnect.options is not defined");const{wcSignClients:t}=N.getState(),o=t.get(n);if(o)return o;const r=await c.SignClient.init(e.options);return t.set(n,r),N.setState({wcSignClients:t}),r}}},ne=()=>{if(!x.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!J())throw new Error("WalletConnect Cosmostation mobile is only supported in mobile");return ee({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`}})},te=()=>{if(!x.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!J())throw new Error("WalletConnect Keplr mobile is only supported in mobile");return ee({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`}}})},oe=()=>{if(!x.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!J())throw new Error("WalletConnect Leap mobile is only supported in mobile");return ee({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`}}})},re=()=>{if(void 0!==window.xfi?.keplr){const e=window.xfi.keplr,n=e=>{const n=()=>{ae(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}};return Object.assign(e,{subscription:n})}throw x.getState()._notFoundFn(),new Error("window.xfi.keplr is not defined")},ie=(e=x.getState().walletType)=>{try{return se(e),!0}catch(e){return!1}},ae=()=>{window.sessionStorage.removeItem(E),N.setState(k)},se=(e=x.getState().walletType)=>{const n=D();n.debug("wallet","Getting wallet adapter",{function:"getWallet",walletType:e});const t=(()=>{switch(e){case"keplr":return $();case"leap":return j();case"cosmostation":return W();case"vectis":return X();case"walletconnect":return ee();case"wc_keplr_mobile":return te();case"wc_leap_mobile":return oe();case"wc_cosmostation_mobile":return ne();case"wc_clot_mobile":return(()=>{if(!x.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!J())throw new Error("WalletConnect Clot mobile is only supported in mobile");return ee({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 H();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 r=t.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(r)>=11))throw new Error("Metamask Snap is not supported in this version");return await o.isSnapInstalled()||await o.installSnap(),window.cosmos=new o.CosmosSnap,n=window.cosmos,!0},enable:async e=>{await o.isSnapInstalled()||await o.installSnap()},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!==U[e]?U[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 x.getState()._notFoundFn(),new Error("window.ethereum is not defined")})();case"station":return Y();case"xdefi":return re();case"cosmiframe":return M();case"compass":return F();case"initia":return K();case"okx":return Q();case"para":return V();case"cactuscosmos":return q();default:throw n.warn("wallet","Unknown wallet type",{function:"getWallet",walletType:e}),new Error("Unknown wallet type")}})(),r=x.getState().walletDefaultOptions;return r&&t.setDefaultOptions?.(r),t},ce=e=>"metamask_snap_leap"===e,le=()=>Boolean(navigator?.userAgent)&&/LeapCosmos/i.test(navigator.userAgent),de=e=>"walletconnect"===e||"wc_keplr_mobile"===e||"wc_leap_mobile"===e||"wc_cosmostation_mobile"===e,ue=e=>"para"===e,ge=async e=>{const n=D();n.time("connect"),n.group("Connect Wallet");try{const{recentChainIds:t,chains:o,walletType:r}=x.getState(),i=e?.walletType||r;if(n.debug("wallet","Starting connection",{function:"connect",walletType:i,chainId:e?.chainId,timestamp:Date.now()}),de(i)){const e=se("walletconnect"),{disable:n}=e;n&&n()}if(!ie(i))throw n.warn("wallet","Wallet not available",{function:A.CONNECT,walletType:i}),new Error(`${i} is not available`);n.debug("wallet","Wallet adapter retrieved",{function:A.CONNECT,walletType:i});const a=se(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`)}),N.setState(e=>{const n=x.getState()._reconnect||Boolean(x.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:A.CONNECT}),await(a.init?.()),n.debug("wallet","Enabling chains",{function:A.CONNECT,chainIds:s,chainCount:s.length}),await a.enable(s),n.debug("wallet","Fetching accounts",{function:A.CONNECT}),!de(i)){let e={};if(ce(i)){const n={};for await(const e of s)n[e]=await a.getKey(e);e=n}else if(le()&&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)])));N.setState(n=>({accounts:{...n.accounts||{},...e}}))}x.setState(e=>({recentChainIds:[...e.recentChainIds||[],...s].filter((e,n,t)=>t.indexOf(e)===n)})),N.setState(e=>({activeChainIds:[...e.activeChainIds||[],...s].filter((e,n,t)=>t.indexOf(e)===n)})),x.setState({walletType:i,_reconnect:Boolean(e?.autoReconnect),_reconnectConnector:i}),N.setState({status:"connected"}),"undefined"!=typeof window&&window.sessionStorage.setItem(E,"Active");const l=s.map(e=>o.find(n=>n.chainId===e)),d=N.getState().accounts;return n.info("wallet","Connection successful",{function:A.CONNECT,walletType:i,chainCount:s.length,chainIds:s,addresses:d?Object.values(d).map(e=>e.bech32Address):[]}),n.debug("store","Session store updated",{function:A.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:A.CONNECT,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,walletType:e?.walletType,chainId:e?.chainId}),null===N.getState().accounts&&N.setState({status:"disconnected"}),N.getState().accounts&&N.getState().activeChainIds&&N.setState({status:"connected"}),n.timeEnd("connect"),n.groupEnd(),t}},he=e=>{const n=D(),t="string"==typeof e?.chainId?[e.chainId]:e?.chainId;n.info("wallet","Disconnecting",{function:A.DISCONNECT,chainId:t||"all chains"}),"undefined"!=typeof window&&window.sessionStorage.removeItem(E);const o=()=>{if(de(x.getState().walletType)){const e=se("walletconnect"),{disable:n}=e;n&&n()}if(ue(x.getState().walletType)){const e=se("para"),{disable:n}=e;n&&n()}};if(t){const e=N.getState().accounts;t.forEach(n=>{delete e?.[n]});0===Object.values(e||{}).length?(o(),N.setState(k),x.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null}),n.debug("store","Session cleared - all chains disconnected",{function:A.DISCONNECT})):(N.setState(n=>({activeChainIds:n.activeChainIds?.filter(e=>!t.includes(e)),accounts:e})),x.setState(e=>({recentChainIds:e.recentChainIds?.filter(e=>!t.includes(e))})),n.debug("store","Partial disconnect - some chains remain connected",{function:A.DISCONNECT}))}else o(),N.setState(k),x.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null}),n.debug("store","Session cleared - disconnected from all chains",{function:A.DISCONNECT});return n.info("wallet","Disconnected successfully",{function:A.DISCONNECT,chainId:t||"all chains"}),Promise.resolve()},fe=async e=>{const n=D(),{recentChainIds:t,_reconnectConnector:o,_reconnect:r}=x.getState();n.debug("wallet","Attempting reconnection",{function:A.RECONNECT,recentChains:t,walletType:o});try{const e=ie(o||void 0);if(t&&e&&o){if(de(o))return;const e=await ge({chainId:t,walletType:o,autoReconnect:r});return n.info("wallet","Reconnection successful",{function:A.RECONNECT}),e}n.warn("wallet","Reconnection skipped",{function:A.RECONNECT,hasRecentChains:Boolean(t),isWalletReady:e,hasConnector:Boolean(o)})}catch(t){n.warn("wallet","Reconnection failed",{function:A.RECONNECT,error:t instanceof Error?t.message:String(t)}),e?.onError?.(t),he()}},we=async e=>{if(!e?.chainId)throw new Error("chainId is required");const{walletType:n}=x.getState(),t=e.walletType||n;if(!ie(t))throw new Error(`${t} is not available`);const o=se(t);return{offlineSigner:o.getOfflineSigner(e.chainId),offlineSignerAmino:o.getOfflineSignerOnlyAmino(e.chainId),offlineSignerAuto:await o.getOfflineSignerAuto(e.chainId)}},me=()=>{D().debug("store","Clearing recent chains",{function:"clearRecentChain"}),x.setState({recentChainIds:null})},pe=async({chainInfo:e})=>{const n=D();n.debug("store","Adding chain",{function:"addChain",chainId:e.chainId,chainName:e.chainName});const{chains:t}=x.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 x.setState(n=>({chains:[...n.chains||[],e]})),n.info("store","Chain added successfully",{function:"addChain",chainId:e.chainId,chainName:e.chainName}),e},Ce=async({chainInfo:e,walletType:n})=>{const t=D();t.debug("wallet","Suggesting chain to wallet",{function:"suggestChain",chainId:e.chainId,chainName:e.chainName,walletType:n});try{const o=se(n);await o.experimentalSuggestChain(e);const{chains:r}=x.getState(),i=r?.find(n=>n.chainId===e.chainId);return i||(x.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}},ye=async e=>{const n=D(),t=x.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 Ce({chainInfo:e.chainInfo,walletType:o});const t=await ge({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}},Se=e=>(P({enabled:e.logger?.enabled??!1,level:e.logger?.level,categories:e.logger?.categories}),x.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),be=async({signingClient:e,senderAddress:n,recipientAddress:t,amount:o,fee:r,memo:i})=>{const a=D();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}},Ie=async({signingClient:e,senderAddress:n,recipientAddress:t,transferAmount:o,sourcePort:r,sourceChannel:i,timeoutHeight:a,timeoutTimestamp:s,fee:c,memo:l})=>{const d=D();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}},Ee=async({signingClient:e,senderAddress:n,msg:t,fee:o,options:r,label:i,codeId:a})=>{const s=D();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}},Ae=async({signingClient:e,senderAddress:n,msg:t,fee:o,contractAddress:r,funds:i,memo:a})=>{const s=D();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}},_e=async(e,n,t)=>{const o=D();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}},ve=async(e,n,t)=>{const o=D();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}},Oe=({chainId:e})=>{const n=x(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},ke=async(e,n,t)=>{const o=D(),r=x.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 S.default(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 Te(e){const n=Oe({chainId:e?.chainId}),t=u.useMemo(()=>["USE_STARGATE_CLIENT",n],[n]);return d.useQuery({queryKey:t,queryFn:async()=>{const e=D();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 ke(n,async e=>{const n=x.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await f.StargateClient.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 Ne(e){const n=Oe({chainId:e?.chainId}),t=u.useMemo(()=>["USE_COSMWASM_CLIENT",n],[n]);return d.useQuery({queryKey:t,queryFn:async()=>{const e=D();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 ke(n,async e=>{const n=x.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await h.CosmWasmClient.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 xe=e=>{const n=x(n=>e||n.walletType),t=["USE_CHECK_WALLET",n];return d.useQuery({queryKey:t,queryFn:()=>{const e=D();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=ie(n);return e.debug("wallet","Wallet check completed",{hook:"useCheckWallet",walletType:n,isAvailable:t}),t}})};var Be=()=>{const e=N(e=>e.activeChainIds),n=x(e=>e.chains);return e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean)};var Le=({children:e})=>{const[n,t]=u.useState(!1);return u.useEffect(()=>{t(!0)},[]),m.jsx(m.Fragment,{children:n?e:null})},Re=()=>{const e=D(),n="undefined"!=typeof window&&"Active"===window.sessionStorage.getItem(E),{_reconnect:o,_onReconnectFailed:r,_reconnectConnector:i,iframeOptions:a,chains:s,pingInterval:c}=x(),{activeChainIds:l,wcSignClients:d}=N(),g=ie(i||void 0);return u.useEffect(()=>{const t=async()=>{if(n&&g&&i&&l?.[0]){const n=N.getState().lastPing;if(n&&Date.now()-n<c)return;const t=se(i);try{if(!await t.getKey(l[0]))throw new Error("No account found");N.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}),fe({onError:r})}}};return window.addEventListener("focus",t),()=>{window.removeEventListener("focus",t)}},[n,g,i,s,l,c]),u.useEffect(()=>{if(!a||!1===a.autoConnect||!a.allowedIframeParentOrigins.length||!s)return;new t.Cosmiframe(a.allowedIframeParentOrigins).isReady().then(n=>{if(n)return e.info("event","Auto-connecting to iframe wallet",{function:"autoConnectIframe"}),ge({chainId:s.map(e=>e.chainId),walletType:"cosmiframe"})})},[a]),u.useEffect(()=>{if(i){if(!g)return;n&&Boolean(l)?(e.info("event","Reconnection triggered",{function:"reconnectEffect",reason:"session active"}),fe({onError:r})):!n&&o&&(e.info("event","Reconnection triggered",{function:"reconnectEffect",reason:"auto-reconnect enabled"}),fe({onError:r}))}},[g]),u.useEffect(()=>{if(i){if(!g)return;"cosmostation"===i&&W().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"cosmostation"}),fe({onError:r})}),"keplr"===i&&$().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"keplr"}),fe({onError:r})}),"leap"===i&&j().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"leap"}),fe({onError:r})}),"compass"===i&&F().subscription?.(()=>{fe({onError:r})}),"vectis"===i&&X().subscription?.(()=>{fe({onError:r})}),"walletconnect"===i&&d.has("walletconnect")&&ee().subscription?.(()=>{fe({onError:r})}),"station"===i&&Y().subscription?.(()=>{fe({onError:r})}),"xdefi"===i&&re().subscription?.(()=>{fe({onError:r})}),"cosmiframe"===i&&M().subscription?.(()=>{fe({onError:r})}),"okx"===i&&Q().subscription?.(()=>{fe({onError:r})})}},[i,d,g]),null},De=()=>(Re(),null);exports.GrazEvents=De,exports.GrazProvider=({children:e,grazOptions:n})=>(u.useEffect(()=>{Se(n)},[n]),m.jsxs(Le,{children:[e,m.jsx(De,{})]})),exports.LOG_CATEGORIES={WALLET:"wallet",TRANSACTION:"transaction",QUERY:"query",STORE:"store",MULTICHAIN:"multichain",EVENT:"event",PERFORMANCE:"performance"},exports.LOG_FUNCTIONS=A,exports.LOG_HOOKS={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"},exports.LogCategory=L,exports.LogLevel=B,exports.WALLET_TYPES=v,exports.WalletType=_,exports.addChain=pe,exports.checkWallet=ie,exports.clearRecentChain=me,exports.clearSession=ae,exports.configureGraz=Se,exports.configureLogger=P,exports.connect=ge,exports.defineChainInfo=e=>e,exports.defineChains=e=>e,exports.disconnect=he,exports.executeContract=Ae,exports.getAvailableWallets=()=>Object.fromEntries(v.map(e=>[e,ie(e)])),exports.getCactusCosmos=q,exports.getChainInfo=({chainId:e}={})=>{const n=D(),t=x.getState().chains?.find(n=>n.chainId===e);return n.debug("store","Getting chain info",{function:"getChainInfo",chainId:e,found:Boolean(t)}),t},exports.getChainInfos=({chainId:e}={})=>{const n=D(),t=x.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},exports.getCosmostation=W,exports.getKeplr=$,exports.getLeap=j,exports.getLogger=D,exports.getMetamaskSnapLeap=H,exports.getOfflineSigners=we,exports.getOkx=Q,exports.getPara=V,exports.getQueryRaw=ve,exports.getQuerySmart=_e,exports.getRecentChainIds=()=>{const e=D(),n=x.getState().recentChainIds;return e.debug("store","Getting recent chain IDs",{function:"getRecentChainIds",chainIds:n}),n},exports.getRecentChains=()=>{const e=D(),{recentChainIds:n,chains:t}=x.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},exports.getVectis=X,exports.getWCCosmostation=ne,exports.getWCKeplr=te,exports.getWCLeap=oe,exports.getWallet=se,exports.getWalletConnect=ee,exports.instantiateContract=Ee,exports.isLeapDappBrowser=le,exports.isLeapSnaps=ce,exports.isPara=ue,exports.isWalletConnect=de,exports.reconnect=fe,exports.sendIbcTokens=Ie,exports.sendTokens=be,exports.suggestChain=Ce,exports.suggestChainAndConnect=ye,exports.useAccount=function(e){const n=x(e=>e.walletType),t=N(e=>e.activeChainIds),o=Oe({chainId:e?.chainId?e.chainId:t||void 0}),r=N(e=>e.accounts),i=N(e=>e.status);return u.useEffect(()=>N.subscribe(e=>e.status,(n,t)=>{if("connected"===n){const{accounts:n,activeChainIds:o}=N.getState(),{chains:r}=x.getState(),{walletType:i}=x.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]),{data:u.useMemo(()=>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:fe,status:i}},exports.useActiveChainCurrency=({denom:e})=>{const n=Be(),t=["USE_ACTIVE_CHAIN_CURRENCY",e];return d.useQuery({queryKey:t,queryFn:({queryKey:[,e]})=>n?.find(n=>n.currencies.find(n=>n.coinMinimalDenom===e))?.currencies.find(e=>e)})},exports.useActiveChainIds=()=>N(e=>e.activeChainIds),exports.useActiveChains=Be,exports.useActiveWalletType=()=>x(w.useShallow(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}))),exports.useAddChain=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),r=["USE_ADD_CHAIN",e,n,t],i=d.useMutation({mutationKey:r,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:i.mutate,addChainAsync:i.mutateAsync,error:i.error,isLoading:i.isPending,isSuccess:i.isSuccess,status:i.status}},exports.useBalance=e=>{const n=Oe({chainId:[e.chainId]})[0],{data:t}=Te({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=u.useMemo(()=>["USE_BALANCE",o,e.chainId,e.bech32Address,e.denom],[e.bech32Address,e.chainId,e.denom,o]);return d.useQuery({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})},exports.useBalanceStaked=e=>{const n=Oe({chainId:[e.chainId]})[0],{data:t}=Te({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=u.useMemo(()=>["USE_BALANCE_STAKED",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return d.useQuery({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})},exports.useBalances=e=>{const n=Oe({chainId:[e.chainId]})[0],{data:t}=Te({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=u.useMemo(()=>["USE_ALL_BALANCES",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return d.useQuery({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})},exports.useChainInfo=({chainId:e}={})=>x(e=>e.chains)?.find(n=>n.chainId===e),exports.useChainInfos=({chainId:e}={})=>{const n=x(e=>e.chains);return e?n?.filter(n=>e.includes(n.chainId)):n},exports.useCheckWallet=xe,exports.useConnect=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),r=["USE_CONNECT",e,n,t],i=d.useMutation({mutationKey:r,mutationFn:ge,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:a}=xe();return{connect:e=>i.mutate(e),connectAsync:e=>i.mutateAsync(e),error:i.error,isLoading:i.isPending,isSuccess:i.isSuccess,isSupported:Boolean(a),status:i.status}},exports.useCosmWasmClient=Ne,exports.useCosmWasmSigningClient=function(e){const n=Oe({chainId:e?.chainId}),t=x(e=>e.walletType),o=N(e=>e.activeChainIds),r="connected"===N.getState().status&&N.getState().accounts&&x.getState()._reconnectConnector===t,i=u.useMemo(()=>["USE_COSMWASM_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return d.useQuery({queryKey:i,queryFn:async()=>{const r=D();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 ke(n,async n=>{if(!o?.includes(n.chainId))return null;if(!ie(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return se(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return se(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return se(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=x.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}},s=i?.gas?f.GasPrice.fromString(`${i.gas.price}${i.gas.denom}`):void 0;return await h.SigningCosmWasmClient.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})},exports.useDisconnect=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),r=["USE_DISCONNECT",e,n,t],i=d.useMutation({mutationKey:r,mutationFn:he,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=>i.mutate(e),disconnectAsync:e=>i.mutateAsync(e),error:i.error,isLoading:i.isPending,isSuccess:i.isSuccess,status:i.status}},exports.useExecuteContract=({contractAddress:e,onError:n,onLoading:t,onSuccess:o})=>{const r=D(),{mutate:i,mutateAsync:a,...s}=d.useMutation({mutationKey:["USE_EXECUTE_CONTRACT",n,t,o,e],mutationFn:n=>Ae({...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}},exports.useGrazEvents=Re,exports.useInstantiateContract=({codeId:e,onError:n,onLoading:t,onSuccess:o})=>{const r=D(),{mutate:i,mutateAsync:a,...s}=d.useMutation({mutationKey:["USE_INSTANTIATE_CONTRACT",n,t,o,e],mutationFn:n=>Ee({...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}},exports.useOfflineSigners=function(e){const n=Oe({chainId:e?.chainId}),t=x(e=>e.walletType),o="connected"===N.getState().status&&N.getState().accounts&&x.getState()._reconnectConnector===t,r=u.useMemo(()=>["USE_OFFLINE_SIGNERS",n,t],[n,t]);return d.useQuery({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(!ie(t))throw new Error(`${t} is not available`);return await ke(n,async e=>await we({chainId:e.chainId,walletType:t}),"useOfflineSigners")},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&Boolean(o),refetchOnWindowFocus:!1})},exports.useQueryClientValidators=e=>{const n=e.status??"BOND_STATUS_BONDED",t=["USE_ACTIVE_CHAIN_VALIDATORS",e.queryClient,n];return d.useQuery({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})},exports.useQueryRaw=e=>{const{data:n}=Ne(),t=n&&Object.values(n)[0],o=["USE_QUERY_RAW",e?.key,e?.address,t];return d.useQuery({queryKey:o,queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.key)throw new Error("address or key undefined");return ve(e.address,e.key,t)},enabled:Boolean(e?.address)&&Boolean(e?.key)&&Boolean(t)})},exports.useQuerySmart=e=>{const{data:n}=Ne(),t=n&&Object.values(n)[0];return d.useQuery({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 _e(e.address,e.queryMsg,t)},enabled:Boolean(e?.address)&&Boolean(e?.queryMsg)&&Boolean(t)})},exports.useRecentChainIds=()=>({data:x(e=>e.recentChainIds),clear:me}),exports.useRecentChains=()=>{const e=x(e=>e.recentChainIds),n=x(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:me}},exports.useSendIbcTokens=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),{mutate:r,mutateAsync:i,...a}=d.useMutation({mutationKey:["USE_SEND_IBC_TOKENS",e,n,t],mutationFn:Ie,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}},exports.useSendTokens=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),{mutate:r,mutateAsync:i,...a}=d.useMutation({mutationKey:["USE_SEND_TOKENS",e,n,t],mutationFn:be,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}},exports.useStargateClient=Te,exports.useStargateSigningClient=function(e){const n=Oe({chainId:e?.chainId}),t=x(e=>e.walletType),o=N(e=>e.activeChainIds),r="connected"===N.getState().status&&N.getState().accounts&&x.getState()._reconnectConnector===t,i=u.useMemo(()=>["USE_STARGATE_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return d.useQuery({queryKey:i,queryFn:async()=>{const r=D();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 ke(n,async n=>{if(!o?.includes(n.chainId))return null;if(!ie(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return se(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return se(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return se(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=x.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}};return await f.SigningStargateClient.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})},exports.useSuggestChain=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),r=["USE_SUGGEST_CHAIN",e,n,t],i=d.useMutation({mutationKey:r,mutationFn:Ce,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:i.error,isLoading:i.isPending,isSuccess:i.isSuccess,suggest:i.mutate,suggestAsync:i.mutateAsync,status:i.status}},exports.useSuggestChainAndConnect=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),r=["USE_SUGGEST_CHAIN_AND_CONNECT",e,n,t],i=d.useMutation({mutationKey:r,mutationFn:ye,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:a}=xe();return{error:i.error,isLoading:i.isPending,isSuccess:i.isSuccess,isSupported:Boolean(a),status:i.status,suggestAndConnect:i.mutate,suggestAndConnectAsync:i.mutateAsync}};
|