graz 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -127,6 +127,92 @@ interface SuggestChainAndConnectArgs {
127
127
  }
128
128
  declare const suggestChainAndConnect: (args: SuggestChainAndConnectArgs) => Promise<ConnectResult>;
129
129
 
130
+ /**
131
+ * Logger types and interfaces for Graz
132
+ */
133
+ declare enum LogLevel {
134
+ ERROR = 0,
135
+ WARN = 1,
136
+ INFO = 2,
137
+ DEBUG = 3,
138
+ TRACE = 4
139
+ }
140
+ declare enum LogCategory {
141
+ WALLET = "wallet",// Wallet connections, disconnections
142
+ TRANSACTION = "transaction",// Transaction signing and broadcasting
143
+ QUERY = "query",// Blockchain queries
144
+ STORE = "store",// State management
145
+ MULTICHAIN = "multichain",// Multi-chain operations
146
+ EVENT = "event",// Wallet events
147
+ PERFORMANCE = "performance"
148
+ }
149
+ /**
150
+ * Error reporter interface for integration with error tracking services
151
+ * (e.g., Sentry, custom error tracking)
152
+ */
153
+ interface ErrorReporter {
154
+ captureException: (error: Error, context?: {
155
+ category?: string;
156
+ context?: Record<string, unknown>;
157
+ }) => void;
158
+ }
159
+ /**
160
+ * Logger configuration options
161
+ */
162
+ interface LoggerOptions {
163
+ /**
164
+ * Enable/disable logging
165
+ * @default true in development, false in production
166
+ */
167
+ enabled?: boolean;
168
+ /**
169
+ * Log level configuration:
170
+ * - Single LogLevel: Minimum level (e.g., LogLevel.INFO logs INFO, WARN, ERROR)
171
+ * - Array of LogLevel: Only log these specific levels
172
+ * - undefined/not specified: Log all levels
173
+ * @default undefined (all levels)
174
+ */
175
+ level?: LogLevel | LogLevel[];
176
+ /**
177
+ * Categories to log:
178
+ * - Array of categories: Only log these specific categories
179
+ * - Empty array or undefined: Log all categories
180
+ * @default undefined (all categories)
181
+ */
182
+ categories?: (keyof typeof LogCategory)[];
183
+ /**
184
+ * Optional error reporter for error tracking integration
185
+ */
186
+ errorReporter?: ErrorReporter;
187
+ }
188
+ /**
189
+ * Logger interface
190
+ */
191
+ interface Logger {
192
+ error(category: LogCategory, message: string, context?: Record<string, unknown>): void;
193
+ warn(category: LogCategory, message: string, context?: Record<string, unknown>): void;
194
+ info(category: LogCategory, message: string, context?: Record<string, unknown>): void;
195
+ debug(category: LogCategory, message: string, context?: Record<string, unknown>): void;
196
+ trace(category: LogCategory, message: string, context?: Record<string, unknown>): void;
197
+ time(label: string): void;
198
+ timeEnd(label: string): void;
199
+ group(label: string): void;
200
+ groupEnd(): void;
201
+ setLevel(level: LogLevel | LogLevel[] | undefined): void;
202
+ setCategories(categories: (keyof typeof LogCategory)[] | undefined): void;
203
+ enable(): void;
204
+ disable(): void;
205
+ }
206
+ /**
207
+ * Global window extensions for Graz debugging
208
+ */
209
+ declare global {
210
+ interface Window {
211
+ __GRAZ_DEBUG__?: boolean;
212
+ grazErrorReporter?: ErrorReporter;
213
+ }
214
+ }
215
+
130
216
  /**
131
217
  * Para wallet entity (compatible with Wallet from @getpara/core-sdk)
132
218
  * Represents a wallet within the Para ecosystem (different from Graz Wallet)
@@ -258,6 +344,14 @@ interface GrazInternalStore {
258
344
  * Interval in milliseconds to ping the wallet.
259
345
  */
260
346
  pingInterval: number;
347
+ /**
348
+ * Logger configuration
349
+ */
350
+ loggerConfig: {
351
+ enabled: boolean;
352
+ level?: LogLevel | LogLevel[];
353
+ categories?: (keyof typeof LogCategory)[];
354
+ } | null;
261
355
  _notFoundFn: () => void;
262
356
  _reconnect: boolean;
263
357
  _reconnectConnector: WalletType | null;
@@ -288,6 +382,14 @@ interface ConfigureGrazArgs {
288
382
  */
289
383
  iframeOptions?: IframeOptions;
290
384
  pingInteval?: number;
385
+ /**
386
+ * Logger configuration
387
+ */
388
+ logger?: {
389
+ enabled?: boolean;
390
+ level?: LogLevel | LogLevel[] | undefined;
391
+ categories?: (keyof typeof LogCategory)[] | undefined;
392
+ };
291
393
  }
292
394
  declare const configureGraz: (args: ConfigureGrazArgs) => ConfigureGrazArgs;
293
395
 
@@ -374,6 +476,88 @@ declare const isLeapDappBrowser: () => boolean;
374
476
  declare const isWalletConnect: (type: WalletType) => boolean;
375
477
  declare const isPara: (type: WalletType) => type is WalletType.PARA;
376
478
 
479
+ /**
480
+ * Logger Categories
481
+ * Used for categorizing logs throughout the Graz library
482
+ */
483
+ declare const LOG_CATEGORIES: {
484
+ /** Wallet connections, disconnections, and adapter operations */
485
+ readonly WALLET: "wallet";
486
+ /** Transaction signing and broadcasting */
487
+ readonly TRANSACTION: "transaction";
488
+ /** Blockchain queries (balance, contract queries, etc.) */
489
+ readonly QUERY: "query";
490
+ /** State management operations (store updates) */
491
+ readonly STORE: "store";
492
+ /** Multi-chain parallel operations */
493
+ readonly MULTICHAIN: "multichain";
494
+ /** Wallet events and listeners */
495
+ readonly EVENT: "event";
496
+ /** Performance metrics and timing */
497
+ readonly PERFORMANCE: "performance";
498
+ };
499
+ /**
500
+ * Logger Function Names
501
+ * Action/method function names used in logging context
502
+ */
503
+ declare const LOG_FUNCTIONS: {
504
+ readonly CONNECT: "connect";
505
+ readonly DISCONNECT: "disconnect";
506
+ readonly RECONNECT: "reconnect";
507
+ readonly GET_WALLET: "getWallet";
508
+ readonly CLEAR_RECENT_CHAIN: "clearRecentChain";
509
+ readonly GET_RECENT_CHAIN_IDS: "getRecentChainIds";
510
+ readonly GET_RECENT_CHAINS: "getRecentChains";
511
+ readonly GET_CHAIN_INFO: "getChainInfo";
512
+ readonly GET_CHAIN_INFOS: "getChainInfos";
513
+ readonly ADD_CHAIN: "addChain";
514
+ readonly SUGGEST_CHAIN: "suggestChain";
515
+ readonly SUGGEST_CHAIN_AND_CONNECT: "suggestChainAndConnect";
516
+ readonly SEND_TOKENS: "sendTokens";
517
+ readonly SEND_IBC_TOKENS: "sendIbcTokens";
518
+ readonly INSTANTIATE_CONTRACT: "instantiateContract";
519
+ readonly EXECUTE_CONTRACT: "executeContract";
520
+ readonly GET_QUERY_SMART: "getQuerySmart";
521
+ readonly GET_QUERY_RAW: "getQueryRaw";
522
+ readonly CREATE_MULTI_CHAIN_ASYNC_FUNCTION: "createMultiChainAsyncFunction";
523
+ readonly HANDLE_FOCUS: "handleFocus";
524
+ readonly AUTO_CONNECT_IFRAME: "autoConnectIframe";
525
+ readonly RECONNECT_EFFECT: "reconnectEffect";
526
+ readonly SUBSCRIPTION: "subscription";
527
+ };
528
+ /**
529
+ * Logger Hook Names
530
+ * React hook names used in logging context
531
+ */
532
+ declare const LOG_HOOKS: {
533
+ readonly USE_CONNECT: "useConnect";
534
+ readonly USE_DISCONNECT: "useDisconnect";
535
+ readonly USE_CHECK_WALLET: "useCheckWallet";
536
+ readonly USE_ADD_CHAIN: "useAddChain";
537
+ readonly USE_SUGGEST_CHAIN: "useSuggestChain";
538
+ readonly USE_SUGGEST_CHAIN_AND_CONNECT: "useSuggestChainAndConnect";
539
+ readonly USE_STARGATE_CLIENT: "useStargateClient";
540
+ readonly USE_COSMWASM_CLIENT: "useCosmWasmClient";
541
+ readonly USE_STARGATE_SIGNING_CLIENT: "useStargateSigningClient";
542
+ readonly USE_COSMWASM_SIGNING_CLIENT: "useCosmWasmSigningClient";
543
+ readonly USE_SEND_TOKENS: "useSendTokens";
544
+ readonly USE_SEND_IBC_TOKENS: "useSendIbcTokens";
545
+ readonly USE_INSTANTIATE_CONTRACT: "useInstantiateContract";
546
+ readonly USE_EXECUTE_CONTRACT: "useExecuteContract";
547
+ };
548
+
549
+ /**
550
+ * Get the singleton logger instance
551
+ * @returns Logger instance
552
+ */
553
+ declare const getLogger: () => Logger;
554
+ /**
555
+ * Configure the logger with custom options
556
+ * This will recreate the logger instance with new options
557
+ * @param options Logger configuration options
558
+ */
559
+ declare const configureLogger: (options: LoggerOptions) => void;
560
+
377
561
  type CactusCosmosWallet = Pick<Keplr, "enable" | "getOfflineSigner" | "signDirect" | "signAmino" | "signArbitrary" | "getKey">;
378
562
  declare const getCactusCosmos: () => Wallet;
379
563
 
