@luno-kit/react 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1143 @@
1
+ import React, { useCallback, useEffect, useMemo, useState, useRef, useContext } from 'react';
2
+ import { create } from 'zustand';
3
+ import { isSameAddress, wsProvider, convertAddress, formatBalance } from '@luno-kit/core';
4
+ export * from '@luno-kit/core';
5
+ import { LegacyClient } from 'dedot';
6
+ import { jsx } from 'react/jsx-runtime';
7
+ import { useQueryClient, useQuery, useMutation } from '@tanstack/react-query';
8
+ import { isNumber } from 'dedot/utils';
9
+
10
+ // src/types/state.ts
11
+ var ConnectionStatus = /* @__PURE__ */ ((ConnectionStatus2) => {
12
+ ConnectionStatus2["Disconnected"] = "disconnected";
13
+ ConnectionStatus2["Connecting"] = "connecting";
14
+ ConnectionStatus2["Disconnecting"] = "disconnecting";
15
+ ConnectionStatus2["Connected"] = "connected";
16
+ return ConnectionStatus2;
17
+ })(ConnectionStatus || {});
18
+
19
+ // src/constants.ts
20
+ var PERSIST_KEY = {
21
+ LAST_CONNECTOR_ID: "lastConnectorId",
22
+ LAST_CHAIN_ID: "lastChainId",
23
+ LAST_SELECTED_ACCOUNT_INFO: "lastSelectedAccountInfo"
24
+ };
25
+ var createApi = async ({
26
+ config,
27
+ chainId
28
+ }) => {
29
+ const chainConfig = config.chains.find((c) => c.genesisHash === chainId);
30
+ const transportConfig = config.transports[chainId];
31
+ if (!chainConfig || !transportConfig) {
32
+ throw new Error(`Configuration missing for chainId: ${chainId}`);
33
+ }
34
+ const provider = wsProvider(transportConfig);
35
+ const apiOptions = {
36
+ provider,
37
+ cacheMetadata: config.cacheMetadata,
38
+ metadata: config.metadata,
39
+ scaledResponses: {
40
+ ...config.scaledResponses,
41
+ ...config.customTypes
42
+ },
43
+ runtimeApis: config.runtimeApis,
44
+ cacheStorage: config.cacheStorage
45
+ };
46
+ const newApi = new LegacyClient(apiOptions);
47
+ try {
48
+ await newApi.connect();
49
+ const actualGenesisHash = await newApi.rpc.chain_getBlockHash(0);
50
+ if (actualGenesisHash !== chainId) {
51
+ await newApi.disconnect();
52
+ throw new Error(
53
+ `Chain genesis hash mismatch. Expected: ${chainId}, Got: ${actualGenesisHash}. This might indicate connecting to the wrong network or incorrect chain configuration.`
54
+ );
55
+ }
56
+ return newApi;
57
+ } catch (error) {
58
+ throw new Error(`Failed to connect to ${chainConfig.name}: ${error?.message || error}`);
59
+ }
60
+ };
61
+
62
+ // src/utils/dispatchError.ts
63
+ function getReadableDispatchError(api, dispatchError) {
64
+ if (dispatchError.type === "Module") {
65
+ try {
66
+ const errorMeta = api.registry.findErrorMeta(dispatchError);
67
+ if (errorMeta) {
68
+ const { docs, name, pallet, fields, fieldCodecs } = errorMeta;
69
+ return `[useSendTransaction]: ${pallet}.${name} error, ${docs.join(" ")}`;
70
+ }
71
+ return `[useSendTransaction]: Module Error (index: ${dispatchError.value.index}, error: ${dispatchError.value.error})`;
72
+ } catch (e) {
73
+ const { value: { error, index } } = dispatchError;
74
+ return `[useSendTransaction]: Module Error (index: ${index}, error: ${error}) - Failed to decode: ${e instanceof Error ? e.message : "Unknown error"}`;
75
+ }
76
+ } else if (dispatchError.type === "Token") {
77
+ return `[useSendTransaction]: Token Error: ${dispatchError.value}`;
78
+ }
79
+ if ("value" in dispatchError) {
80
+ return `[useSendTransaction]: ${dispatchError.type} Error: ${dispatchError.value}`;
81
+ }
82
+ return `[useSendTransaction]: Error: ${dispatchError.type}`;
83
+ }
84
+
85
+ // src/store/createLunoStore.ts
86
+ var activeConnectorUnsubscribeFunctions = [];
87
+ var cleanupActiveConnectorListeners = () => {
88
+ activeConnectorUnsubscribeFunctions.forEach((unsub) => {
89
+ try {
90
+ unsub();
91
+ } catch (e) {
92
+ console.warn("[LunoStore] Error during listener cleanup:", e);
93
+ }
94
+ });
95
+ activeConnectorUnsubscribeFunctions = [];
96
+ };
97
+ var useLunoStore = create((set, get) => ({
98
+ config: void 0,
99
+ status: "disconnected" /* Disconnected */,
100
+ activeConnector: void 0,
101
+ accounts: [],
102
+ account: void 0,
103
+ currentChainId: void 0,
104
+ currentChain: void 0,
105
+ currentApi: void 0,
106
+ isApiReady: false,
107
+ apiError: null,
108
+ _setConfig: async (newConfig) => {
109
+ cleanupActiveConnectorListeners();
110
+ let storedChainId = null;
111
+ try {
112
+ storedChainId = await newConfig.storage.getItem(PERSIST_KEY.LAST_CHAIN_ID);
113
+ } catch (e) {
114
+ console.warn("[LunoStore] Failed to read stored chain ID from storage:", e);
115
+ }
116
+ const normalizedStoredChainId = storedChainId?.toLowerCase();
117
+ const initialChainId = normalizedStoredChainId && newConfig.chains.some((c) => c.genesisHash.toLowerCase() === normalizedStoredChainId) ? normalizedStoredChainId : newConfig.chains[0]?.genesisHash;
118
+ const initialChain = initialChainId ? newConfig.chains.find((c) => c.genesisHash.toLowerCase() === initialChainId) : void 0;
119
+ set({
120
+ config: newConfig,
121
+ status: "disconnected" /* Disconnected */,
122
+ activeConnector: void 0,
123
+ accounts: [],
124
+ currentChainId: initialChainId,
125
+ currentChain: initialChain
126
+ });
127
+ },
128
+ _setApi: (apiInstance) => {
129
+ set({ currentApi: apiInstance });
130
+ },
131
+ _setIsApiReady: (isReady) => {
132
+ set({ isApiReady: isReady });
133
+ },
134
+ setAccount: async (accountOrPublicKey) => {
135
+ if (!accountOrPublicKey) return;
136
+ const { accounts, config } = get();
137
+ const targetPublicKey = typeof accountOrPublicKey === "string" ? accountOrPublicKey.toLowerCase() : accountOrPublicKey.publicKey?.toLowerCase();
138
+ const nextAccount = accounts.find((acc) => acc.publicKey?.toLowerCase() === targetPublicKey);
139
+ if (!nextAccount) {
140
+ throw new Error("[LunoStore] setAccount: The provided account or address is not in the current accounts list. Ignored.");
141
+ }
142
+ set({ account: nextAccount });
143
+ if (config) {
144
+ try {
145
+ const accountInfo = {
146
+ publicKey: nextAccount.publicKey,
147
+ address: nextAccount.address,
148
+ name: nextAccount.name,
149
+ source: nextAccount.meta.source
150
+ };
151
+ await config.storage.setItem(PERSIST_KEY.LAST_SELECTED_ACCOUNT_INFO, JSON.stringify(accountInfo));
152
+ console.log(`[LunoStore] Persisted selected account: ${nextAccount.address}`);
153
+ } catch (e) {
154
+ console.error("[LunoStore] Failed to persist selected account:", e);
155
+ }
156
+ }
157
+ },
158
+ connect: async (connectorId, targetChainId) => {
159
+ const config = get().config;
160
+ if (!config) {
161
+ set({ status: "disconnected" /* Disconnected */ });
162
+ throw new Error("[LunoStore] LunoConfig has not been initialized. Cannot connect.");
163
+ }
164
+ const connector = config.connectors.find((c) => c.id === connectorId);
165
+ if (!connector) {
166
+ set({ status: "disconnected" /* Disconnected */ });
167
+ throw new Error(`[LunoStore] Connector with ID "${connectorId}" not found in LunoConfig.`);
168
+ }
169
+ set({ status: "connecting" /* Connecting */ });
170
+ const previouslyActiveConnector = get().activeConnector;
171
+ if (previouslyActiveConnector && previouslyActiveConnector.id !== connector.id) {
172
+ console.log(`[LunoStore] Switching connector. Cleaning up listeners for old connector: ${previouslyActiveConnector.id}`);
173
+ cleanupActiveConnectorListeners();
174
+ } else if (previouslyActiveConnector && previouslyActiveConnector.id === connector.id) {
175
+ console.log(`[LunoStore] Attempting to reconnect with the same connector: ${connector.id}. Cleaning up existing listeners.`);
176
+ cleanupActiveConnectorListeners();
177
+ }
178
+ try {
179
+ const handleAccountsChanged = async (newAccounts) => {
180
+ console.log(`[LunoStore] accountsChanged event from ${connector.name}:`, newAccounts);
181
+ newAccounts.forEach((acc) => {
182
+ if (!acc.publicKey) {
183
+ console.warn(`[LunoStore] Account ${acc.address} (from ${connector.name}) is missing publicKey.`);
184
+ }
185
+ });
186
+ let selectedAccount2 = newAccounts[0];
187
+ try {
188
+ const storedAccountJson = await config.storage.getItem(PERSIST_KEY.LAST_SELECTED_ACCOUNT_INFO);
189
+ if (storedAccountJson) {
190
+ const storedAccount = JSON.parse(storedAccountJson);
191
+ const restoredAccount = newAccounts.find(
192
+ (acc) => storedAccount.publicKey && acc.publicKey?.toLowerCase() === storedAccount.publicKey.toLowerCase() || isSameAddress(acc.address, storedAccount.address)
193
+ );
194
+ if (restoredAccount) {
195
+ selectedAccount2 = restoredAccount;
196
+ }
197
+ }
198
+ } catch (e) {
199
+ console.warn("[LunoStore] Failed to restore account during accountsChanged:", e);
200
+ }
201
+ set({ accounts: newAccounts, account: selectedAccount2 });
202
+ };
203
+ const handleDisconnect = () => {
204
+ console.log(`[LunoStore] disconnect event from ${connector.name}`);
205
+ if (get().activeConnector?.id === connector.id) {
206
+ cleanupActiveConnectorListeners();
207
+ try {
208
+ config.storage.removeItem(PERSIST_KEY.LAST_CONNECTOR_ID);
209
+ config.storage.removeItem(PERSIST_KEY.LAST_CHAIN_ID);
210
+ console.log("[LunoStore] Removed persisted connection info from storage due to disconnect event.");
211
+ } catch (e) {
212
+ console.error("[LunoStore] Failed to remove connection info from storage:", e);
213
+ }
214
+ set({
215
+ status: "disconnected" /* Disconnected */,
216
+ activeConnector: void 0,
217
+ accounts: []
218
+ });
219
+ } else {
220
+ console.warn(`[LunoStore] Received disconnect event from an inactive connector ${connector.name}. Ignored.`);
221
+ }
222
+ };
223
+ connector.on("accountsChanged", handleAccountsChanged);
224
+ activeConnectorUnsubscribeFunctions.push(() => connector.off("accountsChanged", handleAccountsChanged));
225
+ connector.on("disconnect", handleDisconnect);
226
+ activeConnectorUnsubscribeFunctions.push(() => connector.off("disconnect", handleDisconnect));
227
+ const chainIdToUse = targetChainId || get().currentChainId || config.chains[0]?.genesisHash;
228
+ const accountsFromWallet = await connector.connect(config.appName, config.chains, chainIdToUse);
229
+ accountsFromWallet.forEach((acc) => {
230
+ if (!acc.publicKey) {
231
+ console.error(`[LunoStore] CRITICAL WARNING: Account ${acc.address} from connector ${connector.name} was returned without a publicKey! SS58 address formatting will fail.`);
232
+ }
233
+ });
234
+ let selectedAccount = accountsFromWallet[0];
235
+ try {
236
+ const storedAccountJson = await config.storage.getItem(PERSIST_KEY.LAST_SELECTED_ACCOUNT_INFO);
237
+ if (storedAccountJson) {
238
+ const storedAccount = JSON.parse(storedAccountJson);
239
+ const restoredAccount = accountsFromWallet.find(
240
+ (acc) => storedAccount.publicKey && acc.publicKey?.toLowerCase() === storedAccount.publicKey.toLowerCase() || isSameAddress(acc.address, storedAccount.address)
241
+ );
242
+ if (restoredAccount) {
243
+ selectedAccount = restoredAccount;
244
+ console.log(`[LunoStore] Restored previously selected account: ${selectedAccount.address}`);
245
+ } else {
246
+ console.log("[LunoStore] Previously selected account not found in current accounts list, using first account");
247
+ }
248
+ }
249
+ } catch (e) {
250
+ console.warn("[LunoStore] Failed to restore selected account from storage:", e);
251
+ }
252
+ set({
253
+ activeConnector: connector,
254
+ accounts: accountsFromWallet,
255
+ status: "connected" /* Connected */,
256
+ account: selectedAccount
257
+ });
258
+ try {
259
+ config.storage.setItem(PERSIST_KEY.LAST_CONNECTOR_ID, connector.id);
260
+ console.log(`[LunoStore] Persisted connectorId: ${connector.id}`);
261
+ } catch (e) {
262
+ console.error("[LunoStore] Failed to persist connectorId to storage:", e);
263
+ }
264
+ const currentStoreChainId = get().currentChainId;
265
+ const chainIdToSet = targetChainId || currentStoreChainId || config.chains[0]?.genesisHash;
266
+ if (chainIdToSet) {
267
+ const newChain = config.chains.find((c) => c.genesisHash === chainIdToSet);
268
+ if (newChain) {
269
+ if (chainIdToSet !== currentStoreChainId || !get().currentApi) {
270
+ set({
271
+ currentChainId: chainIdToSet,
272
+ currentChain: newChain,
273
+ currentApi: void 0
274
+ });
275
+ }
276
+ try {
277
+ config.storage.setItem(PERSIST_KEY.LAST_CHAIN_ID, chainIdToSet);
278
+ console.log(`[LunoStore] Persisted chainId: ${chainIdToSet}`);
279
+ } catch (e) {
280
+ console.error("[LunoStore] Failed to persist chainId to storage:", e);
281
+ }
282
+ } else {
283
+ console.warn(`[LunoStore] After connection, target chain ID "${chainIdToSet}" was not found in config. Current chain state might not have changed. Not persisting chainId.`);
284
+ }
285
+ } else {
286
+ console.warn(`[LunoStore] Could not determine target chain ID after connection. Please check config.`);
287
+ }
288
+ } catch (err) {
289
+ cleanupActiveConnectorListeners();
290
+ set({
291
+ status: "disconnected" /* Disconnected */,
292
+ activeConnector: void 0,
293
+ accounts: []
294
+ });
295
+ throw new Error(`[LunoStore] Error connecting with ${connector.name}: ${err?.message || err}`);
296
+ }
297
+ },
298
+ disconnect: async () => {
299
+ const { activeConnector, status, config } = get();
300
+ if (!activeConnector || status === "disconnecting" /* Disconnecting */ || status === "disconnected" /* Disconnected */) {
301
+ console.log("[LunoStore] No active connector or already disconnected/disconnecting. Disconnect action aborted.");
302
+ return;
303
+ }
304
+ set({ status: "disconnecting" /* Disconnecting */ });
305
+ try {
306
+ await activeConnector.disconnect();
307
+ if (config) {
308
+ try {
309
+ console.log("[LunoStore] Attempting to remove persisted connection info due to user disconnect action...");
310
+ await config.storage.removeItem(PERSIST_KEY.LAST_CONNECTOR_ID);
311
+ await config.storage.removeItem(PERSIST_KEY.LAST_CHAIN_ID);
312
+ await config.storage.removeItem(PERSIST_KEY.LAST_SELECTED_ACCOUNT_INFO);
313
+ console.log("[LunoStore] Removed persisted connection info from storage.");
314
+ } catch (e) {
315
+ console.error("[LunoStore] Failed to remove connection info from storage during disconnect action:", e);
316
+ }
317
+ }
318
+ cleanupActiveConnectorListeners();
319
+ set({ status: "disconnected" /* Disconnected */, activeConnector: void 0, accounts: [], account: void 0 });
320
+ if (get().status !== "disconnected" /* Disconnected */) {
321
+ console.warn("[LunoStore] disconnect method called, but status is not yet 'disconnected' (event handler might be delayed or did not fire). Check connector events.");
322
+ }
323
+ } catch (err) {
324
+ set({ status: "connected" /* Connected */ });
325
+ throw new Error(`[LunoStore] Error disconnecting from ${activeConnector.name}: ${err?.message || err}`);
326
+ }
327
+ },
328
+ switchChain: async (newChainId) => {
329
+ const { config, currentChainId, currentApi, activeConnector, account, accounts } = get();
330
+ if (!config) {
331
+ throw new Error("[LunoStore] LunoConfig has not been initialized. Cannot switch chain.");
332
+ }
333
+ if (newChainId === currentChainId) {
334
+ console.log(`[LunoStore] Already on chain ${newChainId}. No switch needed.`);
335
+ return;
336
+ }
337
+ const newChain = config.chains.find((c) => c.genesisHash === newChainId);
338
+ if (!newChain) {
339
+ throw new Error(`[LunoStore] Chain with ID "${newChainId}" not found in LunoConfig.`);
340
+ }
341
+ const prevAccountIndex = accounts.findIndex((acc) => acc.address === account.address);
342
+ const newAccounts = await activeConnector.updateAccountsForChain(newChainId);
343
+ set({ accounts: newAccounts, account: newAccounts[prevAccountIndex] });
344
+ try {
345
+ try {
346
+ if (currentApi && currentApi.status === "connected") {
347
+ await currentApi.disconnect();
348
+ }
349
+ } catch (e) {
350
+ console.warn("[LunoStore] Failed to disconnect from previous chain:", e);
351
+ }
352
+ console.log(`[LunoStore] Attempting to switch chain to ${newChain.name} (ID: ${newChainId})`);
353
+ set({
354
+ currentChainId: newChainId,
355
+ currentChain: newChain,
356
+ currentApi: void 0,
357
+ isApiReady: false,
358
+ apiError: null
359
+ });
360
+ const newApi = await createApi({ config, chainId: newChainId });
361
+ set({
362
+ currentApi: newApi,
363
+ isApiReady: true
364
+ });
365
+ await config.storage.setItem(PERSIST_KEY.LAST_CHAIN_ID, newChainId);
366
+ } catch (e) {
367
+ set({
368
+ apiError: e,
369
+ isApiReady: false
370
+ });
371
+ }
372
+ },
373
+ _setApiError: (err) => {
374
+ set({ apiError: err });
375
+ }
376
+ }));
377
+ var LunoContext = React.createContext({});
378
+ var useIsInitialized = () => {
379
+ const isInitialized = useRef(false);
380
+ return {
381
+ isInitialized: isInitialized.current,
382
+ markAsInitialized: () => {
383
+ isInitialized.current = true;
384
+ }
385
+ };
386
+ };
387
+ var LunoProvider = ({ config: configFromProps, children }) => {
388
+ const {
389
+ _setConfig,
390
+ _setApi,
391
+ _setIsApiReady,
392
+ _setApiError,
393
+ setAccount,
394
+ currentChainId,
395
+ config: configInStore,
396
+ currentApi,
397
+ connect,
398
+ status,
399
+ activeConnector,
400
+ accounts,
401
+ account,
402
+ currentChain,
403
+ isApiReady,
404
+ apiError,
405
+ disconnect,
406
+ switchChain
407
+ } = useLunoStore();
408
+ const { markAsInitialized, isInitialized } = useIsInitialized();
409
+ const clearApiState = useCallback(() => {
410
+ _setApi(void 0);
411
+ _setIsApiReady(false);
412
+ }, [_setApi, _setIsApiReady]);
413
+ useEffect(() => {
414
+ if (configFromProps) {
415
+ console.log("[LunoProvider] Setting config to store:", configFromProps);
416
+ _setConfig(configFromProps);
417
+ }
418
+ }, [configFromProps]);
419
+ useEffect(() => {
420
+ if (isInitialized) return;
421
+ if (!configFromProps || !currentChainId) {
422
+ if (currentApi && currentApi.status === "connected") {
423
+ currentApi.disconnect().catch(console.error);
424
+ }
425
+ clearApiState();
426
+ return;
427
+ }
428
+ const chainConfig = configFromProps.chains.find(
429
+ (c) => c.genesisHash === currentChainId
430
+ );
431
+ const transportConfig = configFromProps.transports[currentChainId];
432
+ if (!chainConfig || !transportConfig) {
433
+ if (currentApi && currentApi.status === "connected") {
434
+ currentApi.disconnect().catch(console.error);
435
+ }
436
+ clearApiState();
437
+ return;
438
+ }
439
+ if (currentApi && currentApi.status === "connected") {
440
+ console.log("[LunoProvider]: Disconnecting API from previous render cycle:", currentApi.runtimeVersion.specName);
441
+ currentApi.disconnect().catch((e) => console.error("[LunoProvider] Error disconnecting previous API:", e));
442
+ }
443
+ clearApiState();
444
+ createApi({ config: configFromProps, chainId: currentChainId }).then((api) => {
445
+ _setApi(api);
446
+ _setIsApiReady(true);
447
+ }).catch((e) => {
448
+ clearApiState();
449
+ _setApiError(e);
450
+ }).finally(() => markAsInitialized());
451
+ }, [configFromProps, currentChainId]);
452
+ useEffect(() => {
453
+ const performAutoConnect = async () => {
454
+ if (!configFromProps.autoConnect) {
455
+ console.log("[LunoProvider]: AutoConnect disabled or config not set.");
456
+ return;
457
+ }
458
+ if (!configFromProps.storage) {
459
+ console.warn("[LunoProvider]: AutoConnect Storage not available, cannot auto-connect.");
460
+ return;
461
+ }
462
+ try {
463
+ const lastConnectorId = await configFromProps.storage.getItem(PERSIST_KEY.LAST_CONNECTOR_ID);
464
+ const lastChainId = await configFromProps.storage.getItem(PERSIST_KEY.LAST_CHAIN_ID);
465
+ if (lastConnectorId && lastChainId) {
466
+ console.log(`[LunoProvider]: AutoConnect Found persisted session: Connector ID "${lastConnectorId}", Chain ID "${lastChainId}"`);
467
+ await connect(lastConnectorId, lastChainId);
468
+ } else {
469
+ console.log("[LunoProvider]: AutoConnect No persisted session found or missing data.");
470
+ }
471
+ } catch (error) {
472
+ console.error("[LunoProvider]: AutoConnect Error during auto-connect process:", error);
473
+ }
474
+ };
475
+ if (configFromProps) {
476
+ performAutoConnect();
477
+ }
478
+ }, [configFromProps]);
479
+ useEffect(() => {
480
+ if (isApiReady && currentApi && currentChain && currentChain.ss58Format !== void 0 && currentChain.ss58Format !== null) {
481
+ try {
482
+ const apiSs58 = currentApi.consts.system.ss58Prefix;
483
+ if (apiSs58 !== null && apiSs58 !== void 0 && apiSs58 !== currentChain.ss58Format) {
484
+ console.error(
485
+ `[LunoProvider]: SS58 Format Mismatch for chain "${currentChain.name}" (genesisHash: ${currentChain.genesisHash}):
486
+ - Configured SS58Format: ${currentChain.ss58Format}
487
+ - Node Runtime SS58Format: ${apiSs58}
488
+ Please verify your Luno configuration for this chain to ensure correct address display and interaction.`
489
+ );
490
+ } else if (apiSs58 === null || apiSs58 === void 0) {
491
+ console.warn(
492
+ `[LunoProvider]: Could not determine SS58 format from the API for chain "${currentChain.name}". Cannot validate configured SS58Format (${currentChain.ss58Format}). The application will use the configured value.`
493
+ );
494
+ }
495
+ } catch (e) {
496
+ console.error(
497
+ `[LunoProvider]: Error retrieving SS58 format from API for chain "${currentChain.name}" while attempting validation:`,
498
+ e
499
+ );
500
+ }
501
+ }
502
+ }, [isApiReady, currentApi, currentChain]);
503
+ const contextValue = useMemo(() => ({
504
+ config: configInStore,
505
+ status,
506
+ activeConnector,
507
+ accounts,
508
+ account,
509
+ setAccount,
510
+ currentChainId,
511
+ currentChain,
512
+ currentApi,
513
+ isApiReady,
514
+ connect,
515
+ disconnect,
516
+ switchChain,
517
+ apiError
518
+ }), [
519
+ configInStore,
520
+ status,
521
+ activeConnector,
522
+ accounts,
523
+ account,
524
+ currentChainId,
525
+ currentChain,
526
+ currentApi,
527
+ isApiReady,
528
+ apiError,
529
+ connect,
530
+ disconnect,
531
+ switchChain,
532
+ setAccount
533
+ ]);
534
+ return /* @__PURE__ */ jsx(LunoContext.Provider, { value: contextValue, children });
535
+ };
536
+ var useLuno = () => {
537
+ const context = useContext(LunoContext);
538
+ if (context === void 0) {
539
+ throw new Error("useLuno must be used within a LunoProvider");
540
+ }
541
+ return context;
542
+ };
543
+
544
+ // src/hooks/useApi.ts
545
+ var useApi = () => {
546
+ const { currentApi, isApiReady, apiError } = useLuno();
547
+ return {
548
+ api: currentApi,
549
+ isApiReady,
550
+ apiError
551
+ };
552
+ };
553
+ var useAccount = () => {
554
+ const { account, currentChain } = useLuno();
555
+ const formattedAccount = useMemo(() => {
556
+ if (!account) return;
557
+ if (!currentChain || currentChain?.ss58Format === void 0 || !account?.publicKey) return account;
558
+ try {
559
+ const newAddress = convertAddress(account.address, currentChain.ss58Format);
560
+ return {
561
+ ...account,
562
+ address: newAddress
563
+ };
564
+ } catch (error) {
565
+ console.error(`[useAccount]: Failed to re-format address for account with publicKey ${account.publicKey}:`, error);
566
+ return { ...account };
567
+ }
568
+ }, [account, currentChain, currentChain?.ss58Format]);
569
+ return {
570
+ account: formattedAccount,
571
+ address: formattedAccount?.address
572
+ };
573
+ };
574
+ var useAccounts = () => {
575
+ const { accounts, setAccount, currentChain } = useLuno();
576
+ const formattedAccounts = useMemo(() => {
577
+ if (!currentChain || currentChain?.ss58Format === void 0) return accounts ?? [];
578
+ return (accounts || []).map((acc) => {
579
+ if (!acc.publicKey) {
580
+ console.warn(`[useAccounts]: Account ${acc.name || acc.address} is missing publicKey. Cannot re-format address.`);
581
+ return acc;
582
+ }
583
+ try {
584
+ const newAddress = convertAddress(acc.address, currentChain.ss58Format);
585
+ return {
586
+ ...acc,
587
+ address: newAddress
588
+ };
589
+ } catch (error) {
590
+ console.error(`[useAccounts]: Failed to re-format address for account with publicKey ${acc.publicKey}:`, error);
591
+ return { ...acc };
592
+ }
593
+ });
594
+ }, [accounts, currentChain, currentChain?.ss58Format]);
595
+ return { accounts: formattedAccounts, selectAccount: setAccount };
596
+ };
597
+
598
+ // src/hooks/useActiveConnector.ts
599
+ var useActiveConnector = () => {
600
+ const { activeConnector } = useLuno();
601
+ return activeConnector;
602
+ };
603
+ var defaultTransform = (data) => data;
604
+ var useSubscription = ({ queryKey: userQueryKey, factory, params, options = {} }) => {
605
+ const [error, setError] = useState(void 0);
606
+ const { currentApi, isApiReady } = useLuno();
607
+ const queryClient = useQueryClient();
608
+ const {
609
+ enabled = true,
610
+ transform = defaultTransform,
611
+ defaultValue
612
+ } = options;
613
+ const isSubscribed = useRef(false);
614
+ const resolvedParams = useMemo(() => {
615
+ if (!params || !currentApi || !isApiReady) return void 0;
616
+ return typeof params === "function" ? [params(currentApi)] : params;
617
+ }, [params, currentApi, isApiReady]);
618
+ const queryKey = useMemo(() => [
619
+ userQueryKey,
620
+ resolvedParams,
621
+ currentApi?.genesisHash
622
+ ], [userQueryKey, resolvedParams, currentApi?.genesisHash]);
623
+ useEffect(() => {
624
+ if (!enabled || !factory || !currentApi || !resolvedParams || !isApiReady || isSubscribed.current) {
625
+ return;
626
+ }
627
+ let unsubscribe = null;
628
+ isSubscribed.current = true;
629
+ try {
630
+ const factoryFn = factory(currentApi);
631
+ const boundFn = typeof factoryFn === "function" ? factoryFn.bind(currentApi) : factoryFn;
632
+ const callback = (result) => {
633
+ try {
634
+ const transformedData = transform(result);
635
+ queryClient.setQueryData(queryKey, transformedData);
636
+ setError(void 0);
637
+ } catch (err) {
638
+ setError(new Error(`[useSubscription]: ${err}`));
639
+ }
640
+ };
641
+ boundFn(...resolvedParams, callback).then((unsub) => {
642
+ unsubscribe = unsub;
643
+ }).catch((err) => {
644
+ setError(new Error(`[useSubscription]: ${err}`));
645
+ });
646
+ } catch (err) {
647
+ setError(new Error(`[useSubscription]: ${err}`));
648
+ }
649
+ return () => {
650
+ if (unsubscribe) {
651
+ unsubscribe();
652
+ isSubscribed.current = false;
653
+ setError(void 0);
654
+ }
655
+ };
656
+ }, [JSON.stringify(queryKey), enabled, queryClient]);
657
+ const { data, isLoading } = useQuery({
658
+ queryKey,
659
+ queryFn: () => {
660
+ return Promise.resolve(defaultValue);
661
+ },
662
+ enabled: false,
663
+ initialData: defaultValue
664
+ });
665
+ return {
666
+ data,
667
+ error,
668
+ isLoading: !!(enabled && isApiReady && !data)
669
+ };
670
+ };
671
+ var DEFAULT_TOKEN_DECIMALS = 10;
672
+ var transformBalance = (results, chainProperties) => {
673
+ const accountInfo = results[0];
674
+ const locks = results[1];
675
+ const free = accountInfo.data.free;
676
+ const reserved = accountInfo.data.reserved;
677
+ const frozen = accountInfo.data.frozen;
678
+ const total = BigInt(free) + BigInt(reserved);
679
+ const transferable = free > frozen ? BigInt(free) - BigInt(frozen) : 0n;
680
+ return {
681
+ free,
682
+ total,
683
+ reserved,
684
+ transferable,
685
+ formattedTransferable: formatBalance(transferable, chainProperties.tokenDecimals),
686
+ formattedTotal: formatBalance(total, chainProperties.tokenDecimals),
687
+ locks: locks.map((lock) => ({
688
+ id: lock.id,
689
+ amount: lock.amount,
690
+ reason: lock.reasons,
691
+ lockHuman: formatBalance(lock.amount, chainProperties.tokenDecimals)
692
+ }))
693
+ };
694
+ };
695
+ var useBalance = ({ address }) => {
696
+ const { currentApi, isApiReady, currentChain } = useLuno();
697
+ return useSubscription({
698
+ queryKey: "/native-balance",
699
+ factory: (api) => api.queryMulti,
700
+ params: (api) => [
701
+ { fn: api.query.system.account, args: [address] },
702
+ { fn: api.query.balances.locks, args: [address] }
703
+ ],
704
+ options: {
705
+ enabled: !!currentApi && isApiReady && !!address,
706
+ transform: (results) => {
707
+ const chainProperties = {
708
+ tokenDecimals: currentChain?.nativeCurrency?.decimals ?? DEFAULT_TOKEN_DECIMALS,
709
+ tokenSymbol: currentChain?.nativeCurrency?.symbol,
710
+ ss58Format: currentChain?.ss58Format
711
+ };
712
+ return transformBalance(results, chainProperties);
713
+ }
714
+ }
715
+ });
716
+ };
717
+
718
+ // src/hooks/useBlockNumber.ts
719
+ var useBlockNumber = () => {
720
+ const { currentApi, isApiReady } = useLuno();
721
+ const transform = (blockNumberBn) => {
722
+ return blockNumberBn;
723
+ };
724
+ return useSubscription({
725
+ queryKey: "/block-number",
726
+ factory: (api) => api.query.system.number,
727
+ params: [],
728
+ options: {
729
+ enabled: !!currentApi && isApiReady,
730
+ transform
731
+ }
732
+ });
733
+ };
734
+
735
+ // src/hooks/useChain.ts
736
+ var useChain = () => {
737
+ const { currentChain, currentChainId } = useLuno();
738
+ return {
739
+ chain: currentChain,
740
+ chainId: currentChainId
741
+ };
742
+ };
743
+
744
+ // src/hooks/useChains.ts
745
+ var useChains = () => {
746
+ const { config } = useLuno();
747
+ return config?.chains ? [...config.chains] : [];
748
+ };
749
+
750
+ // src/hooks/useConnectors.ts
751
+ var useConnectors = () => {
752
+ const { config } = useLuno();
753
+ return config?.connectors ? [...config.connectors] : [];
754
+ };
755
+
756
+ // src/hooks/useConfig.ts
757
+ var useConfig = () => {
758
+ const { config } = useLuno();
759
+ return config;
760
+ };
761
+ function useLunoMutation(mutationFn, hookLevelOptions) {
762
+ const tanstackMutationHookOptions = {};
763
+ if (hookLevelOptions?.onSuccess) {
764
+ tanstackMutationHookOptions.onSuccess = hookLevelOptions.onSuccess;
765
+ }
766
+ if (hookLevelOptions?.onError) {
767
+ tanstackMutationHookOptions.onError = hookLevelOptions.onError;
768
+ }
769
+ if (hookLevelOptions?.onSettled) {
770
+ tanstackMutationHookOptions.onSettled = hookLevelOptions.onSettled;
771
+ }
772
+ const mutation = useMutation({
773
+ mutationFn,
774
+ retry: false,
775
+ throwOnError: false,
776
+ ...tanstackMutationHookOptions
777
+ });
778
+ return {
779
+ mutate: (variables, callTimeOptions) => {
780
+ mutation.mutate(variables, callTimeOptions);
781
+ },
782
+ mutateAsync: (variables, callTimeOptions) => {
783
+ return mutation.mutateAsync(variables, callTimeOptions);
784
+ },
785
+ data: mutation.data,
786
+ error: mutation.error,
787
+ isError: mutation.isError,
788
+ isIdle: mutation.isIdle,
789
+ isPending: mutation.isPending,
790
+ isSuccess: mutation.isSuccess,
791
+ reset: mutation.reset,
792
+ status: mutation.status,
793
+ variables: mutation.variables
794
+ };
795
+ }
796
+
797
+ // src/hooks/useConnect.ts
798
+ var useConnect = (hookLevelConfig) => {
799
+ const { connect, config, activeConnector, status } = useLuno();
800
+ const connectFn = async (variables) => {
801
+ await connect(variables.connectorId, variables.targetChainId);
802
+ };
803
+ const mutationResult = useLunoMutation(connectFn, hookLevelConfig);
804
+ return {
805
+ connect: mutationResult.mutate,
806
+ connectAsync: mutationResult.mutateAsync,
807
+ connectors: config?.connectors ? [...config.connectors] : [],
808
+ activeConnector,
809
+ status,
810
+ data: mutationResult.data,
811
+ error: mutationResult.error,
812
+ isError: mutationResult.isError,
813
+ isIdle: mutationResult.isIdle,
814
+ isPending: mutationResult.isPending,
815
+ isSuccess: mutationResult.isSuccess,
816
+ reset: mutationResult.reset,
817
+ variables: mutationResult.variables
818
+ };
819
+ };
820
+
821
+ // src/hooks/useDisconnect.ts
822
+ var useDisconnect = (hookLevelConfig) => {
823
+ const { disconnect, status } = useLuno();
824
+ const disconnectFn = async () => {
825
+ await disconnect();
826
+ };
827
+ const mutationResult = useLunoMutation(disconnectFn, hookLevelConfig);
828
+ return {
829
+ disconnect: (options) => mutationResult.mutate(void 0, options),
830
+ disconnectAsync: (options) => mutationResult.mutateAsync(void 0, options),
831
+ status,
832
+ data: mutationResult.data,
833
+ error: mutationResult.error,
834
+ isError: mutationResult.isError,
835
+ isIdle: mutationResult.isIdle,
836
+ isPending: mutationResult.isPending,
837
+ isSuccess: mutationResult.isSuccess,
838
+ reset: mutationResult.reset,
839
+ variables: mutationResult.variables
840
+ };
841
+ };
842
+ var useGenesisHash = () => {
843
+ const { currentApi, currentChainId, isApiReady } = useLuno();
844
+ const { data, isLoading, error } = useQuery({
845
+ queryKey: ["/genesis-hash", currentChainId],
846
+ queryFn: async () => {
847
+ return await currentApi.rpc.chain_getBlockHash(0);
848
+ },
849
+ enabled: !!currentApi && isApiReady && !!currentChainId,
850
+ staleTime: Infinity,
851
+ gcTime: Infinity,
852
+ retry: false
853
+ });
854
+ return { data, isLoading, error };
855
+ };
856
+ var useRuntimeVersion = () => {
857
+ const { currentApi, isApiReady, currentChainId } = useLuno();
858
+ return useQuery({
859
+ queryKey: ["luno", "runtimeVersion", currentChainId],
860
+ queryFn: async () => {
861
+ return await currentApi.getRuntimeVersion();
862
+ },
863
+ enabled: !!currentApi && isApiReady && !!currentChainId
864
+ });
865
+ };
866
+ function useSendTransaction(hookLevelConfig) {
867
+ const { account, activeConnector, currentApi, isApiReady } = useLuno();
868
+ const [txStatus, setTxStatus] = useState("idle");
869
+ const [detailedTxStatus, setDetailedTxStatus] = useState("idle");
870
+ const [txError, setTxError] = useState(null);
871
+ const sendTransactionFn = useCallback(async (variables) => {
872
+ if (!currentApi || !isApiReady) {
873
+ throw new Error("[useSendTransaction]: Polkadot API is not ready.");
874
+ }
875
+ if (!activeConnector) {
876
+ throw new Error("[useSendTransaction]: No active connector found.");
877
+ }
878
+ if (!account || !account.address || !account.meta?.source) {
879
+ throw new Error(
880
+ "[useSendTransaction]: No active account, address, or account metadata (source) found."
881
+ );
882
+ }
883
+ if (!variables.extrinsic) {
884
+ throw new Error("[useSendTransaction]: No extrinsic provided to send.");
885
+ }
886
+ const signer = await activeConnector.getSigner();
887
+ if (!signer) {
888
+ throw new Error("[useSendTransaction]: Could not retrieve signer from the injector.");
889
+ }
890
+ setTxStatus("signing");
891
+ setDetailedTxStatus("idle");
892
+ return new Promise((resolve, reject) => {
893
+ let unsubscribe;
894
+ variables.extrinsic.signAndSend(
895
+ account.address,
896
+ { signer },
897
+ ({ status, dispatchError, events, dispatchInfo, txHash, txIndex }) => {
898
+ const resolveAndUnsubscribe = (receipt) => {
899
+ if (unsubscribe) unsubscribe();
900
+ resolve(receipt);
901
+ };
902
+ const rejectAndUnsubscribe = (error) => {
903
+ if (unsubscribe) unsubscribe();
904
+ setTxError(error);
905
+ reject(error);
906
+ };
907
+ switch (status.type) {
908
+ case "Broadcasting":
909
+ setDetailedTxStatus("broadcasting");
910
+ break;
911
+ case "BestChainBlockIncluded":
912
+ setDetailedTxStatus("inBlock");
913
+ break;
914
+ case "Finalized":
915
+ setTxStatus("success");
916
+ setDetailedTxStatus("finalized");
917
+ if (dispatchError) {
918
+ resolveAndUnsubscribe({
919
+ transactionHash: txHash,
920
+ blockHash: status.value?.blockHash,
921
+ blockNumber: status.value?.blockNumber,
922
+ events,
923
+ status: "failed",
924
+ dispatchError,
925
+ errorMessage: getReadableDispatchError(currentApi, dispatchError),
926
+ dispatchInfo
927
+ });
928
+ } else {
929
+ resolveAndUnsubscribe({
930
+ transactionHash: txHash,
931
+ blockHash: status.value?.blockHash,
932
+ blockNumber: status.value?.blockNumber,
933
+ events,
934
+ status: "success",
935
+ dispatchError: void 0,
936
+ errorMessage: void 0,
937
+ dispatchInfo
938
+ });
939
+ }
940
+ break;
941
+ case "Invalid":
942
+ setTxStatus("failed");
943
+ setDetailedTxStatus("invalid");
944
+ rejectAndUnsubscribe(new Error(`Transaction invalid: ${txHash}`));
945
+ break;
946
+ case "Drop":
947
+ setTxStatus("failed");
948
+ setDetailedTxStatus("dropped");
949
+ rejectAndUnsubscribe(new Error(`Transaction dropped: ${txHash}`));
950
+ break;
951
+ }
952
+ }
953
+ ).then((unsub) => {
954
+ unsubscribe = unsub;
955
+ }).catch((error) => {
956
+ setTxStatus("failed");
957
+ console.error("[useSendTransaction]: Error in signAndSend promise:", error?.message || error);
958
+ setTxError(error);
959
+ reject(error);
960
+ });
961
+ });
962
+ }, [currentApi, isApiReady, activeConnector, account, setTxStatus, setDetailedTxStatus]);
963
+ const mutationResult = useLunoMutation(sendTransactionFn, hookLevelConfig);
964
+ return {
965
+ sendTransaction: mutationResult.mutate,
966
+ sendTransactionAsync: mutationResult.mutateAsync,
967
+ data: mutationResult.data,
968
+ error: txError || mutationResult.error,
969
+ isError: Boolean(txError) || mutationResult.isError,
970
+ isIdle: mutationResult.isIdle,
971
+ isPending: mutationResult.isPending,
972
+ isSuccess: mutationResult.isSuccess,
973
+ reset: mutationResult.reset,
974
+ status: mutationResult.status,
975
+ variables: mutationResult.variables,
976
+ txStatus,
977
+ detailedStatus: detailedTxStatus
978
+ };
979
+ }
980
+ function useSendTransactionHash(hookLevelConfig) {
981
+ const { account, activeConnector, currentApi, isApiReady } = useLuno();
982
+ const [txError, setTxError] = useState(null);
983
+ const sendTransactionFn = useCallback(async (variables) => {
984
+ if (!currentApi || !isApiReady) {
985
+ throw new Error("[useSendTransactionHash]: Polkadot API is not ready.");
986
+ }
987
+ if (!activeConnector) {
988
+ throw new Error("[useSendTransactionHash]: No active connector found.");
989
+ }
990
+ if (!account || !account.address || !account.meta?.source) {
991
+ throw new Error(
992
+ "[useSendTransactionHash]: No active account, address, or account metadata (source) found."
993
+ );
994
+ }
995
+ if (!variables.extrinsic) {
996
+ throw new Error("[useSendTransactionHash]: No extrinsic provided to send.");
997
+ }
998
+ const signer = await activeConnector.getSigner();
999
+ if (!signer) {
1000
+ throw new Error("[useSendTransactionHash]: Could not retrieve signer from the injector.");
1001
+ }
1002
+ try {
1003
+ const txHash = await variables.extrinsic.signAndSend(account.address, { signer }).catch((e) => {
1004
+ throw e;
1005
+ });
1006
+ return txHash;
1007
+ } catch (error) {
1008
+ setTxError(error);
1009
+ throw error;
1010
+ }
1011
+ }, [currentApi, isApiReady, activeConnector, account]);
1012
+ const mutationResult = useLunoMutation(sendTransactionFn, hookLevelConfig);
1013
+ return {
1014
+ sendTransaction: mutationResult.mutate,
1015
+ sendTransactionAsync: mutationResult.mutateAsync,
1016
+ data: mutationResult.data,
1017
+ error: txError || mutationResult.error,
1018
+ isError: Boolean(txError) || mutationResult.isError,
1019
+ isIdle: mutationResult.isIdle,
1020
+ isPending: mutationResult.isPending,
1021
+ isSuccess: mutationResult.isSuccess,
1022
+ reset: mutationResult.reset,
1023
+ status: mutationResult.status,
1024
+ variables: mutationResult.variables
1025
+ };
1026
+ }
1027
+
1028
+ // src/hooks/useSignMessage.ts
1029
+ function useSignMessage(hookLevelConfig) {
1030
+ const { activeConnector, account, accounts } = useLuno();
1031
+ const mutationFn = async (variables) => {
1032
+ if (!activeConnector) {
1033
+ throw new Error("[useSignMessage]: No active connector found to sign the message.");
1034
+ }
1035
+ if (!account || !account.address || !account.meta?.source) {
1036
+ throw new Error("[useSignMessage]: No address provided for signing.");
1037
+ }
1038
+ if (!accounts.some((acc) => acc.address === account.address)) {
1039
+ throw new Error(`[useSignMessage]: Address ${account.address} is not managed by ${activeConnector.id}.`);
1040
+ }
1041
+ if (!variables.message) {
1042
+ throw new Error("[useSignMessage]: No message provided for signing.");
1043
+ }
1044
+ const signatureString = await activeConnector.signMessage(
1045
+ variables.message,
1046
+ account.address
1047
+ );
1048
+ if (!signatureString) {
1049
+ throw new Error(
1050
+ "[useSignMessage]: Signature was not obtained. The user may have cancelled the request or the connector failed."
1051
+ );
1052
+ }
1053
+ return {
1054
+ signature: signatureString,
1055
+ rawMessage: variables.message,
1056
+ addressUsed: account.address
1057
+ };
1058
+ };
1059
+ const mutationResult = useLunoMutation(mutationFn, hookLevelConfig);
1060
+ return {
1061
+ signMessage: mutationResult.mutate,
1062
+ signMessageAsync: mutationResult.mutateAsync,
1063
+ data: mutationResult.data,
1064
+ error: mutationResult.error,
1065
+ isError: mutationResult.isError,
1066
+ isIdle: mutationResult.isIdle,
1067
+ isPending: mutationResult.isPending,
1068
+ isSuccess: mutationResult.isSuccess,
1069
+ reset: mutationResult.reset,
1070
+ status: mutationResult.status,
1071
+ variables: mutationResult.variables
1072
+ };
1073
+ }
1074
+ var DEFAULT_SS58_FORMAT = 42;
1075
+ var useSs58Format = () => {
1076
+ const { currentApi, isApiReady, currentChain } = useLuno();
1077
+ const configuredSs58Fallback = currentChain?.ss58Format !== void 0 ? currentChain.ss58Format : DEFAULT_SS58_FORMAT;
1078
+ return useMemo(() => {
1079
+ if (currentApi && isApiReady) {
1080
+ let ss58 = void 0;
1081
+ try {
1082
+ const format = currentApi.consts.system.ss58Prefix;
1083
+ ss58 = isNumber(format) ? format : DEFAULT_SS58_FORMAT;
1084
+ } catch (e) {
1085
+ console.error("[useSs58Format] Error fetching chainSS58:", e);
1086
+ ss58 = configuredSs58Fallback;
1087
+ }
1088
+ return { data: ss58, isLoading: false };
1089
+ } else {
1090
+ return { data: void 0, isLoading: true };
1091
+ }
1092
+ }, [currentApi, isApiReady, configuredSs58Fallback]);
1093
+ };
1094
+
1095
+ // src/hooks/useStatus.ts
1096
+ var useStatus = () => {
1097
+ const { status } = useLuno();
1098
+ return status;
1099
+ };
1100
+
1101
+ // src/hooks/useSwitchChain.ts
1102
+ var useSwitchChain = (hookLevelConfig) => {
1103
+ const { switchChain: storeSwitchChain, config, currentChain, currentChainId } = useLuno();
1104
+ const switchChainFn = async (variables) => {
1105
+ await storeSwitchChain(variables.chainId);
1106
+ };
1107
+ const mutationResult = useLunoMutation(switchChainFn, hookLevelConfig);
1108
+ return {
1109
+ switchChain: mutationResult.mutate,
1110
+ switchChainAsync: mutationResult.mutateAsync,
1111
+ chains: config?.chains ? [...config.chains] : [],
1112
+ currentChain,
1113
+ currentChainId,
1114
+ data: mutationResult.data,
1115
+ error: mutationResult.error,
1116
+ isError: mutationResult.isError,
1117
+ isIdle: mutationResult.isIdle,
1118
+ isPending: mutationResult.isPending,
1119
+ isSuccess: mutationResult.isSuccess,
1120
+ reset: mutationResult.reset,
1121
+ variables: mutationResult.variables
1122
+ };
1123
+ };
1124
+ var useSigner = () => {
1125
+ const { activeConnector } = useLuno();
1126
+ const { account } = useAccount();
1127
+ const [signer, setSigner] = useState(void 0);
1128
+ const [isLoading, setIsLoading] = useState(false);
1129
+ useEffect(() => {
1130
+ if (!activeConnector || !account?.address) {
1131
+ setSigner(void 0);
1132
+ setIsLoading(false);
1133
+ return;
1134
+ }
1135
+ setIsLoading(true);
1136
+ activeConnector.getSigner().then((signer2) => setSigner(signer2)).catch(() => setSigner(void 0)).finally(() => setIsLoading(false));
1137
+ }, [activeConnector, account?.address]);
1138
+ return { signer, isLoading };
1139
+ };
1140
+
1141
+ export { ConnectionStatus, LunoProvider, useAccount, useAccounts, useActiveConnector, useApi, useBalance, useBlockNumber, useChain, useChains, useConfig, useConnect, useConnectors, useDisconnect, useGenesisHash, useRuntimeVersion, useSendTransaction, useSendTransactionHash, useSignMessage, useSigner, useSs58Format, useStatus, useSubscription, useSwitchChain };
1142
+ //# sourceMappingURL=index.js.map
1143
+ //# sourceMappingURL=index.js.map