graz 0.4.0-alpha.4 → 0.4.1

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 CHANGED
@@ -1,14 +1,14 @@
1
1
  /// <reference types="../types/global" />
2
2
  import { DirectSignResponse, OfflineDirectSigner, Coin } from '@cosmjs/proto-signing';
3
3
  import { Key as Key$1, Keplr, ChainInfo, KeplrSignOptions, KeplrIntereactionOptions, OfflineAminoSigner as OfflineAminoSigner$1, AppCurrency } from '@keplr-wallet/types';
4
- import { OfflineAminoSigner, StdSignDoc, AminoSignResponse, StdSignature } from '@cosmjs/amino';
4
+ import { OfflineAminoSigner } from '@cosmjs/amino';
5
5
  import { WalletConnectModalConfig } from '@walletconnect/modal';
6
6
  import { SignClientTypes } from '@walletconnect/types';
7
7
  import * as _tanstack_react_query from '@tanstack/react-query';
8
8
  import { UseQueryResult } from '@tanstack/react-query';
9
9
  import { ParaWeb } from '@getpara/web-sdk';
10
10
  export { ParaWeb } from '@getpara/web-sdk';
11
- import { ParaGrazConfig as ParaGrazConfig$1 } from '@getpara/graz-connector';
11
+ import { ParaGrazConfig as ParaGrazConfig$1, ParaGrazConnector } from '@getpara/graz-connector';
12
12
  import * as _cosmjs_cosmwasm_stargate from '@cosmjs/cosmwasm-stargate';
13
13
  import { SigningCosmWasmClient, InstantiateOptions, CosmWasmClient, InstantiateResult, ExecuteResult, SigningCosmWasmClientOptions } from '@cosmjs/cosmwasm-stargate';
14
14
  import { SigningStargateClient, StdFee, DeliverTxResponse, QueryClient, StakingExtension, StargateClient, SigningStargateClientOptions } from '@cosmjs/stargate';
@@ -196,10 +196,10 @@ interface ParaGrazConfig {
196
196
  */
197
197
  noModal?: boolean;
198
198
  /**
199
- * Optional connector class constructor to use instead of default
200
- * Allows for custom Para connector implementations
199
+ * Required connector class constructor
200
+ * Must be provided to use Para wallet functionality
201
201
  */
202
- connectorClass?: new (config: ParaGrazConfig, chains?: ChainInfo[] | null) => ParaGrazConnector;
202
+ connectorClass: new (config: ParaGrazConfig, chains?: ChainInfo[] | null) => ParaGrazConnector;
203
203
  /**
204
204
  * Props for customizing the Para modal appearance and behavior
205
205
  * Only used when using @getpara/graz-integration with modal support
@@ -212,72 +212,6 @@ interface ParaGrazConfig {
212
212
  */
213
213
  queryClient?: _tanstack_react_query.QueryClient;
214
214
  }
215
- /**
216
- * Para wallet connector interface
217
- * Implements the Graz Wallet interface with Para-specific methods
218
- */
219
- interface ParaGrazConnector extends Omit<Wallet, "experimentalSuggestChain"> {
220
- /**
221
- * Enable connection to one or more chains
222
- * @param chainIds - Single chain ID or array of chain IDs
223
- */
224
- enable(chainIds: string | string[]): Promise<void>;
225
- /**
226
- * Disconnect from Para wallet
227
- */
228
- disconnect(): Promise<void>;
229
- /**
230
- * Get the Para Web SDK client instance
231
- */
232
- getParaWebClient(): ParaWeb;
233
- /**
234
- * Get the connector configuration
235
- */
236
- getConfig(): ParaGrazConfig;
237
- /**
238
- * Get account key for a specific chain
239
- * @param chainId - The chain identifier
240
- */
241
- getKey(chainId: string): Promise<Key>;
242
- /**
243
- * Get offline signer that only supports Amino signing
244
- * @param chainId - The chain identifier
245
- */
246
- getOfflineSignerOnlyAmino(chainId: string): OfflineAminoSigner;
247
- /**
248
- * Get hybrid offline signer supporting both Amino and Direct signing
249
- * @param chainId - The chain identifier
250
- */
251
- getOfflineSigner(chainId: string): OfflineAminoSigner & OfflineDirectSigner;
252
- /**
253
- * Get offline signer, automatically choosing between Amino and Direct
254
- * @param chainId - The chain identifier
255
- */
256
- getOfflineSignerAuto(chainId: string): Promise<OfflineAminoSigner | OfflineDirectSigner>;
257
- /**
258
- * Sign transaction using Amino format
259
- * @param chainId - The chain identifier
260
- * @param signer - The signer address
261
- * @param signDoc - The Amino sign document
262
- * @param signOptions - Optional signing options
263
- */
264
- signAmino(chainId: string, signer: string, signDoc: StdSignDoc, signOptions?: KeplrSignOptions): Promise<AminoSignResponse>;
265
- /**
266
- * Sign transaction using Direct/Protobuf format
267
- * @param chainId - The chain identifier
268
- * @param signer - The signer address
269
- * @param signDoc - The Direct sign document
270
- * @param signOptions - Optional signing options
271
- */
272
- signDirect(chainId: string, signer: string, signDoc: SignDoc, signOptions?: KeplrSignOptions): Promise<DirectSignResponse>;
273
- /**
274
- * Sign arbitrary data
275
- * @param chainId - The chain identifier
276
- * @param signer - The signer address
277
- * @param data - Data to sign (string or bytes)
278
- */
279
- signArbitrary(chainId: string, signer: string, data: string | Uint8Array): Promise<StdSignature>;
280
- }
281
215
 