@@ -801,7 +985,7 @@ declare const useDisconnect: ({ onError, onLoading, onSuccess }?: MutationEventA
801
985
  declare function useOfflineSigners<const TChainIds extends readonly string[]>(args: {
802
986
  chainId: TChainIds;
803
987
  }): UseMultiChainQueryResult<TChainIds, OfflineSigners>;
804
- declare function useOfflineSigners(args?: {}): UseMultiChainQueryResult<undefined, OfflineSigners>;
988
+ declare function useOfflineSigners(args?: Record<string, never>): UseMultiChainQueryResult<undefined, OfflineSigners>;
805
989
  /**
806
990
  * graz query hook to retrieve staked balance for a specific chain and address.
807
991
  *
@@ -1686,11 +1870,20 @@ interface GrazProviderProps {
1686
1870
  * Graz uses `@tanstack/react-query`'s features under the hood, hence you need to wrap `GrazProvider` with `QueryClientProvider`.
1687
1871
  * @example
1688
1872
  * ```tsx
1873
+ * import { GrazProvider, LogLevel } from "graz";
1874
+ *
1689
1875
  * // example next.js application in _app.tsx
1690
1876
  * export default function CustomApp({ Component, pageProps }: AppProps) {
1691
1877
  * return (
1692
1878
  * <QueryClientProvider queryClient={queryClient}>
1693
- * <GrazProvider grazOptions={grazOptions}>
1879
+ * <GrazProvider grazOptions={{
1880
+ * chains: [cosmoshubChainInfo, osmosisChainInfo],
1881
+ * logger: {
1882
+ * enabled: true,
1883
+ * level: LogLevel.DEBUG,
1884
+ * categories: ['wallet', 'transaction'],
1885
+ * }
1886
+ * }}>
1694
1887
  * <Component {...pageProps} />
1695
1888
  * </GrazProvider>
1696
1889
  * </QueryClientProvider>
@@ -1715,4 +1908,4 @@ declare const useGrazEvents: () => null;
1715
1908
  */
1716
1909
  declare const GrazEvents: FC;
1717
1910
 
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 };
1911
+ export { type ActionChainId, type AddChainArgs, type CactusCosmosWallet, type ConfigureGrazArgs, type ConnectArgs, type ConnectResult, type Dictionary, type ErrorReporter, type ExecuteContractArgs, type ExecuteContractMutationArgs, GrazEvents, GrazProvider, type GrazProviderProps, type InstantiateContractArgs, type InstantiateContractMutationArgs, type Key, type KnownKeys, LOG_CATEGORIES, LOG_FUNCTIONS, LOG_HOOKS, LogCategory, LogLevel, type Logger, type LoggerOptions, 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, configureLogger, connect, defineChainInfo, defineChains, disconnect, executeContract, getAvailableWallets, getCactusCosmos, getChainInfo, getChainInfos, getCosmostation, getKeplr, getLeap, getLogger, 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
@@ -127,6 +127,92 @@ interface SuggestChainAndConnectArgs {
127
127
  }
128
128
  declare const suggestChainAndConnect: (args: SuggestChainAndConnectArgs) => Promise<ConnectResult>;
129
129
 
130
+ /**
131
+ * Logger types and interfaces for Graz
132
+ */
133
+ declare enum LogLevel {
134
+ ERROR = 0,
135
+ WARN = 1,
136
+ INFO = 2,
137
+ DEBUG = 3,
138
+ TRACE = 4
139
+ }
140
+ declare enum LogCategory {
141
+ WALLET = "wallet",// Wallet connections, disconnections
142
+ TRANSACTION = "transaction",// Transaction signing and broadcasting
143
+ QUERY = "query",// Blockchain queries
144
+ STORE = "store",// State management
145
+ MULTICHAIN = "multichain",// Multi-chain operations
146
+ EVENT = "event",// Wallet events
147
+ PERFORMANCE = "performance"
148
+ }
149
+ /**
150
+ * Error reporter interface for integration with error tracking services
151
+ * (e.g., Sentry, custom error tracking)
152
+ */
153
+ interface ErrorReporter {
154
+ captureException: (error: Error, context?: {
155
+ category?: string;
156
+ context?: Record<string, unknown>;
157
+ }) => void;
158
+ }
159
+ /**
160
+ * Logger configuration options
161
+ */
162
+ interface LoggerOptions {
163
+ /**
164
+ * Enable/disable logging
165
+ * @default true in development, false in production
166
+ */
167
+ enabled?: boolean;
168
+ /**
169
+ * Log level configuration:
170
+ * - Single LogLevel: Minimum level (e.g., LogLevel.INFO logs INFO, WARN, ERROR)
171
+ * - Array of LogLevel: Only log these specific levels
172
+ * - undefined/not specified: Log all levels
173
+ * @default undefined (all levels)
174
+ */
175
+ level?: LogLevel | LogLevel[];
176
+ /**
177
+ * Categories to log:
178
+ * - Array of categories: Only log these specific categories
179
+ * - Empty array or undefined: Log all categories
180
+ * @default undefined (all categories)
181
+ */
182
+ categories?: (keyof typeof LogCategory)[];
183
+ /**
184
+ * Optional error reporter for error tracking integration
185
+ */
186
+ errorReporter?: ErrorReporter;
187
+ }
188
+ /**
189
+ * Logger interface
190
+ */
191
+ interface Logger {
192
+ error(category: LogCategory, message: string, context?: Record<string, unknown>): void;
193
+ warn(category: LogCategory, message: string, context?: Record<string, unknown>): void;
194
+ info(category: LogCategory, message: string, context?: Record<string, unknown>): void;
195
+ debug(category: LogCategory, message: string, context?: Record<string, unknown>): void;
196
+ trace(category: LogCategory, message: string, context?: Record<string, unknown>): void;
197
+ time(label: string): void;
198
+ timeEnd(label: string): void;
199
+ group(label: string): void;
200
+ groupEnd(): void;
201
+ setLevel(level: LogLevel | LogLevel[] | undefined): void;
202
+ setCategories(categories: (keyof typeof LogCategory)[] | undefined): void;
203
+ enable(): void;
204
+ disable(): void;
205
+ }
206
+ /**
207
+ * Global window extensions for Graz debugging
208
+ */
209
+ declare global {
210
+ interface Window {
211
+ __GRAZ_DEBUG__?: boolean;
212
+ grazErrorReporter?: ErrorReporter;
213
+ }
214
+ }
215
+
130
216
  /**
131
217
  * Para wallet entity (compatible with Wallet from @getpara/core-sdk)
132
218
  * Represents a wallet within the Para ecosystem (different from Graz Wallet)
@@ -258,6 +344,14 @@ interface GrazInternalStore {
258
344
  * Interval in milliseconds to ping the wallet.
259
345
  */
260
346
  pingInterval: number;
347
+ /**
348
+ * Logger configuration
349
+ */
350
+ loggerConfig: {
351
+ enabled: boolean;
352
+ level?: LogLevel | LogLevel[];
353
+ categories?: (keyof typeof LogCategory)[];
354
+ } | null;
261
355
  _notFoundFn: () => void;
262
356
  _reconnect: boolean;
263
357
  _reconnectConnector: WalletType | null;
@@ -288,6 +382,14 @@ interface ConfigureGrazArgs {
288
382
  */
289
383
  iframeOptions?: IframeOptions;
290
384
  pingInteval?: number;
385
+ /**
386
+ * Logger configuration
387
+ */
388
+ logger?: {
389
+ enabled?: boolean;
390
+ level?: LogLevel | LogLevel[] | undefined;
391
+ categories?: (keyof typeof LogCategory)[] | undefined;
392
+ };
291
393
  }
292
394
  declare const configureGraz: (args: ConfigureGrazArgs) => ConfigureGrazArgs;
293
395
 
@@ -374,6 +476,88 @@ declare const isLeapDappBrowser: () => boolean;
374
476
  declare const isWalletConnect: (type: WalletType) => boolean;
375
477
  declare const isPara: (type: WalletType) => type is WalletType.PARA;
376
478
 
479
+ /**
480
+ * Logger Categories
481
+ * Used for categorizing logs throughout the Graz library
482
+ */
483
+ declare const LOG_CATEGORIES: {
484
+ /** Wallet connections, disconnections, and adapter operations */
485
+ readonly WALLET: "wallet";
486
+ /** Transaction signing and broadcasting */
487
+ readonly TRANSACTION: "transaction";
488
+ /** Blockchain queries (balance, contract queries, etc.) */
489
+ readonly QUERY: "query";
490
+ /** State management operations (store updates) */
491
+ readonly STORE: "store";
492
+ /** Multi-chain parallel operations */
493
+ readonly MULTICHAIN: "multichain";
494
+ /** Wallet events and listeners */
495
+ readonly EVENT: "event";
496
+ /** Performance metrics and timing */
497
+ readonly PERFORMANCE: "performance";
498
+ };
499
+ /**
500
+ * Logger Function Names
501
+ * Action/method function names used in logging context
502
+ */
503
+ declare const LOG_FUNCTIONS: {
504
+ readonly CONNECT: "connect";
505
+ readonly DISCONNECT: "disconnect";
506
+ readonly RECONNECT: "reconnect";
507
+ readonly GET_WALLET: "getWallet";
508
+ readonly CLEAR_RECENT_CHAIN: "clearRecentChain";
509
+ readonly GET_RECENT_CHAIN_IDS: "getRecentChainIds";
510
+ readonly GET_RECENT_CHAINS: "getRecentChains";
511
+ readonly GET_CHAIN_INFO: "getChainInfo";
512
+ readonly GET_CHAIN_INFOS: "getChainInfos";
513
+ readonly ADD_CHAIN: "addChain";
514
+ readonly SUGGEST_CHAIN: "suggestChain";
515
+ readonly SUGGEST_CHAIN_AND_CONNECT: "suggestChainAndConnect";
516
+ readonly SEND_TOKENS: "sendTokens";
517
+ readonly SEND_IBC_TOKENS: "sendIbcTokens";
518
+ readonly INSTANTIATE_CONTRACT: "instantiateContract";
519
+ readonly EXECUTE_CONTRACT: "executeContract";
520
+ readonly GET_QUERY_SMART: "getQuerySmart";
521
+ readonly GET_QUERY_RAW: "getQueryRaw";
522
+ readonly CREATE_MULTI_CHAIN_ASYNC_FUNCTION: "createMultiChainAsyncFunction";
523
+ readonly HANDLE_FOCUS: "handleFocus";
524
+ readonly AUTO_CONNECT_IFRAME: "autoConnectIframe";
525
+ readonly RECONNECT_EFFECT: "reconnectEffect";
526
+ readonly SUBSCRIPTION: "subscription";
527
+ };
528
+ /**
529
+ * Logger Hook Names
530
+ * React hook names used in logging context
531
+ */
532
+ declare const LOG_HOOKS: {
533
+ readonly USE_CONNECT: "useConnect";
534
+ readonly USE_DISCONNECT: "useDisconnect";
535
+ readonly USE_CHECK_WALLET: "useCheckWallet";
536
+ readonly USE_ADD_CHAIN: "useAddChain";
537
+ readonly USE_SUGGEST_CHAIN: "useSuggestChain";
538
+ readonly USE_SUGGEST_CHAIN_AND_CONNECT: "useSuggestChainAndConnect";
539
+ readonly USE_STARGATE_CLIENT: "useStargateClient";
540
+ readonly USE_COSMWASM_CLIENT: "useCosmWasmClient";
541
+ readonly USE_STARGATE_SIGNING_CLIENT: "useStargateSigningClient";
542
+ readonly USE_COSMWASM_SIGNING_CLIENT: "useCosmWasmSigningClient";
543
+ readonly USE_SEND_TOKENS: "useSendTokens";
544
+ readonly USE_SEND_IBC_TOKENS: "useSendIbcTokens";
545
+ readonly USE_INSTANTIATE_CONTRACT: "useInstantiateContract";
546
+ readonly USE_EXECUTE_CONTRACT: "useExecuteContract";
547
+ };
548
+
549
+ /**
550
+ * Get the singleton logger instance
551
+ * @returns Logger instance
552
+ */
553
+ declare const getLogger: () => Logger;
554
+ /**
555
+ * Configure the logger with custom options
556
+ * This will recreate the logger instance with new options
557
+ * @param options Logger configuration options
558
+ */
559
+ declare const configureLogger: (options: LoggerOptions) => void;
560
+
377
561
  type CactusCosmosWallet = Pick<Keplr, "enable" | "getOfflineSigner" | "signDirect" | "signAmino" | "signArbitrary" | "getKey">;
378
562
  declare const getCactusCosmos: () => Wallet;
379
563
 
@@ -801,7 +985,7 @@ declare const useDisconnect: ({ onError, onLoading, onSuccess }?: MutationEventA
801
985
  declare function useOfflineSigners<const TChainIds extends readonly string[]>(args: {
802
986
  chainId: TChainIds;
803
987
  }): UseMultiChainQueryResult<TChainIds, OfflineSigners>;
804
- declare function useOfflineSigners(args?: {}): UseMultiChainQueryResult<undefined, OfflineSigners>;
988
+ declare function useOfflineSigners(args?: Record<string, never>): UseMultiChainQueryResult<undefined, OfflineSigners>;
805
989
  /**
806
990
  * graz query hook to retrieve staked balance for a specific chain and address.
807
991
  *
@@ -1686,11 +1870,20 @@ interface GrazProviderProps {
1686
1870
  * Graz uses `@tanstack/react-query`'s features under the hood, hence you need to wrap `GrazProvider` with `QueryClientProvider`.
1687
1871
  * @example
1688
1872
  * ```tsx
1873
+ * import { GrazProvider, LogLevel } from "graz";
1874
+ *
1689
1875
  * // example next.js application in _app.tsx
1690
1876
  * export default function CustomApp({ Component, pageProps }: AppProps) {
1691
1877
  * return (
1692
1878
  * <QueryClientProvider queryClient={queryClient}>
1693
- * <GrazProvider grazOptions={grazOptions}>
1879
+ * <GrazProvider grazOptions={{
1880
+ * chains: [cosmoshubChainInfo, osmosisChainInfo],
1881
+ * logger: {
1882
+ * enabled: true,
1883
+ * level: LogLevel.DEBUG,
1884
+ * categories: ['wallet', 'transaction'],
1885
+ * }
1886
+ * }}>
1694
1887
  * <Component {...pageProps} />
1695
1888
  * </GrazProvider>
1696
1889
  * </QueryClientProvider>
@@ -1715,4 +1908,4 @@ declare const useGrazEvents: () => null;
1715
1908
  */
1716
1909
  declare const GrazEvents: FC;
1717
1910
 
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 };
1911
+ export { type ActionChainId, type AddChainArgs, type CactusCosmosWallet, type ConfigureGrazArgs, type ConnectArgs, type ConnectResult, type Dictionary, type ErrorReporter, type ExecuteContractArgs, type ExecuteContractMutationArgs, GrazEvents, GrazProvider, type GrazProviderProps, type InstantiateContractArgs, type InstantiateContractMutationArgs, type Key, type KnownKeys, LOG_CATEGORIES, LOG_FUNCTIONS, LOG_HOOKS, LogCategory, LogLevel, type Logger, type LoggerOptions, 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, configureLogger, connect, defineChainInfo, defineChains, disconnect, executeContract, getAvailableWallets, getCactusCosmos, getChainInfo, getChainInfos, getCosmostation, getKeplr, getLeap, getLogger, 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")},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}};
1
+ "use strict";var e=require("zustand"),n=require("zustand/middleware"),t=require("@dao-dao/cosmiframe"),o=require("@cosmsnap/snapper"),r=require("@cosmjs/amino"),i=require("long"),a=require("@cosmjs/encoding"),s=require("@walletconnect/modal"),c=require("@walletconnect/sign-client"),l=require("@walletconnect/utils"),d=require("@tanstack/react-query"),u=require("react"),g=require("p-map"),h=require("@cosmjs/cosmwasm-stargate"),f=require("@cosmjs/stargate"),w=require("zustand/shallow"),m=require("react/jsx-runtime");function p(e){return e&&e.__esModule?e:{default:e}}var C,y=p(i),S=p(g),b=Object.defineProperty,I=(e,n,t)=>((e,n,t)=>n in e?b(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t)(e,"symbol"!=typeof n?n+"":n,t),E="connect-graz",A={CONNECT:"connect",DISCONNECT:"disconnect",RECONNECT:"reconnect",GET_WALLET:"getWallet",CLEAR_RECENT_CHAIN:"clearRecentChain",GET_RECENT_CHAIN_IDS:"getRecentChainIds",GET_RECENT_CHAINS:"getRecentChains",GET_CHAIN_INFO:"getChainInfo",GET_CHAIN_INFOS:"getChainInfos",ADD_CHAIN:"addChain",SUGGEST_CHAIN:"suggestChain",SUGGEST_CHAIN_AND_CONNECT:"suggestChainAndConnect",SEND_TOKENS:"sendTokens",SEND_IBC_TOKENS:"sendIbcTokens",INSTANTIATE_CONTRACT:"instantiateContract",EXECUTE_CONTRACT:"executeContract",GET_QUERY_SMART:"getQuerySmart",GET_QUERY_RAW:"getQueryRaw",CREATE_MULTI_CHAIN_ASYNC_FUNCTION:"createMultiChainAsyncFunction",HANDLE_FOCUS:"handleFocus",AUTO_CONNECT_IFRAME:"autoConnectIframe",RECONNECT_EFFECT:"reconnectEffect",SUBSCRIPTION:"subscription"},_=(e=>(e.KEPLR="keplr",e.LEAP="leap",e.VECTIS="vectis",e.COSMOSTATION="cosmostation",e.WALLETCONNECT="walletconnect",e.WC_KEPLR_MOBILE="wc_keplr_mobile",e.WC_LEAP_MOBILE="wc_leap_mobile",e.WC_COSMOSTATION_MOBILE="wc_cosmostation_mobile",e.WC_CLOT_MOBILE="wc_clot_mobile",e.METAMASK_SNAP_LEAP="metamask_snap_leap",e.METAMASK_SNAP_COSMOS="metamask_snap_cosmos",e.STATION="station",e.XDEFI="xdefi",e.COSMIFRAME="cosmiframe",e.COMPASS="compass",e.INITIA="initia",e.OKX="okx",e.PARA="para",e.CACTUSCOSMOS="cactuscosmos",e))(_||{}),v=["keplr","leap","vectis","cosmostation","walletconnect","wc_keplr_mobile","wc_leap_mobile","wc_cosmostation_mobile","wc_clot_mobile","metamask_snap_leap","station","xdefi","metamask_snap_cosmos","cosmiframe","compass","initia","okx","para","cactuscosmos"],O={iframeOptions:null,recentChainIds:null,chains:null,chainsConfig:null,paraConfig:null,multiChainFetchConcurrency:3,walletType:"keplr",walletConnect:{options:null,walletConnectModal:null},walletDefaultOptions:null,pingInterval:36e5,loggerConfig:null,_notFoundFn:()=>null,_onReconnectFailed:()=>null,_reconnect:!1,_reconnectConnector:null},k={accounts:null,activeChainIds:null,status:"disconnected",lastPing:null,wcSignClients:new Map,paraConnector:null},T={name:"graz-session",version:2,partialize:e=>({accounts:e.accounts,activeChainIds:e.activeChainIds,lastPing:e.lastPing,status:e.status}),storage:n.createJSONStorage(()=>sessionStorage)},N=e.create(n.subscribeWithSelector(n.persist(()=>k,T))),x=e.create(n.subscribeWithSelector(n.persist(()=>O,{name:"graz-internal",partialize:e=>({recentChainIds:e.recentChainIds,_reconnect:e._reconnect,_reconnectConnector:e._reconnectConnector,walletType:e.walletType,chains:e.chains}),version:3}))),B=(e=>(e[e.ERROR=0]="ERROR",e[e.WARN=1]="WARN",e[e.INFO=2]="INFO",e[e.DEBUG=3]="DEBUG",e[e.TRACE=4]="TRACE",e))(B||{}),L=(e=>(e.WALLET="wallet",e.TRANSACTION="transaction",e.QUERY="query",e.STORE="store",e.MULTICHAIN="multichain",e.EVENT="event",e.PERFORMANCE="performance",e))(L||{}),R=class{constructor(e){I(this,"level"),I(this,"categories"),I(this,"enabled"),I(this,"timers"),I(this,"errorReporter"),I(this,"levelColors",{error:"color: #ff4444; font-weight: bold;",warn:"color: #ff9800; font-weight: bold;",info:"color: #2196f3; font-weight: bold;",debug:"color: #4caf50; font-weight: bold;",trace:"color: #9e9e9e; font-weight: bold;",reset:"color: inherit; font-weight: normal;"}),I(this,"categoryColors",{wallet:"color: #9c27b0; font-weight: bold;",transaction:"color: #e91e63; font-weight: bold;",query:"color: #00bcd4; font-weight: bold;",store:"color: #ff5722; font-weight: bold;",multichain:"color: #3f51b5; font-weight: bold;",event:"color: #ffc107; font-weight: bold;",performance:"color: #4caf50; font-weight: bold;"}),I(this,"functionColors",{connect:"color: #00e5ff; font-weight: bold;",disconnect:"color: #00e676; font-weight: bold;",reconnect:"color: #ff6d00; font-weight: bold;",getWallet:"color: #d500f9; font-weight: bold;",clearRecentChain:"color: #ff1744; font-weight: bold;",getRecentChainIds:"color: #f50057; font-weight: bold;",getRecentChains:"color: #ff4081; font-weight: bold;",getChainInfo:"color: #e040fb; font-weight: bold;",getChainInfos:"color: #b388ff; font-weight: bold;",addChain:"color: #8c9eff; font-weight: bold;",suggestChain:"color: #536dfe; font-weight: bold;",suggestChainAndConnect:"color: #448aff; font-weight: bold;",sendTokens:"color: #18ffff; font-weight: bold;",sendIbcTokens:"color: #40c4ff; font-weight: bold;",instantiateContract:"color: #69f0ae; font-weight: bold;",executeContract:"color: #b2ff59; font-weight: bold;",getQuerySmart:"color: #eeff41; font-weight: bold;",getQueryRaw:"color: #ffea00; font-weight: bold;",createMultiChainAsyncFunction:"color: #7c4dff; font-weight: bold;",handleFocus:"color: #ff9100; font-weight: bold;",autoConnectIframe:"color: #ff6e40; font-weight: bold;",reconnectEffect:"color: #a1887f; font-weight: bold;",subscription:"color: #90caf9; font-weight: bold;"}),I(this,"hookColors",{useConnect:"color: #00e5ff; font-weight: bold;",useDisconnect:"color: #1de9b6; font-weight: bold;",useCheckWallet:"color: #d500f9; font-weight: bold;",useAddChain:"color: #aa00ff; font-weight: bold;",useSuggestChain:"color: #6200ea; font-weight: bold;",useSuggestChainAndConnect:"color: #651fff; font-weight: bold;",useStargateClient:"color: #2979ff; font-weight: bold;",useCosmWasmClient:"color: #2962ff; font-weight: bold;",useStargateSigningClient:"color: #448aff; font-weight: bold;",useCosmWasmSigningClient:"color: #536dfe; font-weight: bold;",useSendTokens:"color: #00e676; font-weight: bold;",useSendIbcTokens:"color: #76ff03; font-weight: bold;",useInstantiateContract:"color: #c6ff00; font-weight: bold;",useExecuteContract:"color: #aeea00; font-weight: bold;"});const n="undefined"!=typeof window&&window.__GRAZ_DEBUG__;this.level=e?.level,this.categories=new Set(e?.categories??[]),this.enabled=e?.enabled??n??!1,this.timers=new Map,this.errorReporter=e?.errorReporter}formatLog(e,n,t,o){const r=o?`%c[${o}]%c `:"";let i="color: #00e5ff; font-weight: bold;";o&&(i=this.hookColors[o]||this.functionColors[o]||i);const a=o?[i,this.levelColors.reset]:[];return[`%c[graz]%c %c${e.toUpperCase()}%c %c[${n}]%c ${r}${t}`,"color: #673ab7; font-weight: bold;",this.levelColors.reset,this.levelColors[e]||this.levelColors.reset,this.levelColors.reset,this.categoryColors[n]||this.levelColors.reset,this.levelColors.reset,...a]}error(e,n,t){if(!this.shouldLog(0,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("error",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.error(r,...i,Object.keys(a||{}).length>0?a:"");const s=this.errorReporter||"undefined"!=typeof window&&window.grazErrorReporter;if(s){const o=new Error(n);s.captureException(o,{category:e,context:t})}}warn(e,n,t){if(!this.shouldLog(1,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("warn",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.warn(r,...i,Object.keys(a||{}).length>0?a:"")}info(e,n,t){if(!this.shouldLog(2,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("info",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.info(r,...i,Object.keys(a||{}).length>0?a:"")}debug(e,n,t){if(!this.shouldLog(3,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("debug",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.debug(r,...i,Object.keys(a||{}).length>0?a:"")}trace(e,n,t){if(!this.shouldLog(4,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("trace",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.trace(r,...i,Object.keys(a||{}).length>0?a:"")}time(e){this.enabled&&"undefined"!=typeof performance&&this.timers.set(e,performance.now())}timeEnd(e){if(!this.enabled)return;if("undefined"==typeof performance)return;const n=this.timers.get(e);if(void 0!==n){const t=performance.now()-n,[o,...r]=this.formatLog("debug","performance",`⏱️ ${e}: ${t.toFixed(2)}ms`);console.debug(o,...r),this.timers.delete(e)}}group(e){this.enabled&&void 0!==console.group&&console.group(`[graz] ${e}`)}groupEnd(){this.enabled&&void 0!==console.groupEnd&&console.groupEnd()}shouldLog(e,n){if(!this.enabled)return!1;if(void 0!==this.level)if(Array.isArray(this.level)){if(!this.level.includes(e))return!1}else if(e>this.level)return!1;return!(this.categories.size>0&&!this.categories.has(n))}setLevel(e){this.level=e}setCategories(e){this.categories=new Set(e??[])}enable(){this.enabled=!0}disable(){this.enabled=!1}},D=()=>(C||(C=new R),C),P=e=>{C=new R(e)},q=()=>{if(void 0!==window.cactuslink_cosmos){const e=window.cactuslink_cosmos,n=e=>{const n=()=>{ae(),e()};return window.addEventListener("accountsChanged",n),()=>{window.removeEventListener("accountsChanged",n)}};return{...Object.assign(e,{subscription:n}),getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSigner(n),experimentalSuggestChain:async()=>{throw new Error("Cactus Cosmos does not support experimentalSuggestChain")}}}throw x.getState()._notFoundFn(),new Error("window.cactuslink_cosmos is not defined")},F=()=>{if(void 0!==window.compass){const e=window.compass,n=e=>{const n=()=>{ae(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw x.getState()._notFoundFn(),new Error("window.leap is not defined")},M=()=>{const e=x.getState();if(!e.iframeOptions)throw e._notFoundFn(),new Error("no iframe options set");if(!t.isInIframe())throw e._notFoundFn(),new Error("not in iframe");if(!e.iframeOptions.allowedIframeParentOrigins.length)throw e._notFoundFn(),new Error("no iframe allowed origins");const n=new t.Cosmiframe(e.iframeOptions.allowedIframeParentOrigins).getKeplrClient();return{enable:n.enable.bind(n),getKey:n.getKey.bind(n),getOfflineSigner:n.getOfflineSigner.bind(n),getOfflineSignerAuto:n.getOfflineSignerAuto.bind(n),getOfflineSignerOnlyAmino:n.getOfflineSignerOnlyAmino.bind(n),experimentalSuggestChain:n.experimentalSuggestChain.bind(n),signDirect:n.signDirect.bind(n),signAmino:n.signAmino.bind(n)}},U={},W=()=>{if(void 0!==window.cosmostation?.providers.keplr){const e=window.cosmostation.providers.keplr,n=e=>{const n=()=>{ae(),e()};return window.addEventListener("cosmostation_keystorechange",n),()=>{window.removeEventListener("cosmostation_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw x.getState()._notFoundFn(),new Error("window.cosmostation.providers.keplr is not defined")},K=()=>{if(void 0!==window.initia){const e=window.initia;return{enable:async()=>{await e.getAddress()},getKey:async n=>{const t=e.getOfflineSigner(n),[o]=await t.getAccounts();if(!o)throw new Error("Wallet connection failed");const i=(()=>{switch(o.algo){case"secp256k1":return r.rawSecp256k1PubkeyToRawAddress(o.pubkey);case"ed25519":return r.rawEd25519PubkeyToRawAddress(o.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{name:(a=o.address,`${a.slice(0,6)}...${a.slice(-6)}`),algo:o.algo,pubKey:o.pubkey,bech32Address:o.address,address:i,isNanoLedger:!1,isKeystone:!1};var a},getOfflineSigner:n=>{const t=e.getOfflineSigner(n),o=e.getOfflineSignerOnlyAmino(n);return{getAccounts:t.getAccounts.bind(t),signDirect:t.signDirect.bind(t),signAmino:o.signAmino.bind(o)}},getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),experimentalSuggestChain:n=>e.requestAddInitiaLayer({chain_id:n.chainId,chain_name:n.chainName,bech32_prefix:"init",bech32_config:n.bech32Config,slip44:n.bip44.coinType,logo_URIs:{png:n.chainSymbolImageUrl},fees:{fee_tokens:n.feeCurrencies.map(e=>({denom:e.coinDenom,amount:e.coinMinimalDenom,low_gas_price:e.gasPriceStep?.low,average_gas_price:e.gasPriceStep?.average,high_gas_price:e.gasPriceStep?.high}))},apis:{rpc:[{address:n.rpc}],rest:[{address:n.rest}]}}),signDirect:(...n)=>{const[t,o,r]=n;return e.getOfflineSigner(t).signDirect(o,(e=>{const{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}=e;if(!(n&&t&&o&&r))throw new Error("Invalid sign doc");return{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}})(r))},signAmino:(...n)=>{const[t,o,r]=n;return e.getOfflineSignerOnlyAmino(t).signAmino(o,r)},signArbitrary:async(n,t,o)=>{const i=e.getOfflineSigner(n),a=(await i.getAccounts()).find(e=>e.address===t);if(!a)throw new Error(`Wallet not connected to account ${t}`);const s=(()=>{switch(a.algo){case"secp256k1":return r.encodeSecp256k1Pubkey(a.pubkey);case"ed25519":return r.encodeEd25519Pubkey(a.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{signature:await e.signArbitrary(o),pub_key:{type:"secp256k1"===a.algo?r.pubkeyType.secp256k1:r.pubkeyType.ed25519,value:s.value}}},subscription:e=>{const n=()=>{ae(),e()};return window.addEventListener("initia_keystorechange",n),()=>{window.removeEventListener("initia_keystorechange",n)}}}}throw x.getState()._notFoundFn(),new Error("window.initia is not defined")},$=()=>{if(void 0!==window.keplr){const e=window.keplr,n=e=>{const n=()=>{ae(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw x.getState()._notFoundFn(),new Error("window.keplr is not defined")},j=()=>{if(void 0!==window.leap){const e=window.leap,n=e=>{const n=()=>{ae(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw x.getState()._notFoundFn(),new Error("window.leap is not defined")},G={},H=()=>(e=>{const n=window.ethereum;if(n&&e){const t=async()=>await n.request({method:"wallet_getSnaps"}),o=async n=>{try{const o=await t();return Object.values(o).find(t=>t.id===e.id&&(!n||t.version===n))}catch(e){return}},r=async()=>{await n.request({method:"wallet_requestSnaps",params:{[e.id]:e.params||{}}})},i=async()=>{const e=await n.request({method:"web3_clientVersion"});if(!e.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const t=e.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(t)>=11))throw new Error("Metamask Snap is not supported in this version");return await o()||await r(),!0},a=async(t,o,r)=>{const i=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signDirect",params:{chainId:t,signerAddress:o,signDoc:r}}}}),a=r.accountNumber,s=new y.default(a.low,a.high,a.unsigned);return{signature:i.signature,signed:{...i.signed,accountNumber:s.toString(),authInfoBytes:new Uint8Array(Object.values(i.signed.authInfoBytes)),bodyBytes:new Uint8Array(Object.values(i.signed.bodyBytes))}}},s=async(t,o,r)=>await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signAmino",params:{chainId:t,signerAddress:o,signDoc:r}}}}),c=async t=>{if(void 0!==G[t])return G[t];const o=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"getKey",params:{chainId:t}}}});if(!o)throw new Error("No response from Metamask");return o.pubKey=Uint8Array.from(Object.values(o.pubkey)),delete o.pubkey,G[t]=o,G[t]},l=async e=>{const n=await c(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async(...e)=>{const[n,t,o,r]=e;return await s(n,t,o)},u=async(...e)=>{const[n,t,o]=e,r={...o,accountNumber:y.default.fromString(o.accountNumber?.toString()||"0"),authInfoBytes:o.authInfoBytes,bodyBytes:o.bodyBytes};return await a(n,t,r)},g=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>d(e,n,t)});return{enable:async e=>{await o()||await r()},experimentalSuggestChain:async(...t)=>{await i(),await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"suggestChain",params:{chainInfo:t[0]}}}})},getKey:c,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>d(e,n,t)}),getOfflineSignerAuto:async e=>g(e),getOfflineSignerOnlyAmino:g,init:i,signAmino:d,signDirect:u}}throw x.getState()._notFoundFn(),new Error("window.ethereum is not defined")})({id:"npm:@leapwallet/metamask-cosmos-snap"}),Q=()=>{if(void 0!==window.okxwallet?.keplr){const e=window.okxwallet.keplr,n=e=>{const n=()=>{ae(),e()};return window.okxwallet?.on("accountsChanged",n),()=>{window.okxwallet?.removeListener("accountsChanged",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw x.getState()._notFoundFn(),new Error("window.okxwallet.keplr is not defined")},z=null,V=()=>{const e=()=>{const e=N.getState().paraConnector;if(!e)throw new Error("Para connector not initialized. Call connect() first or check paraConfig in GrazProvider.");return e},n=x.getState().paraConfig;if(!n?.paraWeb)throw new Error("Missing Para config. Provide paraConfig with 'paraWeb' to GrazProvider.");return{enable:async e=>{const t=Array.isArray(e)?e:[e];try{const e=await(z||(z=(async()=>{const e=N.getState().paraConnector;if(e)return e;if(!n.connectorClass)throw new Error("Para connector class not provided. Provide 'connectorClass' in paraConfig to use Para wallet.");try{const e=x.getState().chains,t=new n.connectorClass(n,e);if(!t)throw new Error("Para connector initialization failed. Check config and dependencies.");return N.setState(e=>({...e,paraConnector:t})),t}catch(e){throw z=null,new Error(`Para connector init failed: ${e?.message||"Unknown error"}. Check ParaConfig and connectorClass.`)}})()));N.setState({paraConnector:e,status:"connecting"}),await e.enable(t);const o=Object.fromEntries(await Promise.all(t.map(async n=>[n,await e.getKey(n)])));N.setState(e=>({accounts:{...e.accounts||{},...o},activeChainIds:Array.from(new Set([...e.activeChainIds||[],...t])),status:"connected"})),x.setState(e=>({recentChainIds:Array.from(new Set([...e.recentChainIds||[],...t])),walletType:"para",_reconnect:!1,_reconnectConnector:"para"}))}catch(e){throw N.setState({paraConnector:null,status:"disconnected"}),new Error("Para enable failed"+(e instanceof Error?`: ${e.message}`:""))}},disable:async()=>{const e=N.getState().paraConnector;if(e)try{await e.disconnect(),await e.getParaWebClient().logout()}catch(e){throw new Error("Para disconnect failed"+(e?.message?`: ${e.message}`:". Wallet may already be disconnected."))}finally{N.setState({paraConnector:null,status:"disconnected"})}else N.setState({paraConnector:null,status:"disconnected"})},getKey:async n=>{try{return await e().getKey(n)}catch(e){throw new Error(`Failed to get key${e?.message?`: ${e.message}`:""}. Check chain connection and Cosmos API key settings at developer.getpara.com.`)}},getOfflineSigner:n=>{try{return e().getOfflineSigner(n)}catch(e){throw new Error(`Failed to get offline signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerOnlyAmino:n=>{try{return e().getOfflineSignerOnlyAmino(n)}catch(e){throw new Error(`Failed to get Amino signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerAuto:n=>{try{return e().getOfflineSignerAuto(n)}catch(e){throw new Error(`Failed to get auto signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},signAmino:async(n,t,o,r)=>{try{return await e().signAmino(n,t,o,r)}catch(e){throw new Error(`Amino signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signDirect:async(n,t,o,r)=>{try{return await e().signDirect(n,t,o,r)}catch(e){throw new Error(`Direct signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signArbitrary:async(n,t,o)=>{try{return await e().signArbitrary(n,t,o)}catch(e){throw new Error(`Arbitrary signing failed${e?.message?`: ${e.message}`:""}. User rejected or feature not supported.`)}},experimentalSuggestChain:async()=>{throw new Error("Chain suggestion not supported. Configure chains in Para wallet settings.")}}},Y=()=>{if(void 0!==window.station?.keplr){const e=window.station.keplr;return{subscription:e=>{const n=()=>{ae(),e()};return window.addEventListener("station_wallet_change",n),()=>{window.removeEventListener("station_wallet_change",n)}},getKey:async n=>({isKeystone:!1,...await e.getKey(n)}),getOfflineSigner:n=>{try{const t=e.getOfflineSignerOnlyAmino(n),o=(e,n)=>{throw new Error("signDirect not supported by Station")};return Object.assign(t,{signDirect:o})}catch(e){throw console.error(e),e}},experimentalSuggestChain:async n=>{try{if(!n.bech32Config)throw new Error("Bech32Config is required");if(!n.stakeCurrency)throw new Error("StakeCurrency is required");const t=Object.assign(n,{bech32Config:n.bech32Config,chainSymbolImageUrl:n.chainSymbolImageUrl||"",stakeCurrency:{coinDecimals:n.stakeCurrency.coinDecimals,coinDenom:n.stakeCurrency.coinDenom,coinImageUrl:n.stakeCurrency.coinImageUrl||"",coinMinimalDenom:n.stakeCurrency.coinMinimalDenom},currencies:n.currencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom})),feeCurrencies:n.feeCurrencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom,gasPriceStep:{average:e.gasPriceStep?.average||0,high:e.gasPriceStep?.high||0,low:e.gasPriceStep?.low||0}}))});await e.experimentalSuggestChain(t)}catch(e){throw console.error(e),e}},enable:n=>e.enable(n),disable:n=>e.disable(n),getOfflineSignerAuto:n=>e.getOfflineSignerAuto(n),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),signDirect:e.signDirect,signAmino:(n,t,o,r)=>e.signAmino(n,t,o)}}throw x.getState()._notFoundFn(),new Error("window.station is not defined")},X=()=>{if(void 0!==window.vectis){const e=window.vectis.cosmos;return{enable:n=>e.enable(n),getOfflineSigner:n=>{const t=e.getOfflineSigner(n);return{getAccounts:t.getAccounts,signAmino:t.signAmino,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:y.default.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}},getOfflineSignerAuto:async n=>{const t=await e.getOfflineSignerAuto(n);return"signAmino"in t?t:"signDirect"in t?{getAccounts:t.getAccounts,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:y.default.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}:t},getKey:async n=>{const t=await e.getKey(n);return{address:a.fromBech32(t.address).data,algo:t.algo,bech32Address:t.address,name:t.name,pubKey:t.pubKey,isKeystone:!1,isNanoLedger:t.isNanoLedger}},subscription:e=>{const n=()=>{ae(),e()};return window.addEventListener("vectis_accountChanged",n),()=>{window.removeEventListener("vectis_accountChanged",n)}},getOfflineSignerOnlyAmino:(...n)=>{const t=n[0];return e.getOfflineSignerAmino(t)},experimentalSuggestChain:async(...n)=>{const[t]=n;if(!t.bech32Config)throw new Error("Bech32Config is required");if(!t.stakeCurrency)throw new Error("StakeCurrency is required");const o={rpcUrl:t.rpc,restUrl:t.rest,prettyName:t.chainName.replace(" ",""),bech32Prefix:t.bech32Config.bech32PrefixAccAddr,currencies:t.currencies,feeCurrencies:t.feeCurrencies,chainId:t.chainId,chainName:t.chainName,bip44:t.bip44,stakeCurrency:t.stakeCurrency,features:t.features};return e.suggestChains([o])},signDirect:async(...n)=>{const{1:t,2:o}=n,r=await e.signDirect(t,{bodyBytes:o.bodyBytes||Uint8Array.from([]),authInfoBytes:o.authInfoBytes||Uint8Array.from([]),accountNumber:y.default.fromString(o.accountNumber?.toString()||"",!1),chainId:o.chainId||""});return{signature:r.signature,signed:{authInfoBytes:r.signed.authInfoBytes,bodyBytes:r.signed.bodyBytes,chainId:r.signed.chainId,accountNumber:BigInt(r.signed.accountNumber.toString())}}},signAmino:async(...n)=>{const{1:t,2:o}=n;return e.signAmino(t,o)}}}throw x.getState()._notFoundFn(),new Error("window.vectis is not defined")},J=()=>{if("undefined"!=typeof window){const e=navigator.userAgent;return!!/android/i.test(e)||!!/iPad|iPhone|iPod/.test(e)}return!1},Z=(e,n,t=new Error("Promise timed out"))=>{const o=new Promise((e,o)=>{setTimeout(()=>{o(t)},n)});return Promise.race([e,o])},ee=e=>{if(!x.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");const n=e?.walletType||"walletconnect",t=e?.encoding||"base64",o=n=>{if(!e)return;const{appUrl:t,formatNativeUrl:o}=e;if(J()){if(J()&&navigator.userAgent.toLowerCase().includes("android")){const e=o(t.mobile.android,n,"android");window.open(e,"_self","noreferrer noopener")}if(J()&&(navigator.userAgent.toLowerCase().includes("iphone")||navigator.userAgent.toLowerCase().includes("ipad"))){const e=o(t.mobile.ios,n,"ios");window.open(e,"_self","noreferrer noopener")}}},r=()=>{const{wcSignClients:e}=N.getState();if(!e.get(n))throw new Error("walletConnect.signClient is not defined");e.delete(n),N.setState({wcSignClients:e}),x.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})},i=async e=>{const{wcSignClients:t}=N.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");if(!e)throw new Error("No wallet connect session");await o.disconnect({topic:e,reason:l.getSdkError("USER_DISCONNECTED")}),await d(o)},a=e=>{try{const{wcSignClients:t}=N.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");const r=o.session.getAll(),a=r.at(-1);if(!a)return;if(!(1e3*a.expiry>Date.now()+1e3))throw i(a.topic),new Error("invalid session");try{const n=r.find(n=>n.requiredNamespaces.cosmos?.chains?.includes(`cosmos:${e}`));if(!n)throw new Error("no session");return n}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}return a}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},d=async e=>{try{const n=e.core.pairing.pairings.getAll({active:!1});if(!n.length)return;await Promise.all(n.map(async n=>{await e.core.pairing.pairings.delete(n.topic,{code:7001,message:"clear pairing"})}))}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},u=async t=>{const r="string"==typeof t?[t]:t,{wcSignClients:c,activeChainIds:l}=N.getState(),d=c.get(n);if(!d)throw new Error("enable walletConnect.signClient is not defined");const{walletConnect:u}=x.getState();if(!u?.options?.projectId)throw new Error("walletConnect.options.projectId is not defined");const g=new s.WalletConnectModal({projectId:u.options.projectId,enableExplorer:!1,explorerRecommendedWalletIds:"NONE",...u.walletConnectModal}),f=(e=>{try{return a(e)}catch(e){return}})(r);if(!f){const{uri:n,approval:t}=await Z(d.connect({requiredNamespaces:{cosmos:{methods:["cosmos_getAccounts","cosmos_signAmino","cosmos_signDirect"],chains:r.map(e=>`cosmos:${e}`),events:["chainChanged","accountsChanged"]}}}),15e3,new Error("Connection timeout"));if(!n)throw new Error("No wallet connect uri");e?o(n):await g.openModal({uri:n});const i=async e=>e.aborted?Promise.reject(new Error("User closed wallet connect")):new Promise((n,o)=>{t().then(e=>{const t=e.sessionProperties;if(!t)return o(new Error("No session properties"));const r=JSON.parse(String(t.keys));if(0===r.length)return o(new Error("No accounts"));if(!r[0])return o(new Error("No accounts"));const i={};return r.forEach(e=>{i[e.chainId]={address:e.address,algo:e.algo,bech32Address:e.bech32Address,isNanoLedger:e.isNanoLedger,isKeystone:e.isKeystone,name:e.name,pubKey:e.pubKey}}),N.setState(e=>({accounts:{...e.accounts||{},...i}})),n(e)}).catch(o),e.addEventListener("abort",()=>{o(new Error("User closed wallet connect"))},{once:!0})});try{const e=new AbortController,n=e.signal;g.subscribeModal(n=>{n.open||e.abort()}),await i(n)}catch(e){if(g.closeModal(),!e.message.toLowerCase().includes("no matching key"))return Promise.reject(e)}return e||g.closeModal(),Promise.resolve()}try{await Z((async()=>{const e=Object.fromEntries(await Promise.all((l||r).map(async e=>[e,await h(e)])));N.setState({accounts:e})})(),15e3,new Error("Connection timeout"))}catch(e){if(i(f.topic),!e.message.toLowerCase().includes("no matching key"))throw e}},g=async e=>{const n=await h(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},h=async e=>{const n=a([e]);if(!n?.topic)throw new Error("No wallet connect session");const o=n.sessionProperties&&JSON.parse(String(n.sessionProperties.keys));if(!o)throw new Error("No wallet connect key");if(0===o.length)throw new Error("No wallet connect session");const r=o.find(n=>n.chainId===e);if(!r)throw new Error(`No wallet connect key for chainId ${e}`);return{...r,pubKey:Buffer.from(String(r.pubKey),t)}},f=async(...e)=>{const[r,i,s]=e,{signature:c,signed:l}=await(async(...e)=>{const[r,i,s]=e,{accounts:c,wcSignClients:l}=N.getState(),d=l.get(n);if(!d)throw new Error("walletConnect.signClient is not defined");if(!c)throw new Error("account is not defined");const u=a([r])?.topic;if(!u)throw new Error("No wallet connect session");if(!s.bodyBytes)throw new Error("No bodyBytes");if(!s.authInfoBytes)throw new Error("No authInfoBytes");return o(),await d.request({topic:u,chainId:`cosmos:${r}`,request:{method:"cosmos_signDirect",params:{signerAddress:i,signDoc:{chainId:s.chainId,accountNumber:s.accountNumber?.toString(),bodyBytes:s.bodyBytes?Buffer.from(s.bodyBytes).toString(t):null,authInfoBytes:s.authInfoBytes?Buffer.from(s.authInfoBytes).toString(t):null}}}})})(r,i,s);return{signed:{chainId:l.chainId??"",accountNumber:l.accountNumber?BigInt(l.accountNumber):BigInt(0),authInfoBytes:l.authInfoBytes?new Uint8Array(Buffer.from(l.authInfoBytes,t)):new Uint8Array([]),bodyBytes:l.bodyBytes?new Uint8Array(Buffer.from(l.bodyBytes,t)):new Uint8Array([])},signature:c}},w=async(...e)=>{const[t,r,i,s]=e,c=await(async(...e)=>{const[t,r,i,s]=e,{wcSignClients:c}=N.getState(),l=c.get(n),{accounts:d}=N.getState();if(!l)throw new Error("walletConnect.signClient is not defined");if(!d)throw new Error("account is not defined");const u=a([t])?.topic;if(!u)throw new Error("No wallet connect session");return o(),await l.request({topic:u,chainId:`cosmos:${t}`,request:{method:"cosmos_signDirect",params:{signerAddress:r,signDoc:i}}})})(t,r,i);return c},m=e=>({getAccounts:async()=>[await g(e)],signAmino:(n,t)=>w(e,n,t)});return{enable:u,disable:async e=>{const{wcSignClients:t}=N.getState(),o=t.get(n);if(void 0===e){const e=o?.session.getAll();void 0!==e&&await Promise.all(e.map(e=>i(e.topic)))}else"string"==typeof e?await i(a([e])?.topic):await Promise.all(e.map(e=>i(a([e])?.topic)));0===o?.session.getAll().length&&r()},experimentalSuggestChain:async(...e)=>{await Promise.reject(new Error("WalletConnect does not support experimentalSuggestChain"))},getKey:h,getOfflineSigner:e=>({getAccounts:async()=>[await g(e)],signDirect:(n,t)=>f(e,n,t),signAmino:(n,t)=>w(e,n,t)}),getOfflineSignerAuto:async e=>(await h(e)).isNanoLedger?m(e):(e=>({getAccounts:async()=>[await g(e)],signDirect:(n,t)=>f(e,n,t)}))(e),getOfflineSignerOnlyAmino:m,signAmino:w,signDirect:f,subscription:e=>{const{wcSignClients:t}=N.getState(),o=t.get(n);if(!o)return()=>{};const i=n=>{const t=N.getState().accounts;if("accountsChanged"===n.params.event.name&&t&&!Object.values(t).map(e=>e.bech32Address).includes(n.params.event.data[0])){const e=n.params.chainId.split(":")[1];e&&u([e])}else e()};return o.events.on("session_delete",r),o.events.on("session_expire",r),o.events.on("session_event",i),()=>{o.events.off("session_delete",r),o.events.off("session_expire",r),o.events.off("session_event",i)}},init:async()=>{const{walletConnect:e}=x.getState();if(!e?.options)throw new Error("walletConnect.options is not defined");const{wcSignClients:t}=N.getState(),o=t.get(n);if(o)return o;const r=await c.SignClient.init(e.options);return t.set(n,r),N.setState({wcSignClients:t}),r}}},ne=()=>{if(!x.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!J())throw new Error("WalletConnect Cosmostation mobile is only supported in mobile");return ee({encoding:"hex",appUrl:{mobile:{ios:"cosmostation://",android:"cosmostation://"}},walletType:"wc_cosmostation_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,"");return n?`${o}://wc?${n}`:`${o}://wc`}})},te=()=>{if(!x.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!J())throw new Error("WalletConnect Keplr mobile is only supported in mobile");return ee({encoding:"base64",appUrl:{mobile:{ios:"keplrwallet://",android:"intent://"}},walletType:"wc_keplr_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`:`${o}://wcV2#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},oe=()=>{if(!x.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!J())throw new Error("WalletConnect Leap mobile is only supported in mobile");return ee({encoding:"base64",appUrl:{mobile:{ios:"leapcosmos://",android:"intent://"}},walletType:"wc_leap_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`:`${o}://wcV2#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},re=()=>{if(void 0!==window.xfi?.keplr){const e=window.xfi.keplr,n=e=>{const n=()=>{ae(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}};return Object.assign(e,{subscription:n})}throw x.getState()._notFoundFn(),new Error("window.xfi.keplr is not defined")},ie=(e=x.getState().walletType)=>{try{return se(e),!0}catch(e){return!1}},ae=()=>{window.sessionStorage.removeItem(E),N.setState(k)},se=(e=x.getState().walletType)=>{const n=D();n.debug("wallet","Getting wallet adapter",{function:"getWallet",walletType:e});const t=(()=>{switch(e){case"keplr":return $();case"leap":return j();case"cosmostation":return W();case"vectis":return X();case"walletconnect":return ee();case"wc_keplr_mobile":return te();case"wc_leap_mobile":return oe();case"wc_cosmostation_mobile":return ne();case"wc_clot_mobile":return(()=>{if(!x.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!J())throw new Error("WalletConnect Clot mobile is only supported in mobile");return ee({encoding:"base64",appUrl:{mobile:{android:"clot://",ios:"clot://"}},walletType:"wc_clot_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);return"ios"===t?r?`${o}://wcV2?${r}`:`${o}://wcV2`:r?`${o}://wc?uri=${r}`:`${o}://wc`}})})();case"metamask_snap_leap":return H();case"metamask_snap_cosmos":return(()=>{const e=window.ethereum;let n=window.cosmos;if(e)return{init:async()=>{const t=await e.request({method:"web3_clientVersion"});if(!t.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const r=t.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(r)>=11))throw new Error("Metamask Snap is not supported in this version");return await o.isSnapInstalled()||await o.installSnap(),window.cosmos=new o.CosmosSnap,n=window.cosmos,!0},enable:async e=>{await o.isSnapInstalled()||await o.installSnap()},getOfflineSigner:e=>n.getOfflineSigner(e),experimentalSuggestChain:async e=>{if(!e.bech32Config)throw new Error("Bech32Config is required");if(!e.stakeCurrency)throw new Error("StakeCurrency is required");await n.experimentalSuggestChain({...e,stakeCurrency:e.stakeCurrency,bech32Config:e.bech32Config})},signAmino:async(e,t,o)=>n.signAmino(e,t,o),getKey:async e=>void 0!==U[e]?U[e]:n.getKey(e),getOfflineSignerAuto:async e=>(await n.getKey(e)).isNanoLedger?n.getOfflineSignerOnlyAmino(e):n.getOfflineSigner(e),getOfflineSignerOnlyAmino:e=>n.getOfflineSignerOnlyAmino(e),signDirect:async(e,t,o)=>n.signDirect(e,t,o),signArbitrary:async(e,t,o)=>n.signArbitrary(e,t,o),disable:async e=>{e&&await n.deleteChain(e)}};throw x.getState()._notFoundFn(),new Error("window.ethereum is not defined")})();case"station":return Y();case"xdefi":return re();case"cosmiframe":return M();case"compass":return F();case"initia":return K();case"okx":return Q();case"para":return V();case"cactuscosmos":return q();default:throw n.warn("wallet","Unknown wallet type",{function:"getWallet",walletType:e}),new Error("Unknown wallet type")}})(),r=x.getState().walletDefaultOptions;return r&&t.setDefaultOptions?.(r),t},ce=e=>"metamask_snap_leap"===e,le=()=>Boolean(navigator?.userAgent)&&/LeapCosmos/i.test(navigator.userAgent),de=e=>"walletconnect"===e||"wc_keplr_mobile"===e||"wc_leap_mobile"===e||"wc_cosmostation_mobile"===e,ue=e=>"para"===e,ge=async e=>{const n=D();n.time("connect"),n.group("Connect Wallet");try{const{recentChainIds:t,chains:o,walletType:r}=x.getState(),i=e?.walletType||r;if(n.debug("wallet","Starting connection",{function:"connect",walletType:i,chainId:e?.chainId,timestamp:Date.now()}),de(i)){const e=se("walletconnect"),{disable:n}=e;n&&n()}if(!ie(i))throw n.warn("wallet","Wallet not available",{function:A.CONNECT,walletType:i}),new Error(`${i} is not available`);n.debug("wallet","Wallet adapter retrieved",{function:A.CONNECT,walletType:i});const a=se(i),s="string"==typeof e?.chainId?[e.chainId]:e?.chainId||t;if(!s)throw new Error("No last known connected chain, connect action requires chain ids");const c=o?.map(e=>e.chainId);if(s.forEach(e=>{if(!c?.includes(e))throw new Error(`Chain ${e} is not provided in GrazProvider`)}),N.setState(e=>{const n=x.getState()._reconnect||Boolean(x.getState()._reconnectConnector)||Boolean(s);return e.activeChainIds&&s.filter(n=>!e.activeChainIds?.includes(n)).length>0?{status:"connecting"}:n?{status:"reconnecting"}:{status:"connecting"}}),n.debug("wallet","Initializing wallet",{function:A.CONNECT}),await(a.init?.()),n.debug("wallet","Enabling chains",{function:A.CONNECT,chainIds:s,chainCount:s.length}),await a.enable(s),n.debug("wallet","Fetching accounts",{function:A.CONNECT}),!de(i)){let e={};if(ce(i)){const n={};for await(const e of s)n[e]=await a.getKey(e);e=n}else if(le()&&a.getKeys){const n=await a.getKeys(s);s.forEach((t,o)=>{const r=n[o];r&&(e[t]=r)})}else e=Object.fromEntries(await Promise.all(s.map(async e=>[e,await a.getKey(e)])));N.setState(n=>({accounts:{...n.accounts||{},...e}}))}x.setState(e=>({recentChainIds:[...e.recentChainIds||[],...s].filter((e,n,t)=>t.indexOf(e)===n)})),N.setState(e=>({activeChainIds:[...e.activeChainIds||[],...s].filter((e,n,t)=>t.indexOf(e)===n)})),x.setState({walletType:i,_reconnect:Boolean(e?.autoReconnect),_reconnectConnector:i}),N.setState({status:"connected"}),"undefined"!=typeof window&&window.sessionStorage.setItem(E,"Active");const l=s.map(e=>o.find(n=>n.chainId===e)),d=N.getState().accounts;return n.info("wallet","Connection successful",{function:A.CONNECT,walletType:i,chainCount:s.length,chainIds:s,addresses:d?Object.values(d).map(e=>e.bech32Address):[]}),n.debug("store","Session store updated",{function:A.CONNECT,accountCount:Object.keys(d||{}).length}),n.timeEnd("connect"),n.groupEnd(),{accounts:d,walletType:i,chains:l}}catch(t){throw n.error("wallet","Connection failed",{function:A.CONNECT,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,walletType:e?.walletType,chainId:e?.chainId}),null===N.getState().accounts&&N.setState({status:"disconnected"}),N.getState().accounts&&N.getState().activeChainIds&&N.setState({status:"connected"}),n.timeEnd("connect"),n.groupEnd(),t}},he=e=>{const n=D(),t="string"==typeof e?.chainId?[e.chainId]:e?.chainId;n.info("wallet","Disconnecting",{function:A.DISCONNECT,chainId:t||"all chains"}),"undefined"!=typeof window&&window.sessionStorage.removeItem(E);const o=()=>{if(de(x.getState().walletType)){const e=se("walletconnect"),{disable:n}=e;n&&n()}if(ue(x.getState().walletType)){const e=se("para"),{disable:n}=e;n&&n()}};if(t){const e=N.getState().accounts;t.forEach(n=>{delete e?.[n]});0===Object.values(e||{}).length?(o(),N.setState(k),x.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null}),n.debug("store","Session cleared - all chains disconnected",{function:A.DISCONNECT})):(N.setState(n=>({activeChainIds:n.activeChainIds?.filter(e=>!t.includes(e)),accounts:e})),x.setState(e=>({recentChainIds:e.recentChainIds?.filter(e=>!t.includes(e))})),n.debug("store","Partial disconnect - some chains remain connected",{function:A.DISCONNECT}))}else o(),N.setState(k),x.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null}),n.debug("store","Session cleared - disconnected from all chains",{function:A.DISCONNECT});return n.info("wallet","Disconnected successfully",{function:A.DISCONNECT,chainId:t||"all chains"}),Promise.resolve()},fe=async e=>{const n=D(),{recentChainIds:t,_reconnectConnector:o,_reconnect:r}=x.getState();n.debug("wallet","Attempting reconnection",{function:A.RECONNECT,recentChains:t,walletType:o});try{const e=ie(o||void 0);if(t&&e&&o){if(de(o))return;const e=await ge({chainId:t,walletType:o,autoReconnect:r});return n.info("wallet","Reconnection successful",{function:A.RECONNECT}),e}n.warn("wallet","Reconnection skipped",{function:A.RECONNECT,hasRecentChains:Boolean(t),isWalletReady:e,hasConnector:Boolean(o)})}catch(t){n.warn("wallet","Reconnection failed",{function:A.RECONNECT,error:t instanceof Error?t.message:String(t)}),e?.onError?.(t),he()}},we=async e=>{if(!e?.chainId)throw new Error("chainId is required");const{walletType:n}=x.getState(),t=e.walletType||n;if(!ie(t))throw new Error(`${t} is not available`);const o=se(t);return{offlineSigner:o.getOfflineSigner(e.chainId),offlineSignerAmino:o.getOfflineSignerOnlyAmino(e.chainId),offlineSignerAuto:await o.getOfflineSignerAuto(e.chainId)}},me=()=>{D().debug("store","Clearing recent chains",{function:"clearRecentChain"}),x.setState({recentChainIds:null})},pe=async({chainInfo:e})=>{const n=D();n.debug("store","Adding chain",{function:"addChain",chainId:e.chainId,chainName:e.chainName});const{chains:t}=x.getState(),o=t?.find(n=>n.chainId===e.chainId);if(o)throw n.warn("store","Chain already exists",{function:"addChain",chainId:e.chainId}),new Error(`Chain with chainId "${e.chainId}" already exists in the store`);return x.setState(n=>({chains:[...n.chains||[],e]})),n.info("store","Chain added successfully",{function:"addChain",chainId:e.chainId,chainName:e.chainName}),e},Ce=async({chainInfo:e,walletType:n})=>{const t=D();t.debug("wallet","Suggesting chain to wallet",{function:"suggestChain",chainId:e.chainId,chainName:e.chainName,walletType:n});try{const o=se(n);await o.experimentalSuggestChain(e);const{chains:r}=x.getState(),i=r?.find(n=>n.chainId===e.chainId);return i||(x.setState(n=>({chains:[...n.chains||[],e]})),t.debug("store","Chain added to store after suggestion",{function:"suggestChain",chainId:e.chainId})),t.info("wallet","Chain suggested successfully",{function:"suggestChain",chainId:e.chainId,chainName:e.chainName,walletType:n}),e}catch(o){throw t.error("wallet","Failed to suggest chain",{function:"suggestChain",error:o instanceof Error?o.message:String(o),chainId:e.chainId,walletType:n}),o}},ye=async e=>{const n=D(),t=x.getState().walletType,o=e.walletType??t;n.info("wallet","Suggesting chain and connecting",{function:"suggestChainAndConnect",chainId:e.chainInfo.chainId,chainName:e.chainInfo.chainName,walletType:o}),n.time("suggest-chain-and-connect");try{await Ce({chainInfo:e.chainInfo,walletType:o});const t=await ge({chainId:e.chainInfo.chainId,walletType:e.walletType,autoReconnect:e.autoReconnect});return n.timeEnd("suggest-chain-and-connect"),n.info("wallet","Chain suggested and connected successfully",{function:"suggestChainAndConnect",chainId:e.chainInfo.chainId,walletType:t.walletType}),t}catch(t){throw n.timeEnd("suggest-chain-and-connect"),n.error("wallet","Failed to suggest chain and connect",{function:"suggestChainAndConnect",error:t instanceof Error?t.message:String(t),chainId:e.chainInfo.chainId}),t}},Se=e=>(P({enabled:e.logger?.enabled??!1,level:e.logger?.level,categories:e.logger?.categories}),x.setState(n=>{const t=n.chains??[],o=e.chains,r=new Map;o.forEach(e=>r.set(e.chainId,e)),t.forEach(e=>{r.has(e.chainId)||r.set(e.chainId,e)});const i=Array.from(r.values());return{iframeOptions:e.iframeOptions||n.iframeOptions,walletConnect:e.walletConnect||n.walletConnect,walletType:e.defaultWallet||n.walletType,paraConfig:e.paraConfig||n.paraConfig,walletDefaultOptions:e.walletDefaultOptions||n.walletDefaultOptions,chains:i,chainsConfig:e.chainsConfig||n.chainsConfig,multiChainFetchConcurrency:e.multiChainFetchConcurrency||n.multiChainFetchConcurrency,pingInterval:e.pingInteval||n.pingInterval,loggerConfig:e.logger?{enabled:e.logger.enabled??n.loggerConfig?.enabled??!1,level:e.logger.level??n.loggerConfig?.level??1,categories:e.logger.categories??n.loggerConfig?.categories??[]}:n.loggerConfig,_notFoundFn:e.onNotFound||n._notFoundFn,_onReconnectFailed:e.onReconnectFailed||n._onReconnectFailed,_reconnect:void 0===e.autoReconnect||(e.autoReconnect||n._reconnect)}}),e),be=async({signingClient:e,senderAddress:n,recipientAddress:t,amount:o,fee:r,memo:i})=>{const a=D();if(!e)throw new Error("No connected account detected");if(!n)throw new Error("senderAddress is not defined");a.debug("transaction","Signing transaction",{function:"sendTokens",senderAddress:n,recipientAddress:t,amount:o});try{const s=await e.sendTokens(n,t,o,r,i);return a.info("transaction","Transaction broadcasted",{function:"sendTokens",txHash:s.transactionHash,height:s.height}),s}catch(e){throw a.error("transaction","Transaction failed",{function:"sendTokens",error:e instanceof Error?e.message:String(e),senderAddress:n,recipientAddress:t}),e}},Ie=async({signingClient:e,senderAddress:n,recipientAddress:t,transferAmount:o,sourcePort:r,sourceChannel:i,timeoutHeight:a,timeoutTimestamp:s,fee:c,memo:l})=>{const d=D();if(!e)throw new Error("Stargate signing client is not ready");if(!n)throw new Error("senderAddress is not defined");d.debug("transaction","Signing IBC transfer",{function:"sendIbcTokens",senderAddress:n,recipientAddress:t,transferAmount:o,sourceChannel:i,sourcePort:r});try{const u=await e.sendIbcTokens(n,t,o,r,i,a,s,c,l);return d.info("transaction","IBC transfer successful",{function:"sendIbcTokens",txHash:u.transactionHash,height:u.height}),u}catch(e){throw d.error("transaction","IBC transfer failed",{function:"sendIbcTokens",error:e instanceof Error?e.message:String(e),senderAddress:n,recipientAddress:t,sourceChannel:i}),e}},Ee=async({signingClient:e,senderAddress:n,msg:t,fee:o,options:r,label:i,codeId:a})=>{const s=D();if(!e)throw new Error("CosmWasm signing client is not ready");s.debug("transaction","Instantiating contract",{function:"instantiateContract",senderAddress:n,codeId:a,label:i});try{const c=await e.instantiate(n,a,t,i,o,r);return s.info("transaction","Contract instantiated",{function:"instantiateContract",contractAddress:c.contractAddress,txHash:c.transactionHash}),c}catch(e){throw s.error("transaction","Contract instantiation failed",{function:"instantiateContract",error:e instanceof Error?e.message:String(e),codeId:a,senderAddress:n}),e}},Ae=async({signingClient:e,senderAddress:n,msg:t,fee:o,contractAddress:r,funds:i,memo:a})=>{const s=D();if(!e)throw new Error("CosmWasm signing client is not ready");s.debug("transaction","Executing contract",{function:"executeContract",senderAddress:n,contractAddress:r,msg:t});try{const c=await e.execute(n,r,t,o,a,i);return s.info("transaction","Contract execution successful",{function:"executeContract",txHash:c.transactionHash,events:c.events.length}),c}catch(e){throw s.error("transaction","Contract execution failed",{function:"executeContract",error:e instanceof Error?e.message:String(e),contractAddress:r,senderAddress:n}),e}},_e=async(e,n,t)=>{const o=D();if(!t)throw new Error("CosmWasm client is not ready");o.debug("query","Querying smart contract",{function:"getQuerySmart",address:e,queryMsg:n});try{const r=await t.queryContractSmart(e,n);return o.debug("query","Smart query successful",{function:"getQuerySmart",address:e}),r}catch(n){throw o.error("query","Smart query failed",{function:"getQuerySmart",error:n instanceof Error?n.message:String(n),address:e}),n}},ve=async(e,n,t)=>{const o=D();if(!t)throw new Error("CosmWasm client is not ready");o.debug("query","Querying raw contract data",{function:"getQueryRaw",address:e,key:n});try{const r=(new TextEncoder).encode(n),i=await t.queryContractRaw(e,r);return o.debug("query","Raw query successful",{function:"getQueryRaw",address:e}),i}catch(n){throw o.error("query","Raw query failed",{function:"getQueryRaw",error:n instanceof Error?n.message:String(n),address:e}),n}},Oe=({chainId:e})=>{const n=x(e=>e.chains);if(!n)throw new Error("No chains found in GrazProvider");return e&&e.length>0?e.map(e=>n.find(n=>n.chainId===e)).filter(Boolean):n},ke=async(e,n,t)=>{const o=D(),r=x.getState().multiChainFetchConcurrency,i=t?{hook:t}:{function:"createMultiChainAsyncFunction"};o.debug("multichain","Starting parallel operations",{...i,chainCount:e.length,concurrency:r,chainIds:e.map(e=>e.chainId)}),o.time("multichain-operation");try{const t=await S.default(e,n,{concurrency:r}),a=Object.fromEntries(t.map((n,t)=>[e[t].chainId,n]));return o.timeEnd("multichain-operation"),o.info("multichain","All chains completed",{...i,chainCount:e.length,chainIds:e.map(e=>e.chainId),successCount:Object.keys(a).length}),a}catch(n){throw o.timeEnd("multichain-operation"),o.error("multichain","Multi-chain operation failed",{...i,error:n instanceof Error?n.message:String(n),chainCount:e.length,chainIds:e.map(e=>e.chainId)}),n}};function Te(e){const n=Oe({chainId:e?.chainId}),t=u.useMemo(()=>["USE_STARGATE_CLIENT",n],[n]);return d.useQuery({queryKey:t,queryFn:async()=>{const e=D();if(e.debug("query","Creating Stargate clients",{hook:"useStargateClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId)}),!n||n.length<1)throw new Error("No chains found");try{const t=await ke(n,async e=>{const n=x.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await f.StargateClient.connect(t)},"useStargateClient");return e.debug("query","Stargate clients created successfully",{hook:"useStargateClient",clientCount:Object.keys(t).length}),t}catch(n){throw e.error("query","Failed to create Stargate clients",{hook:"useStargateClient",error:n instanceof Error?n.message:String(n)}),n}},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}function Ne(e){const n=Oe({chainId:e?.chainId}),t=u.useMemo(()=>["USE_COSMWASM_CLIENT",n],[n]);return d.useQuery({queryKey:t,queryFn:async()=>{const e=D();if(e.debug("query","Creating CosmWasm clients",{hook:"useCosmWasmClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId)}),!n||n.length<1)throw new Error("No chains found");try{const t=await ke(n,async e=>{const n=x.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await h.CosmWasmClient.connect(t)},"useCosmWasmClient");return e.debug("query","CosmWasm clients created successfully",{hook:"useCosmWasmClient",clientCount:Object.keys(t).length}),t}catch(n){throw e.error("query","Failed to create CosmWasm clients",{hook:"useCosmWasmClient",error:n instanceof Error?n.message:String(n)}),n}},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}var xe=e=>{const n=x(n=>e||n.walletType),t=["USE_CHECK_WALLET",n];return d.useQuery({queryKey:t,queryFn:()=>{const e=D();if(e.debug("wallet","Checking wallet availability",{hook:"useCheckWallet",walletType:n}),!n)return e.debug("wallet","No wallet type provided",{hook:"useCheckWallet"}),!1;const t=ie(n);return e.debug("wallet","Wallet check completed",{hook:"useCheckWallet",walletType:n,isAvailable:t}),t}})};var Be=()=>{const e=N(e=>e.activeChainIds),n=x(e=>e.chains);return e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean)};var Le=({children:e})=>{const[n,t]=u.useState(!1);return u.useEffect(()=>{t(!0)},[]),m.jsx(m.Fragment,{children:n?e:null})},Re=()=>{const e=D(),n="undefined"!=typeof window&&"Active"===window.sessionStorage.getItem(E),{_reconnect:o,_onReconnectFailed:r,_reconnectConnector:i,iframeOptions:a,chains:s,pingInterval:c}=x(),{activeChainIds:l,wcSignClients:d}=N(),g=ie(i||void 0);return u.useEffect(()=>{const t=async()=>{if(n&&g&&i&&l?.[0]){const n=N.getState().lastPing;if(n&&Date.now()-n<c)return;const t=se(i);try{if(!await t.getKey(l[0]))throw new Error("No account found");N.setState({lastPing:Date.now()}),e.debug("event","Wallet ping successful",{function:"handleFocus"})}catch(n){e.debug("event","Wallet ping failed, triggering reconnect",{function:"handleFocus",error:n instanceof Error?n.message:String(n),walletType:i}),fe({onError:r})}}};return window.addEventListener("focus",t),()=>{window.removeEventListener("focus",t)}},[n,g,i,s,l,c]),u.useEffect(()=>{if(!a||!1===a.autoConnect||!a.allowedIframeParentOrigins.length||!s)return;new t.Cosmiframe(a.allowedIframeParentOrigins).isReady().then(n=>{if(n)return e.info("event","Auto-connecting to iframe wallet",{function:"autoConnectIframe"}),ge({chainId:s.map(e=>e.chainId),walletType:"cosmiframe"})})},[a]),u.useEffect(()=>{if(i){if(!g)return;n&&Boolean(l)?(e.info("event","Reconnection triggered",{function:"reconnectEffect",reason:"session active"}),fe({onError:r})):!n&&o&&(e.info("event","Reconnection triggered",{function:"reconnectEffect",reason:"auto-reconnect enabled"}),fe({onError:r}))}},[g]),u.useEffect(()=>{if(i){if(!g)return;"cosmostation"===i&&W().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"cosmostation"}),fe({onError:r})}),"keplr"===i&&$().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"keplr"}),fe({onError:r})}),"leap"===i&&j().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"leap"}),fe({onError:r})}),"compass"===i&&F().subscription?.(()=>{fe({onError:r})}),"vectis"===i&&X().subscription?.(()=>{fe({onError:r})}),"walletconnect"===i&&d.has("walletconnect")&&ee().subscription?.(()=>{fe({onError:r})}),"station"===i&&Y().subscription?.(()=>{fe({onError:r})}),"xdefi"===i&&re().subscription?.(()=>{fe({onError:r})}),"cosmiframe"===i&&M().subscription?.(()=>{fe({onError:r})}),"okx"===i&&Q().subscription?.(()=>{fe({onError:r})})}},[i,d,g]),null},De=()=>(Re(),null);exports.GrazEvents=De,exports.GrazProvider=({children:e,grazOptions:n})=>(u.useEffect(()=>{Se(n)},[n]),m.jsxs(Le,{children:[e,m.jsx(De,{})]})),exports.LOG_CATEGORIES={WALLET:"wallet",TRANSACTION:"transaction",QUERY:"query",STORE:"store",MULTICHAIN:"multichain",EVENT:"event",PERFORMANCE:"performance"},exports.LOG_FUNCTIONS=A,exports.LOG_HOOKS={USE_CONNECT:"useConnect",USE_DISCONNECT:"useDisconnect",USE_CHECK_WALLET:"useCheckWallet",USE_ADD_CHAIN:"useAddChain",USE_SUGGEST_CHAIN:"useSuggestChain",USE_SUGGEST_CHAIN_AND_CONNECT:"useSuggestChainAndConnect",USE_STARGATE_CLIENT:"useStargateClient",USE_COSMWASM_CLIENT:"useCosmWasmClient",USE_STARGATE_SIGNING_CLIENT:"useStargateSigningClient",USE_COSMWASM_SIGNING_CLIENT:"useCosmWasmSigningClient",USE_SEND_TOKENS:"useSendTokens",USE_SEND_IBC_TOKENS:"useSendIbcTokens",USE_INSTANTIATE_CONTRACT:"useInstantiateContract",USE_EXECUTE_CONTRACT:"useExecuteContract"},exports.LogCategory=L,exports.LogLevel=B,exports.WALLET_TYPES=v,exports.WalletType=_,exports.addChain=pe,exports.checkWallet=ie,exports.clearRecentChain=me,exports.clearSession=ae,exports.configureGraz=Se,exports.configureLogger=P,exports.connect=ge,exports.defineChainInfo=e=>e,exports.defineChains=e=>e,exports.disconnect=he,exports.executeContract=Ae,exports.getAvailableWallets=()=>Object.fromEntries(v.map(e=>[e,ie(e)])),exports.getCactusCosmos=q,exports.getChainInfo=({chainId:e}={})=>{const n=D(),t=x.getState().chains?.find(n=>n.chainId===e);return n.debug("store","Getting chain info",{function:"getChainInfo",chainId:e,found:Boolean(t)}),t},exports.getChainInfos=({chainId:e}={})=>{const n=D(),t=x.getState().chains,o=e?t?.filter(n=>e.includes(n.chainId)):t??void 0;return n.debug("store","Getting chain infos",{function:"getChainInfos",requestedChainIds:e,resultCount:o?.length??0}),o},exports.getCosmostation=W,exports.getKeplr=$,exports.getLeap=j,exports.getLogger=D,exports.getMetamaskSnapLeap=H,exports.getOfflineSigners=we,exports.getOkx=Q,exports.getPara=V,exports.getQueryRaw=ve,exports.getQuerySmart=_e,exports.getRecentChainIds=()=>{const e=D(),n=x.getState().recentChainIds;return e.debug("store","Getting recent chain IDs",{function:"getRecentChainIds",chainIds:n}),n},exports.getRecentChains=()=>{const e=D(),{recentChainIds:n,chains:t}=x.getState(),o=n?.map(e=>t.find(n=>n.chainId===e))??null;return e.debug("store","Getting recent chains",{function:"getRecentChains",chainIds:n,chainCount:o?.length??0}),o},exports.getVectis=X,exports.getWCCosmostation=ne,exports.getWCKeplr=te,exports.getWCLeap=oe,exports.getWallet=se,exports.getWalletConnect=ee,exports.instantiateContract=Ee,exports.isLeapDappBrowser=le,exports.isLeapSnaps=ce,exports.isPara=ue,exports.isWalletConnect=de,exports.reconnect=fe,exports.sendIbcTokens=Ie,exports.sendTokens=be,exports.suggestChain=Ce,exports.suggestChainAndConnect=ye,exports.useAccount=function(e){const n=x(e=>e.walletType),t=N(e=>e.activeChainIds),o=Oe({chainId:e?.chainId?e.chainId:t||void 0}),r=N(e=>e.accounts),i=N(e=>e.status);return u.useEffect(()=>N.subscribe(e=>e.status,(n,t)=>{if("connected"===n){const{accounts:n,activeChainIds:o}=N.getState(),{chains:r}=x.getState(),{walletType:i}=x.getState();if(!n||!o||!r)return e?.onDisconnect?.();e?.onConnect?.({accounts:n,chains:o.map(e=>r.find(n=>n.chainId===e)),walletType:i,isReconnect:"reconnecting"===t})}"disconnected"===n&&e?.onDisconnect?.()}),[e]),{data:u.useMemo(()=>r?((e,n)=>{const t=e.map(n);return Object.fromEntries(t.map((n,t)=>[e[t].chainId,n]))})(o,e=>r[e.chainId]):void 0,[r,o]),isConnected:"connected"===i,isConnecting:"connecting"===i,isDisconnected:"disconnected"===i,isReconnecting:"reconnecting"===i,isLoading:"connecting"===i||"reconnecting"===i,walletType:"connected"===i?n:void 0,reconnect:fe,status:i}},exports.useActiveChainCurrency=({denom:e})=>{const n=Be(),t=["USE_ACTIVE_CHAIN_CURRENCY",e];return d.useQuery({queryKey:t,queryFn:({queryKey:[,e]})=>n?.find(n=>n.currencies.find(n=>n.coinMinimalDenom===e))?.currencies.find(e=>e)})},exports.useActiveChainIds=()=>N(e=>e.activeChainIds),exports.useActiveChains=Be,exports.useActiveWalletType=()=>x(w.useShallow(e=>({walletType:e.walletType,isCosmostation:"cosmostation"===e.walletType,isCosmostationMobile:"wc_cosmostation_mobile"===e.walletType,isKeplr:"keplr"===e.walletType,isKeplrMobile:"wc_keplr_mobile"===e.walletType,isLeap:"leap"===e.walletType,isLeapMobile:"wc_leap_mobile"===e.walletType,isVectis:"vectis"===e.walletType,isWalletConnect:"walletconnect"===e.walletType,isMetamaskSnapLeap:"metamask_snap_leap"===e.walletType,isStation:"station"===e.walletType,isCosmiframe:"cosmiframe"===e.walletType}))),exports.useAddChain=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),r=["USE_ADD_CHAIN",e,n,t],i=d.useMutation({mutationKey:r,mutationFn:pe,onError:(n,t)=>(o.error("store","useAddChain mutation failed",{hook:"useAddChain",error:n instanceof Error?n.message:String(n),chainId:t.chainInfo.chainId}),Promise.resolve(e?.(n,t.chainInfo))),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>(o.info("store","useAddChain mutation successful",{hook:"useAddChain",chainId:e.chainId,chainName:e.chainName}),Promise.resolve(t?.(e)))});return{addChain:i.mutate,addChainAsync:i.mutateAsync,error:i.error,isLoading:i.isPending,isSuccess:i.isSuccess,status:i.status}},exports.useBalance=e=>{const n=Oe({chainId:[e.chainId]})[0],{data:t}=Te({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=u.useMemo(()=>["USE_BALANCE",o,e.chainId,e.bech32Address,e.denom],[e.bech32Address,e.chainId,e.denom,o]);return d.useQuery({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);const t=await o.getBalance(e.bech32Address,e.denom);return"0"===t.amount?void 0:t},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},exports.useBalanceStaked=e=>{const n=Oe({chainId:[e.chainId]})[0],{data:t}=Te({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=u.useMemo(()=>["USE_BALANCE_STAKED",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return d.useQuery({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getBalanceStaked(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},exports.useBalances=e=>{const n=Oe({chainId:[e.chainId]})[0],{data:t}=Te({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=u.useMemo(()=>["USE_ALL_BALANCES",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return d.useQuery({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getAllBalances(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},exports.useChainInfo=({chainId:e}={})=>x(e=>e.chains)?.find(n=>n.chainId===e),exports.useChainInfos=({chainId:e}={})=>{const n=x(e=>e.chains);return e?n?.filter(n=>e.includes(n.chainId)):n},exports.useCheckWallet=xe,exports.useConnect=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),r=["USE_CONNECT",e,n,t],i=d.useMutation({mutationKey:r,mutationFn:ge,onError:(n,t)=>{o.error("wallet","useConnect mutation failed",{error:n instanceof Error?n.message:String(n),chainId:t?.chainId}),e?.(n,t)},onMutate:n,onSuccess:e=>(o.info("wallet","useConnect mutation successful",{hook:"useConnect",walletType:e.walletType,chainCount:e.chains.length}),Promise.resolve(t?.(e)))}),{data:a}=xe();return{connect:e=>i.mutate(e),connectAsync:e=>i.mutateAsync(e),error:i.error,isLoading:i.isPending,isSuccess:i.isSuccess,isSupported:Boolean(a),status:i.status}},exports.useCosmWasmClient=Ne,exports.useCosmWasmSigningClient=function(e){const n=Oe({chainId:e?.chainId}),t=x(e=>e.walletType),o=N(e=>e.activeChainIds),r="connected"===N.getState().status&&N.getState().accounts&&x.getState()._reconnectConnector===t,i=u.useMemo(()=>["USE_COSMWASM_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return d.useQuery({queryKey:i,queryFn:async()=>{const r=D();if(r.debug("query","Creating CosmWasm signing clients",{hook:"useCosmWasmSigningClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId),walletType:t}),!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");try{const i=await ke(n,async n=>{if(!o?.includes(n.chainId))return null;if(!ie(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return se(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return se(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return se(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=x.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}},s=i?.gas?f.GasPrice.fromString(`${i.gas.price}${i.gas.denom}`):void 0;return await h.SigningCosmWasmClient.connectWithSigner(a,r,{gasPrice:s,...e?.opts?.[n.chainId]||{}})},"useCosmWasmSigningClient");return r.debug("query","CosmWasm signing clients created successfully",{hook:"useCosmWasmSigningClient",clientCount:Object.keys(i).length}),i}catch(e){throw r.error("query","Failed to create CosmWasm signing clients",{hook:"useCosmWasmSigningClient",error:e instanceof Error?e.message:String(e),walletType:t}),e}},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})},exports.useDisconnect=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),r=["USE_DISCONNECT",e,n,t],i=d.useMutation({mutationKey:r,mutationFn:he,onError:n=>(o.error("wallet","useDisconnect mutation failed",{hook:"useDisconnect",error:n instanceof Error?n.message:String(n)}),Promise.resolve(e?.(n,void 0))),onMutate:n,onSuccess:()=>(o.info("wallet","useDisconnect mutation successful",{hook:"useDisconnect"}),Promise.resolve(t?.(void 0)))});return{disconnect:e=>i.mutate(e),disconnectAsync:e=>i.mutateAsync(e),error:i.error,isLoading:i.isPending,isSuccess:i.isSuccess,status:i.status}},exports.useExecuteContract=({contractAddress:e,onError:n,onLoading:t,onSuccess:o})=>{const r=D(),{mutate:i,mutateAsync:a,...s}=d.useMutation({mutationKey:["USE_EXECUTE_CONTRACT",n,t,o,e],mutationFn:n=>Ae({...n,fee:n.fee??"auto",contractAddress:e,memo:n.memo??"",funds:n.funds??[]}),onError:(t,o)=>(r.error("transaction","useExecuteContract mutation failed",{hook:"useExecuteContract",error:t instanceof Error?t.message:String(t),contractAddress:e}),Promise.resolve(n?.(t,o))),onMutate:t,onSuccess:n=>(r.info("transaction","useExecuteContract mutation successful",{hook:"useExecuteContract",txHash:n.transactionHash,contractAddress:e}),Promise.resolve(o?.(n)))});return{...s,executeContract:i,executeContractAsync:a}},exports.useGrazEvents=Re,exports.useInstantiateContract=({codeId:e,onError:n,onLoading:t,onSuccess:o})=>{const r=D(),{mutate:i,mutateAsync:a,...s}=d.useMutation({mutationKey:["USE_INSTANTIATE_CONTRACT",n,t,o,e],mutationFn:n=>Ee({...n,fee:n.fee??"auto",codeId:e}),onError:(t,o)=>(r.error("transaction","useInstantiateContract mutation failed",{error:t instanceof Error?t.message:String(t),codeId:e}),Promise.resolve(n?.(t,o))),onMutate:t,onSuccess:e=>(r.info("transaction","useInstantiateContract mutation successful",{hook:"useInstantiateContract",contractAddress:e.contractAddress,txHash:e.transactionHash}),Promise.resolve(o?.(e)))});return{...s,instantiateContract:i,instantiateContractAsync:a}},exports.useOfflineSigners=function(e){const n=Oe({chainId:e?.chainId}),t=x(e=>e.walletType),o="connected"===N.getState().status&&N.getState().accounts&&x.getState()._reconnectConnector===t,r=u.useMemo(()=>["USE_OFFLINE_SIGNERS",n,t],[n,t]);return d.useQuery({queryKey:r,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chain found");if(!t)throw new Error("Wallet is not defined");if(!ie(t))throw new Error(`${t} is not available`);return await ke(n,async e=>await we({chainId:e.chainId,walletType:t}),"useOfflineSigners")},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&Boolean(o),refetchOnWindowFocus:!1})},exports.useQueryClientValidators=e=>{const n=e.status??"BOND_STATUS_BONDED",t=["USE_ACTIVE_CHAIN_VALIDATORS",e.queryClient,n];return d.useQuery({queryKey:t,queryFn:async()=>{if(!e.queryClient)throw new Error("Query client is not defined");return await e.queryClient.staking.validators(n)},enabled:void 0!==e.queryClient})},exports.useQueryRaw=e=>{const{data:n}=Ne(),t=n&&Object.values(n)[0],o=["USE_QUERY_RAW",e?.key,e?.address,t];return d.useQuery({queryKey:o,queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.key)throw new Error("address or key undefined");return ve(e.address,e.key,t)},enabled:Boolean(e?.address)&&Boolean(e?.key)&&Boolean(t)})},exports.useQuerySmart=e=>{const{data:n}=Ne(),t=n&&Object.values(n)[0];return d.useQuery({queryKey:["USE_QUERY_SMART",e?.address,e?.queryMsg,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.queryMsg)throw new Error("address or queryMsg undefined");return _e(e.address,e.queryMsg,t)},enabled:Boolean(e?.address)&&Boolean(e?.queryMsg)&&Boolean(t)})},exports.useRecentChainIds=()=>({data:x(e=>e.recentChainIds),clear:me}),exports.useRecentChains=()=>{const e=x(e=>e.recentChainIds),n=x(e=>e.chains),t=e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean);return{data:t,clear:me}},exports.useSendIbcTokens=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),{mutate:r,mutateAsync:i,...a}=d.useMutation({mutationKey:["USE_SEND_IBC_TOKENS",e,n,t],mutationFn:Ie,onError:(n,t)=>(o.error("transaction","useSendIbcTokens mutation failed",{error:n instanceof Error?n.message:String(n),sourceChannel:t.sourceChannel}),Promise.resolve(e?.(n,t))),onMutate:n,onSuccess:e=>(o.info("transaction","useSendIbcTokens mutation successful",{hook:"useSendIbcTokens",txHash:e.transactionHash}),Promise.resolve(t?.(e)))});return{...a,sendIbcTokens:r,sendIbcTokensAsync:i}},exports.useSendTokens=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),{mutate:r,mutateAsync:i,...a}=d.useMutation({mutationKey:["USE_SEND_TOKENS",e,n,t],mutationFn:be,onError:(n,t)=>(o.error("transaction","useSendTokens mutation failed",{hook:"useSendTokens",error:n instanceof Error?n.message:String(n),recipientAddress:t.recipientAddress}),Promise.resolve(e?.(n,t))),onMutate:n,onSuccess:e=>(o.info("transaction","useSendTokens mutation successful",{hook:"useSendTokens",txHash:e.transactionHash}),Promise.resolve(t?.(e)))});return{...a,sendTokens:r,sendTokensAsync:i}},exports.useStargateClient=Te,exports.useStargateSigningClient=function(e){const n=Oe({chainId:e?.chainId}),t=x(e=>e.walletType),o=N(e=>e.activeChainIds),r="connected"===N.getState().status&&N.getState().accounts&&x.getState()._reconnectConnector===t,i=u.useMemo(()=>["USE_STARGATE_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return d.useQuery({queryKey:i,queryFn:async()=>{const r=D();if(r.debug("query","Creating Stargate signing clients",{hook:"useStargateSigningClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId),walletType:t}),!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");try{const i=await ke(n,async n=>{if(!o?.includes(n.chainId))return null;if(!ie(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return se(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return se(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return se(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=x.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}};return await f.SigningStargateClient.connectWithSigner(a,r,e?.opts?.[n.chainId])},"useStargateSigningClient");return r.debug("query","Stargate signing clients created successfully",{hook:"useStargateSigningClient",clientCount:Object.keys(i).length}),i}catch(e){throw r.error("query","Failed to create Stargate signing clients",{hook:"useStargateSigningClient",error:e instanceof Error?e.message:String(e),walletType:t}),e}},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})},exports.useSuggestChain=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),r=["USE_SUGGEST_CHAIN",e,n,t],i=d.useMutation({mutationKey:r,mutationFn:Ce,onError:(n,t)=>(o.error("wallet","useSuggestChain mutation failed",{hook:"useSuggestChain",error:n instanceof Error?n.message:String(n),chainId:t.chainInfo.chainId,walletType:t.walletType}),Promise.resolve(e?.(n,t.chainInfo))),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>(o.info("wallet","useSuggestChain mutation successful",{hook:"useSuggestChain",chainId:e.chainId,chainName:e.chainName}),Promise.resolve(t?.(e)))});return{error:i.error,isLoading:i.isPending,isSuccess:i.isSuccess,suggest:i.mutate,suggestAsync:i.mutateAsync,status:i.status}},exports.useSuggestChainAndConnect=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=D(),r=["USE_SUGGEST_CHAIN_AND_CONNECT",e,n,t],i=d.useMutation({mutationKey:r,mutationFn:ye,onError:(n,t)=>(o.error("wallet","useSuggestChainAndConnect mutation failed",{error:n instanceof Error?n.message:String(n),chainId:t.chainInfo.chainId}),Promise.resolve(e?.(n,t))),onMutate:e=>n?.(e),onSuccess:e=>(o.info("wallet","useSuggestChainAndConnect mutation successful",{hook:"useSuggestChainAndConnect",walletType:e.walletType,chainCount:e.chains.length}),Promise.resolve(t?.(e)))}),{data:a}=xe();return{error:i.error,isLoading:i.isPending,isSuccess:i.isSuccess,isSupported:Boolean(a),status:i.status,suggestAndConnect:i.mutate,suggestAndConnectAsync:i.mutateAsync}};
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 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};
1
+ import{create as e}from"zustand";import{createJSONStorage as n,subscribeWithSelector as t,persist as o}from"zustand/middleware";import{Cosmiframe as r,isInIframe as i}from"@dao-dao/cosmiframe";import{isSnapInstalled as a,installSnap as s,CosmosSnap as c}from"@cosmsnap/snapper";import{encodeEd25519Pubkey as l,encodeSecp256k1Pubkey as d,pubkeyType as u,rawEd25519PubkeyToRawAddress as g,rawSecp256k1PubkeyToRawAddress as h}from"@cosmjs/amino";import f from"long";import{fromBech32 as w}from"@cosmjs/encoding";import{WalletConnectModal as m}from"@walletconnect/modal";import{SignClient as p}from"@walletconnect/sign-client";import{getSdkError as C}from"@walletconnect/utils";import{useQuery as y,useMutation as S}from"@tanstack/react-query";import{useMemo as b,useEffect as I,useState as E}from"react";import A from"p-map";import{CosmWasmClient as _,SigningCosmWasmClient as v}from"@cosmjs/cosmwasm-stargate";import{StargateClient as O,SigningStargateClient as T,GasPrice as k}from"@cosmjs/stargate";import{useShallow as N}from"zustand/shallow";import{jsxs as B,jsx as D,Fragment as L}from"react/jsx-runtime";var R,F=Object.defineProperty,U=(e,n,t)=>((e,n,t)=>n in e?F(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t)(e,"symbol"!=typeof n?n+"":n,t),P="connect-graz",q={WALLET:"wallet",TRANSACTION:"transaction",QUERY:"query",STORE:"store",MULTICHAIN:"multichain",EVENT:"event",PERFORMANCE:"performance"},M={CONNECT:"connect",DISCONNECT:"disconnect",RECONNECT:"reconnect",GET_WALLET:"getWallet",CLEAR_RECENT_CHAIN:"clearRecentChain",GET_RECENT_CHAIN_IDS:"getRecentChainIds",GET_RECENT_CHAINS:"getRecentChains",GET_CHAIN_INFO:"getChainInfo",GET_CHAIN_INFOS:"getChainInfos",ADD_CHAIN:"addChain",SUGGEST_CHAIN:"suggestChain",SUGGEST_CHAIN_AND_CONNECT:"suggestChainAndConnect",SEND_TOKENS:"sendTokens",SEND_IBC_TOKENS:"sendIbcTokens",INSTANTIATE_CONTRACT:"instantiateContract",EXECUTE_CONTRACT:"executeContract",GET_QUERY_SMART:"getQuerySmart",GET_QUERY_RAW:"getQueryRaw",CREATE_MULTI_CHAIN_ASYNC_FUNCTION:"createMultiChainAsyncFunction",HANDLE_FOCUS:"handleFocus",AUTO_CONNECT_IFRAME:"autoConnectIframe",RECONNECT_EFFECT:"reconnectEffect",SUBSCRIPTION:"subscription"},W={USE_CONNECT:"useConnect",USE_DISCONNECT:"useDisconnect",USE_CHECK_WALLET:"useCheckWallet",USE_ADD_CHAIN:"useAddChain",USE_SUGGEST_CHAIN:"useSuggestChain",USE_SUGGEST_CHAIN_AND_CONNECT:"useSuggestChainAndConnect",USE_STARGATE_CLIENT:"useStargateClient",USE_COSMWASM_CLIENT:"useCosmWasmClient",USE_STARGATE_SIGNING_CLIENT:"useStargateSigningClient",USE_COSMWASM_SIGNING_CLIENT:"useCosmWasmSigningClient",USE_SEND_TOKENS:"useSendTokens",USE_SEND_IBC_TOKENS:"useSendIbcTokens",USE_INSTANTIATE_CONTRACT:"useInstantiateContract",USE_EXECUTE_CONTRACT:"useExecuteContract"},x=(e=>(e.KEPLR="keplr",e.LEAP="leap",e.VECTIS="vectis",e.COSMOSTATION="cosmostation",e.WALLETCONNECT="walletconnect",e.WC_KEPLR_MOBILE="wc_keplr_mobile",e.WC_LEAP_MOBILE="wc_leap_mobile",e.WC_COSMOSTATION_MOBILE="wc_cosmostation_mobile",e.WC_CLOT_MOBILE="wc_clot_mobile",e.METAMASK_SNAP_LEAP="metamask_snap_leap",e.METAMASK_SNAP_COSMOS="metamask_snap_cosmos",e.STATION="station",e.XDEFI="xdefi",e.COSMIFRAME="cosmiframe",e.COMPASS="compass",e.INITIA="initia",e.OKX="okx",e.PARA="para",e.CACTUSCOSMOS="cactuscosmos",e))(x||{}),K=["keplr","leap","vectis","cosmostation","walletconnect","wc_keplr_mobile","wc_leap_mobile","wc_cosmostation_mobile","wc_clot_mobile","metamask_snap_leap","station","xdefi","metamask_snap_cosmos","cosmiframe","compass","initia","okx","para","cactuscosmos"],$={iframeOptions:null,recentChainIds:null,chains:null,chainsConfig:null,paraConfig:null,multiChainFetchConcurrency:3,walletType:"keplr",walletConnect:{options:null,walletConnectModal:null},walletDefaultOptions:null,pingInterval:36e5,loggerConfig:null,_notFoundFn:()=>null,_onReconnectFailed:()=>null,_reconnect:!1,_reconnectConnector:null},j={accounts:null,activeChainIds:null,status:"disconnected",lastPing:null,wcSignClients:new Map,paraConnector:null},G=e(t(o(()=>j,{name:"graz-session",version:2,partialize:e=>({accounts:e.accounts,activeChainIds:e.activeChainIds,lastPing:e.lastPing,status:e.status}),storage:n(()=>sessionStorage)}))),H=e(t(o(()=>$,{name:"graz-internal",partialize:e=>({recentChainIds:e.recentChainIds,_reconnect:e._reconnect,_reconnectConnector:e._reconnectConnector,walletType:e.walletType,chains:e.chains}),version:3}))),z=(e=>(e[e.ERROR=0]="ERROR",e[e.WARN=1]="WARN",e[e.INFO=2]="INFO",e[e.DEBUG=3]="DEBUG",e[e.TRACE=4]="TRACE",e))(z||{}),Q=(e=>(e.WALLET="wallet",e.TRANSACTION="transaction",e.QUERY="query",e.STORE="store",e.MULTICHAIN="multichain",e.EVENT="event",e.PERFORMANCE="performance",e))(Q||{}),V=class{constructor(e){U(this,"level"),U(this,"categories"),U(this,"enabled"),U(this,"timers"),U(this,"errorReporter"),U(this,"levelColors",{error:"color: #ff4444; font-weight: bold;",warn:"color: #ff9800; font-weight: bold;",info:"color: #2196f3; font-weight: bold;",debug:"color: #4caf50; font-weight: bold;",trace:"color: #9e9e9e; font-weight: bold;",reset:"color: inherit; font-weight: normal;"}),U(this,"categoryColors",{wallet:"color: #9c27b0; font-weight: bold;",transaction:"color: #e91e63; font-weight: bold;",query:"color: #00bcd4; font-weight: bold;",store:"color: #ff5722; font-weight: bold;",multichain:"color: #3f51b5; font-weight: bold;",event:"color: #ffc107; font-weight: bold;",performance:"color: #4caf50; font-weight: bold;"}),U(this,"functionColors",{connect:"color: #00e5ff; font-weight: bold;",disconnect:"color: #00e676; font-weight: bold;",reconnect:"color: #ff6d00; font-weight: bold;",getWallet:"color: #d500f9; font-weight: bold;",clearRecentChain:"color: #ff1744; font-weight: bold;",getRecentChainIds:"color: #f50057; font-weight: bold;",getRecentChains:"color: #ff4081; font-weight: bold;",getChainInfo:"color: #e040fb; font-weight: bold;",getChainInfos:"color: #b388ff; font-weight: bold;",addChain:"color: #8c9eff; font-weight: bold;",suggestChain:"color: #536dfe; font-weight: bold;",suggestChainAndConnect:"color: #448aff; font-weight: bold;",sendTokens:"color: #18ffff; font-weight: bold;",sendIbcTokens:"color: #40c4ff; font-weight: bold;",instantiateContract:"color: #69f0ae; font-weight: bold;",executeContract:"color: #b2ff59; font-weight: bold;",getQuerySmart:"color: #eeff41; font-weight: bold;",getQueryRaw:"color: #ffea00; font-weight: bold;",createMultiChainAsyncFunction:"color: #7c4dff; font-weight: bold;",handleFocus:"color: #ff9100; font-weight: bold;",autoConnectIframe:"color: #ff6e40; font-weight: bold;",reconnectEffect:"color: #a1887f; font-weight: bold;",subscription:"color: #90caf9; font-weight: bold;"}),U(this,"hookColors",{useConnect:"color: #00e5ff; font-weight: bold;",useDisconnect:"color: #1de9b6; font-weight: bold;",useCheckWallet:"color: #d500f9; font-weight: bold;",useAddChain:"color: #aa00ff; font-weight: bold;",useSuggestChain:"color: #6200ea; font-weight: bold;",useSuggestChainAndConnect:"color: #651fff; font-weight: bold;",useStargateClient:"color: #2979ff; font-weight: bold;",useCosmWasmClient:"color: #2962ff; font-weight: bold;",useStargateSigningClient:"color: #448aff; font-weight: bold;",useCosmWasmSigningClient:"color: #536dfe; font-weight: bold;",useSendTokens:"color: #00e676; font-weight: bold;",useSendIbcTokens:"color: #76ff03; font-weight: bold;",useInstantiateContract:"color: #c6ff00; font-weight: bold;",useExecuteContract:"color: #aeea00; font-weight: bold;"});const n="undefined"!=typeof window&&window.__GRAZ_DEBUG__;this.level=e?.level,this.categories=new Set(e?.categories??[]),this.enabled=e?.enabled??n??!1,this.timers=new Map,this.errorReporter=e?.errorReporter}formatLog(e,n,t,o){const r=o?`%c[${o}]%c `:"";let i="color: #00e5ff; font-weight: bold;";o&&(i=this.hookColors[o]||this.functionColors[o]||i);const a=o?[i,this.levelColors.reset]:[];return[`%c[graz]%c %c${e.toUpperCase()}%c %c[${n}]%c ${r}${t}`,"color: #673ab7; font-weight: bold;",this.levelColors.reset,this.levelColors[e]||this.levelColors.reset,this.levelColors.reset,this.categoryColors[n]||this.levelColors.reset,this.levelColors.reset,...a]}error(e,n,t){if(!this.shouldLog(0,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("error",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.error(r,...i,Object.keys(a||{}).length>0?a:"");const s=this.errorReporter||"undefined"!=typeof window&&window.grazErrorReporter;if(s){const o=new Error(n);s.captureException(o,{category:e,context:t})}}warn(e,n,t){if(!this.shouldLog(1,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("warn",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.warn(r,...i,Object.keys(a||{}).length>0?a:"")}info(e,n,t){if(!this.shouldLog(2,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("info",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.info(r,...i,Object.keys(a||{}).length>0?a:"")}debug(e,n,t){if(!this.shouldLog(3,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("debug",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.debug(r,...i,Object.keys(a||{}).length>0?a:"")}trace(e,n,t){if(!this.shouldLog(4,e))return;const o=t?.function||t?.hook,[r,...i]=this.formatLog("trace",e,n,o),a=t?{...t}:void 0;a&&(delete a.function,delete a.hook),console.trace(r,...i,Object.keys(a||{}).length>0?a:"")}time(e){this.enabled&&"undefined"!=typeof performance&&this.timers.set(e,performance.now())}timeEnd(e){if(!this.enabled)return;if("undefined"==typeof performance)return;const n=this.timers.get(e);if(void 0!==n){const t=performance.now()-n,[o,...r]=this.formatLog("debug","performance",`⏱️ ${e}: ${t.toFixed(2)}ms`);console.debug(o,...r),this.timers.delete(e)}}group(e){this.enabled&&void 0!==console.group&&console.group(`[graz] ${e}`)}groupEnd(){this.enabled&&void 0!==console.groupEnd&&console.groupEnd()}shouldLog(e,n){if(!this.enabled)return!1;if(void 0!==this.level)if(Array.isArray(this.level)){if(!this.level.includes(e))return!1}else if(e>this.level)return!1;return!(this.categories.size>0&&!this.categories.has(n))}setLevel(e){this.level=e}setCategories(e){this.categories=new Set(e??[])}enable(){this.enabled=!0}disable(){this.enabled=!1}},Y=()=>(R||(R=new V),R),X=e=>{R=new V(e)},J=()=>{if(void 0!==window.cactuslink_cosmos){const e=window.cactuslink_cosmos,n=e=>{const n=()=>{be(),e()};return window.addEventListener("accountsChanged",n),()=>{window.removeEventListener("accountsChanged",n)}};return{...Object.assign(e,{subscription:n}),getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSigner(n),experimentalSuggestChain:async()=>{throw new Error("Cactus Cosmos does not support experimentalSuggestChain")}}}throw H.getState()._notFoundFn(),new Error("window.cactuslink_cosmos is not defined")},Z=()=>{if(void 0!==window.compass){const e=window.compass,n=e=>{const n=()=>{be(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw H.getState()._notFoundFn(),new Error("window.leap is not defined")},ee=()=>{const e=H.getState();if(!e.iframeOptions)throw e._notFoundFn(),new Error("no iframe options set");if(!i())throw e._notFoundFn(),new Error("not in iframe");if(!e.iframeOptions.allowedIframeParentOrigins.length)throw e._notFoundFn(),new Error("no iframe allowed origins");const n=new r(e.iframeOptions.allowedIframeParentOrigins).getKeplrClient();return{enable:n.enable.bind(n),getKey:n.getKey.bind(n),getOfflineSigner:n.getOfflineSigner.bind(n),getOfflineSignerAuto:n.getOfflineSignerAuto.bind(n),getOfflineSignerOnlyAmino:n.getOfflineSignerOnlyAmino.bind(n),experimentalSuggestChain:n.experimentalSuggestChain.bind(n),signDirect:n.signDirect.bind(n),signAmino:n.signAmino.bind(n)}},ne={},te=()=>{if(void 0!==window.cosmostation?.providers.keplr){const e=window.cosmostation.providers.keplr,n=e=>{const n=()=>{be(),e()};return window.addEventListener("cosmostation_keystorechange",n),()=>{window.removeEventListener("cosmostation_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw H.getState()._notFoundFn(),new Error("window.cosmostation.providers.keplr is not defined")},oe=()=>{if(void 0!==window.initia){const e=window.initia;return{enable:async()=>{await e.getAddress()},getKey:async n=>{const t=e.getOfflineSigner(n),[o]=await t.getAccounts();if(!o)throw new Error("Wallet connection failed");const r=(()=>{switch(o.algo){case"secp256k1":return h(o.pubkey);case"ed25519":return g(o.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{name:(i=o.address,`${i.slice(0,6)}...${i.slice(-6)}`),algo:o.algo,pubKey:o.pubkey,bech32Address:o.address,address:r,isNanoLedger:!1,isKeystone:!1};var i},getOfflineSigner:n=>{const t=e.getOfflineSigner(n),o=e.getOfflineSignerOnlyAmino(n);return{getAccounts:t.getAccounts.bind(t),signDirect:t.signDirect.bind(t),signAmino:o.signAmino.bind(o)}},getOfflineSignerAuto:n=>Promise.resolve(e.getOfflineSigner(n)),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),experimentalSuggestChain:n=>e.requestAddInitiaLayer({chain_id:n.chainId,chain_name:n.chainName,bech32_prefix:"init",bech32_config:n.bech32Config,slip44:n.bip44.coinType,logo_URIs:{png:n.chainSymbolImageUrl},fees:{fee_tokens:n.feeCurrencies.map(e=>({denom:e.coinDenom,amount:e.coinMinimalDenom,low_gas_price:e.gasPriceStep?.low,average_gas_price:e.gasPriceStep?.average,high_gas_price:e.gasPriceStep?.high}))},apis:{rpc:[{address:n.rpc}],rest:[{address:n.rest}]}}),signDirect:(...n)=>{const[t,o,r]=n;return e.getOfflineSigner(t).signDirect(o,(e=>{const{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}=e;if(!(n&&t&&o&&r))throw new Error("Invalid sign doc");return{bodyBytes:n,authInfoBytes:t,chainId:o,accountNumber:r}})(r))},signAmino:(...n)=>{const[t,o,r]=n;return e.getOfflineSignerOnlyAmino(t).signAmino(o,r)},signArbitrary:async(n,t,o)=>{const r=e.getOfflineSigner(n),i=(await r.getAccounts()).find(e=>e.address===t);if(!i)throw new Error(`Wallet not connected to account ${t}`);const a=(()=>{switch(i.algo){case"secp256k1":return d(i.pubkey);case"ed25519":return l(i.pubkey);default:throw new Error("sr25519 public key algorithm is not supported")}})();return{signature:await e.signArbitrary(o),pub_key:{type:"secp256k1"===i.algo?u.secp256k1:u.ed25519,value:a.value}}},subscription:e=>{const n=()=>{be(),e()};return window.addEventListener("initia_keystorechange",n),()=>{window.removeEventListener("initia_keystorechange",n)}}}}throw H.getState()._notFoundFn(),new Error("window.initia is not defined")},re=()=>{if(void 0!==window.keplr){const e=window.keplr,n=e=>{const n=()=>{be(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw H.getState()._notFoundFn(),new Error("window.keplr is not defined")},ie=()=>{if(void 0!==window.leap){const e=window.leap,n=e=>{const n=()=>{be(),e()};return window.addEventListener("leap_keystorechange",n),()=>{window.removeEventListener("leap_keystorechange",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw H.getState()._notFoundFn(),new Error("window.leap is not defined")},ae={},se=()=>(e=>{const n=window.ethereum;if(n&&e){const t=async()=>await n.request({method:"wallet_getSnaps"}),o=async n=>{try{const o=await t();return Object.values(o).find(t=>t.id===e.id&&(!n||t.version===n))}catch(e){return}},r=async()=>{await n.request({method:"wallet_requestSnaps",params:{[e.id]:e.params||{}}})},i=async()=>{const e=await n.request({method:"web3_clientVersion"});if(!e.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const t=e.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(t)>=11))throw new Error("Metamask Snap is not supported in this version");return await o()||await r(),!0},a=async(t,o,r)=>{const i=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signDirect",params:{chainId:t,signerAddress:o,signDoc:r}}}}),a=r.accountNumber,s=new f(a.low,a.high,a.unsigned);return{signature:i.signature,signed:{...i.signed,accountNumber:s.toString(),authInfoBytes:new Uint8Array(Object.values(i.signed.authInfoBytes)),bodyBytes:new Uint8Array(Object.values(i.signed.bodyBytes))}}},s=async(t,o,r)=>await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"signAmino",params:{chainId:t,signerAddress:o,signDoc:r}}}}),c=async t=>{if(void 0!==ae[t])return ae[t];const o=await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"getKey",params:{chainId:t}}}});if(!o)throw new Error("No response from Metamask");return o.pubKey=Uint8Array.from(Object.values(o.pubkey)),delete o.pubkey,ae[t]=o,ae[t]},l=async e=>{const n=await c(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async(...e)=>{const[n,t,o,r]=e;return await s(n,t,o)},u=async(...e)=>{const[n,t,o]=e,r={...o,accountNumber:f.fromString(o.accountNumber?.toString()||"0"),authInfoBytes:o.authInfoBytes,bodyBytes:o.bodyBytes};return await a(n,t,r)},g=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>d(e,n,t)});return{enable:async e=>{await o()||await r()},experimentalSuggestChain:async(...t)=>{await i(),await n.request({method:"wallet_invokeSnap",params:{snapId:e.id,request:{method:"suggestChain",params:{chainInfo:t[0]}}}})},getKey:c,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>d(e,n,t)}),getOfflineSignerAuto:async e=>g(e),getOfflineSignerOnlyAmino:g,init:i,signAmino:d,signDirect:u}}throw H.getState()._notFoundFn(),new Error("window.ethereum is not defined")})({id:"npm:@leapwallet/metamask-cosmos-snap"}),ce=()=>{if(void 0!==window.okxwallet?.keplr){const e=window.okxwallet.keplr,n=e=>{const n=()=>{be(),e()};return window.okxwallet?.on("accountsChanged",n),()=>{window.okxwallet?.removeListener("accountsChanged",n)}},t=n=>{e.defaultOptions=n};return Object.assign(e,{subscription:n,setDefaultOptions:t})}throw H.getState()._notFoundFn(),new Error("window.okxwallet.keplr is not defined")},le=null,de=()=>{const e=()=>{const e=G.getState().paraConnector;if(!e)throw new Error("Para connector not initialized. Call connect() first or check paraConfig in GrazProvider.");return e},n=H.getState().paraConfig;if(!n?.paraWeb)throw new Error("Missing Para config. Provide paraConfig with 'paraWeb' to GrazProvider.");return{enable:async e=>{const t=Array.isArray(e)?e:[e];try{const e=await(le||(le=(async()=>{const e=G.getState().paraConnector;if(e)return e;if(!n.connectorClass)throw new Error("Para connector class not provided. Provide 'connectorClass' in paraConfig to use Para wallet.");try{const e=H.getState().chains,t=new n.connectorClass(n,e);if(!t)throw new Error("Para connector initialization failed. Check config and dependencies.");return G.setState(e=>({...e,paraConnector:t})),t}catch(e){throw le=null,new Error(`Para connector init failed: ${e?.message||"Unknown error"}. Check ParaConfig and connectorClass.`)}})()));G.setState({paraConnector:e,status:"connecting"}),await e.enable(t);const o=Object.fromEntries(await Promise.all(t.map(async n=>[n,await e.getKey(n)])));G.setState(e=>({accounts:{...e.accounts||{},...o},activeChainIds:Array.from(new Set([...e.activeChainIds||[],...t])),status:"connected"})),H.setState(e=>({recentChainIds:Array.from(new Set([...e.recentChainIds||[],...t])),walletType:"para",_reconnect:!1,_reconnectConnector:"para"}))}catch(e){throw G.setState({paraConnector:null,status:"disconnected"}),new Error("Para enable failed"+(e instanceof Error?`: ${e.message}`:""))}},disable:async()=>{const e=G.getState().paraConnector;if(e)try{await e.disconnect(),await e.getParaWebClient().logout()}catch(e){throw new Error("Para disconnect failed"+(e?.message?`: ${e.message}`:". Wallet may already be disconnected."))}finally{G.setState({paraConnector:null,status:"disconnected"})}else G.setState({paraConnector:null,status:"disconnected"})},getKey:async n=>{try{return await e().getKey(n)}catch(e){throw new Error(`Failed to get key${e?.message?`: ${e.message}`:""}. Check chain connection and Cosmos API key settings at developer.getpara.com.`)}},getOfflineSigner:n=>{try{return e().getOfflineSigner(n)}catch(e){throw new Error(`Failed to get offline signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerOnlyAmino:n=>{try{return e().getOfflineSignerOnlyAmino(n)}catch(e){throw new Error(`Failed to get Amino signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},getOfflineSignerAuto:n=>{try{return e().getOfflineSignerAuto(n)}catch(e){throw new Error(`Failed to get auto signer${e?.message?`: ${e.message}`:""}. Check Para auth and Cosmos support in developer portal.`)}},signAmino:async(n,t,o,r)=>{try{return await e().signAmino(n,t,o,r)}catch(e){throw new Error(`Amino signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signDirect:async(n,t,o,r)=>{try{return await e().signDirect(n,t,o,r)}catch(e){throw new Error(`Direct signing failed${e?.message?`: ${e.message}`:""}. User rejected or invalid transaction/signer.`)}},signArbitrary:async(n,t,o)=>{try{return await e().signArbitrary(n,t,o)}catch(e){throw new Error(`Arbitrary signing failed${e?.message?`: ${e.message}`:""}. User rejected or feature not supported.`)}},experimentalSuggestChain:async()=>{throw new Error("Chain suggestion not supported. Configure chains in Para wallet settings.")}}},ue=()=>{if(void 0!==window.station?.keplr){const e=window.station.keplr;return{subscription:e=>{const n=()=>{be(),e()};return window.addEventListener("station_wallet_change",n),()=>{window.removeEventListener("station_wallet_change",n)}},getKey:async n=>({isKeystone:!1,...await e.getKey(n)}),getOfflineSigner:n=>{try{const t=e.getOfflineSignerOnlyAmino(n),o=(e,n)=>{throw new Error("signDirect not supported by Station")};return Object.assign(t,{signDirect:o})}catch(e){throw console.error(e),e}},experimentalSuggestChain:async n=>{try{if(!n.bech32Config)throw new Error("Bech32Config is required");if(!n.stakeCurrency)throw new Error("StakeCurrency is required");const t=Object.assign(n,{bech32Config:n.bech32Config,chainSymbolImageUrl:n.chainSymbolImageUrl||"",stakeCurrency:{coinDecimals:n.stakeCurrency.coinDecimals,coinDenom:n.stakeCurrency.coinDenom,coinImageUrl:n.stakeCurrency.coinImageUrl||"",coinMinimalDenom:n.stakeCurrency.coinMinimalDenom},currencies:n.currencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom})),feeCurrencies:n.feeCurrencies.map(e=>({coinDecimals:e.coinDecimals,coinDenom:e.coinDenom,coinImageUrl:e.coinImageUrl||"",coinMinimalDenom:e.coinMinimalDenom,gasPriceStep:{average:e.gasPriceStep?.average||0,high:e.gasPriceStep?.high||0,low:e.gasPriceStep?.low||0}}))});await e.experimentalSuggestChain(t)}catch(e){throw console.error(e),e}},enable:n=>e.enable(n),disable:n=>e.disable(n),getOfflineSignerAuto:n=>e.getOfflineSignerAuto(n),getOfflineSignerOnlyAmino:n=>e.getOfflineSignerOnlyAmino(n),signDirect:e.signDirect,signAmino:(n,t,o,r)=>e.signAmino(n,t,o)}}throw H.getState()._notFoundFn(),new Error("window.station is not defined")},ge=()=>{if(void 0!==window.vectis){const e=window.vectis.cosmos;return{enable:n=>e.enable(n),getOfflineSigner:n=>{const t=e.getOfflineSigner(n);return{getAccounts:t.getAccounts,signAmino:t.signAmino,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:f.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}},getOfflineSignerAuto:async n=>{const t=await e.getOfflineSignerAuto(n);return"signAmino"in t?t:"signDirect"in t?{getAccounts:t.getAccounts,signDirect:async(e,n)=>{const o=await t.signDirect(e,{accountNumber:f.fromString(n.accountNumber.toString()||"",!1),authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId||""});return{signature:o.signature,signed:{authInfoBytes:o.signed.authInfoBytes,bodyBytes:o.signed.bodyBytes,chainId:o.signed.chainId,accountNumber:BigInt(o.signed.accountNumber.toString())}}}}:t},getKey:async n=>{const t=await e.getKey(n);return{address:w(t.address).data,algo:t.algo,bech32Address:t.address,name:t.name,pubKey:t.pubKey,isKeystone:!1,isNanoLedger:t.isNanoLedger}},subscription:e=>{const n=()=>{be(),e()};return window.addEventListener("vectis_accountChanged",n),()=>{window.removeEventListener("vectis_accountChanged",n)}},getOfflineSignerOnlyAmino:(...n)=>{const t=n[0];return e.getOfflineSignerAmino(t)},experimentalSuggestChain:async(...n)=>{const[t]=n;if(!t.bech32Config)throw new Error("Bech32Config is required");if(!t.stakeCurrency)throw new Error("StakeCurrency is required");const o={rpcUrl:t.rpc,restUrl:t.rest,prettyName:t.chainName.replace(" ",""),bech32Prefix:t.bech32Config.bech32PrefixAccAddr,currencies:t.currencies,feeCurrencies:t.feeCurrencies,chainId:t.chainId,chainName:t.chainName,bip44:t.bip44,stakeCurrency:t.stakeCurrency,features:t.features};return e.suggestChains([o])},signDirect:async(...n)=>{const{1:t,2:o}=n,r=await e.signDirect(t,{bodyBytes:o.bodyBytes||Uint8Array.from([]),authInfoBytes:o.authInfoBytes||Uint8Array.from([]),accountNumber:f.fromString(o.accountNumber?.toString()||"",!1),chainId:o.chainId||""});return{signature:r.signature,signed:{authInfoBytes:r.signed.authInfoBytes,bodyBytes:r.signed.bodyBytes,chainId:r.signed.chainId,accountNumber:BigInt(r.signed.accountNumber.toString())}}},signAmino:async(...n)=>{const{1:t,2:o}=n;return e.signAmino(t,o)}}}throw H.getState()._notFoundFn(),new Error("window.vectis is not defined")},he=()=>{if("undefined"!=typeof window){const e=navigator.userAgent;return!!/android/i.test(e)||!!/iPad|iPhone|iPod/.test(e)}return!1},fe=(e,n,t=new Error("Promise timed out"))=>{const o=new Promise((e,o)=>{setTimeout(()=>{o(t)},n)});return Promise.race([e,o])},we=e=>{if(!H.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");const n=e?.walletType||"walletconnect",t=e?.encoding||"base64",o=n=>{if(!e)return;const{appUrl:t,formatNativeUrl:o}=e;if(he()){if(he()&&navigator.userAgent.toLowerCase().includes("android")){const e=o(t.mobile.android,n,"android");window.open(e,"_self","noreferrer noopener")}if(he()&&(navigator.userAgent.toLowerCase().includes("iphone")||navigator.userAgent.toLowerCase().includes("ipad"))){const e=o(t.mobile.ios,n,"ios");window.open(e,"_self","noreferrer noopener")}}},r=()=>{const{wcSignClients:e}=G.getState();if(!e.get(n))throw new Error("walletConnect.signClient is not defined");e.delete(n),G.setState({wcSignClients:e}),H.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null})},i=async e=>{const{wcSignClients:t}=G.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");if(!e)throw new Error("No wallet connect session");await o.disconnect({topic:e,reason:C("USER_DISCONNECTED")}),await s(o)},a=e=>{try{const{wcSignClients:t}=G.getState(),o=t.get(n);if(!o)throw new Error("walletConnect.signClient is not defined");const r=o.session.getAll(),a=r.at(-1);if(!a)return;if(!(1e3*a.expiry>Date.now()+1e3))throw i(a.topic),new Error("invalid session");try{const n=r.find(n=>n.requiredNamespaces.cosmos?.chains?.includes(`cosmos:${e}`));if(!n)throw new Error("no session");return n}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}return a}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},s=async e=>{try{const n=e.core.pairing.pairings.getAll({active:!1});if(!n.length)return;await Promise.all(n.map(async n=>{await e.core.pairing.pairings.delete(n.topic,{code:7001,message:"clear pairing"})}))}catch(e){if(!e.message.toLowerCase().includes("no matching key"))throw e}},c=async t=>{const r="string"==typeof t?[t]:t,{wcSignClients:s,activeChainIds:c}=G.getState(),l=s.get(n);if(!l)throw new Error("enable walletConnect.signClient is not defined");const{walletConnect:u}=H.getState();if(!u?.options?.projectId)throw new Error("walletConnect.options.projectId is not defined");const g=new m({projectId:u.options.projectId,enableExplorer:!1,explorerRecommendedWalletIds:"NONE",...u.walletConnectModal}),h=(e=>{try{return a(e)}catch(e){return}})(r);if(!h){const{uri:n,approval:t}=await fe(l.connect({requiredNamespaces:{cosmos:{methods:["cosmos_getAccounts","cosmos_signAmino","cosmos_signDirect"],chains:r.map(e=>`cosmos:${e}`),events:["chainChanged","accountsChanged"]}}}),15e3,new Error("Connection timeout"));if(!n)throw new Error("No wallet connect uri");e?o(n):await g.openModal({uri:n});const i=async e=>e.aborted?Promise.reject(new Error("User closed wallet connect")):new Promise((n,o)=>{t().then(e=>{const t=e.sessionProperties;if(!t)return o(new Error("No session properties"));const r=JSON.parse(String(t.keys));if(0===r.length)return o(new Error("No accounts"));if(!r[0])return o(new Error("No accounts"));const i={};return r.forEach(e=>{i[e.chainId]={address:e.address,algo:e.algo,bech32Address:e.bech32Address,isNanoLedger:e.isNanoLedger,isKeystone:e.isKeystone,name:e.name,pubKey:e.pubKey}}),G.setState(e=>({accounts:{...e.accounts||{},...i}})),n(e)}).catch(o),e.addEventListener("abort",()=>{o(new Error("User closed wallet connect"))},{once:!0})});try{const e=new AbortController,n=e.signal;g.subscribeModal(n=>{n.open||e.abort()}),await i(n)}catch(e){if(g.closeModal(),!e.message.toLowerCase().includes("no matching key"))return Promise.reject(e)}return e||g.closeModal(),Promise.resolve()}try{await fe((async()=>{const e=Object.fromEntries(await Promise.all((c||r).map(async e=>[e,await d(e)])));G.setState({accounts:e})})(),15e3,new Error("Connection timeout"))}catch(e){if(i(h.topic),!e.message.toLowerCase().includes("no matching key"))throw e}},l=async e=>{const n=await d(e);return{address:n.bech32Address,algo:n.algo,pubkey:n.pubKey}},d=async e=>{const n=a([e]);if(!n?.topic)throw new Error("No wallet connect session");const o=n.sessionProperties&&JSON.parse(String(n.sessionProperties.keys));if(!o)throw new Error("No wallet connect key");if(0===o.length)throw new Error("No wallet connect session");const r=o.find(n=>n.chainId===e);if(!r)throw new Error(`No wallet connect key for chainId ${e}`);return{...r,pubKey:Buffer.from(String(r.pubKey),t)}},u=async(...e)=>{const[r,i,s]=e,{signature:c,signed:l}=await(async(...e)=>{const[r,i,s]=e,{accounts:c,wcSignClients:l}=G.getState(),d=l.get(n);if(!d)throw new Error("walletConnect.signClient is not defined");if(!c)throw new Error("account is not defined");const u=a([r])?.topic;if(!u)throw new Error("No wallet connect session");if(!s.bodyBytes)throw new Error("No bodyBytes");if(!s.authInfoBytes)throw new Error("No authInfoBytes");return o(),await d.request({topic:u,chainId:`cosmos:${r}`,request:{method:"cosmos_signDirect",params:{signerAddress:i,signDoc:{chainId:s.chainId,accountNumber:s.accountNumber?.toString(),bodyBytes:s.bodyBytes?Buffer.from(s.bodyBytes).toString(t):null,authInfoBytes:s.authInfoBytes?Buffer.from(s.authInfoBytes).toString(t):null}}}})})(r,i,s);return{signed:{chainId:l.chainId??"",accountNumber:l.accountNumber?BigInt(l.accountNumber):BigInt(0),authInfoBytes:l.authInfoBytes?new Uint8Array(Buffer.from(l.authInfoBytes,t)):new Uint8Array([]),bodyBytes:l.bodyBytes?new Uint8Array(Buffer.from(l.bodyBytes,t)):new Uint8Array([])},signature:c}},g=async(...e)=>{const[t,r,i,s]=e,c=await(async(...e)=>{const[t,r,i,s]=e,{wcSignClients:c}=G.getState(),l=c.get(n),{accounts:d}=G.getState();if(!l)throw new Error("walletConnect.signClient is not defined");if(!d)throw new Error("account is not defined");const u=a([t])?.topic;if(!u)throw new Error("No wallet connect session");return o(),await l.request({topic:u,chainId:`cosmos:${t}`,request:{method:"cosmos_signDirect",params:{signerAddress:r,signDoc:i}}})})(t,r,i);return c},h=e=>({getAccounts:async()=>[await l(e)],signAmino:(n,t)=>g(e,n,t)});return{enable:c,disable:async e=>{const{wcSignClients:t}=G.getState(),o=t.get(n);if(void 0===e){const e=o?.session.getAll();void 0!==e&&await Promise.all(e.map(e=>i(e.topic)))}else"string"==typeof e?await i(a([e])?.topic):await Promise.all(e.map(e=>i(a([e])?.topic)));0===o?.session.getAll().length&&r()},experimentalSuggestChain:async(...e)=>{await Promise.reject(new Error("WalletConnect does not support experimentalSuggestChain"))},getKey:d,getOfflineSigner:e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t),signAmino:(n,t)=>g(e,n,t)}),getOfflineSignerAuto:async e=>(await d(e)).isNanoLedger?h(e):(e=>({getAccounts:async()=>[await l(e)],signDirect:(n,t)=>u(e,n,t)}))(e),getOfflineSignerOnlyAmino:h,signAmino:g,signDirect:u,subscription:e=>{const{wcSignClients:t}=G.getState(),o=t.get(n);if(!o)return()=>{};const i=n=>{const t=G.getState().accounts;if("accountsChanged"===n.params.event.name&&t&&!Object.values(t).map(e=>e.bech32Address).includes(n.params.event.data[0])){const e=n.params.chainId.split(":")[1];e&&c([e])}else e()};return o.events.on("session_delete",r),o.events.on("session_expire",r),o.events.on("session_event",i),()=>{o.events.off("session_delete",r),o.events.off("session_expire",r),o.events.off("session_event",i)}},init:async()=>{const{walletConnect:e}=H.getState();if(!e?.options)throw new Error("walletConnect.options is not defined");const{wcSignClients:t}=G.getState(),o=t.get(n);if(o)return o;const r=await p.init(e.options);return t.set(n,r),G.setState({wcSignClients:t}),r}}},me=()=>{if(!H.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!he())throw new Error("WalletConnect Cosmostation mobile is only supported in mobile");return we({encoding:"hex",appUrl:{mobile:{ios:"cosmostation://",android:"cosmostation://"}},walletType:"wc_cosmostation_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,"");return n?`${o}://wc?${n}`:`${o}://wc`}})},pe=()=>{if(!H.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!he())throw new Error("WalletConnect Keplr mobile is only supported in mobile");return we({encoding:"base64",appUrl:{mobile:{ios:"keplrwallet://",android:"intent://"}},walletType:"wc_keplr_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`:`${o}://wcV2#Intent;package=com.chainapsis.keplr;scheme=keplrwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},Ce=()=>{if(!H.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!he())throw new Error("WalletConnect Leap mobile is only supported in mobile");return we({encoding:"base64",appUrl:{mobile:{ios:"leapcosmos://",android:"intent://"}},walletType:"wc_leap_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);switch(t){case"ios":return r?`${o}://wcV2?${r}`:`${o}://wcV2`;case"android":return r?`${o}://wcV2?${r}#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`:`${o}://wcV2#Intent;package=io.leapwallet.cosmos;scheme=leapwallet;end;`;default:return r?`${o}://wc?uri=${r}`:`${o}://wc`}}})},ye=()=>{if(void 0!==window.xfi?.keplr){const e=window.xfi.keplr,n=e=>{const n=()=>{be(),e()};return window.addEventListener("keplr_keystorechange",n),()=>{window.removeEventListener("keplr_keystorechange",n)}};return Object.assign(e,{subscription:n})}throw H.getState()._notFoundFn(),new Error("window.xfi.keplr is not defined")},Se=(e=H.getState().walletType)=>{try{return Ie(e),!0}catch(e){return!1}},be=()=>{window.sessionStorage.removeItem(P),G.setState(j)},Ie=(e=H.getState().walletType)=>{const n=Y();n.debug("wallet","Getting wallet adapter",{function:"getWallet",walletType:e});const t=(()=>{switch(e){case"keplr":return re();case"leap":return ie();case"cosmostation":return te();case"vectis":return ge();case"walletconnect":return we();case"wc_keplr_mobile":return pe();case"wc_leap_mobile":return Ce();case"wc_cosmostation_mobile":return me();case"wc_clot_mobile":return(()=>{if(!H.getState().walletConnect?.options?.projectId?.trim())throw new Error("walletConnect.options.projectId is not defined");if(!he())throw new Error("WalletConnect Clot mobile is only supported in mobile");return we({encoding:"base64",appUrl:{mobile:{android:"clot://",ios:"clot://"}},walletType:"wc_clot_mobile",formatNativeUrl:(e,n,t)=>{const o=e.replace(/\//g,"").replace(/:/g,""),r=n&&encodeURIComponent(n);return"ios"===t?r?`${o}://wcV2?${r}`:`${o}://wcV2`:r?`${o}://wc?uri=${r}`:`${o}://wc`}})})();case"metamask_snap_leap":return se();case"metamask_snap_cosmos":return(()=>{const e=window.ethereum;let n=window.cosmos;if(e)return{init:async()=>{const t=await e.request({method:"web3_clientVersion"});if(!t.includes("MetaMask"))throw new Error("Metamask is not installed");if(void 0!==window.okxwallet&&window.okxwallet.isOkxWallet)throw new Error("You have OKX Wallet installed. Please disable and reload the page to use Metamask Snap.");const o=t.split("MetaMask/v")[1]?.split(".")[0];if(!(Number(o)>=11))throw new Error("Metamask Snap is not supported in this version");return await a()||await s(),window.cosmos=new c,n=window.cosmos,!0},enable:async e=>{await a()||await s()},getOfflineSigner:e=>n.getOfflineSigner(e),experimentalSuggestChain:async e=>{if(!e.bech32Config)throw new Error("Bech32Config is required");if(!e.stakeCurrency)throw new Error("StakeCurrency is required");await n.experimentalSuggestChain({...e,stakeCurrency:e.stakeCurrency,bech32Config:e.bech32Config})},signAmino:async(e,t,o)=>n.signAmino(e,t,o),getKey:async e=>void 0!==ne[e]?ne[e]:n.getKey(e),getOfflineSignerAuto:async e=>(await n.getKey(e)).isNanoLedger?n.getOfflineSignerOnlyAmino(e):n.getOfflineSigner(e),getOfflineSignerOnlyAmino:e=>n.getOfflineSignerOnlyAmino(e),signDirect:async(e,t,o)=>n.signDirect(e,t,o),signArbitrary:async(e,t,o)=>n.signArbitrary(e,t,o),disable:async e=>{e&&await n.deleteChain(e)}};throw H.getState()._notFoundFn(),new Error("window.ethereum is not defined")})();case"station":return ue();case"xdefi":return ye();case"cosmiframe":return ee();case"compass":return Z();case"initia":return oe();case"okx":return ce();case"para":return de();case"cactuscosmos":return J();default:throw n.warn("wallet","Unknown wallet type",{function:"getWallet",walletType:e}),new Error("Unknown wallet type")}})(),o=H.getState().walletDefaultOptions;return o&&t.setDefaultOptions?.(o),t},Ee=()=>Object.fromEntries(K.map(e=>[e,Se(e)])),Ae=e=>"metamask_snap_leap"===e,_e=()=>Boolean(navigator?.userAgent)&&/LeapCosmos/i.test(navigator.userAgent),ve=e=>"walletconnect"===e||"wc_keplr_mobile"===e||"wc_leap_mobile"===e||"wc_cosmostation_mobile"===e,Oe=e=>"para"===e,Te=async e=>{const n=Y();n.time("connect"),n.group("Connect Wallet");try{const{recentChainIds:t,chains:o,walletType:r}=H.getState(),i=e?.walletType||r;if(n.debug("wallet","Starting connection",{function:"connect",walletType:i,chainId:e?.chainId,timestamp:Date.now()}),ve(i)){const e=Ie("walletconnect"),{disable:n}=e;n&&n()}if(!Se(i))throw n.warn("wallet","Wallet not available",{function:M.CONNECT,walletType:i}),new Error(`${i} is not available`);n.debug("wallet","Wallet adapter retrieved",{function:M.CONNECT,walletType:i});const a=Ie(i),s="string"==typeof e?.chainId?[e.chainId]:e?.chainId||t;if(!s)throw new Error("No last known connected chain, connect action requires chain ids");const c=o?.map(e=>e.chainId);if(s.forEach(e=>{if(!c?.includes(e))throw new Error(`Chain ${e} is not provided in GrazProvider`)}),G.setState(e=>{const n=H.getState()._reconnect||Boolean(H.getState()._reconnectConnector)||Boolean(s);return e.activeChainIds&&s.filter(n=>!e.activeChainIds?.includes(n)).length>0?{status:"connecting"}:n?{status:"reconnecting"}:{status:"connecting"}}),n.debug("wallet","Initializing wallet",{function:M.CONNECT}),await(a.init?.()),n.debug("wallet","Enabling chains",{function:M.CONNECT,chainIds:s,chainCount:s.length}),await a.enable(s),n.debug("wallet","Fetching accounts",{function:M.CONNECT}),!ve(i)){let e={};if(Ae(i)){const n={};for await(const e of s)n[e]=await a.getKey(e);e=n}else if(_e()&&a.getKeys){const n=await a.getKeys(s);s.forEach((t,o)=>{const r=n[o];r&&(e[t]=r)})}else e=Object.fromEntries(await Promise.all(s.map(async e=>[e,await a.getKey(e)])));G.setState(n=>({accounts:{...n.accounts||{},...e}}))}H.setState(e=>({recentChainIds:[...e.recentChainIds||[],...s].filter((e,n,t)=>t.indexOf(e)===n)})),G.setState(e=>({activeChainIds:[...e.activeChainIds||[],...s].filter((e,n,t)=>t.indexOf(e)===n)})),H.setState({walletType:i,_reconnect:Boolean(e?.autoReconnect),_reconnectConnector:i}),G.setState({status:"connected"}),"undefined"!=typeof window&&window.sessionStorage.setItem(P,"Active");const l=s.map(e=>o.find(n=>n.chainId===e)),d=G.getState().accounts;return n.info("wallet","Connection successful",{function:M.CONNECT,walletType:i,chainCount:s.length,chainIds:s,addresses:d?Object.values(d).map(e=>e.bech32Address):[]}),n.debug("store","Session store updated",{function:M.CONNECT,accountCount:Object.keys(d||{}).length}),n.timeEnd("connect"),n.groupEnd(),{accounts:d,walletType:i,chains:l}}catch(t){throw n.error("wallet","Connection failed",{function:M.CONNECT,error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,walletType:e?.walletType,chainId:e?.chainId}),null===G.getState().accounts&&G.setState({status:"disconnected"}),G.getState().accounts&&G.getState().activeChainIds&&G.setState({status:"connected"}),n.timeEnd("connect"),n.groupEnd(),t}},ke=e=>{const n=Y(),t="string"==typeof e?.chainId?[e.chainId]:e?.chainId;n.info("wallet","Disconnecting",{function:M.DISCONNECT,chainId:t||"all chains"}),"undefined"!=typeof window&&window.sessionStorage.removeItem(P);const o=()=>{if(ve(H.getState().walletType)){const e=Ie("walletconnect"),{disable:n}=e;n&&n()}if(Oe(H.getState().walletType)){const e=Ie("para"),{disable:n}=e;n&&n()}};if(t){const e=G.getState().accounts;t.forEach(n=>{delete e?.[n]});0===Object.values(e||{}).length?(o(),G.setState(j),H.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null}),n.debug("store","Session cleared - all chains disconnected",{function:M.DISCONNECT})):(G.setState(n=>({activeChainIds:n.activeChainIds?.filter(e=>!t.includes(e)),accounts:e})),H.setState(e=>({recentChainIds:e.recentChainIds?.filter(e=>!t.includes(e))})),n.debug("store","Partial disconnect - some chains remain connected",{function:M.DISCONNECT}))}else o(),G.setState(j),H.setState({_reconnect:!1,_reconnectConnector:null,recentChainIds:null}),n.debug("store","Session cleared - disconnected from all chains",{function:M.DISCONNECT});return n.info("wallet","Disconnected successfully",{function:M.DISCONNECT,chainId:t||"all chains"}),Promise.resolve()},Ne=async e=>{const n=Y(),{recentChainIds:t,_reconnectConnector:o,_reconnect:r}=H.getState();n.debug("wallet","Attempting reconnection",{function:M.RECONNECT,recentChains:t,walletType:o});try{const e=Se(o||void 0);if(t&&e&&o){if(ve(o))return;const e=await Te({chainId:t,walletType:o,autoReconnect:r});return n.info("wallet","Reconnection successful",{function:M.RECONNECT}),e}n.warn("wallet","Reconnection skipped",{function:M.RECONNECT,hasRecentChains:Boolean(t),isWalletReady:e,hasConnector:Boolean(o)})}catch(t){n.warn("wallet","Reconnection failed",{function:M.RECONNECT,error:t instanceof Error?t.message:String(t)}),e?.onError?.(t),ke()}},Be=async e=>{if(!e?.chainId)throw new Error("chainId is required");const{walletType:n}=H.getState(),t=e.walletType||n;if(!Se(t))throw new Error(`${t} is not available`);const o=Ie(t);return{offlineSigner:o.getOfflineSigner(e.chainId),offlineSignerAmino:o.getOfflineSignerOnlyAmino(e.chainId),offlineSignerAuto:await o.getOfflineSignerAuto(e.chainId)}},De=()=>{Y().debug("store","Clearing recent chains",{function:"clearRecentChain"}),H.setState({recentChainIds:null})},Le=()=>{const e=Y(),n=H.getState().recentChainIds;return e.debug("store","Getting recent chain IDs",{function:"getRecentChainIds",chainIds:n}),n},Re=()=>{const e=Y(),{recentChainIds:n,chains:t}=H.getState(),o=n?.map(e=>t.find(n=>n.chainId===e))??null;return e.debug("store","Getting recent chains",{function:"getRecentChains",chainIds:n,chainCount:o?.length??0}),o},Fe=({chainId:e}={})=>{const n=Y(),t=H.getState().chains?.find(n=>n.chainId===e);return n.debug("store","Getting chain info",{function:"getChainInfo",chainId:e,found:Boolean(t)}),t},Ue=({chainId:e}={})=>{const n=Y(),t=H.getState().chains,o=e?t?.filter(n=>e.includes(n.chainId)):t??void 0;return n.debug("store","Getting chain infos",{function:"getChainInfos",requestedChainIds:e,resultCount:o?.length??0}),o},Pe=async({chainInfo:e})=>{const n=Y();n.debug("store","Adding chain",{function:"addChain",chainId:e.chainId,chainName:e.chainName});const{chains:t}=H.getState(),o=t?.find(n=>n.chainId===e.chainId);if(o)throw n.warn("store","Chain already exists",{function:"addChain",chainId:e.chainId}),new Error(`Chain with chainId "${e.chainId}" already exists in the store`);return H.setState(n=>({chains:[...n.chains||[],e]})),n.info("store","Chain added successfully",{function:"addChain",chainId:e.chainId,chainName:e.chainName}),e},qe=async({chainInfo:e,walletType:n})=>{const t=Y();t.debug("wallet","Suggesting chain to wallet",{function:"suggestChain",chainId:e.chainId,chainName:e.chainName,walletType:n});try{const o=Ie(n);await o.experimentalSuggestChain(e);const{chains:r}=H.getState(),i=r?.find(n=>n.chainId===e.chainId);return i||(H.setState(n=>({chains:[...n.chains||[],e]})),t.debug("store","Chain added to store after suggestion",{function:"suggestChain",chainId:e.chainId})),t.info("wallet","Chain suggested successfully",{function:"suggestChain",chainId:e.chainId,chainName:e.chainName,walletType:n}),e}catch(o){throw t.error("wallet","Failed to suggest chain",{function:"suggestChain",error:o instanceof Error?o.message:String(o),chainId:e.chainId,walletType:n}),o}},Me=async e=>{const n=Y(),t=H.getState().walletType,o=e.walletType??t;n.info("wallet","Suggesting chain and connecting",{function:"suggestChainAndConnect",chainId:e.chainInfo.chainId,chainName:e.chainInfo.chainName,walletType:o}),n.time("suggest-chain-and-connect");try{await qe({chainInfo:e.chainInfo,walletType:o});const t=await Te({chainId:e.chainInfo.chainId,walletType:e.walletType,autoReconnect:e.autoReconnect});return n.timeEnd("suggest-chain-and-connect"),n.info("wallet","Chain suggested and connected successfully",{function:"suggestChainAndConnect",chainId:e.chainInfo.chainId,walletType:t.walletType}),t}catch(t){throw n.timeEnd("suggest-chain-and-connect"),n.error("wallet","Failed to suggest chain and connect",{function:"suggestChainAndConnect",error:t instanceof Error?t.message:String(t),chainId:e.chainInfo.chainId}),t}},We=e=>(X({enabled:e.logger?.enabled??!1,level:e.logger?.level,categories:e.logger?.categories}),H.setState(n=>{const t=n.chains??[],o=e.chains,r=new Map;o.forEach(e=>r.set(e.chainId,e)),t.forEach(e=>{r.has(e.chainId)||r.set(e.chainId,e)});const i=Array.from(r.values());return{iframeOptions:e.iframeOptions||n.iframeOptions,walletConnect:e.walletConnect||n.walletConnect,walletType:e.defaultWallet||n.walletType,paraConfig:e.paraConfig||n.paraConfig,walletDefaultOptions:e.walletDefaultOptions||n.walletDefaultOptions,chains:i,chainsConfig:e.chainsConfig||n.chainsConfig,multiChainFetchConcurrency:e.multiChainFetchConcurrency||n.multiChainFetchConcurrency,pingInterval:e.pingInteval||n.pingInterval,loggerConfig:e.logger?{enabled:e.logger.enabled??n.loggerConfig?.enabled??!1,level:e.logger.level??n.loggerConfig?.level??1,categories:e.logger.categories??n.loggerConfig?.categories??[]}:n.loggerConfig,_notFoundFn:e.onNotFound||n._notFoundFn,_onReconnectFailed:e.onReconnectFailed||n._onReconnectFailed,_reconnect:void 0===e.autoReconnect||(e.autoReconnect||n._reconnect)}}),e),xe=async({signingClient:e,senderAddress:n,recipientAddress:t,amount:o,fee:r,memo:i})=>{const a=Y();if(!e)throw new Error("No connected account detected");if(!n)throw new Error("senderAddress is not defined");a.debug("transaction","Signing transaction",{function:"sendTokens",senderAddress:n,recipientAddress:t,amount:o});try{const s=await e.sendTokens(n,t,o,r,i);return a.info("transaction","Transaction broadcasted",{function:"sendTokens",txHash:s.transactionHash,height:s.height}),s}catch(e){throw a.error("transaction","Transaction failed",{function:"sendTokens",error:e instanceof Error?e.message:String(e),senderAddress:n,recipientAddress:t}),e}},Ke=async({signingClient:e,senderAddress:n,recipientAddress:t,transferAmount:o,sourcePort:r,sourceChannel:i,timeoutHeight:a,timeoutTimestamp:s,fee:c,memo:l})=>{const d=Y();if(!e)throw new Error("Stargate signing client is not ready");if(!n)throw new Error("senderAddress is not defined");d.debug("transaction","Signing IBC transfer",{function:"sendIbcTokens",senderAddress:n,recipientAddress:t,transferAmount:o,sourceChannel:i,sourcePort:r});try{const u=await e.sendIbcTokens(n,t,o,r,i,a,s,c,l);return d.info("transaction","IBC transfer successful",{function:"sendIbcTokens",txHash:u.transactionHash,height:u.height}),u}catch(e){throw d.error("transaction","IBC transfer failed",{function:"sendIbcTokens",error:e instanceof Error?e.message:String(e),senderAddress:n,recipientAddress:t,sourceChannel:i}),e}},$e=async({signingClient:e,senderAddress:n,msg:t,fee:o,options:r,label:i,codeId:a})=>{const s=Y();if(!e)throw new Error("CosmWasm signing client is not ready");s.debug("transaction","Instantiating contract",{function:"instantiateContract",senderAddress:n,codeId:a,label:i});try{const c=await e.instantiate(n,a,t,i,o,r);return s.info("transaction","Contract instantiated",{function:"instantiateContract",contractAddress:c.contractAddress,txHash:c.transactionHash}),c}catch(e){throw s.error("transaction","Contract instantiation failed",{function:"instantiateContract",error:e instanceof Error?e.message:String(e),codeId:a,senderAddress:n}),e}},je=async({signingClient:e,senderAddress:n,msg:t,fee:o,contractAddress:r,funds:i,memo:a})=>{const s=Y();if(!e)throw new Error("CosmWasm signing client is not ready");s.debug("transaction","Executing contract",{function:"executeContract",senderAddress:n,contractAddress:r,msg:t});try{const c=await e.execute(n,r,t,o,a,i);return s.info("transaction","Contract execution successful",{function:"executeContract",txHash:c.transactionHash,events:c.events.length}),c}catch(e){throw s.error("transaction","Contract execution failed",{function:"executeContract",error:e instanceof Error?e.message:String(e),contractAddress:r,senderAddress:n}),e}},Ge=async(e,n,t)=>{const o=Y();if(!t)throw new Error("CosmWasm client is not ready");o.debug("query","Querying smart contract",{function:"getQuerySmart",address:e,queryMsg:n});try{const r=await t.queryContractSmart(e,n);return o.debug("query","Smart query successful",{function:"getQuerySmart",address:e}),r}catch(n){throw o.error("query","Smart query failed",{function:"getQuerySmart",error:n instanceof Error?n.message:String(n),address:e}),n}},He=async(e,n,t)=>{const o=Y();if(!t)throw new Error("CosmWasm client is not ready");o.debug("query","Querying raw contract data",{function:"getQueryRaw",address:e,key:n});try{const r=(new TextEncoder).encode(n),i=await t.queryContractRaw(e,r);return o.debug("query","Raw query successful",{function:"getQueryRaw",address:e}),i}catch(n){throw o.error("query","Raw query failed",{function:"getQueryRaw",error:n instanceof Error?n.message:String(n),address:e}),n}},ze=e=>e,Qe=e=>e,Ve=({chainId:e})=>{const n=H(e=>e.chains);if(!n)throw new Error("No chains found in GrazProvider");return e&&e.length>0?e.map(e=>n.find(n=>n.chainId===e)).filter(Boolean):n},Ye=async(e,n,t)=>{const o=Y(),r=H.getState().multiChainFetchConcurrency,i=t?{hook:t}:{function:"createMultiChainAsyncFunction"};o.debug("multichain","Starting parallel operations",{...i,chainCount:e.length,concurrency:r,chainIds:e.map(e=>e.chainId)}),o.time("multichain-operation");try{const t=await A(e,n,{concurrency:r}),a=Object.fromEntries(t.map((n,t)=>[e[t].chainId,n]));return o.timeEnd("multichain-operation"),o.info("multichain","All chains completed",{...i,chainCount:e.length,chainIds:e.map(e=>e.chainId),successCount:Object.keys(a).length}),a}catch(n){throw o.timeEnd("multichain-operation"),o.error("multichain","Multi-chain operation failed",{...i,error:n instanceof Error?n.message:String(n),chainCount:e.length,chainIds:e.map(e=>e.chainId)}),n}};function Xe(e){const n=Ve({chainId:e?.chainId}),t=b(()=>["USE_STARGATE_CLIENT",n],[n]);return y({queryKey:t,queryFn:async()=>{const e=Y();if(e.debug("query","Creating Stargate clients",{hook:"useStargateClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId)}),!n||n.length<1)throw new Error("No chains found");try{const t=await Ye(n,async e=>{const n=H.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await O.connect(t)},"useStargateClient");return e.debug("query","Stargate clients created successfully",{hook:"useStargateClient",clientCount:Object.keys(t).length}),t}catch(n){throw e.error("query","Failed to create Stargate clients",{hook:"useStargateClient",error:n instanceof Error?n.message:String(n)}),n}},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}function Je(e){const n=Ve({chainId:e?.chainId}),t=b(()=>["USE_COSMWASM_CLIENT",n],[n]);return y({queryKey:t,queryFn:async()=>{const e=Y();if(e.debug("query","Creating CosmWasm clients",{hook:"useCosmWasmClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId)}),!n||n.length<1)throw new Error("No chains found");try{const t=await Ye(n,async e=>{const n=H.getState().chainsConfig?.[e.chainId],t={url:e.rpc,headers:{...n?.rpcHeaders||{}}};return await _.connect(t)},"useCosmWasmClient");return e.debug("query","CosmWasm clients created successfully",{hook:"useCosmWasmClient",clientCount:Object.keys(t).length}),t}catch(n){throw e.error("query","Failed to create CosmWasm clients",{hook:"useCosmWasmClient",error:n instanceof Error?n.message:String(n)}),n}},enabled:Boolean(n)&&n.length>0&&(void 0===e?.enabled||Boolean(e.enabled)),refetchOnWindowFocus:!1})}var Ze=()=>H(N(e=>({walletType:e.walletType,isCosmostation:"cosmostation"===e.walletType,isCosmostationMobile:"wc_cosmostation_mobile"===e.walletType,isKeplr:"keplr"===e.walletType,isKeplrMobile:"wc_keplr_mobile"===e.walletType,isLeap:"leap"===e.walletType,isLeapMobile:"wc_leap_mobile"===e.walletType,isVectis:"vectis"===e.walletType,isWalletConnect:"walletconnect"===e.walletType,isMetamaskSnapLeap:"metamask_snap_leap"===e.walletType,isStation:"station"===e.walletType,isCosmiframe:"cosmiframe"===e.walletType}))),en=e=>{const n=H(n=>e||n.walletType);return y({queryKey:["USE_CHECK_WALLET",n],queryFn:()=>{const e=Y();if(e.debug("wallet","Checking wallet availability",{hook:"useCheckWallet",walletType:n}),!n)return e.debug("wallet","No wallet type provided",{hook:"useCheckWallet"}),!1;const t=Se(n);return e.debug("wallet","Wallet check completed",{hook:"useCheckWallet",walletType:n,isAvailable:t}),t}})};function nn(e){const n=H(e=>e.walletType),t=G(e=>e.activeChainIds),o=Ve({chainId:e?.chainId?e.chainId:t||void 0}),r=G(e=>e.accounts),i=G(e=>e.status);I(()=>G.subscribe(e=>e.status,(n,t)=>{if("connected"===n){const{accounts:n,activeChainIds:o}=G.getState(),{chains:r}=H.getState(),{walletType:i}=H.getState();if(!n||!o||!r)return e?.onDisconnect?.();e?.onConnect?.({accounts:n,chains:o.map(e=>r.find(n=>n.chainId===e)),walletType:i,isReconnect:"reconnecting"===t})}"disconnected"===n&&e?.onDisconnect?.()}),[e]);return{data:b(()=>r?((e,n)=>{const t=e.map(n);return Object.fromEntries(t.map((n,t)=>[e[t].chainId,n]))})(o,e=>r[e.chainId]):void 0,[r,o]),isConnected:"connected"===i,isConnecting:"connecting"===i,isDisconnected:"disconnected"===i,isReconnecting:"reconnecting"===i,isLoading:"connecting"===i||"reconnecting"===i,walletType:"connected"===i?n:void 0,reconnect:Ne,status:i}}var tn=e=>{const n=Ve({chainId:[e.chainId]})[0],{data:t}=Xe({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=b(()=>["USE_ALL_BALANCES",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return y({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getAllBalances(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},on=e=>{const n=Ve({chainId:[e.chainId]})[0],{data:t}=Xe({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=b(()=>["USE_BALANCE",o,e.chainId,e.bech32Address,e.denom],[e.bech32Address,e.chainId,e.denom,o]);return y({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);const t=await o.getBalance(e.bech32Address,e.denom);return"0"===t.amount?void 0:t},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},rn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),r=S({mutationKey:["USE_CONNECT",e,n,t],mutationFn:Te,onError:(n,t)=>{o.error("wallet","useConnect mutation failed",{error:n instanceof Error?n.message:String(n),chainId:t?.chainId}),e?.(n,t)},onMutate:n,onSuccess:e=>(o.info("wallet","useConnect mutation successful",{hook:"useConnect",walletType:e.walletType,chainCount:e.chains.length}),Promise.resolve(t?.(e)))}),{data:i}=en();return{connect:e=>r.mutate(e),connectAsync:e=>r.mutateAsync(e),error:r.error,isLoading:r.isPending,isSuccess:r.isSuccess,isSupported:Boolean(i),status:r.status}},an=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),r=S({mutationKey:["USE_DISCONNECT",e,n,t],mutationFn:ke,onError:n=>(o.error("wallet","useDisconnect mutation failed",{hook:"useDisconnect",error:n instanceof Error?n.message:String(n)}),Promise.resolve(e?.(n,void 0))),onMutate:n,onSuccess:()=>(o.info("wallet","useDisconnect mutation successful",{hook:"useDisconnect"}),Promise.resolve(t?.(void 0)))});return{disconnect:e=>r.mutate(e),disconnectAsync:e=>r.mutateAsync(e),error:r.error,isLoading:r.isPending,isSuccess:r.isSuccess,status:r.status}};function sn(e){const n=Ve({chainId:e?.chainId}),t=H(e=>e.walletType),o="connected"===G.getState().status&&G.getState().accounts&&H.getState()._reconnectConnector===t,r=b(()=>["USE_OFFLINE_SIGNERS",n,t],[n,t]);return y({queryKey:r,queryFn:async()=>{if(!n||n.length<1)throw new Error("No chain found");if(!t)throw new Error("Wallet is not defined");if(!Se(t))throw new Error(`${t} is not available`);return await Ye(n,async e=>await Be({chainId:e.chainId,walletType:t}),"useOfflineSigners")},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&Boolean(o),refetchOnWindowFocus:!1})}var cn=e=>{const n=Ve({chainId:[e.chainId]})[0],{data:t}=Xe({chainId:[e.chainId],enabled:void 0===e.enabled||e.enabled}),o=t?.[e.chainId],r=b(()=>["USE_BALANCE_STAKED",o,e.chainId,e.bech32Address],[e.bech32Address,e.chainId,o]);return y({queryKey:r,queryFn:async()=>{if(!o)throw new Error(`Client is not ready for ${e.chainId}`);if(!n?.bech32Config?.bech32PrefixAccAddr)throw new Error(`Bech32Config is missing for ${e.chainId}`);return await o.getBalanceStaked(e.bech32Address)},enabled:Boolean(o)&&Boolean(n)&&(void 0===e.enabled||e.enabled),refetchOnMount:!1,refetchOnReconnect:!0,refetchOnWindowFocus:!1})},ln=()=>G(e=>e.activeChainIds),dn=()=>{const e=G(e=>e.activeChainIds),n=H(e=>e.chains);return e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean)},un=({chainId:e}={})=>H(e=>e.chains)?.find(n=>n.chainId===e),gn=({chainId:e}={})=>{const n=H(e=>e.chains);return e?n?.filter(n=>e.includes(n.chainId)):n},hn=({denom:e})=>{const n=dn();return y({queryKey:["USE_ACTIVE_CHAIN_CURRENCY",e],queryFn:({queryKey:[,e]})=>n?.find(n=>n.currencies.find(n=>n.coinMinimalDenom===e))?.currencies.find(e=>e)})},fn=e=>{const n=e.status??"BOND_STATUS_BONDED",t=["USE_ACTIVE_CHAIN_VALIDATORS",e.queryClient,n];return y({queryKey:t,queryFn:async()=>{if(!e.queryClient)throw new Error("Query client is not defined");return await e.queryClient.staking.validators(n)},enabled:void 0!==e.queryClient})},wn=()=>({data:H(e=>e.recentChainIds),clear:De}),mn=()=>{const e=H(e=>e.recentChainIds),n=H(e=>e.chains),t=e?.map(e=>{const t=n?.find(n=>n.chainId===e);if(t)return t}).filter(Boolean);return{data:t,clear:De}},pn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),r=S({mutationKey:["USE_ADD_CHAIN",e,n,t],mutationFn:Pe,onError:(n,t)=>(o.error("store","useAddChain mutation failed",{hook:"useAddChain",error:n instanceof Error?n.message:String(n),chainId:t.chainInfo.chainId}),Promise.resolve(e?.(n,t.chainInfo))),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>(o.info("store","useAddChain mutation successful",{hook:"useAddChain",chainId:e.chainId,chainName:e.chainName}),Promise.resolve(t?.(e)))});return{addChain:r.mutate,addChainAsync:r.mutateAsync,error:r.error,isLoading:r.isPending,isSuccess:r.isSuccess,status:r.status}},Cn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),r=S({mutationKey:["USE_SUGGEST_CHAIN",e,n,t],mutationFn:qe,onError:(n,t)=>(o.error("wallet","useSuggestChain mutation failed",{hook:"useSuggestChain",error:n instanceof Error?n.message:String(n),chainId:t.chainInfo.chainId,walletType:t.walletType}),Promise.resolve(e?.(n,t.chainInfo))),onMutate:e=>n?.(e.chainInfo),onSuccess:e=>(o.info("wallet","useSuggestChain mutation successful",{hook:"useSuggestChain",chainId:e.chainId,chainName:e.chainName}),Promise.resolve(t?.(e)))});return{error:r.error,isLoading:r.isPending,isSuccess:r.isSuccess,suggest:r.mutate,suggestAsync:r.mutateAsync,status:r.status}},yn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),r=S({mutationKey:["USE_SUGGEST_CHAIN_AND_CONNECT",e,n,t],mutationFn:Me,onError:(n,t)=>(o.error("wallet","useSuggestChainAndConnect mutation failed",{error:n instanceof Error?n.message:String(n),chainId:t.chainInfo.chainId}),Promise.resolve(e?.(n,t))),onMutate:e=>n?.(e),onSuccess:e=>(o.info("wallet","useSuggestChainAndConnect mutation successful",{hook:"useSuggestChainAndConnect",walletType:e.walletType,chainCount:e.chains.length}),Promise.resolve(t?.(e)))}),{data:i}=en();return{error:r.error,isLoading:r.isPending,isSuccess:r.isSuccess,isSupported:Boolean(i),status:r.status,suggestAndConnect:r.mutate,suggestAndConnectAsync:r.mutateAsync}},Sn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),{mutate:r,mutateAsync:i,...a}=S({mutationKey:["USE_SEND_TOKENS",e,n,t],mutationFn:xe,onError:(n,t)=>(o.error("transaction","useSendTokens mutation failed",{hook:"useSendTokens",error:n instanceof Error?n.message:String(n),recipientAddress:t.recipientAddress}),Promise.resolve(e?.(n,t))),onMutate:n,onSuccess:e=>(o.info("transaction","useSendTokens mutation successful",{hook:"useSendTokens",txHash:e.transactionHash}),Promise.resolve(t?.(e)))});return{...a,sendTokens:r,sendTokensAsync:i}},bn=({onError:e,onLoading:n,onSuccess:t}={})=>{const o=Y(),{mutate:r,mutateAsync:i,...a}=S({mutationKey:["USE_SEND_IBC_TOKENS",e,n,t],mutationFn:Ke,onError:(n,t)=>(o.error("transaction","useSendIbcTokens mutation failed",{error:n instanceof Error?n.message:String(n),sourceChannel:t.sourceChannel}),Promise.resolve(e?.(n,t))),onMutate:n,onSuccess:e=>(o.info("transaction","useSendIbcTokens mutation successful",{hook:"useSendIbcTokens",txHash:e.transactionHash}),Promise.resolve(t?.(e)))});return{...a,sendIbcTokens:r,sendIbcTokensAsync:i}},In=({codeId:e,onError:n,onLoading:t,onSuccess:o})=>{const r=Y(),{mutate:i,mutateAsync:a,...s}=S({mutationKey:["USE_INSTANTIATE_CONTRACT",n,t,o,e],mutationFn:n=>$e({...n,fee:n.fee??"auto",codeId:e}),onError:(t,o)=>(r.error("transaction","useInstantiateContract mutation failed",{error:t instanceof Error?t.message:String(t),codeId:e}),Promise.resolve(n?.(t,o))),onMutate:t,onSuccess:e=>(r.info("transaction","useInstantiateContract mutation successful",{hook:"useInstantiateContract",contractAddress:e.contractAddress,txHash:e.transactionHash}),Promise.resolve(o?.(e)))});return{...s,instantiateContract:i,instantiateContractAsync:a}},En=({contractAddress:e,onError:n,onLoading:t,onSuccess:o})=>{const r=Y(),{mutate:i,mutateAsync:a,...s}=S({mutationKey:["USE_EXECUTE_CONTRACT",n,t,o,e],mutationFn:n=>je({...n,fee:n.fee??"auto",contractAddress:e,memo:n.memo??"",funds:n.funds??[]}),onError:(t,o)=>(r.error("transaction","useExecuteContract mutation failed",{hook:"useExecuteContract",error:t instanceof Error?t.message:String(t),contractAddress:e}),Promise.resolve(n?.(t,o))),onMutate:t,onSuccess:n=>(r.info("transaction","useExecuteContract mutation successful",{hook:"useExecuteContract",txHash:n.transactionHash,contractAddress:e}),Promise.resolve(o?.(n)))});return{...s,executeContract:i,executeContractAsync:a}},An=e=>{const{data:n}=Je(),t=n&&Object.values(n)[0];return y({queryKey:["USE_QUERY_SMART",e?.address,e?.queryMsg,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.queryMsg)throw new Error("address or queryMsg undefined");return Ge(e.address,e.queryMsg,t)},enabled:Boolean(e?.address)&&Boolean(e?.queryMsg)&&Boolean(t)})},_n=e=>{const{data:n}=Je(),t=n&&Object.values(n)[0];return y({queryKey:["USE_QUERY_RAW",e?.key,e?.address,t],queryFn:({queryKey:[,n]})=>{if(!e?.address||!e.key)throw new Error("address or key undefined");return He(e.address,e.key,t)},enabled:Boolean(e?.address)&&Boolean(e?.key)&&Boolean(t)})};function vn(e){const n=Ve({chainId:e?.chainId}),t=H(e=>e.walletType),o=G(e=>e.activeChainIds),r="connected"===G.getState().status&&G.getState().accounts&&H.getState()._reconnectConnector===t,i=b(()=>["USE_STARGATE_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return y({queryKey:i,queryFn:async()=>{const r=Y();if(r.debug("query","Creating Stargate signing clients",{hook:"useStargateSigningClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId),walletType:t}),!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");try{const i=await Ye(n,async n=>{if(!o?.includes(n.chainId))return null;if(!Se(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return Ie(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return Ie(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return Ie(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=H.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}};return await T.connectWithSigner(a,r,e?.opts?.[n.chainId])},"useStargateSigningClient");return r.debug("query","Stargate signing clients created successfully",{hook:"useStargateSigningClient",clientCount:Object.keys(i).length}),i}catch(e){throw r.error("query","Failed to create Stargate signing clients",{hook:"useStargateSigningClient",error:e instanceof Error?e.message:String(e),walletType:t}),e}},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})}function On(e){const n=Ve({chainId:e?.chainId}),t=H(e=>e.walletType),o=G(e=>e.activeChainIds),r="connected"===G.getState().status&&G.getState().accounts&&H.getState()._reconnectConnector===t,i=b(()=>["USE_COSMWASM_SIGNING_CLIENT",n,t,e,o],[o,e,n,t]);return y({queryKey:i,queryFn:async()=>{const r=Y();if(r.debug("query","Creating CosmWasm signing clients",{hook:"useCosmWasmSigningClient",chainCount:n?.length||0,chainIds:n?.map(e=>e.chainId),walletType:t}),!n||n.length<1)throw new Error("No chains found");if(!t)throw new Error("Wallet is not defined");try{const i=await Ye(n,async n=>{if(!o?.includes(n.chainId))return null;if(!Se(t))throw new Error(`${t} is not available`);const r=await(async()=>{switch(e?.offlineSigner){case"offlineSigner":return Ie(t).getOfflineSigner(n.chainId);case"offlineSignerAuto":default:return Ie(t).getOfflineSignerAuto(n.chainId);case"offlineSignerOnlyAmino":return Ie(t).getOfflineSignerOnlyAmino(n.chainId)}})(),i=H.getState().chainsConfig?.[n.chainId],a={url:n.rpc,headers:{...i?.rpcHeaders||{}}},s=i?.gas?k.fromString(`${i.gas.price}${i.gas.denom}`):void 0;return await v.connectWithSigner(a,r,{gasPrice:s,...e?.opts?.[n.chainId]||{}})},"useCosmWasmSigningClient");return r.debug("query","CosmWasm signing clients created successfully",{hook:"useCosmWasmSigningClient",clientCount:Object.keys(i).length}),i}catch(e){throw r.error("query","Failed to create CosmWasm signing clients",{hook:"useCosmWasmSigningClient",error:e instanceof Error?e.message:String(e),walletType:t}),e}},enabled:Boolean(n)&&n.length>0&&Boolean(t)&&(void 0===e?.enabled||Boolean(e.enabled))&&Boolean(r),refetchOnWindowFocus:!1})}var Tn=({children:e})=>{const[n,t]=E(!1);return I(()=>{t(!0)},[]),D(L,{children:n?e:null})},kn=()=>{const e=Y(),n="undefined"!=typeof window&&"Active"===window.sessionStorage.getItem(P),{_reconnect:t,_onReconnectFailed:o,_reconnectConnector:i,iframeOptions:a,chains:s,pingInterval:c}=H(),{activeChainIds:l,wcSignClients:d}=G(),u=Se(i||void 0);return I(()=>{const t=async()=>{if(n&&u&&i&&l?.[0]){const n=G.getState().lastPing;if(n&&Date.now()-n<c)return;const t=Ie(i);try{if(!await t.getKey(l[0]))throw new Error("No account found");G.setState({lastPing:Date.now()}),e.debug("event","Wallet ping successful",{function:"handleFocus"})}catch(n){e.debug("event","Wallet ping failed, triggering reconnect",{function:"handleFocus",error:n instanceof Error?n.message:String(n),walletType:i}),Ne({onError:o})}}};return window.addEventListener("focus",t),()=>{window.removeEventListener("focus",t)}},[n,u,i,s,l,c]),I(()=>{if(!a||!1===a.autoConnect||!a.allowedIframeParentOrigins.length||!s)return;new r(a.allowedIframeParentOrigins).isReady().then(n=>{if(n)return e.info("event","Auto-connecting to iframe wallet",{function:"autoConnectIframe"}),Te({chainId:s.map(e=>e.chainId),walletType:"cosmiframe"})})},[a]),I(()=>{if(i){if(!u)return;n&&Boolean(l)?(e.info("event","Reconnection triggered",{function:"reconnectEffect",reason:"session active"}),Ne({onError:o})):!n&&t&&(e.info("event","Reconnection triggered",{function:"reconnectEffect",reason:"auto-reconnect enabled"}),Ne({onError:o}))}},[u]),I(()=>{if(i){if(!u)return;"cosmostation"===i&&te().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"cosmostation"}),Ne({onError:o})}),"keplr"===i&&re().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"keplr"}),Ne({onError:o})}),"leap"===i&&ie().subscription?.(()=>{e.debug("event","Account changed",{function:"subscription",walletType:"leap"}),Ne({onError:o})}),"compass"===i&&Z().subscription?.(()=>{Ne({onError:o})}),"vectis"===i&&ge().subscription?.(()=>{Ne({onError:o})}),"walletconnect"===i&&d.has("walletconnect")&&we().subscription?.(()=>{Ne({onError:o})}),"station"===i&&ue().subscription?.(()=>{Ne({onError:o})}),"xdefi"===i&&ye().subscription?.(()=>{Ne({onError:o})}),"cosmiframe"===i&&ee().subscription?.(()=>{Ne({onError:o})}),"okx"===i&&ce().subscription?.(()=>{Ne({onError:o})})}},[i,d,u]),null},Nn=()=>(kn(),null),Bn=({children:e,grazOptions:n})=>(I(()=>{We(n)},[n]),B(Tn,{children:[e,D(Nn,{})]}));export{Nn as GrazEvents,Bn as GrazProvider,q as LOG_CATEGORIES,M as LOG_FUNCTIONS,W as LOG_HOOKS,Q as LogCategory,z as LogLevel,K as WALLET_TYPES,x as WalletType,Pe as addChain,Se as checkWallet,De as clearRecentChain,be as clearSession,We as configureGraz,X as configureLogger,Te as connect,Qe as defineChainInfo,ze as defineChains,ke as disconnect,je as executeContract,Ee as getAvailableWallets,J as getCactusCosmos,Fe as getChainInfo,Ue as getChainInfos,te as getCosmostation,re as getKeplr,ie as getLeap,Y as getLogger,se as getMetamaskSnapLeap,Be as getOfflineSigners,ce as getOkx,de as getPara,He as getQueryRaw,Ge as getQuerySmart,Le as getRecentChainIds,Re as getRecentChains,ge as getVectis,me as getWCCosmostation,pe as getWCKeplr,Ce as getWCLeap,Ie as getWallet,we as getWalletConnect,$e as instantiateContract,_e as isLeapDappBrowser,Ae as isLeapSnaps,Oe as isPara,ve as isWalletConnect,Ne as reconnect,Ke as sendIbcTokens,xe as sendTokens,qe as suggestChain,Me as suggestChainAndConnect,nn as useAccount,hn as useActiveChainCurrency,ln as useActiveChainIds,dn as useActiveChains,Ze as useActiveWalletType,pn as useAddChain,on as useBalance,cn as useBalanceStaked,tn as useBalances,un as useChainInfo,gn as useChainInfos,en as useCheckWallet,rn as useConnect,Je as useCosmWasmClient,On as useCosmWasmSigningClient,an as useDisconnect,En as useExecuteContract,kn as useGrazEvents,In as useInstantiateContract,sn as useOfflineSigners,fn as useQueryClientValidators,_n as useQueryRaw,An as useQuerySmart,wn as useRecentChainIds,mn as useRecentChains,bn as useSendIbcTokens,Sn as useSendTokens,Xe as useStargateClient,vn as useStargateSigningClient,Cn as useSuggestChain,yn as useSuggestChainAndConnect};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "graz",
3
3
  "description": "React hooks for Cosmos",
4
- "version": "0.4.1",
4
+ "version": "0.4.2",
5
5
  "author": "Nur Fikri <kikiding.space@gmail.com>",
6
6
  "repository": "https://github.com/graz-sh/graz.git",
7
7
  "homepage": "https://github.com/graz-sh/graz",
@@ -67,11 +67,11 @@
67
67
  "@getpara/graz-connector": "2.0.0-alpha.51",
68
68
  "@getpara/web-sdk": "2.0.0-alpha.51",
69
69
  "@types/node": "^18.17.15",
70
- "@types/react": "^18.2.21",
70
+ "@types/react": "^19.0.0",
71
71
  "@vitest/ui": "^2.1.9",
72
72
  "arg": "^5.0.2",
73
73
  "jsdom": "^23.0.0",
74
- "react": "^18.2.0",
74
+ "react": "^19.0.0",
75
75
  "typescript": "^5.4.0",
76
76
  "vite": "^5.4.20",
77
77
  "vitest": "^2.1.9"