282
216
  interface ChainConfig {
283
217
  path?: string;
@@ -1781,4 +1715,4 @@ declare const useGrazEvents: () => null;
1781
1715
  */
1782
1716
  declare const GrazEvents: FC;
1783
1717
 
1784
- export { type ActionChainId, type AddChainArgs, type CactusCosmosWallet, type ConfigureGrazArgs, type ConnectArgs, type ConnectResult, type Dictionary, type ExecuteContractArgs, type ExecuteContractMutationArgs, GrazEvents, GrazProvider, type GrazProviderProps, type InstantiateContractArgs, type InstantiateContractMutationArgs, type Key, type KnownKeys, type Maybe, type OfflineSigners, type ParaGrazConfig, type ParaGrazConnector, type ParaGrazConnectorEvents, type ParaModalProps, type ParaWallet, type ReconnectArgs, type SendIbcTokensArgs, type SendTokensArgs, type SignAminoParams, type SignDirectParams, type SignDoc, type SuggestChainAndConnectArgs, type SuggestChainArgs, type UseAccountArgs, type UseAccountResult, type UseAddChainArgs, type UseConnectChainArgs, type UseExecuteContractArgs, type UseInstantiateContractArgs, type UseSuggestChainAndConnectArgs, type UseSuggestChainArgs, WALLET_TYPES, type Wallet, WalletType, addChain, checkWallet, clearRecentChain, clearSession, configureGraz, connect, defineChainInfo, defineChains, disconnect, executeContract, getAvailableWallets, getCactusCosmos, getChainInfo, getChainInfos, getCosmostation, getKeplr, getLeap, getMetamaskSnapLeap, getOfflineSigners, getOkx, getPara, getQueryRaw, getQuerySmart, getRecentChainIds, getRecentChains, getVectis, getWCCosmostation, getWCKeplr, getWCLeap, getWallet, getWalletConnect, instantiateContract, isLeapDappBrowser, isLeapSnaps, isPara, isWalletConnect, reconnect, sendIbcTokens, sendTokens, suggestChain, suggestChainAndConnect, useAccount, useActiveChainCurrency, useActiveChainIds, useActiveChains, useActiveWalletType, useAddChain, useBalance, useBalanceStaked, useBalances, useChainInfo, useChainInfos, useCheckWallet, useConnect, useCosmWasmClient, useCosmWasmSigningClient, useDisconnect, useExecuteContract, useGrazEvents, useInstantiateContract, useOfflineSigners, useQueryClientValidators, useQueryRaw, useQuerySmart, useRecentChainIds, useRecentChains, useSendIbcTokens, useSendTokens, useStargateClient, useStargateSigningClient, useSuggestChain, useSuggestChainAndConnect };
1718
+ export { type ActionChainId, type AddChainArgs, type CactusCosmosWallet, type ConfigureGrazArgs, type ConnectArgs, type ConnectResult, type Dictionary, type ExecuteContractArgs, type ExecuteContractMutationArgs, GrazEvents, GrazProvider, type GrazProviderProps, type InstantiateContractArgs, type InstantiateContractMutationArgs, type Key, type KnownKeys, type Maybe, type OfflineSigners, type ParaGrazConfig, type ParaGrazConnectorEvents, type ParaModalProps, type ParaWallet, type ReconnectArgs, type SendIbcTokensArgs, type SendTokensArgs, type SignAminoParams, type SignDirectParams, type SignDoc, type SuggestChainAndConnectArgs, type SuggestChainArgs, type UseAccountArgs, type UseAccountResult, type UseAddChainArgs, type UseConnectChainArgs, type UseExecuteContractArgs, type UseInstantiateContractArgs, type UseSuggestChainAndConnectArgs, type UseSuggestChainArgs, WALLET_TYPES, type Wallet, WalletType, addChain, checkWallet, clearRecentChain, clearSession, configureGraz, connect, defineChainInfo, defineChains, disconnect, executeContract, getAvailableWallets, getCactusCosmos, getChainInfo, getChainInfos, getCosmostation, getKeplr, getLeap, getMetamaskSnapLeap, getOfflineSigners, getOkx, getPara, getQueryRaw, getQuerySmart, getRecentChainIds, getRecentChains, getVectis, getWCCosmostation, getWCKeplr, getWCLeap, getWallet, getWalletConnect, instantiateContract, isLeapDappBrowser, isLeapSnaps, isPara, isWalletConnect, reconnect, sendIbcTokens, sendTokens, suggestChain, suggestChainAndConnect, useAccount, useActiveChainCurrency, useActiveChainIds, useActiveChains, useActiveWalletType, useAddChain, useBalance, useBalanceStaked, useBalances, useChainInfo, useChainInfos, useCheckWallet, useConnect, useCosmWasmClient, useCosmWasmSigningClient, useDisconnect, useExecuteContract, useGrazEvents, useInstantiateContract, useOfflineSigners, useQueryClientValidators, useQueryRaw, useQuerySmart, useRecentChainIds, useRecentChains, useSendIbcTokens, useSendTokens, useStargateClient, useStargateSigningClient, useSuggestChain, useSuggestChainAndConnect };
package/dist/index.d.ts CHANGED
@@ -1,14 +1,14 @@
1
1
  /// <reference types="../types/global" />
2
2
  import { DirectSignResponse, OfflineDirectSigner, Coin } from '@cosmjs/proto-signing';
3
3
  import { Key as Key$1, Keplr, ChainInfo, KeplrSignOptions, KeplrIntereactionOptions, OfflineAminoSigner as OfflineAminoSigner$1, AppCurrency } from '@keplr-wallet/types';
4
- import { OfflineAminoSigner, StdSignDoc, AminoSignResponse, StdSignature } from '@cosmjs/amino';
4
+ import { OfflineAminoSigner } from '@cosmjs/amino';
5
5
  import { WalletConnectModalConfig } from '@walletconnect/modal';
6
6
  import { SignClientTypes } from '@walletconnect/types';
7
7
  import * as _tanstack_react_query from '@tanstack/react-query';
8
8
  import { UseQueryResult } from '@tanstack/react-query';
9
9
  import { ParaWeb } from '@getpara/web-sdk';
10
10
  export { ParaWeb } from '@getpara/web-sdk';
11
- import { ParaGrazConfig as ParaGrazConfig$1 } from '@getpara/graz-connector';
11
+ import { ParaGrazConfig as ParaGrazConfig$1, ParaGrazConnector } from '@getpara/graz-connector';
12
12
  import * as _cosmjs_cosmwasm_stargate from '@cosmjs/cosmwasm-stargate';
13
13
  import { SigningCosmWasmClient, InstantiateOptions, CosmWasmClient, InstantiateResult, ExecuteResult, SigningCosmWasmClientOptions } from '@cosmjs/cosmwasm-stargate';
14
14
  import { SigningStargateClient, StdFee, DeliverTxResponse, QueryClient, StakingExtension, StargateClient, SigningStargateClientOptions } from '@cosmjs/stargate';
@@ -196,10 +196,10 @@ interface ParaGrazConfig {
196
196
  */
197
197
  noModal?: boolean;
198
198
  /**
199
- * Optional connector class constructor to use instead of default
200
- * Allows for custom Para connector implementations
199
+ * Required connector class constructor
200
+ * Must be provided to use Para wallet functionality
201
201
  */
202
- connectorClass?: new (config: ParaGrazConfig, chains?: ChainInfo[] | null) => ParaGrazConnector;
202
+ connectorClass: new (config: ParaGrazConfig, chains?: ChainInfo[] | null) => ParaGrazConnector;
203
203
  /**
204
204
  * Props for customizing the Para modal appearance and behavior
205
205
  * Only used when using @getpara/graz-integration with modal support
@@ -212,72 +212,6 @@ interface ParaGrazConfig {
212
212
  */
213
213
  queryClient?: _tanstack_react_query.QueryClient;
214
214
  }
215
- /**
216
- * Para wallet connector interface
217
- * Implements the Graz Wallet interface with Para-specific methods
218
- */
219
- interface ParaGrazConnector extends Omit<Wallet, "experimentalSuggestChain"> {
220
- /**
221
- * Enable connection to one or more chains
222
- * @param chainIds - Single chain ID or array of chain IDs
223
- */
224
- enable(chainIds: string | string[]): Promise<void>;
225
- /**
226
- * Disconnect from Para wallet
227
- */
228
- disconnect(): Promise<void>;
229
- /**
230
- * Get the Para Web SDK client instance
231
- */
232
- getParaWebClient(): ParaWeb;
233
- /**
234
- * Get the connector configuration
235
- */
236
- getConfig(): ParaGrazConfig;
237
- /**
238
- * Get account key for a specific chain
239
- * @param chainId - The chain identifier
240
- */
241
- getKey(chainId: string): Promise<Key>;
242
- /**
243
- * Get offline signer that only supports Amino signing
244
- * @param chainId - The chain identifier
245
- */
246
- getOfflineSignerOnlyAmino(chainId: string): OfflineAminoSigner;
247
- /**
248
- * Get hybrid offline signer supporting both Amino and Direct signing
249
- * @param chainId - The chain identifier
250
- */
251
- getOfflineSigner(chainId: string): OfflineAminoSigner & OfflineDirectSigner;
252
- /**
253
- * Get offline signer, automatically choosing between Amino and Direct
254
- * @param chainId - The chain identifier
255
- */
256
- getOfflineSignerAuto(chainId: string): Promise<OfflineAminoSigner | OfflineDirectSigner>;
257
- /**
258
- * Sign transaction using Amino format
259
- * @param chainId - The chain identifier
260
- * @param signer - The signer address
261
- * @param signDoc - The Amino sign document
262
- * @param signOptions - Optional signing options
263
- */
264
- signAmino(chainId: string, signer: string, signDoc: StdSignDoc, signOptions?: KeplrSignOptions): Promise<AminoSignResponse>;
265
- /**
266
- * Sign transaction using Direct/Protobuf format
267
- * @param chainId - The chain identifier
268
- * @param signer - The signer address
269
- * @param signDoc - The Direct sign document
270
- * @param signOptions - Optional signing options
271
- */
272
- signDirect(chainId: string, signer: string, signDoc: SignDoc, signOptions?: KeplrSignOptions): Promise<DirectSignResponse>;
273
- /**
274
- * Sign arbitrary data
275
- * @param chainId - The chain identifier
276
- * @param signer - The signer address
277
- * @param data - Data to sign (string or bytes)
278
- */
279
- signArbitrary(chainId: string, signer: string, data: string | Uint8Array): Promise<StdSignature>;
280
- }
281
215
 
282
216
  interface ChainConfig {
283
217
  path?: string;
@@ -1781,4 +1715,4 @@ declare const useGrazEvents: () => null;
1781
1715
  */
1782
1716
  declare const GrazEvents: FC;
1783
1717
 
1784
- export { type ActionChainId, type AddChainArgs, type CactusCosmosWallet, type ConfigureGrazArgs, type ConnectArgs, type ConnectResult, type Dictionary, type ExecuteContractArgs, type ExecuteContractMutationArgs, GrazEvents, GrazProvider, type GrazProviderProps, type InstantiateContractArgs, type InstantiateContractMutationArgs, type Key, type KnownKeys, type Maybe, type OfflineSigners, type ParaGrazConfig, type ParaGrazConnector, type ParaGrazConnectorEvents, type ParaModalProps, type ParaWallet, type ReconnectArgs, type SendIbcTokensArgs, type SendTokensArgs, type SignAminoParams, type SignDirectParams, type SignDoc, type SuggestChainAndConnectArgs, type SuggestChainArgs, type UseAccountArgs, type UseAccountResult, type UseAddChainArgs, type UseConnectChainArgs, type UseExecuteContractArgs, type UseInstantiateContractArgs, type UseSuggestChainAndConnectArgs, type UseSuggestChainArgs, WALLET_TYPES, type Wallet, WalletType, addChain, checkWallet, clearRecentChain, clearSession, configureGraz, connect, defineChainInfo, defineChains, disconnect, executeContract, getAvailableWallets, getCactusCosmos, getChainInfo, getChainInfos, getCosmostation, getKeplr, getLeap, getMetamaskSnapLeap, getOfflineSigners, getOkx, getPara, getQueryRaw, getQuerySmart, getRecentChainIds, getRecentChains, getVectis, getWCCosmostation, getWCKeplr, getWCLeap, getWallet, getWalletConnect, instantiateContract, isLeapDappBrowser, isLeapSnaps, isPara, isWalletConnect, reconnect, sendIbcTokens, sendTokens, suggestChain, suggestChainAndConnect, useAccount, useActiveChainCurrency, useActiveChainIds, useActiveChains, useActiveWalletType, useAddChain, useBalance, useBalanceStaked, useBalances, useChainInfo, useChainInfos, useCheckWallet, useConnect, useCosmWasmClient, useCosmWasmSigningClient, useDisconnect, useExecuteContract, useGrazEvents, useInstantiateContract, useOfflineSigners, useQueryClientValidators, useQueryRaw, useQuerySmart, useRecentChainIds, useRecentChains, useSendIbcTokens, useSendTokens, useStargateClient, useStargateSigningClient, useSuggestChain, useSuggestChainAndConnect };
1718
+ export { type ActionChainId, type AddChainArgs, type CactusCosmosWallet, type ConfigureGrazArgs, type ConnectArgs, type ConnectResult, type Dictionary, type ExecuteContractArgs, type ExecuteContractMutationArgs, GrazEvents, GrazProvider, type GrazProviderProps, type InstantiateContractArgs, type InstantiateContractMutationArgs, type Key, type KnownKeys, type Maybe, type OfflineSigners, type ParaGrazConfig, type ParaGrazConnectorEvents, type ParaModalProps, type ParaWallet, type ReconnectArgs, type SendIbcTokensArgs, type SendTokensArgs, type SignAminoParams, type SignDirectParams, type SignDoc, type SuggestChainAndConnectArgs, type SuggestChainArgs, type UseAccountArgs, type UseAccountResult, type UseAddChainArgs, type UseConnectChainArgs, type UseExecuteContractArgs, type UseInstantiateContractArgs, type UseSuggestChainAndConnectArgs, type UseSuggestChainArgs, WALLET_TYPES, type Wallet, WalletType, addChain, checkWallet, clearRecentChain, clearSession, configureGraz, connect, defineChainInfo, defineChains, disconnect, executeContract, getAvailableWallets, getCactusCosmos, getChainInfo, getChainInfos, getCosmostation, getKeplr, getLeap, getMetamaskSnapLeap, getOfflineSigners, getOkx, getPara, getQueryRaw, getQuerySmart, getRecentChainIds, getRecentChains, getVectis, getWCCosmostation, getWCKeplr, getWCLeap, getWallet, getWalletConnect, instantiateContract, isLeapDappBrowser, isLeapSnaps, isPara, isWalletConnect, reconnect, sendIbcTokens, sendTokens, suggestChain, suggestChainAndConnect, useAccount, useActiveChainCurrency, useActiveChainIds, useActiveChains, useActiveWalletType, useAddChain, useBalance, useBalanceStaked, useBalances, useChainInfo, useChainInfos, useCheckWallet, useConnect, useCosmWasmClient, useCosmWasmSigningClient, useDisconnect, useExecuteContract, useGrazEvents, useInstantiateContract, useOfflineSigners, useQueryClientValidators, useQueryRaw, useQuerySmart, useRecentChainIds, useRecentChains, useSendIbcTokens, useSendTokens, useStargateClient, useStargateSigningClient, useSuggestChain, useSuggestChainAndConnect };
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"),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")},L=()=>{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")},D={},q=()=>(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!==D[t])return D[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,D[t]=r,D[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"}),F=()=>{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;if(!n.connectorClass)throw new Error("Para connector class not provided. Provide 'connectorClass' in paraConfig to use Para wallet.");try{const e=O.getState().chains,t=new n.connectorClass(n,e);if(!t)throw new Error("Para connector initialization failed. Check config and dependencies.");return v.setState(e=>({...e,paraConnector:t})),t}catch(e){throw K=null,new Error(`Para connector init failed: ${e?.message||"Unknown error"}. Check ParaConfig and connectorClass.`)}})()));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){throw v.setState({paraConnector:null,status:"disconnected"}),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])},Q=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 Q({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`}})},z=()=>{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 Q({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 Q({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 L();case"cosmostation":return T();case"vectis":return W();case"walletconnect":return Q();case"wc_keplr_mobile":return z();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 Q({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 q();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 F();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&&L().subscription?.(()=>{ie({onError:r})}),"compass"===o&&x().subscription?.(()=>{ie({onError:r})}),"vectis"===o&&W().subscription?.(()=>{ie({onError:r})}),"walletconnect"===o&&l.has("walletconnect")&&Q().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&&F().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=L,exports.getMetamaskSnapLeap=q,exports.getOfflineSigners=ae,exports.getOkx=F,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=z,exports.getWCLeap=V,exports.getWallet=J,exports.getWalletConnect=Q,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}};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{create as e}from"zustand";import{createJSONStorage as n,subscribeWithSelector as t,persist as o}from"zustand/middleware";import{Cosmiframe as r,isInIframe as i}from"@dao-dao/cosmiframe";import{isSnapInstalled as a,installSnap as s,CosmosSnap as c}from"@cosmsnap/snapper";import{encodeEd25519Pubkey as l,encodeSecp256k1Pubkey as d,pubkeyType as u,rawEd25519PubkeyToRawAddress as g,rawSecp256k1PubkeyToRawAddress as w}from"@cosmjs/amino";import f from"long";import{fromBech32 as h}from"@cosmjs/encoding";import{WalletConnectModal as m}from"@walletconnect/modal";import{SignClient as p}from"@walletconnect/sign-client";import{getSdkError as y}from"@walletconnect/utils";import{useQuery as S,useMutation as C}from"@tanstack/react-query";import{useMemo as I,useEffect as b,useState as E}from"react";import A from"p-map";import{CosmWasmClient as _,SigningCosmWasmClient as v}from"@cosmjs/cosmwasm-stargate";import{StargateClient as O,SigningStargateClient as k,GasPrice as N}from"@cosmjs/stargate";import{useShallow as B}from"zustand/shallow";import{jsxs as T,jsx as P,Fragment as D}from"react/jsx-runtime";var F="graz-reconnect-session",L=(e=>(e.KEPLR="keplr",e.LEAP="leap",e.VECTIS="vectis",e.COSMOSTATION="cosmostation",e.WALLETCONNECT="walletconnect",e.WC_KEPLR_MOBILE="wc_keplr_mobile",e.WC_LEAP_MOBILE="wc_leap_mobile",e.WC_COSMOSTATION_MOBILE="wc_cosmostation_mobile",e.WC_CLOT_MOBILE="wc_clot_mobile",e.METAMASK_SNAP_LEAP="metamask_snap_leap",e.METAMASK_SNAP_COSMOS="metamask_snap_cosmos",e.STATION="station",e.XDEFI="xdefi",e.COSMIFRAME="cosmiframe",e.COMPASS="compass",e.INITIA="initia",e.OKX="okx",e.PARA="para",e.CACTUSCOSMOS="cactuscosmos",e))(L||{}),K=["keplr","leap","vectis","cosmostation","walletconnect","wc_keplr_mobile","wc_leap_mobile","wc_cosmostation_mobile","wc_clot_mobile","metamask_snap_leap","station","xdefi","metamask_snap_cosmos","cosmiframe","compass","initia","okx","para","cactuscosmos"],M={iframeOptions:null,recentChainIds:null,chains:null,chainsConfig:null,paraConfig:null,multiChainFetchConcurrency:3,walletType:"keplr",walletConnect:{options:null,walletConnectModal:null},walletDefaultOptions:null,pingInterval:36e5,_notFoundFn:()=>null,_onReconnectFailed:()=>null,_reconnect:!1,_reconnectConnector:null},U={accounts:null,activeChainIds:null,status:"disconnected",lastPing:null,wcSignClients:new Map,paraConnector:null},q=e(t(o(()=>U,{name:"graz-session",version:2,partialize:e=>({accounts:e.accounts,activeChainIds:e.activeChainIds,lastPing:e.lastPing,status:e.status}),storage:n(()=>sessionStorage)}))),$=e(t(o(()=>M,{name:"graz-internal",partialize:e=>({recentChainIds:e.recentChainIds,_reconnect:e._reconnect,_reconnectConnector:e._reconnectConnector,walletType:e.walletType,chains:e.chains}),version:3}))),x=()=>{if(void 0!==window.cactuslink_cosmos){const e=window.cactuslink_cosmos,n=e=>{const n=()=>{de(),e()};return window.addEventListener("accountsChanged",n),()=>{window.removeEventListener("accountsChanged",n)}};return{...Object.assign(e,{subscription:n}),getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSigner(n),experimentalSuggestChain:async()=>{throw new Error("Cactus Cosmos does not support experimentalSuggestChain")}}}throw $.getState()._notFoundFn(),new Error("window.cactuslink_cosmos is not defined")},j=()=>{if(void 0!==window.compass){const e=window.compass,n=e=>{const n=()=>{de(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.leap is not defined")},W=()=>{const e=$.getState();if(!e.iframeOptions)throw e._notFoundFn(),new Error("no iframe options set");if(!i())throw e._notFoundFn(),new Error("not in iframe");if(!e.iframeOptions.allowedIframeParentOrigins.length)throw e._notFoundFn(),new Error("no iframe allowed origins");const n=new r(e.iframeOptions.allowedIframeParentOrigins).getKeplrClient();return{enable:n.enable.bind(n),getKey:n.getKey.bind(n),getOfflineSigner:n.getOfflineSigner.bind(n),getOfflineSignerAuto:n.getOfflineSignerAuto.bind(n),getOfflineSignerOnlyAmino:n.getOfflineSignerOnlyAmino.bind(n),experimentalSuggestChain:n.experimentalSuggestChain.bind(n),signDirect:n.signDirect.bind(n),signAmino:n.signAmino.bind(n)}},R={},z=()=>{if(void 0!==window.cosmostation?.providers.keplr){const e=window.cosmostation.providers.keplr,n=e=>{const n=()=>{de(),e()};return window.addEventListener("cosmostation_keystorechange",n),()=>{window.removeEventListener("cosmostation_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.cosmostation.providers.keplr is not defined")},G=()=>{if(void 0!==window.initia){const e=window.initia;return{enable:async()=>{await e.getAddress()},getKey:async n=>{const t=e.getOfflineSigner(n),[o]=await t.getAccounts();if(!o)throw new Error("Wallet connection failed");const r=(()=>{switch(o.algo){case"secp256k1":return w(o.pubkey);case"ed25519":return g(o.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{name:(i=o.address,`${i.slice(0,6)}...${i.slice(-6)}`),algo:o.algo,pubKey:o.pubkey,bech32Address:o.address,address:r,isNanoLedger:!1,isKeystone:!1};var i},getOfflineSigner:n=>{const t=e.getOfflineSigner(n),o=e.getOfflineSignerOnlyAmino(n);return{getAccounts:t.getAccounts.bind(t),signDirect:t.signDirect.bind(t),signAmino:o.signAmino.bind(o)}},getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),experimentalSuggestChain:n=>e.requestAddInitiaLayer({chain_id:n.chainId,chain_name:n.chainName,bech32_prefix:"init",bech32_config:n.bech32Config,slip44:n.bip44.coinType,logo_URIs:{png:n.chainSymbolImageUrl},fees:{fee_tokens:n.feeCurrencies.map(e=>({denom:e.coinDenom,amount:e.coinMinimalDenom,low_gas_price:e.gasPriceStep?.low,average_gas_price:e.gasPriceStep?.average,high_gas_price:e.gasPriceStep?.high}))},apis:{rpc:[{address:n.rpc}],rest:[{address:n.rest}]}}),signDirect:(...n)=>{const[t,o,r]=n;return e.getOfflineSigner(t).signDirect(o,(e=>{const{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}=e;if(!(n&&t&&o&&r))throw new Error("Invalid sign doc");return{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}})(r))},signAmino:(...n)=>{const[t,o,r]=n;return e.getOfflineSignerOnlyAmino(t).signAmino(o,r)},signArbitrary:async(n,t,o)=>{const r=e.getOfflineSigner(n),i=(await r.getAccounts()).find(e=>e.address===t);if(!i)throw new Error(`Wallet not connected to account ${t}`);const a=(()=>{switch(i.algo){case"secp256k1":return d(i.pubkey);case"ed25519":return l(i.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{signature:await e.signArbitrary(o),pub_key:{type:"secp256k1"===i.algo?u.secp256k1:u.ed25519,value:a.value}}},subscription:e=>{const n=()=>{de(),e()};return window.addEventListener("initia_keystorechange",n),()=>{window.removeEventListener("initia_keystorechange",n)}}}}throw $.getState()._notFoundFn(),new Error("window.initia is not defined")},V=()=>{if(void 0!==window.keplr){const e=window.keplr,n=e=>{const n=()=>{de(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.keplr is not defined")},H=()=>{if(void 0!==window.leap){const e=window.leap,n=e=>{const n=()=>{de(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.leap is not defined")},X={},Y=()=>(e=>{const n=window.ethereum;if(n&&e){const t=async()=>await n.request({method:"wallet_getSnaps"}),o=async n=>{try{const o=await t();return Object.values(o).find(t=>t.id===e.id&&(!n||t.version===n))}catch(e){return}},r=async()=>{await n.request({method:"wallet_requestSnaps",params:{[e.id]:e.params||{}}})},i=async()=>{const e=await n.request({method:"web3_clientVersion"});if(!e.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const t=e.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(t)>=11))throw new Error("Metamask Snap is not supported in this version");return await o()||await r(),!0},a=async(t,o,r)=>{const i=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signDirect",params:{chainId:t,signerAddress:o,signDoc:r}}}}),a=r.accountNumber,s=new f(a.low,a.high,a.unsigned);return{signature:i.signature,signed:{...i.signed,accountNumber:s.toString(),authInfoBytes:new Uint8Array(Object.values(i.signed.authInfoBytes)),bodyBytes:new Uint8Array(Object.values(i.signed.bodyBytes))}}},s=async(t,o,r)=>await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signAmino",params:{chainId:t,signerAddress:o,signDoc:r}}}}),c=async t=>{if(void 0!==X[t])return X[t];const o=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"getKey",params:{chainId:t}}}});if(!o)throw new Error("No response from Metamask");return o.pubKey=Uint8Array.from(Object.values(o.pubkey)),delete o.pubkey,X[t]=o,X[t]},l=async e=>{const n=await c(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async(...e)=>{const[n,t,o,r]=e;return await s(n,t,o)},u=async(...e)=>{const[n,t,o]=e,r={...o,accountNumber:f.fromString(o.accountNumber?.toString()||"0"),authInfoBytes:o.authInfoBytes,bodyBytes:o.bodyBytes};return await a(n,t,r)},g=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>d(e,n,t)});return{enable:async e=>{await o()||await r()},experimentalSuggestChain:async(...t)=>{await i(),await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"suggestChain",params:{chainInfo:t[0]}}}})},getKey:c,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>d(e,n,t)}),getOfflineSignerAuto:async e=>g(e),getOfflineSignerOnlyAmino:g,init:i,signAmino:d,signDirect:u}}throw $.getState()._notFoundFn(),new Error("window.ethereum is not defined")})({id:"npm:@leapwallet/metamask-cosmos-snap"}),Q=()=>{if(void 0!==window.okxwallet?.keplr){const e=window.okxwallet.keplr,n=e=>{const n=()=>{de(),e()};return window.okxwallet?.on("accountsChanged",n),()=>{window.okxwallet?.removeListener("accountsChanged",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.okxwallet.keplr is not defined")},J=null,Z=()=>{const e=()=>{const e=q.getState().paraConnector;if(!e)throw new Error("Para connector not initialized. Call connect() first or check paraConfig in GrazProvider.");return e},n=$.getState().paraConfig;if(!n?.paraWeb)throw new Error("Missing Para config. Provide paraConfig with 'paraWeb' to GrazProvider.");return{enable:async e=>{const t=Array.isArray(e)?e:[e];try{const e=await(J||(J=(async()=>{const e=q.getState().paraConnector;if(e)return e;try{let e;if(n.connectorClass)e=n.connectorClass;else{if("undefined"==typeof window)throw new Error("Para connector requires client-side execution (SSR is unsupported).");const n=new Function("specifier","return import(specifier)"),t=await n("@getpara/graz-integration"),o=t?.ParaGrazConnector;if("function"!=typeof o)throw new Error("Invalid ParaGrazConnector in @getpara/graz-integration. Check the package/export.");e=o}const t=$.getState().chains,o=new e(n,t);if(q.setState(e=>({...e,paraConnector:o})),!o)throw new Error("Para connector initialization failed. Check config and dependencies.");return o}catch(e){if(J=null,"MODULE_NOT_FOUND"===e?.code||e?.message?.includes("Cannot find module")||e?.message?.includes("Failed to resolve"))throw new Error("Para integration package not found. Install @getpara/graz-integration to use Para wallet: npm install @getpara/graz-integration");throw new Error(`Para connector init failed: ${e?.message||"Unknown error"}. Check @getpara/graz-integration and ParaConfig.`)}})()));q.setState({paraConnector:e,status:"connecting"}),await e.enable(t);const o=Object.fromEntries(await Promise.all(t.map(async n=>[n,await e.getKey(n)])));q.setState(e=>({accounts:{...e.accounts||{},...o},activeChainIds:Array.from(new Set([...e.activeChainIds||[],...t])),status:"connected"})),$.setState(e=>({recentChainIds:Array.from(new Set([...e.recentChainIds||[],...t])),walletType:"para",_reconnect:!1,_reconnectConnector:"para"}))}catch(e){q.setState({paraConnector:null,status:"disconnected"});if(e?.message?.includes("not found")||e?.message?.includes("Cannot find"))throw new Error("Para wallet connection failed: Required packages not installed. Install @getpara/graz-integration to enable Para wallet.");throw new Error("Para enable failed"+(e instanceof Error?`: ${e.message}`:""))}},disable:async()=>{const e=q.getState().paraConnector;if(e)try{await e.disconnect(),await e.getParaWebClient().logout()}catch(e){throw new Error("Para disconnect failed"+(e?.message?`: ${e.message}`:". Wallet may already be disconnected."))}finally{q.setState({paraConnector:null,status:"disconnected"})}else q.setState({paraConnector:null,status:"disconnected"})},getKey:async n=>{try{return await e().getKey(n)}catch(e){throw new Error(`Failed to get key${e?.message?`: ${e.message}`:""}. Check chain connection and Cosmos API key settings at developer.getpara.com.`)}},getOfflineSigner:n=>{try{return e().getOfflineSigner(n)}catch(e){throw new Error(`Failed to get offline signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerOnlyAmino:n=>{try{return e().getOfflineSignerOnlyAmino(n)}catch(e){throw new Error(`Failed to get Amino signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerAuto:n=>{try{return e().getOfflineSignerAuto(n)}catch(e){throw new Error(`Failed to get auto signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},signAmino:async(n,t,o,r)=>{try{return await e().signAmino(n,t,o,r)}catch(e){throw new Error(`Amino signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signDirect:async(n,t,o,r)=>{try{return await e().signDirect(n,t,o,r)}catch(e){throw new Error(`Direct signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signArbitrary:async(n,t,o)=>{try{return await e().signArbitrary(n,t,o)}catch(e){throw new Error(`Arbitrary signing failed${e?.message?`: ${e.message}`:""}. User rejected or feature not supported.`)}},experimentalSuggestChain:async()=>{throw new Error("Chain suggestion not supported. Configure chains in Para wallet settings.")}}},ee=()=>{if(void 0!==window.station?.keplr){const e=window.station.keplr;return{subscription:e=>{const n=()=>{de(),e()};return window.addEventListener("station_wallet_change",n),()=>{window.removeEventListener("station_wallet_change",n)}},getKey:async n=>({isKeystone:!1,...await e.getKey(n)}),getOfflineSigner:n=>{try{const t=e.getOfflineSignerOnlyAmino(n),o=(e,n)=>{throw new Error("signDirect not supported by Station")};return Object.assign(t,{signDirect:o})}catch(e){throw console.error(e),e}},experimentalSuggestChain:async n=>{try{if(!n.bech32Config)throw new Error("Bech32Config is required");if(!n.stakeCurrency)throw new Error("StakeCurrency is required");const t=Object.assign(n,{bech32Config:n.bech32Config,chainSymbolImageUrl:n.chainSymbolImageUrl||"",stakeCurrency:{coinDecimals:n.stakeCurrency.coinDecimals,coinDenom:n.stakeCurrency.coinDenom,coinImageUrl:n.stakeCurrency.coinImageUrl||"",coinMinimalDenom:n.stakeCurrency.coinMinimalDenom},currencies:n.currencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom})),feeCurrencies:n.feeCurrencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom,gasPriceStep:{average:e.gasPriceStep?.average||0,high:e.gasPriceStep?.high||0,low:e.gasPriceStep?.low||0}}))});await e.experimentalSuggestChain(t)}catch(e){throw console.error(e),e}},enable:n=>e.enable(n),disable:n=>e.disable(n),getOfflineSignerAuto:n=>e.getOfflineSignerAuto(n),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),signDirect:e.signDirect,signAmino:(n,t,o,r)=>e.signAmino(n,t,o)}}throw $.getState()._notFoundFn(),new Error("window.station is not defined")},ne=()=>{if(void 0!==window.vectis){const e=window.vectis.cosmos;return{enable:n=>e.enable(n),getOfflineSigner:n=>{const t=e.getOfflineSigner(n);return{getAccounts:t.getAccounts,signAmino:t.signAmino,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:f.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}},getOfflineSignerAuto:async n=>{const t=await e.getOfflineSignerAuto(n);return"signAmino"in t?t:"signDirect"in t?{getAccounts:t.getAccounts,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:f.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}:t},getKey:async n=>{const t=await e.getKey(n);return{address:h(t.address).data,algo:t.algo,bech32Address:t.address,name:t.name,pubKey:t.pubKey,isKeystone:!1,isNanoLedger:t.isNanoLedger}},subscription:e=>{const n=()=>{de(),e()};return window.addEventListener("vectis_accountChanged",n),()=>{window.removeEventListener("vectis_accountChanged",n)}},getOfflineSignerOnlyAmino:(...n)=>{const t=n[0];return e.getOfflineSignerAmino(t)},experimentalSuggestChain:async(...n)=>{const[t]=n;if(!t.bech32Config)throw new Error("Bech32Config is required");if(!t.stakeCurrency)throw new Error("StakeCurrency is required");const o={rpcUrl:t.rpc,restUrl:t.rest,prettyName:t.chainName.replace(" ",""),bech32Prefix:t.bech32Config.bech32PrefixAccAddr,currencies:t.currencies,feeCurrencies:t.feeCurrencies,chainId:t.chainId,chainName:t.chainName,bip44:t.bip44,stakeCurrency:t.stakeCurrency,features:t.features};return e.suggestChains([o])},signDirect:async(...n)=>{const{1:t,2:o}=n,r=await e.signDirect(t,{bodyBytes:o.bodyBytes||Uint8Array.from([]),authInfoBytes:o.authInfoBytes||Uint8Array.from([]),accountNumber:f.fromString(o.accountNumber?.toString()||"",!1),chainId:o.chainId||""});return{signature:r.signature,signed:{authInfoBytes:r.signed.authInfoBytes,bodyBytes:r.signed.bodyBytes,chainId:r.signed.chainId,accountNumber:BigInt(r.signed.accountNumber.toString())}}},signAmino:async(...n)=>{const{1:t,2:o}=n;return e.signAmino(t,o)}}}throw $.getState()._notFoundFn(),new Error("window.vectis is not defined")},te=()=>{if("undefined"!=typeof window){const e=navigator.userAgent;return!!/android/i.test(e)||!!/iPad|iPhone|iPod/.test(e)}return!1},oe=(e,n,t=new Error("Promise timed out"))=>{const o=new Promise((e,o)=>{setTimeout(()=>{o(t)},n)});return Promise.race([e,o])},re=e=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");const n=e?.walletType||"walletconnect",t=e?.encoding||"base64",o=n=>{if(!e)return;const{appUrl:t,formatNativeUrl:o}=e;if(te()){if(te()&&navigator.userAgent.toLowerCase().includes("android")){const e=o(t.mobile.android,n,"android");window.open(e,"_self","noreferrer noopener")}if(te()&&(navigator.userAgent.toLowerCase().includes("iphone")||navigator.userAgent.toLowerCase().includes("ipad"))){const e=o(t.mobile.ios,n,"ios");window.open(e,"_self","noreferrer noopener")}}},r=()=>{const{wcSignClients:e}=q.getState();if(!e.get(n))throw new Error("walletConnect.signClient is not defined");e.delete(n),q.setState({wcSignClients:e}),$.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})},i=async e=>{const{wcSignClients:t}=q.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");if(!e)throw new Error("No wallet connect session");await o.disconnect({topic:e,reason:y("USER_DISCONNECTED")}),await s(o)},a=e=>{try{const{wcSignClients:t}=q.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");const r=o.session.getAll(),a=r.at(-1);if(!a)return;if(!(1e3*a.expiry>Date.now()+1e3))throw i(a.topic),new Error("invalid session");try{const n=r.find(n=>n.requiredNamespaces.cosmos?.chains?.includes(`cosmos:${e}`));if(!n)throw new Error("no session");return n}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}return a}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},s=async e=>{try{const n=e.core.pairing.pairings.getAll({active:!1});if(!n.length)return;await Promise.all(n.map(async n=>{await e.core.pairing.pairings.delete(n.topic,{code:7001,message:"clear pairing"})}))}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},c=async t=>{const r="string"==typeof t?[t]:t,{wcSignClients:s,activeChainIds:c}=q.getState(),l=s.get(n);if(!l)throw new Error("enable walletConnect.signClient is not defined");const{walletConnect:u}=$.getState();if(!u?.options?.projectId)throw new Error("walletConnect.options.projectId is not defined");const g=new m({projectId:u.options.projectId,enableExplorer:!1,explorerRecommendedWalletIds:"NONE",...u.walletConnectModal}),w=(e=>{try{return a(e)}catch(e){return}})(r);if(!w){const{uri:n,approval:t}=await oe(l.connect({requiredNamespaces:{cosmos:{methods:["cosmos_getAccounts","cosmos_signAmino","cosmos_signDirect"],chains:r.map(e=>`cosmos:${e}`),events:["chainChanged","accountsChanged"]}}}),15e3,new Error("Connection timeout"));if(!n)throw new Error("No wallet connect uri");e?o(n):await g.openModal({uri:n});const i=async e=>e.aborted?Promise.reject(new Error("User closed wallet connect")):new Promise((n,o)=>{t().then(e=>{const t=e.sessionProperties;if(!t)return o(new Error("No session properties"));const r=JSON.parse(String(t.keys));if(0===r.length)return o(new Error("No accounts"));if(!r[0])return o(new Error("No accounts"));const i={};return r.forEach(e=>{i[e.chainId]={address:e.address,algo:e.algo,bech32Address:e.bech32Address,isNanoLedger:e.isNanoLedger,isKeystone:e.isKeystone,name:e.name,pubKey:e.pubKey}}),q.setState(e=>({accounts:{...e.accounts||{},...i}})),n(e)}).catch(o),e.addEventListener("abort",()=>{o(new Error("User closed wallet connect"))},{once:!0})});try{const e=new AbortController,n=e.signal;g.subscribeModal(n=>{n.open||e.abort()}),await i(n)}catch(e){if(g.closeModal(),!e.message.toLowerCase().includes("no matching key"))return Promise.reject(e)}return e||g.closeModal(),Promise.resolve()}try{await oe((async()=>{const e=Object.fromEntries(await Promise.all((c||r).map(async e=>[e,await d(e)])));q.setState({accounts:e})})(),15e3,new Error("Connection timeout"))}catch(e){if(i(w.topic),!e.message.toLowerCase().includes("no matching key"))throw e}},l=async e=>{const n=await d(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async e=>{const n=a([e]);if(!n?.topic)throw new Error("No wallet connect session");const o=n.sessionProperties&&JSON.parse(String(n.sessionProperties.keys));if(!o)throw new Error("No wallet connect key");if(0===o.length)throw new Error("No wallet connect session");const r=o.find(n=>n.chainId===e);if(!r)throw new Error(`No wallet connect key for chainId ${e}`);return{...r,pubKey:Buffer.from(String(r.pubKey),t)}},u=async(...e)=>{const[r,i,s]=e,{signature:c,signed:l}=await(async(...e)=>{const[r,i,s]=e,{accounts:c,wcSignClients:l}=q.getState(),d=l.get(n);if(!d)throw new Error("walletConnect.signClient is not defined");if(!c)throw new Error("account is not defined");const u=a([r])?.topic;if(!u)throw new Error("No wallet connect session");if(!s.bodyBytes)throw new Error("No bodyBytes");if(!s.authInfoBytes)throw new Error("No authInfoBytes");return o(),await d.request({topic:u,chainId:`cosmos:${r}`,request:{method:"cosmos_signDirect",params:{signerAddress:i,signDoc:{chainId:s.chainId,accountNumber:s.accountNumber?.toString(),bodyBytes:s.bodyBytes?Buffer.from(s.bodyBytes).toString(t):null,authInfoBytes:s.authInfoBytes?Buffer.from(s.authInfoBytes).toString(t):null}}}})})(r,i,s);return{signed:{chainId:l.chainId??"",accountNumber:l.accountNumber?BigInt(l.accountNumber):BigInt(0),authInfoBytes:l.authInfoBytes?new Uint8Array(Buffer.from(l.authInfoBytes,t)):new Uint8Array([]),bodyBytes:l.bodyBytes?new Uint8Array(Buffer.from(l.bodyBytes,t)):new Uint8Array([])},signature:c}},g=async(...e)=>{const[t,r,i,s]=e,c=await(async(...e)=>{const[t,r,i,s]=e,{wcSignClients:c}=q.getState(),l=c.get(n),{accounts:d}=q.getState();if(!l)throw new Error("walletConnect.signClient is not defined");if(!d)throw new Error("account is not defined");const u=a([t])?.topic;if(!u)throw new Error("No wallet connect session");return o(),await l.request({topic:u,chainId:`cosmos:${t}`,request:{method:"cosmos_signDirect",params:{signerAddress:r,signDoc:i}}})})(t,r,i);return c},w=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>g(e,n,t)});return{enable:c,disable:async e=>{const{wcSignClients:t}=q.getState(),o=t.get(n);if(void 0===e){const e=o?.session.getAll();void 0!==e&&await Promise.all(e.map(e=>i(e.topic)))}else"string"==typeof e?await i(a([e])?.topic):await Promise.all(e.map(e=>i(a([e])?.topic)));0===o?.session.getAll().length&&r()},experimentalSuggestChain:async(...e)=>{await Promise.reject(new Error("WalletConnect does not support experimentalSuggestChain"))},getKey:d,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>g(e,n,t)}),getOfflineSignerAuto:async e=>(await d(e)).isNanoLedger?w(e):(e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t)}))(e),getOfflineSignerOnlyAmino:w,signAmino:g,signDirect:u,subscription:e=>{const{wcSignClients:t}=q.getState(),o=t.get(n);if(!o)return()=>{};const i=n=>{const t=q.getState().accounts;if("accountsChanged"===n.params.event.name&&t&&!Object.values(t).map(e=>e.bech32Address).includes(n.params.event.data[0])){const e=n.params.chainId.split(":")[1];e&&c([e])}else e()};return o.events.on("session_delete",r),o.events.on("session_expire",r),o.events.on("session_event",i),()=>{o.events.off("session_delete",r),o.events.off("session_expire",r),o.events.off("session_event",i)}},init:async()=>{const{walletConnect:e}=$.getState();if(!e?.options)throw new Error("walletConnect.options is not defined");const{wcSignClients:t}=q.getState(),o=t.get(n);if(o)return o;const r=await p.init(e.options);return t.set(n,r),q.setState({wcSignClients:t}),r}}},ie=()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Cosmostation mobile is only supported in mobile");return re({encoding:"hex",appUrl:{mobile:{ios:"cosmostation://",android:"cosmostation://"}},walletType:"wc_cosmostation_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,"");return n?`${o}://wc?${n}`:`${o}://wc`}})},ae=()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Keplr mobile is only supported in mobile");return re({encoding:"base64",appUrl:{mobile:{ios:"keplrwallet://",android:"intent://"}},walletType:"wc_keplr_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`:`${o}://wcV2#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},se=()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Leap mobile is only supported in mobile");return re({encoding:"base64",appUrl:{mobile:{ios:"leapcosmos://",android:"intent://"}},walletType:"wc_leap_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`:`${o}://wcV2#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},ce=()=>{if(void 0!==window.xfi?.keplr){const e=window.xfi.keplr,n=e=>{const n=()=>{de(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}};return Object.assign(e,{subscription:n})}throw $.getState()._notFoundFn(),new Error("window.xfi.keplr is not defined")},le=(e=$.getState().walletType)=>{try{return ue(e),!0}catch(e){return!1}},de=()=>{window.sessionStorage.removeItem(F),q.setState(U)},ue=(e=$.getState().walletType)=>{const n=(()=>{switch(e){case"keplr":return V();case"leap":return H();case"cosmostation":return z();case"vectis":return ne();case"walletconnect":return re();case"wc_keplr_mobile":return ae();case"wc_leap_mobile":return se();case"wc_cosmostation_mobile":return ie();case"wc_clot_mobile":return(()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Clot mobile is only supported in mobile");return re({encoding:"base64",appUrl:{mobile:{android:"clot://",ios:"clot://"}},walletType:"wc_clot_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);return"ios"===t?r?`${o}://wcV2?${r}`:`${o}://wcV2`:r?`${o}://wc?uri=${r}`:`${o}://wc`}})})();case"metamask_snap_leap":return Y();case"metamask_snap_cosmos":return(()=>{const e=window.ethereum;let n=window.cosmos;if(e)return{init:async()=>{const t=await e.request({method:"web3_clientVersion"});if(!t.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const o=t.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(o)>=11))throw new Error("Metamask Snap is not supported in this version");return await a()||await s(),window.cosmos=new c,n=window.cosmos,!0},enable:async e=>{await a()||await s()},getOfflineSigner:e=>n.getOfflineSigner(e),experimentalSuggestChain:async e=>{if(!e.bech32Config)throw new Error("Bech32Config is required");if(!e.stakeCurrency)throw new Error("StakeCurrency is required");await n.experimentalSuggestChain({...e,stakeCurrency:e.stakeCurrency,bech32Config:e.bech32Config})},signAmino:async(e,t,o)=>n.signAmino(e,t,o),getKey:async e=>void 0!==R[e]?R[e]:n.getKey(e),getOfflineSignerAuto:async e=>(await n.getKey(e)).isNanoLedger?n.getOfflineSignerOnlyAmino(e):n.getOfflineSigner(e),getOfflineSignerOnlyAmino:e=>n.getOfflineSignerOnlyAmino(e),signDirect:async(e,t,o)=>n.signDirect(e,t,o),signArbitrary:async(e,t,o)=>n.signArbitrary(e,t,o),disable:async e=>{e&&await n.deleteChain(e)}};throw $.getState()._notFoundFn(),new Error("window.ethereum is not defined")})();case"station":return ee();case"xdefi":return ce();case"cosmiframe":return W();case"compass":return j();case"initia":return G();case"okx":return Q();case"para":return Z();case"cactuscosmos":return x();default:throw new Error("Unknown wallet type")}})(),t=$.getState().walletDefaultOptions;return t&&n.setDefaultOptions?.(t),n},ge=()=>Object.fromEntries(K.map(e=>[e,le(e)])),we=e=>"metamask_snap_leap"===e,fe=()=>Boolean(navigator?.userAgent)&&/LeapCosmos/i.test(navigator.userAgent),he=e=>"walletconnect"===e||"wc_keplr_mobile"===e||"wc_leap_mobile"===e||"wc_cosmostation_mobile"===e,me=e=>"para"===e,pe=async e=>{try{const{recentChainIds:n,chains:t,walletType:o}=$.getState(),r=e?.walletType||o;if(he(r)){const e=ue("walletconnect"),{disable:n}=e;n&&n()}if(!le(r))throw new Error(`${r} is not available`);const i=ue(r),a="string"==typeof e?.chainId?[e.chainId]:e?.chainId||n;if(!a)throw new Error("No last known connected chain, connect action requires chain ids");const s=t?.map(e=>e.chainId);a.forEach(e=>{if(!s?.includes(e))throw new Error(`Chain ${e} is not provided in GrazProvider`)}),q.setState(e=>{const n=$.getState()._reconnect||Boolean($.getState()._reconnectConnector)||Boolean(a);return e.activeChainIds&&a.filter(n=>!e.activeChainIds?.includes(n)).length>0?{status:"connecting"}:n?{status:"reconnecting"}:{status:"connecting"}});const{accounts:c}=q.getState();if(await(i.init?.()),await i.enable(a),!he(r)){let e={};if(we(r)){const n={};for await(const e of a)n[e]=await i.getKey(e);e=n}else if(fe()&&i.getKeys){const n=await i.getKeys(a);a.forEach((t,o)=>{const r=n[o];r&&(e[t]=r)})}else e=Object.fromEntries(await Promise.all(a.map(async e=>[e,await i.getKey(e)])));q.setState(n=>({accounts:{...n.accounts||{},...e}}))}$.setState(e=>({recentChainIds:[...e.recentChainIds||[],...a].filter((e,n,t)=>t.indexOf(e)===n)})),q.setState(e=>({activeChainIds:[...e.activeChainIds||[],...a].filter((e,n,t)=>t.indexOf(e)===n)})),$.setState({walletType:r,_reconnect:Boolean(e?.autoReconnect),_reconnectConnector:r}),q.setState({status:"connected"}),"undefined"!=typeof window&&window.sessionStorage.setItem(F,"Active");const l=a.map(e=>t.find(n=>n.chainId===e));return{accounts:q.getState().accounts,walletType:r,chains:l}}catch(e){throw console.error("connect ",e),null===q.getState().accounts&&q.setState({status:"disconnected"}),q.getState().accounts&&q.getState().activeChainIds&&q.setState({status:"connected"}),e}},ye=e=>{"undefined"!=typeof window&&window.sessionStorage.removeItem(F);const n="string"==typeof e?.chainId?[e.chainId]:e?.chainId,t=()=>{if(he($.getState().walletType)){const e=ue("walletconnect"),{disable:n}=e;n&&n()}if(me($.getState().walletType)){const e=ue("para"),{disable:n}=e;n&&n()}};if(n){const e=q.getState().accounts;n.forEach(n=>{delete e?.[n]});0===Object.values(e||{}).length?(t(),q.setState(U),$.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})):(q.setState(t=>({activeChainIds:t.activeChainIds?.filter(e=>!n.includes(e)),accounts:e})),$.setState(e=>({recentChainIds:e.recentChainIds?.filter(e=>!n.includes(e))})))}else t(),q.setState(U),$.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null});return Promise.resolve()},Se=async e=>{const{recentChainIds:n,_reconnectConnector:t,_reconnect:o}=$.getState();try{const e=le(t||void 0);if(n&&e&&t){if(he(t))return;return await pe({chainId:n,walletType:t,autoReconnect:o})}}catch(n){e?.onError?.(n),ye()}},Ce=async e=>{if(!e?.chainId)throw new Error("chainId is required");const{walletType:n}=$.getState(),t=e.walletType||n;if(!le(t))throw new Error(`${t} is not available`);const o=ue(t);return{offlineSigner:o.getOfflineSigner(e.chainId),offlineSignerAmino:o.getOfflineSignerOnlyAmino(e.chainId),offlineSignerAuto:await o.getOfflineSignerAuto(e.chainId)}},Ie=()=>{$.setState({recentChainIds:null})},be=()=>$.getState().recentChainIds,Ee=()=>{const{recentChainIds:e,chains:n}=$.getState();return e?.map(e=>n.find(n=>n.chainId===e))??null},Ae=({chainId:e}={})=>$.getState().chains?.find(n=>n.chainId===e),_e=({chainId:e}={})=>{const n=$.getState().chains;return e?n?.filter(n=>e.includes(n.chainId)):n??void 0},ve=async({chainInfo:e})=>{const{chains:n}=$.getState(),t=n?.find(n=>n.chainId===e.chainId);if(t)throw new Error(`Chain with chainId "${e.chainId}" already exists in the store`);return $.setState(n=>({chains:[...n.chains||[],e]})),e},Oe=async({chainInfo:e,walletType:n})=>{const t=ue(n);await t.experimentalSuggestChain(e);const{chains:o}=$.getState(),r=o?.find(n=>n.chainId===e.chainId);return r||$.setState(n=>({chains:[...n.chains||[],e]})),e},ke=async e=>{const n=$.getState().walletType;await Oe({chainInfo:e.chainInfo,walletType:e.walletType??n});return await pe({chainId:e.chainInfo.chainId,walletType:e.walletType,autoReconnect:e.autoReconnect})},Ne=e=>($.setState(n=>{const t=n.chains??[],o=e.chains,r=new Map;o.forEach(e=>r.set(e.chainId,e)),t.forEach(e=>{r.has(e.chainId)||r.set(e.chainId,e)});const i=Array.from(r.values());return{iframeOptions:e.iframeOptions||n.iframeOptions,walletConnect:e.walletConnect||n.walletConnect,walletType:e.defaultWallet||n.walletType,paraConfig:e.paraConfig||n.paraConfig,walletDefaultOptions:e.walletDefaultOptions||n.walletDefaultOptions,chains:i,chainsConfig:e.chainsConfig||n.chainsConfig,multiChainFetchConcurrency:e.multiChainFetchConcurrency||n.multiChainFetchConcurrency,pingInterval:e.pingInteval||n.pingInterval,_notFoundFn:e.onNotFound||n._notFoundFn,_onReconnectFailed:e.onReconnectFailed||n._onReconnectFailed,_reconnect:void 0===e.autoReconnect||(e.autoReconnect||n._reconnect)}}),e),Be=async({signingClient:e,senderAddress:n,recipientAddress:t,amount:o,fee:r,memo:i})=>{if(!e)throw new Error("No connected account detected");if(!n)throw new Error("senderAddress is not defined");return e.sendTokens(n,t,o,r,i)},Te=async({signingClient:e,senderAddress:n,recipientAddress:t,transferAmount:o,sourcePort:r,sourceChannel:i,timeoutHeight:a,timeoutTimestamp:s,fee:c,memo:l})=>{if(!e)throw new Error("Stargate signing client is not ready");if(!n)throw new Error("senderAddress is not defined");return e.sendIbcTokens(n,t,o,r,i,a,s,c,l)},Pe=async({signingClient:e,senderAddress:n,msg:t,fee:o,options:r,label:i,codeId:a})=>{if(!e)throw new Error("CosmWasm signing client is not ready");return e.instantiate(n,a,t,i,o,r)},De=async({signingClient:e,senderAddress:n,msg:t,fee:o,contractAddress:r,funds:i,memo:a})=>{if(!e)throw new Error("CosmWasm signing client is not ready");return e.execute(n,r,t,o,a,i)},Fe=async(e,n,t)=>{if(!t)throw new Error("CosmWasm client is not ready");return await t.queryContractSmart(e,n)},Le=(e,n,t)=>{if(!t)throw new Error("CosmWasm client is not ready");const o=(new TextEncoder).encode(n);return t.queryContractRaw(e,o)},Ke=e=>e,Me=e=>e,Ue=({chainId:e})=>{const n=$(e=>e.chains);if(!n)throw new Error("No chains found in GrazProvider");return e&&e.length>0?e.map(e=>n.find(n=>n.chainId===e)).filter(Boolean):n},qe=async(e,n)=>{const t=$.getState().multiChainFetchConcurrency,o=await A(e,n,{concurrency:t});return Object.fromEntries(o.map((n,t)=>[e[t].chainId,n]))};function $e(e){const n=Ue({chainId:e?.chainId}),t=I(()=>["USE_STARGATE_CLIENT",n],[n]);return S({queryKey:t,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");return await qe(n,async e=>{const n=$.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await O.connect(t)})},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}function xe(e){const n=Ue({chainId:e?.chainId}),t=I(()=>["USE_COSMWASM_CLIENT",n],[n]);return S({queryKey:t,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");return await qe(n,async e=>{const n=$.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await _.connect(t)})},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}var je=()=>$(B(e=>({walletType:e.walletType,isCosmostation:"cosmostation"===e.walletType,isCosmostationMobile:"wc_cosmostation_mobile"===e.walletType,isKeplr:"keplr"===e.walletType,isKeplrMobile:"wc_keplr_mobile"===e.walletType,isLeap:"leap"===e.walletType,isLeapMobile:"wc_leap_mobile"===e.walletType,isVectis:"vectis"===e.walletType,isWalletConnect:"walletconnect"===e.walletType,isMetamaskSnapLeap:"metamask_snap_leap"===e.walletType,isStation:"station"===e.walletType,isCosmiframe:"cosmiframe"===e.walletType}))),We=e=>{const n=$(n=>e||n.walletType);return S({queryKey:["USE_CHECK_WALLET",n],queryFn:()=>!!n&&le(n)})};function Re(e){const n=$(e=>e.walletType),t=q(e=>e.activeChainIds),o=Ue({chainId:e?.chainId?e.chainId:t||void 0}),r=q(e=>e.accounts),i=q(e=>e.status);b(()=>q.subscribe(e=>e.status,(n,t)=>{if("connected"===n){const{accounts:n,activeChainIds:o}=q.getState(),{chains:r}=$.getState(),{walletType:i}=$.getState();if(!n||!o||!r)return e?.onDisconnect?.();e?.onConnect?.({accounts:n,chains:o.map(e=>r.find(n=>n.chainId===e)),walletType:i,isReconnect:"reconnecting"===t})}"disconnected"===n&&e?.onDisconnect?.()}),[e]);return{data:I(()=>r?((e,n)=>{const t=e.map(n);return Object.fromEntries(t.map((n,t)=>[e[t].chainId,n]))})(o,e=>r[e.chainId]):void 0,[r,o]),isConnected:"connected"===i,isConnecting:"connecting"===i,isDisconnected:"disconnected"===i,isReconnecting:"reconnecting"===i,isLoading:"connecting"===i||"reconnecting"===i,walletType:"connected"===i?n:void 0,reconnect:Se,status:i}}var ze=e=>{const n=Ue({chainId:[e.chainId]})[0],{data:t}=$e({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=I(()=>["USE_ALL_BALANCES",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return S({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getAllBalances(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},Ge=e=>{const n=Ue({chainId:[e.chainId]})[0],{data:t}=$e({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=I(()=>["USE_BALANCE",o,e.chainId,e.bech32Address,e.denom],[e.bech32Address,e.chainId,e.denom,o]);return S({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);const t=await o.getBalance(e.bech32Address,e.denom);return"0"===t.amount?void 0:t},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},Ve=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_CONNECT",e,n,t],mutationFn:pe,onError:(n,t)=>e?.(n,t),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))}),{data:r}=We();return{connect:e=>o.mutate(e),connectAsync:e=>o.mutateAsync(e),error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,isSupported:Boolean(r),status:o.status}},He=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_DISCONNECT",e,n,t],mutationFn:ye,onError:n=>Promise.resolve(e?.(n,void 0)),onMutate:n,onSuccess:()=>Promise.resolve(t?.(void 0))});return{disconnect:e=>o.mutate(e),disconnectAsync:e=>o.mutateAsync(e),error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,status:o.status}};function Xe(e){const n=Ue({chainId:e?.chainId}),t=$(e=>e.walletType),o="connected"===q.getState().status&&q.getState().accounts&&$.getState()._reconnectConnector===t,r=I(()=>["USE_OFFLINE_SIGNERS",n,t],[n,t]);return S({queryKey:r,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chain found");if(!t)throw new Error("Wallet is not defined");if(!le(t))throw new Error(`${t} is not available`);return await qe(n,async e=>await Ce({chainId:e.chainId,walletType:t}))},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&Boolean(o),refetchOnWindowFocus:!1})}var Ye=e=>{const n=Ue({chainId:[e.chainId]})[0],{data:t}=$e({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=I(()=>["USE_BALANCE_STAKED",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return S({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getBalanceStaked(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},Qe=()=>q(e=>e.activeChainIds),Je=()=>{const e=q(e=>e.activeChainIds),n=$(e=>e.chains);return e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean)},Ze=({chainId:e}={})=>$(e=>e.chains)?.find(n=>n.chainId===e),en=({chainId:e}={})=>{const n=$(e=>e.chains);return e?n?.filter(n=>e.includes(n.chainId)):n},nn=({denom:e})=>{const n=Je();return S({queryKey:["USE_ACTIVE_CHAIN_CURRENCY",e],queryFn:({queryKey:[,e]})=>n?.find(n=>n.currencies.find(n=>n.coinMinimalDenom===e))?.currencies.find(e=>e)})},tn=e=>{const n=e.status??"BOND_STATUS_BONDED",t=["USE_ACTIVE_CHAIN_VALIDATORS",e.queryClient,n];return S({queryKey:t,queryFn:async()=>{if(!e.queryClient)throw new Error("Query client is not defined");return await e.queryClient.staking.validators(n)},enabled:void 0!==e.queryClient})},on=()=>({data:$(e=>e.recentChainIds),clear:Ie}),rn=()=>{const e=$(e=>e.recentChainIds),n=$(e=>e.chains),t=e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean);return{data:t,clear:Ie}},an=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_ADD_CHAIN",e,n,t],mutationFn:ve,onError:(n,t)=>Promise.resolve(e?.(n,t.chainInfo)),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>Promise.resolve(t?.(e))});return{addChain:o.mutate,addChainAsync:o.mutateAsync,error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,status:o.status}},sn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_SUGGEST_CHAIN",e,n,t],mutationFn:Oe,onError:(n,t)=>Promise.resolve(e?.(n,t.chainInfo)),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>Promise.resolve(t?.(e))});return{error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,suggest:o.mutate,suggestAsync:o.mutateAsync,status:o.status}},cn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_SUGGEST_CHAIN_AND_CONNECT",e,n,t],mutationFn:ke,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:e=>n?.(e),onSuccess:e=>Promise.resolve(t?.(e))}),{data:r}=We();return{error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,isSupported:Boolean(r),status:o.status,suggestAndConnect:o.mutate,suggestAndConnectAsync:o.mutateAsync}},ln=({onError:e,onLoading:n,onSuccess:t}={})=>{const{mutate:o,mutateAsync:r,...i}=C({mutationKey:["USE_SEND_TOKENS",e,n,t],mutationFn:Be,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))});return{...i,sendTokens:o,sendTokensAsync:r}},dn=({onError:e,onLoading:n,onSuccess:t}={})=>{const{mutate:o,mutateAsync:r,...i}=C({mutationKey:["USE_SEND_IBC_TOKENS",e,n,t],mutationFn:Te,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))});return{...i,sendIbcTokens:o,sendIbcTokensAsync:r}},un=({codeId:e,onError:n,onLoading:t,onSuccess:o})=>{const{mutate:r,mutateAsync:i,...a}=C({mutationKey:["USE_INSTANTIATE_CONTRACT",n,t,o,e],mutationFn:n=>Pe({...n,fee:n.fee??"auto",codeId:e}),onError:(e,t)=>Promise.resolve(n?.(e,t)),onMutate:t,onSuccess:e=>Promise.resolve(o?.(e))});return{...a,instantiateContract:r,instantiateContractAsync:i}},gn=({contractAddress:e,onError:n,onLoading:t,onSuccess:o})=>{const{mutate:r,mutateAsync:i,...a}=C({mutationKey:["USE_EXECUTE_CONTRACT",n,t,o,e],mutationFn:n=>De({...n,fee:n.fee??"auto",contractAddress:e,memo:n.memo??"",funds:n.funds??[]}),onError:(e,t)=>Promise.resolve(n?.(e,t)),onMutate:t,onSuccess:e=>Promise.resolve(o?.(e))});return{...a,executeContract:r,executeContractAsync:i}},wn=e=>{const{data:n}=xe(),t=n&&Object.values(n)[0];return S({queryKey:["USE_QUERY_SMART",e?.address,e?.queryMsg,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.queryMsg)throw new Error("address or queryMsg undefined");return Fe(e.address,e.queryMsg,t)},enabled:Boolean(e?.address)&&Boolean(e?.queryMsg)&&Boolean(t)})},fn=e=>{const{data:n}=xe(),t=n&&Object.values(n)[0];return S({queryKey:["USE_QUERY_RAW",e?.key,e?.address,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.key)throw new Error("address or key undefined");return Le(e.address,e.key,t)},enabled:Boolean(e?.address)&&Boolean(e?.key)&&Boolean(t)})};function hn(e){const n=Ue({chainId:e?.chainId}),t=$(e=>e.walletType),o=q(e=>e.activeChainIds),r="connected"===q.getState().status&&q.getState().accounts&&$.getState()._reconnectConnector===t,i=I(()=>["USE_STARGATE_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return S({queryKey:i,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");return await qe(n,async n=>{if(!o?.includes(n.chainId))return null;if(!le(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return ue(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return ue(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return ue(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=$.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}};return await k.connectWithSigner(a,r,e?.opts?.[n.chainId])})},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})}function mn(e){const n=Ue({chainId:e?.chainId}),t=$(e=>e.walletType),o=q(e=>e.activeChainIds),r="connected"===q.getState().status&&q.getState().accounts&&$.getState()._reconnectConnector===t,i=I(()=>["USE_COSMWASM_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return S({queryKey:i,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");return await qe(n,async n=>{if(!o?.includes(n.chainId))return null;if(!le(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return ue(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return ue(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return ue(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=$.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}},s=i?.gas?N.fromString(`${i.gas.price}${i.gas.denom}`):void 0;return await v.connectWithSigner(a,r,{gasPrice:s,...e?.opts?.[n.chainId]||{}})})},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})}var pn=({children:e})=>{const[n,t]=E(!1);return b(()=>{t(!0)},[]),P(D,{children:n?e:null})},yn=()=>{const e="undefined"!=typeof window&&"Active"===window.sessionStorage.getItem(F),{_reconnect:n,_onReconnectFailed:t,_reconnectConnector:o,iframeOptions:i,chains:a,pingInterval:s}=$(),{activeChainIds:c,wcSignClients:l}=q(),d=le(o||void 0);return b(()=>{const n=async()=>{if(e&&d&&o&&c?.[0]){const e=q.getState().lastPing;if(e&&Date.now()-e<s)return;const n=ue(o);try{if(!await n.getKey(c[0]))throw new Error("No account found");q.setState({lastPing:Date.now()})}catch(e){Se({onError:t})}}};return window.addEventListener("focus",n),()=>{window.removeEventListener("focus",n)}},[e,d,o,a,c,s]),b(()=>{if(!i||!1===i.autoConnect||!i.allowedIframeParentOrigins.length||!a)return;new r(i.allowedIframeParentOrigins).isReady().then(e=>{if(e)return pe({chainId:a.map(e=>e.chainId),walletType:"cosmiframe"})})},[i]),b(()=>{if(o){if(!d)return;(e&&Boolean(c)||!e&&n)&&Se({onError:t})}},[d]),b(()=>{if(o){if(!d)return;"cosmostation"===o&&z().subscription?.(()=>{Se({onError:t})}),"keplr"===o&&V().subscription?.(()=>{Se({onError:t})}),"leap"===o&&H().subscription?.(()=>{Se({onError:t})}),"compass"===o&&j().subscription?.(()=>{Se({onError:t})}),"vectis"===o&&ne().subscription?.(()=>{Se({onError:t})}),"walletconnect"===o&&l.has("walletconnect")&&re().subscription?.(()=>{Se({onError:t})}),"station"===o&&ee().subscription?.(()=>{Se({onError:t})}),"xdefi"===o&&ce().subscription?.(()=>{Se({onError:t})}),"cosmiframe"===o&&W().subscription?.(()=>{Se({onError:t})}),"okx"===o&&Q().subscription?.(()=>{Se({onError:t})})}},[o,l,d]),null},Sn=()=>(yn(),null),Cn=({children:e,grazOptions:n})=>(b(()=>{Ne(n)},[n]),T(pn,{children:[e,P(Sn,{})]}));export{Sn as GrazEvents,Cn as GrazProvider,K as WALLET_TYPES,L as WalletType,ve as addChain,le as checkWallet,Ie as clearRecentChain,de as clearSession,Ne as configureGraz,pe as connect,Me as defineChainInfo,Ke as defineChains,ye as disconnect,De as executeContract,ge as getAvailableWallets,x as getCactusCosmos,Ae as getChainInfo,_e as getChainInfos,z as getCosmostation,V as getKeplr,H as getLeap,Y as getMetamaskSnapLeap,Ce as getOfflineSigners,Q as getOkx,Z as getPara,Le as getQueryRaw,Fe as getQuerySmart,be as getRecentChainIds,Ee as getRecentChains,ne as getVectis,ie as getWCCosmostation,ae as getWCKeplr,se as getWCLeap,ue as getWallet,re as getWalletConnect,Pe as instantiateContract,fe as isLeapDappBrowser,we as isLeapSnaps,me as isPara,he as isWalletConnect,Se as reconnect,Te as sendIbcTokens,Be as sendTokens,Oe as suggestChain,ke as suggestChainAndConnect,Re as useAccount,nn as useActiveChainCurrency,Qe as useActiveChainIds,Je as useActiveChains,je as useActiveWalletType,an as useAddChain,Ge as useBalance,Ye as useBalanceStaked,ze as useBalances,Ze as useChainInfo,en as useChainInfos,We as useCheckWallet,Ve as useConnect,xe as useCosmWasmClient,mn as useCosmWasmSigningClient,He as useDisconnect,gn as useExecuteContract,yn as useGrazEvents,un as useInstantiateContract,Xe as useOfflineSigners,tn as useQueryClientValidators,fn as useQueryRaw,wn as useQuerySmart,on as useRecentChainIds,rn as useRecentChains,dn as useSendIbcTokens,ln as useSendTokens,$e as useStargateClient,hn as useStargateSigningClient,sn as useSuggestChain,cn as useSuggestChainAndConnect};
1
+ import{create as e}from"zustand";import{createJSONStorage as n,subscribeWithSelector as t,persist as o}from"zustand/middleware";import{Cosmiframe as r,isInIframe as i}from"@dao-dao/cosmiframe";import{isSnapInstalled as a,installSnap as s,CosmosSnap as c}from"@cosmsnap/snapper";import{encodeEd25519Pubkey as l,encodeSecp256k1Pubkey as d,pubkeyType as u,rawEd25519PubkeyToRawAddress as g,rawSecp256k1PubkeyToRawAddress as w}from"@cosmjs/amino";import f from"long";import{fromBech32 as h}from"@cosmjs/encoding";import{WalletConnectModal as m}from"@walletconnect/modal";import{SignClient as p}from"@walletconnect/sign-client";import{getSdkError as y}from"@walletconnect/utils";import{useQuery as S,useMutation as C}from"@tanstack/react-query";import{useMemo as I,useEffect as b,useState as E}from"react";import A from"p-map";import{CosmWasmClient as _,SigningCosmWasmClient as v}from"@cosmjs/cosmwasm-stargate";import{StargateClient as O,SigningStargateClient as k,GasPrice as B}from"@cosmjs/stargate";import{useShallow as N}from"zustand/shallow";import{jsxs as T,jsx as P,Fragment as D}from"react/jsx-runtime";var F="graz-reconnect-session",L=(e=>(e.KEPLR="keplr",e.LEAP="leap",e.VECTIS="vectis",e.COSMOSTATION="cosmostation",e.WALLETCONNECT="walletconnect",e.WC_KEPLR_MOBILE="wc_keplr_mobile",e.WC_LEAP_MOBILE="wc_leap_mobile",e.WC_COSMOSTATION_MOBILE="wc_cosmostation_mobile",e.WC_CLOT_MOBILE="wc_clot_mobile",e.METAMASK_SNAP_LEAP="metamask_snap_leap",e.METAMASK_SNAP_COSMOS="metamask_snap_cosmos",e.STATION="station",e.XDEFI="xdefi",e.COSMIFRAME="cosmiframe",e.COMPASS="compass",e.INITIA="initia",e.OKX="okx",e.PARA="para",e.CACTUSCOSMOS="cactuscosmos",e))(L||{}),K=["keplr","leap","vectis","cosmostation","walletconnect","wc_keplr_mobile","wc_leap_mobile","wc_cosmostation_mobile","wc_clot_mobile","metamask_snap_leap","station","xdefi","metamask_snap_cosmos","cosmiframe","compass","initia","okx","para","cactuscosmos"],M={iframeOptions:null,recentChainIds:null,chains:null,chainsConfig:null,paraConfig:null,multiChainFetchConcurrency:3,walletType:"keplr",walletConnect:{options:null,walletConnectModal:null},walletDefaultOptions:null,pingInterval:36e5,_notFoundFn:()=>null,_onReconnectFailed:()=>null,_reconnect:!1,_reconnectConnector:null},U={accounts:null,activeChainIds:null,status:"disconnected",lastPing:null,wcSignClients:new Map,paraConnector:null},q=e(t(o(()=>U,{name:"graz-session",version:2,partialize:e=>({accounts:e.accounts,activeChainIds:e.activeChainIds,lastPing:e.lastPing,status:e.status}),storage:n(()=>sessionStorage)}))),$=e(t(o(()=>M,{name:"graz-internal",partialize:e=>({recentChainIds:e.recentChainIds,_reconnect:e._reconnect,_reconnectConnector:e._reconnectConnector,walletType:e.walletType,chains:e.chains}),version:3}))),x=()=>{if(void 0!==window.cactuslink_cosmos){const e=window.cactuslink_cosmos,n=e=>{const n=()=>{de(),e()};return window.addEventListener("accountsChanged",n),()=>{window.removeEventListener("accountsChanged",n)}};return{...Object.assign(e,{subscription:n}),getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSigner(n),experimentalSuggestChain:async()=>{throw new Error("Cactus Cosmos does not support experimentalSuggestChain")}}}throw $.getState()._notFoundFn(),new Error("window.cactuslink_cosmos is not defined")},j=()=>{if(void 0!==window.compass){const e=window.compass,n=e=>{const n=()=>{de(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.leap is not defined")},W=()=>{const e=$.getState();if(!e.iframeOptions)throw e._notFoundFn(),new Error("no iframe options set");if(!i())throw e._notFoundFn(),new Error("not in iframe");if(!e.iframeOptions.allowedIframeParentOrigins.length)throw e._notFoundFn(),new Error("no iframe allowed origins");const n=new r(e.iframeOptions.allowedIframeParentOrigins).getKeplrClient();return{enable:n.enable.bind(n),getKey:n.getKey.bind(n),getOfflineSigner:n.getOfflineSigner.bind(n),getOfflineSignerAuto:n.getOfflineSignerAuto.bind(n),getOfflineSignerOnlyAmino:n.getOfflineSignerOnlyAmino.bind(n),experimentalSuggestChain:n.experimentalSuggestChain.bind(n),signDirect:n.signDirect.bind(n),signAmino:n.signAmino.bind(n)}},R={},V=()=>{if(void 0!==window.cosmostation?.providers.keplr){const e=window.cosmostation.providers.keplr,n=e=>{const n=()=>{de(),e()};return window.addEventListener("cosmostation_keystorechange",n),()=>{window.removeEventListener("cosmostation_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.cosmostation.providers.keplr is not defined")},z=()=>{if(void 0!==window.initia){const e=window.initia;return{enable:async()=>{await e.getAddress()},getKey:async n=>{const t=e.getOfflineSigner(n),[o]=await t.getAccounts();if(!o)throw new Error("Wallet connection failed");const r=(()=>{switch(o.algo){case"secp256k1":return w(o.pubkey);case"ed25519":return g(o.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{name:(i=o.address,`${i.slice(0,6)}...${i.slice(-6)}`),algo:o.algo,pubKey:o.pubkey,bech32Address:o.address,address:r,isNanoLedger:!1,isKeystone:!1};var i},getOfflineSigner:n=>{const t=e.getOfflineSigner(n),o=e.getOfflineSignerOnlyAmino(n);return{getAccounts:t.getAccounts.bind(t),signDirect:t.signDirect.bind(t),signAmino:o.signAmino.bind(o)}},getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),experimentalSuggestChain:n=>e.requestAddInitiaLayer({chain_id:n.chainId,chain_name:n.chainName,bech32_prefix:"init",bech32_config:n.bech32Config,slip44:n.bip44.coinType,logo_URIs:{png:n.chainSymbolImageUrl},fees:{fee_tokens:n.feeCurrencies.map(e=>({denom:e.coinDenom,amount:e.coinMinimalDenom,low_gas_price:e.gasPriceStep?.low,average_gas_price:e.gasPriceStep?.average,high_gas_price:e.gasPriceStep?.high}))},apis:{rpc:[{address:n.rpc}],rest:[{address:n.rest}]}}),signDirect:(...n)=>{const[t,o,r]=n;return e.getOfflineSigner(t).signDirect(o,(e=>{const{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}=e;if(!(n&&t&&o&&r))throw new Error("Invalid sign doc");return{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}})(r))},signAmino:(...n)=>{const[t,o,r]=n;return e.getOfflineSignerOnlyAmino(t).signAmino(o,r)},signArbitrary:async(n,t,o)=>{const r=e.getOfflineSigner(n),i=(await r.getAccounts()).find(e=>e.address===t);if(!i)throw new Error(`Wallet not connected to account ${t}`);const a=(()=>{switch(i.algo){case"secp256k1":return d(i.pubkey);case"ed25519":return l(i.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{signature:await e.signArbitrary(o),pub_key:{type:"secp256k1"===i.algo?u.secp256k1:u.ed25519,value:a.value}}},subscription:e=>{const n=()=>{de(),e()};return window.addEventListener("initia_keystorechange",n),()=>{window.removeEventListener("initia_keystorechange",n)}}}}throw $.getState()._notFoundFn(),new Error("window.initia is not defined")},G=()=>{if(void 0!==window.keplr){const e=window.keplr,n=e=>{const n=()=>{de(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.keplr is not defined")},H=()=>{if(void 0!==window.leap){const e=window.leap,n=e=>{const n=()=>{de(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.leap is not defined")},X={},Y=()=>(e=>{const n=window.ethereum;if(n&&e){const t=async()=>await n.request({method:"wallet_getSnaps"}),o=async n=>{try{const o=await t();return Object.values(o).find(t=>t.id===e.id&&(!n||t.version===n))}catch(e){return}},r=async()=>{await n.request({method:"wallet_requestSnaps",params:{[e.id]:e.params||{}}})},i=async()=>{const e=await n.request({method:"web3_clientVersion"});if(!e.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const t=e.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(t)>=11))throw new Error("Metamask Snap is not supported in this version");return await o()||await r(),!0},a=async(t,o,r)=>{const i=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signDirect",params:{chainId:t,signerAddress:o,signDoc:r}}}}),a=r.accountNumber,s=new f(a.low,a.high,a.unsigned);return{signature:i.signature,signed:{...i.signed,accountNumber:s.toString(),authInfoBytes:new Uint8Array(Object.values(i.signed.authInfoBytes)),bodyBytes:new Uint8Array(Object.values(i.signed.bodyBytes))}}},s=async(t,o,r)=>await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signAmino",params:{chainId:t,signerAddress:o,signDoc:r}}}}),c=async t=>{if(void 0!==X[t])return X[t];const o=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"getKey",params:{chainId:t}}}});if(!o)throw new Error("No response from Metamask");return o.pubKey=Uint8Array.from(Object.values(o.pubkey)),delete o.pubkey,X[t]=o,X[t]},l=async e=>{const n=await c(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async(...e)=>{const[n,t,o,r]=e;return await s(n,t,o)},u=async(...e)=>{const[n,t,o]=e,r={...o,accountNumber:f.fromString(o.accountNumber?.toString()||"0"),authInfoBytes:o.authInfoBytes,bodyBytes:o.bodyBytes};return await a(n,t,r)},g=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>d(e,n,t)});return{enable:async e=>{await o()||await r()},experimentalSuggestChain:async(...t)=>{await i(),await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"suggestChain",params:{chainInfo:t[0]}}}})},getKey:c,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>d(e,n,t)}),getOfflineSignerAuto:async e=>g(e),getOfflineSignerOnlyAmino:g,init:i,signAmino:d,signDirect:u}}throw $.getState()._notFoundFn(),new Error("window.ethereum is not defined")})({id:"npm:@leapwallet/metamask-cosmos-snap"}),Q=()=>{if(void 0!==window.okxwallet?.keplr){const e=window.okxwallet.keplr,n=e=>{const n=()=>{de(),e()};return window.okxwallet?.on("accountsChanged",n),()=>{window.okxwallet?.removeListener("accountsChanged",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw $.getState()._notFoundFn(),new Error("window.okxwallet.keplr is not defined")},J=null,Z=()=>{const e=()=>{const e=q.getState().paraConnector;if(!e)throw new Error("Para connector not initialized. Call connect() first or check paraConfig in GrazProvider.");return e},n=$.getState().paraConfig;if(!n?.paraWeb)throw new Error("Missing Para config. Provide paraConfig with 'paraWeb' to GrazProvider.");return{enable:async e=>{const t=Array.isArray(e)?e:[e];try{const e=await(J||(J=(async()=>{const e=q.getState().paraConnector;if(e)return e;if(!n.connectorClass)throw new Error("Para connector class not provided. Provide 'connectorClass' in paraConfig to use Para wallet.");try{const e=$.getState().chains,t=new n.connectorClass(n,e);if(!t)throw new Error("Para connector initialization failed. Check config and dependencies.");return q.setState(e=>({...e,paraConnector:t})),t}catch(e){throw J=null,new Error(`Para connector init failed: ${e?.message||"Unknown error"}. Check ParaConfig and connectorClass.`)}})()));q.setState({paraConnector:e,status:"connecting"}),await e.enable(t);const o=Object.fromEntries(await Promise.all(t.map(async n=>[n,await e.getKey(n)])));q.setState(e=>({accounts:{...e.accounts||{},...o},activeChainIds:Array.from(new Set([...e.activeChainIds||[],...t])),status:"connected"})),$.setState(e=>({recentChainIds:Array.from(new Set([...e.recentChainIds||[],...t])),walletType:"para",_reconnect:!1,_reconnectConnector:"para"}))}catch(e){throw q.setState({paraConnector:null,status:"disconnected"}),new Error("Para enable failed"+(e instanceof Error?`: ${e.message}`:""))}},disable:async()=>{const e=q.getState().paraConnector;if(e)try{await e.disconnect(),await e.getParaWebClient().logout()}catch(e){throw new Error("Para disconnect failed"+(e?.message?`: ${e.message}`:". Wallet may already be disconnected."))}finally{q.setState({paraConnector:null,status:"disconnected"})}else q.setState({paraConnector:null,status:"disconnected"})},getKey:async n=>{try{return await e().getKey(n)}catch(e){throw new Error(`Failed to get key${e?.message?`: ${e.message}`:""}. Check chain connection and Cosmos API key settings at developer.getpara.com.`)}},getOfflineSigner:n=>{try{return e().getOfflineSigner(n)}catch(e){throw new Error(`Failed to get offline signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerOnlyAmino:n=>{try{return e().getOfflineSignerOnlyAmino(n)}catch(e){throw new Error(`Failed to get Amino signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerAuto:n=>{try{return e().getOfflineSignerAuto(n)}catch(e){throw new Error(`Failed to get auto signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},signAmino:async(n,t,o,r)=>{try{return await e().signAmino(n,t,o,r)}catch(e){throw new Error(`Amino signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signDirect:async(n,t,o,r)=>{try{return await e().signDirect(n,t,o,r)}catch(e){throw new Error(`Direct signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signArbitrary:async(n,t,o)=>{try{return await e().signArbitrary(n,t,o)}catch(e){throw new Error(`Arbitrary signing failed${e?.message?`: ${e.message}`:""}. User rejected or feature not supported.`)}},experimentalSuggestChain:async()=>{throw new Error("Chain suggestion not supported. Configure chains in Para wallet settings.")}}},ee=()=>{if(void 0!==window.station?.keplr){const e=window.station.keplr;return{subscription:e=>{const n=()=>{de(),e()};return window.addEventListener("station_wallet_change",n),()=>{window.removeEventListener("station_wallet_change",n)}},getKey:async n=>({isKeystone:!1,...await e.getKey(n)}),getOfflineSigner:n=>{try{const t=e.getOfflineSignerOnlyAmino(n),o=(e,n)=>{throw new Error("signDirect not supported by Station")};return Object.assign(t,{signDirect:o})}catch(e){throw console.error(e),e}},experimentalSuggestChain:async n=>{try{if(!n.bech32Config)throw new Error("Bech32Config is required");if(!n.stakeCurrency)throw new Error("StakeCurrency is required");const t=Object.assign(n,{bech32Config:n.bech32Config,chainSymbolImageUrl:n.chainSymbolImageUrl||"",stakeCurrency:{coinDecimals:n.stakeCurrency.coinDecimals,coinDenom:n.stakeCurrency.coinDenom,coinImageUrl:n.stakeCurrency.coinImageUrl||"",coinMinimalDenom:n.stakeCurrency.coinMinimalDenom},currencies:n.currencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom})),feeCurrencies:n.feeCurrencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom,gasPriceStep:{average:e.gasPriceStep?.average||0,high:e.gasPriceStep?.high||0,low:e.gasPriceStep?.low||0}}))});await e.experimentalSuggestChain(t)}catch(e){throw console.error(e),e}},enable:n=>e.enable(n),disable:n=>e.disable(n),getOfflineSignerAuto:n=>e.getOfflineSignerAuto(n),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),signDirect:e.signDirect,signAmino:(n,t,o,r)=>e.signAmino(n,t,o)}}throw $.getState()._notFoundFn(),new Error("window.station is not defined")},ne=()=>{if(void 0!==window.vectis){const e=window.vectis.cosmos;return{enable:n=>e.enable(n),getOfflineSigner:n=>{const t=e.getOfflineSigner(n);return{getAccounts:t.getAccounts,signAmino:t.signAmino,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:f.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}},getOfflineSignerAuto:async n=>{const t=await e.getOfflineSignerAuto(n);return"signAmino"in t?t:"signDirect"in t?{getAccounts:t.getAccounts,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:f.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}:t},getKey:async n=>{const t=await e.getKey(n);return{address:h(t.address).data,algo:t.algo,bech32Address:t.address,name:t.name,pubKey:t.pubKey,isKeystone:!1,isNanoLedger:t.isNanoLedger}},subscription:e=>{const n=()=>{de(),e()};return window.addEventListener("vectis_accountChanged",n),()=>{window.removeEventListener("vectis_accountChanged",n)}},getOfflineSignerOnlyAmino:(...n)=>{const t=n[0];return e.getOfflineSignerAmino(t)},experimentalSuggestChain:async(...n)=>{const[t]=n;if(!t.bech32Config)throw new Error("Bech32Config is required");if(!t.stakeCurrency)throw new Error("StakeCurrency is required");const o={rpcUrl:t.rpc,restUrl:t.rest,prettyName:t.chainName.replace(" ",""),bech32Prefix:t.bech32Config.bech32PrefixAccAddr,currencies:t.currencies,feeCurrencies:t.feeCurrencies,chainId:t.chainId,chainName:t.chainName,bip44:t.bip44,stakeCurrency:t.stakeCurrency,features:t.features};return e.suggestChains([o])},signDirect:async(...n)=>{const{1:t,2:o}=n,r=await e.signDirect(t,{bodyBytes:o.bodyBytes||Uint8Array.from([]),authInfoBytes:o.authInfoBytes||Uint8Array.from([]),accountNumber:f.fromString(o.accountNumber?.toString()||"",!1),chainId:o.chainId||""});return{signature:r.signature,signed:{authInfoBytes:r.signed.authInfoBytes,bodyBytes:r.signed.bodyBytes,chainId:r.signed.chainId,accountNumber:BigInt(r.signed.accountNumber.toString())}}},signAmino:async(...n)=>{const{1:t,2:o}=n;return e.signAmino(t,o)}}}throw $.getState()._notFoundFn(),new Error("window.vectis is not defined")},te=()=>{if("undefined"!=typeof window){const e=navigator.userAgent;return!!/android/i.test(e)||!!/iPad|iPhone|iPod/.test(e)}return!1},oe=(e,n,t=new Error("Promise timed out"))=>{const o=new Promise((e,o)=>{setTimeout(()=>{o(t)},n)});return Promise.race([e,o])},re=e=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");const n=e?.walletType||"walletconnect",t=e?.encoding||"base64",o=n=>{if(!e)return;const{appUrl:t,formatNativeUrl:o}=e;if(te()){if(te()&&navigator.userAgent.toLowerCase().includes("android")){const e=o(t.mobile.android,n,"android");window.open(e,"_self","noreferrer noopener")}if(te()&&(navigator.userAgent.toLowerCase().includes("iphone")||navigator.userAgent.toLowerCase().includes("ipad"))){const e=o(t.mobile.ios,n,"ios");window.open(e,"_self","noreferrer noopener")}}},r=()=>{const{wcSignClients:e}=q.getState();if(!e.get(n))throw new Error("walletConnect.signClient is not defined");e.delete(n),q.setState({wcSignClients:e}),$.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})},i=async e=>{const{wcSignClients:t}=q.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");if(!e)throw new Error("No wallet connect session");await o.disconnect({topic:e,reason:y("USER_DISCONNECTED")}),await s(o)},a=e=>{try{const{wcSignClients:t}=q.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");const r=o.session.getAll(),a=r.at(-1);if(!a)return;if(!(1e3*a.expiry>Date.now()+1e3))throw i(a.topic),new Error("invalid session");try{const n=r.find(n=>n.requiredNamespaces.cosmos?.chains?.includes(`cosmos:${e}`));if(!n)throw new Error("no session");return n}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}return a}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},s=async e=>{try{const n=e.core.pairing.pairings.getAll({active:!1});if(!n.length)return;await Promise.all(n.map(async n=>{await e.core.pairing.pairings.delete(n.topic,{code:7001,message:"clear pairing"})}))}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},c=async t=>{const r="string"==typeof t?[t]:t,{wcSignClients:s,activeChainIds:c}=q.getState(),l=s.get(n);if(!l)throw new Error("enable walletConnect.signClient is not defined");const{walletConnect:u}=$.getState();if(!u?.options?.projectId)throw new Error("walletConnect.options.projectId is not defined");const g=new m({projectId:u.options.projectId,enableExplorer:!1,explorerRecommendedWalletIds:"NONE",...u.walletConnectModal}),w=(e=>{try{return a(e)}catch(e){return}})(r);if(!w){const{uri:n,approval:t}=await oe(l.connect({requiredNamespaces:{cosmos:{methods:["cosmos_getAccounts","cosmos_signAmino","cosmos_signDirect"],chains:r.map(e=>`cosmos:${e}`),events:["chainChanged","accountsChanged"]}}}),15e3,new Error("Connection timeout"));if(!n)throw new Error("No wallet connect uri");e?o(n):await g.openModal({uri:n});const i=async e=>e.aborted?Promise.reject(new Error("User closed wallet connect")):new Promise((n,o)=>{t().then(e=>{const t=e.sessionProperties;if(!t)return o(new Error("No session properties"));const r=JSON.parse(String(t.keys));if(0===r.length)return o(new Error("No accounts"));if(!r[0])return o(new Error("No accounts"));const i={};return r.forEach(e=>{i[e.chainId]={address:e.address,algo:e.algo,bech32Address:e.bech32Address,isNanoLedger:e.isNanoLedger,isKeystone:e.isKeystone,name:e.name,pubKey:e.pubKey}}),q.setState(e=>({accounts:{...e.accounts||{},...i}})),n(e)}).catch(o),e.addEventListener("abort",()=>{o(new Error("User closed wallet connect"))},{once:!0})});try{const e=new AbortController,n=e.signal;g.subscribeModal(n=>{n.open||e.abort()}),await i(n)}catch(e){if(g.closeModal(),!e.message.toLowerCase().includes("no matching key"))return Promise.reject(e)}return e||g.closeModal(),Promise.resolve()}try{await oe((async()=>{const e=Object.fromEntries(await Promise.all((c||r).map(async e=>[e,await d(e)])));q.setState({accounts:e})})(),15e3,new Error("Connection timeout"))}catch(e){if(i(w.topic),!e.message.toLowerCase().includes("no matching key"))throw e}},l=async e=>{const n=await d(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async e=>{const n=a([e]);if(!n?.topic)throw new Error("No wallet connect session");const o=n.sessionProperties&&JSON.parse(String(n.sessionProperties.keys));if(!o)throw new Error("No wallet connect key");if(0===o.length)throw new Error("No wallet connect session");const r=o.find(n=>n.chainId===e);if(!r)throw new Error(`No wallet connect key for chainId ${e}`);return{...r,pubKey:Buffer.from(String(r.pubKey),t)}},u=async(...e)=>{const[r,i,s]=e,{signature:c,signed:l}=await(async(...e)=>{const[r,i,s]=e,{accounts:c,wcSignClients:l}=q.getState(),d=l.get(n);if(!d)throw new Error("walletConnect.signClient is not defined");if(!c)throw new Error("account is not defined");const u=a([r])?.topic;if(!u)throw new Error("No wallet connect session");if(!s.bodyBytes)throw new Error("No bodyBytes");if(!s.authInfoBytes)throw new Error("No authInfoBytes");return o(),await d.request({topic:u,chainId:`cosmos:${r}`,request:{method:"cosmos_signDirect",params:{signerAddress:i,signDoc:{chainId:s.chainId,accountNumber:s.accountNumber?.toString(),bodyBytes:s.bodyBytes?Buffer.from(s.bodyBytes).toString(t):null,authInfoBytes:s.authInfoBytes?Buffer.from(s.authInfoBytes).toString(t):null}}}})})(r,i,s);return{signed:{chainId:l.chainId??"",accountNumber:l.accountNumber?BigInt(l.accountNumber):BigInt(0),authInfoBytes:l.authInfoBytes?new Uint8Array(Buffer.from(l.authInfoBytes,t)):new Uint8Array([]),bodyBytes:l.bodyBytes?new Uint8Array(Buffer.from(l.bodyBytes,t)):new Uint8Array([])},signature:c}},g=async(...e)=>{const[t,r,i,s]=e,c=await(async(...e)=>{const[t,r,i,s]=e,{wcSignClients:c}=q.getState(),l=c.get(n),{accounts:d}=q.getState();if(!l)throw new Error("walletConnect.signClient is not defined");if(!d)throw new Error("account is not defined");const u=a([t])?.topic;if(!u)throw new Error("No wallet connect session");return o(),await l.request({topic:u,chainId:`cosmos:${t}`,request:{method:"cosmos_signDirect",params:{signerAddress:r,signDoc:i}}})})(t,r,i);return c},w=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>g(e,n,t)});return{enable:c,disable:async e=>{const{wcSignClients:t}=q.getState(),o=t.get(n);if(void 0===e){const e=o?.session.getAll();void 0!==e&&await Promise.all(e.map(e=>i(e.topic)))}else"string"==typeof e?await i(a([e])?.topic):await Promise.all(e.map(e=>i(a([e])?.topic)));0===o?.session.getAll().length&&r()},experimentalSuggestChain:async(...e)=>{await Promise.reject(new Error("WalletConnect does not support experimentalSuggestChain"))},getKey:d,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>g(e,n,t)}),getOfflineSignerAuto:async e=>(await d(e)).isNanoLedger?w(e):(e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t)}))(e),getOfflineSignerOnlyAmino:w,signAmino:g,signDirect:u,subscription:e=>{const{wcSignClients:t}=q.getState(),o=t.get(n);if(!o)return()=>{};const i=n=>{const t=q.getState().accounts;if("accountsChanged"===n.params.event.name&&t&&!Object.values(t).map(e=>e.bech32Address).includes(n.params.event.data[0])){const e=n.params.chainId.split(":")[1];e&&c([e])}else e()};return o.events.on("session_delete",r),o.events.on("session_expire",r),o.events.on("session_event",i),()=>{o.events.off("session_delete",r),o.events.off("session_expire",r),o.events.off("session_event",i)}},init:async()=>{const{walletConnect:e}=$.getState();if(!e?.options)throw new Error("walletConnect.options is not defined");const{wcSignClients:t}=q.getState(),o=t.get(n);if(o)return o;const r=await p.init(e.options);return t.set(n,r),q.setState({wcSignClients:t}),r}}},ie=()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Cosmostation mobile is only supported in mobile");return re({encoding:"hex",appUrl:{mobile:{ios:"cosmostation://",android:"cosmostation://"}},walletType:"wc_cosmostation_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,"");return n?`${o}://wc?${n}`:`${o}://wc`}})},ae=()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Keplr mobile is only supported in mobile");return re({encoding:"base64",appUrl:{mobile:{ios:"keplrwallet://",android:"intent://"}},walletType:"wc_keplr_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`:`${o}://wcV2#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},se=()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Leap mobile is only supported in mobile");return re({encoding:"base64",appUrl:{mobile:{ios:"leapcosmos://",android:"intent://"}},walletType:"wc_leap_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`:`${o}://wcV2#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},ce=()=>{if(void 0!==window.xfi?.keplr){const e=window.xfi.keplr,n=e=>{const n=()=>{de(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}};return Object.assign(e,{subscription:n})}throw $.getState()._notFoundFn(),new Error("window.xfi.keplr is not defined")},le=(e=$.getState().walletType)=>{try{return ue(e),!0}catch(e){return!1}},de=()=>{window.sessionStorage.removeItem(F),q.setState(U)},ue=(e=$.getState().walletType)=>{const n=(()=>{switch(e){case"keplr":return G();case"leap":return H();case"cosmostation":return V();case"vectis":return ne();case"walletconnect":return re();case"wc_keplr_mobile":return ae();case"wc_leap_mobile":return se();case"wc_cosmostation_mobile":return ie();case"wc_clot_mobile":return(()=>{if(!$.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!te())throw new Error("WalletConnect Clot mobile is only supported in mobile");return re({encoding:"base64",appUrl:{mobile:{android:"clot://",ios:"clot://"}},walletType:"wc_clot_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);return"ios"===t?r?`${o}://wcV2?${r}`:`${o}://wcV2`:r?`${o}://wc?uri=${r}`:`${o}://wc`}})})();case"metamask_snap_leap":return Y();case"metamask_snap_cosmos":return(()=>{const e=window.ethereum;let n=window.cosmos;if(e)return{init:async()=>{const t=await e.request({method:"web3_clientVersion"});if(!t.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const o=t.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(o)>=11))throw new Error("Metamask Snap is not supported in this version");return await a()||await s(),window.cosmos=new c,n=window.cosmos,!0},enable:async e=>{await a()||await s()},getOfflineSigner:e=>n.getOfflineSigner(e),experimentalSuggestChain:async e=>{if(!e.bech32Config)throw new Error("Bech32Config is required");if(!e.stakeCurrency)throw new Error("StakeCurrency is required");await n.experimentalSuggestChain({...e,stakeCurrency:e.stakeCurrency,bech32Config:e.bech32Config})},signAmino:async(e,t,o)=>n.signAmino(e,t,o),getKey:async e=>void 0!==R[e]?R[e]:n.getKey(e),getOfflineSignerAuto:async e=>(await n.getKey(e)).isNanoLedger?n.getOfflineSignerOnlyAmino(e):n.getOfflineSigner(e),getOfflineSignerOnlyAmino:e=>n.getOfflineSignerOnlyAmino(e),signDirect:async(e,t,o)=>n.signDirect(e,t,o),signArbitrary:async(e,t,o)=>n.signArbitrary(e,t,o),disable:async e=>{e&&await n.deleteChain(e)}};throw $.getState()._notFoundFn(),new Error("window.ethereum is not defined")})();case"station":return ee();case"xdefi":return ce();case"cosmiframe":return W();case"compass":return j();case"initia":return z();case"okx":return Q();case"para":return Z();case"cactuscosmos":return x();default:throw new Error("Unknown wallet type")}})(),t=$.getState().walletDefaultOptions;return t&&n.setDefaultOptions?.(t),n},ge=()=>Object.fromEntries(K.map(e=>[e,le(e)])),we=e=>"metamask_snap_leap"===e,fe=()=>Boolean(navigator?.userAgent)&&/LeapCosmos/i.test(navigator.userAgent),he=e=>"walletconnect"===e||"wc_keplr_mobile"===e||"wc_leap_mobile"===e||"wc_cosmostation_mobile"===e,me=e=>"para"===e,pe=async e=>{try{const{recentChainIds:n,chains:t,walletType:o}=$.getState(),r=e?.walletType||o;if(he(r)){const e=ue("walletconnect"),{disable:n}=e;n&&n()}if(!le(r))throw new Error(`${r} is not available`);const i=ue(r),a="string"==typeof e?.chainId?[e.chainId]:e?.chainId||n;if(!a)throw new Error("No last known connected chain, connect action requires chain ids");const s=t?.map(e=>e.chainId);a.forEach(e=>{if(!s?.includes(e))throw new Error(`Chain ${e} is not provided in GrazProvider`)}),q.setState(e=>{const n=$.getState()._reconnect||Boolean($.getState()._reconnectConnector)||Boolean(a);return e.activeChainIds&&a.filter(n=>!e.activeChainIds?.includes(n)).length>0?{status:"connecting"}:n?{status:"reconnecting"}:{status:"connecting"}});const{accounts:c}=q.getState();if(await(i.init?.()),await i.enable(a),!he(r)){let e={};if(we(r)){const n={};for await(const e of a)n[e]=await i.getKey(e);e=n}else if(fe()&&i.getKeys){const n=await i.getKeys(a);a.forEach((t,o)=>{const r=n[o];r&&(e[t]=r)})}else e=Object.fromEntries(await Promise.all(a.map(async e=>[e,await i.getKey(e)])));q.setState(n=>({accounts:{...n.accounts||{},...e}}))}$.setState(e=>({recentChainIds:[...e.recentChainIds||[],...a].filter((e,n,t)=>t.indexOf(e)===n)})),q.setState(e=>({activeChainIds:[...e.activeChainIds||[],...a].filter((e,n,t)=>t.indexOf(e)===n)})),$.setState({walletType:r,_reconnect:Boolean(e?.autoReconnect),_reconnectConnector:r}),q.setState({status:"connected"}),"undefined"!=typeof window&&window.sessionStorage.setItem(F,"Active");const l=a.map(e=>t.find(n=>n.chainId===e));return{accounts:q.getState().accounts,walletType:r,chains:l}}catch(e){throw console.error("connect ",e),null===q.getState().accounts&&q.setState({status:"disconnected"}),q.getState().accounts&&q.getState().activeChainIds&&q.setState({status:"connected"}),e}},ye=e=>{"undefined"!=typeof window&&window.sessionStorage.removeItem(F);const n="string"==typeof e?.chainId?[e.chainId]:e?.chainId,t=()=>{if(he($.getState().walletType)){const e=ue("walletconnect"),{disable:n}=e;n&&n()}if(me($.getState().walletType)){const e=ue("para"),{disable:n}=e;n&&n()}};if(n){const e=q.getState().accounts;n.forEach(n=>{delete e?.[n]});0===Object.values(e||{}).length?(t(),q.setState(U),$.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})):(q.setState(t=>({activeChainIds:t.activeChainIds?.filter(e=>!n.includes(e)),accounts:e})),$.setState(e=>({recentChainIds:e.recentChainIds?.filter(e=>!n.includes(e))})))}else t(),q.setState(U),$.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null});return Promise.resolve()},Se=async e=>{const{recentChainIds:n,_reconnectConnector:t,_reconnect:o}=$.getState();try{const e=le(t||void 0);if(n&&e&&t){if(he(t))return;return await pe({chainId:n,walletType:t,autoReconnect:o})}}catch(n){e?.onError?.(n),ye()}},Ce=async e=>{if(!e?.chainId)throw new Error("chainId is required");const{walletType:n}=$.getState(),t=e.walletType||n;if(!le(t))throw new Error(`${t} is not available`);const o=ue(t);return{offlineSigner:o.getOfflineSigner(e.chainId),offlineSignerAmino:o.getOfflineSignerOnlyAmino(e.chainId),offlineSignerAuto:await o.getOfflineSignerAuto(e.chainId)}},Ie=()=>{$.setState({recentChainIds:null})},be=()=>$.getState().recentChainIds,Ee=()=>{const{recentChainIds:e,chains:n}=$.getState();return e?.map(e=>n.find(n=>n.chainId===e))??null},Ae=({chainId:e}={})=>$.getState().chains?.find(n=>n.chainId===e),_e=({chainId:e}={})=>{const n=$.getState().chains;return e?n?.filter(n=>e.includes(n.chainId)):n??void 0},ve=async({chainInfo:e})=>{const{chains:n}=$.getState(),t=n?.find(n=>n.chainId===e.chainId);if(t)throw new Error(`Chain with chainId "${e.chainId}" already exists in the store`);return $.setState(n=>({chains:[...n.chains||[],e]})),e},Oe=async({chainInfo:e,walletType:n})=>{const t=ue(n);await t.experimentalSuggestChain(e);const{chains:o}=$.getState(),r=o?.find(n=>n.chainId===e.chainId);return r||$.setState(n=>({chains:[...n.chains||[],e]})),e},ke=async e=>{const n=$.getState().walletType;await Oe({chainInfo:e.chainInfo,walletType:e.walletType??n});return await pe({chainId:e.chainInfo.chainId,walletType:e.walletType,autoReconnect:e.autoReconnect})},Be=e=>($.setState(n=>{const t=n.chains??[],o=e.chains,r=new Map;o.forEach(e=>r.set(e.chainId,e)),t.forEach(e=>{r.has(e.chainId)||r.set(e.chainId,e)});const i=Array.from(r.values());return{iframeOptions:e.iframeOptions||n.iframeOptions,walletConnect:e.walletConnect||n.walletConnect,walletType:e.defaultWallet||n.walletType,paraConfig:e.paraConfig||n.paraConfig,walletDefaultOptions:e.walletDefaultOptions||n.walletDefaultOptions,chains:i,chainsConfig:e.chainsConfig||n.chainsConfig,multiChainFetchConcurrency:e.multiChainFetchConcurrency||n.multiChainFetchConcurrency,pingInterval:e.pingInteval||n.pingInterval,_notFoundFn:e.onNotFound||n._notFoundFn,_onReconnectFailed:e.onReconnectFailed||n._onReconnectFailed,_reconnect:void 0===e.autoReconnect||(e.autoReconnect||n._reconnect)}}),e),Ne=async({signingClient:e,senderAddress:n,recipientAddress:t,amount:o,fee:r,memo:i})=>{if(!e)throw new Error("No connected account detected");if(!n)throw new Error("senderAddress is not defined");return e.sendTokens(n,t,o,r,i)},Te=async({signingClient:e,senderAddress:n,recipientAddress:t,transferAmount:o,sourcePort:r,sourceChannel:i,timeoutHeight:a,timeoutTimestamp:s,fee:c,memo:l})=>{if(!e)throw new Error("Stargate signing client is not ready");if(!n)throw new Error("senderAddress is not defined");return e.sendIbcTokens(n,t,o,r,i,a,s,c,l)},Pe=async({signingClient:e,senderAddress:n,msg:t,fee:o,options:r,label:i,codeId:a})=>{if(!e)throw new Error("CosmWasm signing client is not ready");return e.instantiate(n,a,t,i,o,r)},De=async({signingClient:e,senderAddress:n,msg:t,fee:o,contractAddress:r,funds:i,memo:a})=>{if(!e)throw new Error("CosmWasm signing client is not ready");return e.execute(n,r,t,o,a,i)},Fe=async(e,n,t)=>{if(!t)throw new Error("CosmWasm client is not ready");return await t.queryContractSmart(e,n)},Le=(e,n,t)=>{if(!t)throw new Error("CosmWasm client is not ready");const o=(new TextEncoder).encode(n);return t.queryContractRaw(e,o)},Ke=e=>e,Me=e=>e,Ue=({chainId:e})=>{const n=$(e=>e.chains);if(!n)throw new Error("No chains found in GrazProvider");return e&&e.length>0?e.map(e=>n.find(n=>n.chainId===e)).filter(Boolean):n},qe=async(e,n)=>{const t=$.getState().multiChainFetchConcurrency,o=await A(e,n,{concurrency:t});return Object.fromEntries(o.map((n,t)=>[e[t].chainId,n]))};function $e(e){const n=Ue({chainId:e?.chainId}),t=I(()=>["USE_STARGATE_CLIENT",n],[n]);return S({queryKey:t,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");return await qe(n,async e=>{const n=$.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await O.connect(t)})},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}function xe(e){const n=Ue({chainId:e?.chainId}),t=I(()=>["USE_COSMWASM_CLIENT",n],[n]);return S({queryKey:t,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");return await qe(n,async e=>{const n=$.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await _.connect(t)})},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}var je=()=>$(N(e=>({walletType:e.walletType,isCosmostation:"cosmostation"===e.walletType,isCosmostationMobile:"wc_cosmostation_mobile"===e.walletType,isKeplr:"keplr"===e.walletType,isKeplrMobile:"wc_keplr_mobile"===e.walletType,isLeap:"leap"===e.walletType,isLeapMobile:"wc_leap_mobile"===e.walletType,isVectis:"vectis"===e.walletType,isWalletConnect:"walletconnect"===e.walletType,isMetamaskSnapLeap:"metamask_snap_leap"===e.walletType,isStation:"station"===e.walletType,isCosmiframe:"cosmiframe"===e.walletType}))),We=e=>{const n=$(n=>e||n.walletType);return S({queryKey:["USE_CHECK_WALLET",n],queryFn:()=>!!n&&le(n)})};function Re(e){const n=$(e=>e.walletType),t=q(e=>e.activeChainIds),o=Ue({chainId:e?.chainId?e.chainId:t||void 0}),r=q(e=>e.accounts),i=q(e=>e.status);b(()=>q.subscribe(e=>e.status,(n,t)=>{if("connected"===n){const{accounts:n,activeChainIds:o}=q.getState(),{chains:r}=$.getState(),{walletType:i}=$.getState();if(!n||!o||!r)return e?.onDisconnect?.();e?.onConnect?.({accounts:n,chains:o.map(e=>r.find(n=>n.chainId===e)),walletType:i,isReconnect:"reconnecting"===t})}"disconnected"===n&&e?.onDisconnect?.()}),[e]);return{data:I(()=>r?((e,n)=>{const t=e.map(n);return Object.fromEntries(t.map((n,t)=>[e[t].chainId,n]))})(o,e=>r[e.chainId]):void 0,[r,o]),isConnected:"connected"===i,isConnecting:"connecting"===i,isDisconnected:"disconnected"===i,isReconnecting:"reconnecting"===i,isLoading:"connecting"===i||"reconnecting"===i,walletType:"connected"===i?n:void 0,reconnect:Se,status:i}}var Ve=e=>{const n=Ue({chainId:[e.chainId]})[0],{data:t}=$e({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=I(()=>["USE_ALL_BALANCES",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return S({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getAllBalances(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},ze=e=>{const n=Ue({chainId:[e.chainId]})[0],{data:t}=$e({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=I(()=>["USE_BALANCE",o,e.chainId,e.bech32Address,e.denom],[e.bech32Address,e.chainId,e.denom,o]);return S({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);const t=await o.getBalance(e.bech32Address,e.denom);return"0"===t.amount?void 0:t},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},Ge=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_CONNECT",e,n,t],mutationFn:pe,onError:(n,t)=>e?.(n,t),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))}),{data:r}=We();return{connect:e=>o.mutate(e),connectAsync:e=>o.mutateAsync(e),error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,isSupported:Boolean(r),status:o.status}},He=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_DISCONNECT",e,n,t],mutationFn:ye,onError:n=>Promise.resolve(e?.(n,void 0)),onMutate:n,onSuccess:()=>Promise.resolve(t?.(void 0))});return{disconnect:e=>o.mutate(e),disconnectAsync:e=>o.mutateAsync(e),error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,status:o.status}};function Xe(e){const n=Ue({chainId:e?.chainId}),t=$(e=>e.walletType),o="connected"===q.getState().status&&q.getState().accounts&&$.getState()._reconnectConnector===t,r=I(()=>["USE_OFFLINE_SIGNERS",n,t],[n,t]);return S({queryKey:r,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chain found");if(!t)throw new Error("Wallet is not defined");if(!le(t))throw new Error(`${t} is not available`);return await qe(n,async e=>await Ce({chainId:e.chainId,walletType:t}))},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&Boolean(o),refetchOnWindowFocus:!1})}var Ye=e=>{const n=Ue({chainId:[e.chainId]})[0],{data:t}=$e({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=I(()=>["USE_BALANCE_STAKED",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return S({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getBalanceStaked(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},Qe=()=>q(e=>e.activeChainIds),Je=()=>{const e=q(e=>e.activeChainIds),n=$(e=>e.chains);return e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean)},Ze=({chainId:e}={})=>$(e=>e.chains)?.find(n=>n.chainId===e),en=({chainId:e}={})=>{const n=$(e=>e.chains);return e?n?.filter(n=>e.includes(n.chainId)):n},nn=({denom:e})=>{const n=Je();return S({queryKey:["USE_ACTIVE_CHAIN_CURRENCY",e],queryFn:({queryKey:[,e]})=>n?.find(n=>n.currencies.find(n=>n.coinMinimalDenom===e))?.currencies.find(e=>e)})},tn=e=>{const n=e.status??"BOND_STATUS_BONDED",t=["USE_ACTIVE_CHAIN_VALIDATORS",e.queryClient,n];return S({queryKey:t,queryFn:async()=>{if(!e.queryClient)throw new Error("Query client is not defined");return await e.queryClient.staking.validators(n)},enabled:void 0!==e.queryClient})},on=()=>({data:$(e=>e.recentChainIds),clear:Ie}),rn=()=>{const e=$(e=>e.recentChainIds),n=$(e=>e.chains),t=e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean);return{data:t,clear:Ie}},an=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_ADD_CHAIN",e,n,t],mutationFn:ve,onError:(n,t)=>Promise.resolve(e?.(n,t.chainInfo)),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>Promise.resolve(t?.(e))});return{addChain:o.mutate,addChainAsync:o.mutateAsync,error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,status:o.status}},sn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_SUGGEST_CHAIN",e,n,t],mutationFn:Oe,onError:(n,t)=>Promise.resolve(e?.(n,t.chainInfo)),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>Promise.resolve(t?.(e))});return{error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,suggest:o.mutate,suggestAsync:o.mutateAsync,status:o.status}},cn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=C({mutationKey:["USE_SUGGEST_CHAIN_AND_CONNECT",e,n,t],mutationFn:ke,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:e=>n?.(e),onSuccess:e=>Promise.resolve(t?.(e))}),{data:r}=We();return{error:o.error,isLoading:o.isPending,isSuccess:o.isSuccess,isSupported:Boolean(r),status:o.status,suggestAndConnect:o.mutate,suggestAndConnectAsync:o.mutateAsync}},ln=({onError:e,onLoading:n,onSuccess:t}={})=>{const{mutate:o,mutateAsync:r,...i}=C({mutationKey:["USE_SEND_TOKENS",e,n,t],mutationFn:Ne,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))});return{...i,sendTokens:o,sendTokensAsync:r}},dn=({onError:e,onLoading:n,onSuccess:t}={})=>{const{mutate:o,mutateAsync:r,...i}=C({mutationKey:["USE_SEND_IBC_TOKENS",e,n,t],mutationFn:Te,onError:(n,t)=>Promise.resolve(e?.(n,t)),onMutate:n,onSuccess:e=>Promise.resolve(t?.(e))});return{...i,sendIbcTokens:o,sendIbcTokensAsync:r}},un=({codeId:e,onError:n,onLoading:t,onSuccess:o})=>{const{mutate:r,mutateAsync:i,...a}=C({mutationKey:["USE_INSTANTIATE_CONTRACT",n,t,o,e],mutationFn:n=>Pe({...n,fee:n.fee??"auto",codeId:e}),onError:(e,t)=>Promise.resolve(n?.(e,t)),onMutate:t,onSuccess:e=>Promise.resolve(o?.(e))});return{...a,instantiateContract:r,instantiateContractAsync:i}},gn=({contractAddress:e,onError:n,onLoading:t,onSuccess:o})=>{const{mutate:r,mutateAsync:i,...a}=C({mutationKey:["USE_EXECUTE_CONTRACT",n,t,o,e],mutationFn:n=>De({...n,fee:n.fee??"auto",contractAddress:e,memo:n.memo??"",funds:n.funds??[]}),onError:(e,t)=>Promise.resolve(n?.(e,t)),onMutate:t,onSuccess:e=>Promise.resolve(o?.(e))});return{...a,executeContract:r,executeContractAsync:i}},wn=e=>{const{data:n}=xe(),t=n&&Object.values(n)[0];return S({queryKey:["USE_QUERY_SMART",e?.address,e?.queryMsg,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.queryMsg)throw new Error("address or queryMsg undefined");return Fe(e.address,e.queryMsg,t)},enabled:Boolean(e?.address)&&Boolean(e?.queryMsg)&&Boolean(t)})},fn=e=>{const{data:n}=xe(),t=n&&Object.values(n)[0];return S({queryKey:["USE_QUERY_RAW",e?.key,e?.address,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.key)throw new Error("address or key undefined");return Le(e.address,e.key,t)},enabled:Boolean(e?.address)&&Boolean(e?.key)&&Boolean(t)})};function hn(e){const n=Ue({chainId:e?.chainId}),t=$(e=>e.walletType),o=q(e=>e.activeChainIds),r="connected"===q.getState().status&&q.getState().accounts&&$.getState()._reconnectConnector===t,i=I(()=>["USE_STARGATE_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return S({queryKey:i,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");return await qe(n,async n=>{if(!o?.includes(n.chainId))return null;if(!le(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return ue(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return ue(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return ue(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=$.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}};return await k.connectWithSigner(a,r,e?.opts?.[n.chainId])})},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})}function mn(e){const n=Ue({chainId:e?.chainId}),t=$(e=>e.walletType),o=q(e=>e.activeChainIds),r="connected"===q.getState().status&&q.getState().accounts&&$.getState()._reconnectConnector===t,i=I(()=>["USE_COSMWASM_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return S({queryKey:i,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");return await qe(n,async n=>{if(!o?.includes(n.chainId))return null;if(!le(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return ue(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return ue(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return ue(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=$.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}},s=i?.gas?B.fromString(`${i.gas.price}${i.gas.denom}`):void 0;return await v.connectWithSigner(a,r,{gasPrice:s,...e?.opts?.[n.chainId]||{}})})},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})}var pn=({children:e})=>{const[n,t]=E(!1);return b(()=>{t(!0)},[]),P(D,{children:n?e:null})},yn=()=>{const e="undefined"!=typeof window&&"Active"===window.sessionStorage.getItem(F),{_reconnect:n,_onReconnectFailed:t,_reconnectConnector:o,iframeOptions:i,chains:a,pingInterval:s}=$(),{activeChainIds:c,wcSignClients:l}=q(),d=le(o||void 0);return b(()=>{const n=async()=>{if(e&&d&&o&&c?.[0]){const e=q.getState().lastPing;if(e&&Date.now()-e<s)return;const n=ue(o);try{if(!await n.getKey(c[0]))throw new Error("No account found");q.setState({lastPing:Date.now()})}catch(e){Se({onError:t})}}};return window.addEventListener("focus",n),()=>{window.removeEventListener("focus",n)}},[e,d,o,a,c,s]),b(()=>{if(!i||!1===i.autoConnect||!i.allowedIframeParentOrigins.length||!a)return;new r(i.allowedIframeParentOrigins).isReady().then(e=>{if(e)return pe({chainId:a.map(e=>e.chainId),walletType:"cosmiframe"})})},[i]),b(()=>{if(o){if(!d)return;(e&&Boolean(c)||!e&&n)&&Se({onError:t})}},[d]),b(()=>{if(o){if(!d)return;"cosmostation"===o&&V().subscription?.(()=>{Se({onError:t})}),"keplr"===o&&G().subscription?.(()=>{Se({onError:t})}),"leap"===o&&H().subscription?.(()=>{Se({onError:t})}),"compass"===o&&j().subscription?.(()=>{Se({onError:t})}),"vectis"===o&&ne().subscription?.(()=>{Se({onError:t})}),"walletconnect"===o&&l.has("walletconnect")&&re().subscription?.(()=>{Se({onError:t})}),"station"===o&&ee().subscription?.(()=>{Se({onError:t})}),"xdefi"===o&&ce().subscription?.(()=>{Se({onError:t})}),"cosmiframe"===o&&W().subscription?.(()=>{Se({onError:t})}),"okx"===o&&Q().subscription?.(()=>{Se({onError:t})})}},[o,l,d]),null},Sn=()=>(yn(),null),Cn=({children:e,grazOptions:n})=>(b(()=>{Be(n)},[n]),T(pn,{children:[e,P(Sn,{})]}));export{Sn as GrazEvents,Cn as GrazProvider,K as WALLET_TYPES,L as WalletType,ve as addChain,le as checkWallet,Ie as clearRecentChain,de as clearSession,Be as configureGraz,pe as connect,Me as defineChainInfo,Ke as defineChains,ye as disconnect,De as executeContract,ge as getAvailableWallets,x as getCactusCosmos,Ae as getChainInfo,_e as getChainInfos,V as getCosmostation,G as getKeplr,H as getLeap,Y as getMetamaskSnapLeap,Ce as getOfflineSigners,Q as getOkx,Z as getPara,Le as getQueryRaw,Fe as getQuerySmart,be as getRecentChainIds,Ee as getRecentChains,ne as getVectis,ie as getWCCosmostation,ae as getWCKeplr,se as getWCLeap,ue as getWallet,re as getWalletConnect,Pe as instantiateContract,fe as isLeapDappBrowser,we as isLeapSnaps,me as isPara,he as isWalletConnect,Se as reconnect,Te as sendIbcTokens,Ne as sendTokens,Oe as suggestChain,ke as suggestChainAndConnect,Re as useAccount,nn as useActiveChainCurrency,Qe as useActiveChainIds,Je as useActiveChains,je as useActiveWalletType,an as useAddChain,ze as useBalance,Ye as useBalanceStaked,Ve as useBalances,Ze as useChainInfo,en as useChainInfos,We as useCheckWallet,Ge as useConnect,xe as useCosmWasmClient,mn as useCosmWasmSigningClient,He as useDisconnect,gn as useExecuteContract,yn as useGrazEvents,un as useInstantiateContract,Xe as useOfflineSigners,tn as useQueryClientValidators,fn as useQueryRaw,wn as useQuerySmart,on as useRecentChainIds,rn as useRecentChains,dn as useSendIbcTokens,ln as useSendTokens,$e as useStargateClient,hn as useStargateSigningClient,sn as useSuggestChain,cn as useSuggestChainAndConnect};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "graz",
3
3
  "description": "React hooks for Cosmos",
4
- "version": "0.4.0-alpha.4",
4
+ "version": "0.4.1",
5
5
  "author": "Nur Fikri <kikiding.space@gmail.com>",
6
6
  "repository": "https://github.com/graz-sh/graz.git",
7
7
  "homepage": "https://github.com/graz-sh/graz",
@@ -68,12 +68,13 @@
68
68
  "@getpara/web-sdk": "2.0.0-alpha.51",
69
69
  "@types/node": "^18.17.15",
70
70
  "@types/react": "^18.2.21",
71
- "@vitest/ui": "^1.0.0",
71
+ "@vitest/ui": "^2.1.9",
72
72
  "arg": "^5.0.2",
73
73
  "jsdom": "^23.0.0",
74
74
  "react": "^18.2.0",
75
75
  "typescript": "^5.4.0",
76
- "vitest": "^1.0.0"
76
+ "vite": "^5.4.20",
77
+ "vitest": "^2.1.9"
77
78
  },
78
79
  "keywords": [
79
80
  "graz",