@luno-kit/react 0.0.6 → 0.0.8

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.cts CHANGED
@@ -1,9 +1,9 @@
1
- import React, { ReactNode } from 'react';
2
- import { Config, Account, Connector, AccountBalance, Chain, Signer } from '@luno-kit/core';
3
1
  export * from '@luno-kit/core';
2
+ import React, { ReactNode } from 'react';
3
+ import { Config, Account, HexString, Connector, AccountBalance, Chain, PapiSigner, Signer } from '@luno-kit/core/types';
4
4
  import { LegacyClient, SubstrateRuntimeVersion } from 'dedot';
5
- import { HexString } from 'dedot/utils';
6
- import { GenericStorageQuery, Callback, IEventRecord, ISubmittableExtrinsic } from 'dedot/types';
5
+ import { GenericStorageQuery, Callback, TxPaymentInfo, ISubmittableExtrinsic, IEventRecord } from 'dedot/types';
6
+ import { ConnectionStatus, TxStatus } from './types/index.cjs';
7
7
  import { MutateOptions, UseQueryResult } from '@tanstack/react-query';
8
8
  import { DispatchError, DispatchInfo } from 'dedot/codecs';
9
9
 
@@ -13,22 +13,6 @@ interface LunoProviderProps {
13
13
  }
14
14
  declare const LunoProvider: React.FC<LunoProviderProps>;
15
15
 
16
- declare enum ConnectionStatus {
17
- Disconnected = "disconnected",
18
- Connecting = "connecting",
19
- Disconnecting = "disconnecting",
20
- Connected = "connected"
21
- }
22
-
23
- type TxStatus = 'idle' | 'signing' | 'pending' | 'success' | 'failed';
24
-
25
- interface UseApiResult {
26
- api?: LegacyClient;
27
- isApiReady: boolean;
28
- apiError: Error | null;
29
- }
30
- declare const useApi: () => UseApiResult;
31
-
32
16
  interface UseAccountResult {
33
17
  account?: Account;
34
18
  address?: string;
@@ -43,6 +27,13 @@ declare const useAccounts: () => UseAccountsResult;
43
27
 
44
28
  declare const useActiveConnector: () => Connector | undefined;
45
29
 
30
+ interface UseApiResult {
31
+ api?: LegacyClient;
32
+ isApiReady: boolean;
33
+ apiError: Error | null;
34
+ }
35
+ declare const useApi: () => UseApiResult;
36
+
46
37
  type SubscriptionFn<TArgs extends any[], TData> = (...params: [...TArgs, Callback<TData>]) => Promise<() => Promise<void>>;
47
38
  interface UseSubscriptionOptions<TData, TTransformed = TData> {
48
39
  enabled?: boolean;
@@ -65,7 +56,7 @@ interface UseSubscriptionResult<TTransformed> {
65
56
  error?: Error;
66
57
  isLoading: boolean;
67
58
  }
68
- declare const useSubscription: <TArgs extends any[], TData, TTransformed = TData>({ queryKey: userQueryKey, factory, params, options }: UseSubscriptionProps<TArgs, TData, TTransformed>) => UseSubscriptionResult<TTransformed>;
59
+ declare const useSubscription: <TArgs extends any[], TData, TTransformed = TData>({ queryKey: userQueryKey, factory, params, options, }: UseSubscriptionProps<TArgs, TData, TTransformed>) => UseSubscriptionResult<TTransformed>;
69
60
 
70
61
  interface ChainProperties {
71
62
  ss58Format?: number;
@@ -89,8 +80,6 @@ declare const useChain: () => UseChainResult;
89
80
 
90
81
  declare const useChains: () => Chain[];
91
82
 
92
- declare const useConnectors: () => Connector[];
93
-
94
83
  declare const useConfig: () => Config | undefined;
95
84
 
96
85
  type LunoMutationOptions<TData = unknown, TError = Error, TVariables = void, TContext = unknown> = Partial<Pick<MutateOptions<TData, TError, TVariables, TContext>, 'onSuccess' | 'onError' | 'onSettled'>>;
@@ -117,6 +106,8 @@ interface UseConnectResult {
117
106
  }
118
107
  declare const useConnect: (hookLevelConfig?: UseConnectOptions) => UseConnectResult;
119
108
 
109
+ declare const useConnectors: () => Connector[];
110
+
120
111
  type UseDisconnectOptions = LunoMutationOptions<void, Error, void, unknown>;
121
112
  interface UseDisconnectResult {
122
113
  disconnect: (options?: UseDisconnectOptions) => void;
@@ -133,6 +124,16 @@ interface UseDisconnectResult {
133
124
  }
134
125
  declare const useDisconnect: (hookLevelConfig?: UseDisconnectOptions) => UseDisconnectResult;
135
126
 
127
+ interface PaymentInfo extends TxPaymentInfo {
128
+ partialFeeFormatted: string;
129
+ }
130
+ declare function useEstimatePaymentInfo(): {
131
+ data: PaymentInfo | null;
132
+ isLoading: boolean;
133
+ error: Error | null;
134
+ estimate: (extrinsic: ISubmittableExtrinsic, senderAddress?: string) => Promise<PaymentInfo | undefined>;
135
+ };
136
+
136
137
  interface UseGenesisHashResult {
137
138
  data?: HexString;
138
139
  error: Error | null;
@@ -140,6 +141,12 @@ interface UseGenesisHashResult {
140
141
  }
141
142
  declare const useGenesisHash: () => UseGenesisHashResult;
142
143
 
144
+ interface UsePapiSignerResult {
145
+ data?: PapiSigner;
146
+ isLoading: boolean;
147
+ }
148
+ declare function usePapiSigner(): UsePapiSignerResult;
149
+
143
150
  type UseRuntimeVersionResult = UseQueryResult<SubstrateRuntimeVersion, Error>;
144
151
  declare const useRuntimeVersion: () => UseRuntimeVersionResult;
145
152
 
@@ -194,6 +201,12 @@ interface UseSendTransactionHashResult {
194
201
  }
195
202
  declare function useSendTransactionHash(hookLevelConfig?: UseSendTransactionHashOptions): UseSendTransactionHashResult;
196
203
 
204
+ interface UseSignerResult {
205
+ data?: Signer;
206
+ isLoading: boolean;
207
+ }
208
+ declare const useSigner: () => UseSignerResult;
209
+
197
210
  interface SignMessageVariables {
198
211
  message: string;
199
212
  }
@@ -247,10 +260,4 @@ interface UseSwitchChainResult {
247
260
  }
248
261
  declare const useSwitchChain: (hookLevelConfig?: UseSwitchChainOptions) => UseSwitchChainResult;
249
262
 
250
- interface UseSignerResult {
251
- data?: Signer;
252
- isLoading: boolean;
253
- }
254
- declare const useSigner: () => UseSignerResult;
255
-
256
- export { type ChainProperties, type ConnectVariables, ConnectionStatus, type DetailedTxStatus, LunoProvider, type QueryMultiItem, type SendTransactionHashVariables, type SendTransactionVariables, type SignMessageData, type SignMessageVariables, type SwitchChainVariables, type TransactionReceipt, type UseAccountResult, type UseAccountsResult, type UseApiResult, type UseBalanceProps, type UseBalanceResult, type UseBlockNumberResult, type UseChainResult, type UseConnectOptions, type UseConnectResult, type UseDisconnectOptions, type UseDisconnectResult, type UseGenesisHashResult, type UseRuntimeVersionResult, type UseSendTransactionHashOptions, type UseSendTransactionHashResult, type UseSendTransactionOptions, type UseSendTransactionResult, type UseSignMessageOptions, type UseSignMessageResult, type UseSignerResult, type UseSs58FormatResult, type UseSubscriptionOptions, type UseSubscriptionProps, type UseSubscriptionResult, type UseSwitchChainOptions, type UseSwitchChainResult, useAccount, useAccounts, useActiveConnector, useApi, useBalance, useBlockNumber, useChain, useChains, useConfig, useConnect, useConnectors, useDisconnect, useGenesisHash, useRuntimeVersion, useSendTransaction, useSendTransactionHash, useSignMessage, useSigner, useSs58Format, useStatus, useSubscription, useSwitchChain };
263
+ export { type ChainProperties, type ConnectVariables, ConnectionStatus, type DetailedTxStatus, LunoProvider, type QueryMultiItem, type SendTransactionHashVariables, type SendTransactionVariables, type SignMessageData, type SignMessageVariables, type SwitchChainVariables, type TransactionReceipt, type UseAccountResult, type UseAccountsResult, type UseApiResult, type UseBalanceProps, type UseBalanceResult, type UseBlockNumberResult, type UseChainResult, type UseConnectOptions, type UseConnectResult, type UseDisconnectOptions, type UseDisconnectResult, type UseGenesisHashResult, type UsePapiSignerResult, type UseRuntimeVersionResult, type UseSendTransactionHashOptions, type UseSendTransactionHashResult, type UseSendTransactionOptions, type UseSendTransactionResult, type UseSignMessageOptions, type UseSignMessageResult, type UseSignerResult, type UseSs58FormatResult, type UseSubscriptionOptions, type UseSubscriptionProps, type UseSubscriptionResult, type UseSwitchChainOptions, type UseSwitchChainResult, useAccount, useAccounts, useActiveConnector, useApi, useBalance, useBlockNumber, useChain, useChains, useConfig, useConnect, useConnectors, useDisconnect, useEstimatePaymentInfo, useGenesisHash, usePapiSigner, useRuntimeVersion, useSendTransaction, useSendTransactionHash, useSignMessage, useSigner, useSs58Format, useStatus, useSubscription, useSwitchChain };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import React, { ReactNode } from 'react';
2
- import { Config, Account, Connector, AccountBalance, Chain, Signer } from '@luno-kit/core';
3
1
  export * from '@luno-kit/core';
2
+ import React, { ReactNode } from 'react';
3
+ import { Config, Account, HexString, Connector, AccountBalance, Chain, PapiSigner, Signer } from '@luno-kit/core/types';
4
4
  import { LegacyClient, SubstrateRuntimeVersion } from 'dedot';
5
- import { HexString } from 'dedot/utils';
6
- import { GenericStorageQuery, Callback, IEventRecord, ISubmittableExtrinsic } from 'dedot/types';
5
+ import { GenericStorageQuery, Callback, TxPaymentInfo, ISubmittableExtrinsic, IEventRecord } from 'dedot/types';
6
+ import { ConnectionStatus, TxStatus } from './types/index.js';
7
7
  import { MutateOptions, UseQueryResult } from '@tanstack/react-query';
8
8
  import { DispatchError, DispatchInfo } from 'dedot/codecs';
9
9
 
@@ -13,22 +13,6 @@ interface LunoProviderProps {
13
13
  }
14
14
  declare const LunoProvider: React.FC<LunoProviderProps>;
15
15
 
16
- declare enum ConnectionStatus {
17
- Disconnected = "disconnected",
18
- Connecting = "connecting",
19
- Disconnecting = "disconnecting",
20
- Connected = "connected"
21
- }
22
-
23
- type TxStatus = 'idle' | 'signing' | 'pending' | 'success' | 'failed';
24
-
25
- interface UseApiResult {
26
- api?: LegacyClient;
27
- isApiReady: boolean;
28
- apiError: Error | null;
29
- }
30
- declare const useApi: () => UseApiResult;
31
-
32
16
  interface UseAccountResult {
33
17
  account?: Account;
34
18
  address?: string;
@@ -43,6 +27,13 @@ declare const useAccounts: () => UseAccountsResult;
43
27
 
44
28
  declare const useActiveConnector: () => Connector | undefined;
45
29
 
30
+ interface UseApiResult {
31
+ api?: LegacyClient;
32
+ isApiReady: boolean;
33
+ apiError: Error | null;
34
+ }
35
+ declare const useApi: () => UseApiResult;
36
+
46
37
  type SubscriptionFn<TArgs extends any[], TData> = (...params: [...TArgs, Callback<TData>]) => Promise<() => Promise<void>>;
47
38
  interface UseSubscriptionOptions<TData, TTransformed = TData> {
48
39
  enabled?: boolean;
@@ -65,7 +56,7 @@ interface UseSubscriptionResult<TTransformed> {
65
56
  error?: Error;
66
57
  isLoading: boolean;
67
58
  }
68
- declare const useSubscription: <TArgs extends any[], TData, TTransformed = TData>({ queryKey: userQueryKey, factory, params, options }: UseSubscriptionProps<TArgs, TData, TTransformed>) => UseSubscriptionResult<TTransformed>;
59
+ declare const useSubscription: <TArgs extends any[], TData, TTransformed = TData>({ queryKey: userQueryKey, factory, params, options, }: UseSubscriptionProps<TArgs, TData, TTransformed>) => UseSubscriptionResult<TTransformed>;
69
60
 
70
61
  interface ChainProperties {
71
62
  ss58Format?: number;
@@ -89,8 +80,6 @@ declare const useChain: () => UseChainResult;
89
80
 
90
81
  declare const useChains: () => Chain[];
91
82
 
92
- declare const useConnectors: () => Connector[];
93
-
94
83
  declare const useConfig: () => Config | undefined;
95
84
 
96
85
  type LunoMutationOptions<TData = unknown, TError = Error, TVariables = void, TContext = unknown> = Partial<Pick<MutateOptions<TData, TError, TVariables, TContext>, 'onSuccess' | 'onError' | 'onSettled'>>;
@@ -117,6 +106,8 @@ interface UseConnectResult {
117
106
  }
118
107
  declare const useConnect: (hookLevelConfig?: UseConnectOptions) => UseConnectResult;
119
108
 
109
+ declare const useConnectors: () => Connector[];
110
+
120
111
  type UseDisconnectOptions = LunoMutationOptions<void, Error, void, unknown>;
121
112
  interface UseDisconnectResult {
122
113
  disconnect: (options?: UseDisconnectOptions) => void;
@@ -133,6 +124,16 @@ interface UseDisconnectResult {
133
124
  }
134
125
  declare const useDisconnect: (hookLevelConfig?: UseDisconnectOptions) => UseDisconnectResult;
135
126
 
127
+ interface PaymentInfo extends TxPaymentInfo {
128
+ partialFeeFormatted: string;
129
+ }
130
+ declare function useEstimatePaymentInfo(): {
131
+ data: PaymentInfo | null;
132
+ isLoading: boolean;
133
+ error: Error | null;
134
+ estimate: (extrinsic: ISubmittableExtrinsic, senderAddress?: string) => Promise<PaymentInfo | undefined>;
135
+ };
136
+
136
137
  interface UseGenesisHashResult {
137
138
  data?: HexString;
138
139
  error: Error | null;
@@ -140,6 +141,12 @@ interface UseGenesisHashResult {
140
141
  }
141
142
  declare const useGenesisHash: () => UseGenesisHashResult;
142
143
 
144
+ interface UsePapiSignerResult {
145
+ data?: PapiSigner;
146
+ isLoading: boolean;
147
+ }
148
+ declare function usePapiSigner(): UsePapiSignerResult;
149
+
143
150
  type UseRuntimeVersionResult = UseQueryResult<SubstrateRuntimeVersion, Error>;
144
151
  declare const useRuntimeVersion: () => UseRuntimeVersionResult;
145
152
 
@@ -194,6 +201,12 @@ interface UseSendTransactionHashResult {
194
201
  }
195
202
  declare function useSendTransactionHash(hookLevelConfig?: UseSendTransactionHashOptions): UseSendTransactionHashResult;
196
203
 
204
+ interface UseSignerResult {
205
+ data?: Signer;
206
+ isLoading: boolean;
207
+ }
208
+ declare const useSigner: () => UseSignerResult;
209
+
197
210
  interface SignMessageVariables {
198
211
  message: string;
199
212
  }
@@ -247,10 +260,4 @@ interface UseSwitchChainResult {
247
260
  }
248
261
  declare const useSwitchChain: (hookLevelConfig?: UseSwitchChainOptions) => UseSwitchChainResult;
249
262
 
250
- interface UseSignerResult {
251
- data?: Signer;
252
- isLoading: boolean;
253
- }
254
- declare const useSigner: () => UseSignerResult;
255
-
256
- export { type ChainProperties, type ConnectVariables, ConnectionStatus, type DetailedTxStatus, LunoProvider, type QueryMultiItem, type SendTransactionHashVariables, type SendTransactionVariables, type SignMessageData, type SignMessageVariables, type SwitchChainVariables, type TransactionReceipt, type UseAccountResult, type UseAccountsResult, type UseApiResult, type UseBalanceProps, type UseBalanceResult, type UseBlockNumberResult, type UseChainResult, type UseConnectOptions, type UseConnectResult, type UseDisconnectOptions, type UseDisconnectResult, type UseGenesisHashResult, type UseRuntimeVersionResult, type UseSendTransactionHashOptions, type UseSendTransactionHashResult, type UseSendTransactionOptions, type UseSendTransactionResult, type UseSignMessageOptions, type UseSignMessageResult, type UseSignerResult, type UseSs58FormatResult, type UseSubscriptionOptions, type UseSubscriptionProps, type UseSubscriptionResult, type UseSwitchChainOptions, type UseSwitchChainResult, useAccount, useAccounts, useActiveConnector, useApi, useBalance, useBlockNumber, useChain, useChains, useConfig, useConnect, useConnectors, useDisconnect, useGenesisHash, useRuntimeVersion, useSendTransaction, useSendTransactionHash, useSignMessage, useSigner, useSs58Format, useStatus, useSubscription, useSwitchChain };
263
+ export { type ChainProperties, type ConnectVariables, ConnectionStatus, type DetailedTxStatus, LunoProvider, type QueryMultiItem, type SendTransactionHashVariables, type SendTransactionVariables, type SignMessageData, type SignMessageVariables, type SwitchChainVariables, type TransactionReceipt, type UseAccountResult, type UseAccountsResult, type UseApiResult, type UseBalanceProps, type UseBalanceResult, type UseBlockNumberResult, type UseChainResult, type UseConnectOptions, type UseConnectResult, type UseDisconnectOptions, type UseDisconnectResult, type UseGenesisHashResult, type UsePapiSignerResult, type UseRuntimeVersionResult, type UseSendTransactionHashOptions, type UseSendTransactionHashResult, type UseSendTransactionOptions, type UseSendTransactionResult, type UseSignMessageOptions, type UseSignMessageResult, type UseSignerResult, type UseSs58FormatResult, type UseSubscriptionOptions, type UseSubscriptionProps, type UseSubscriptionResult, type UseSwitchChainOptions, type UseSwitchChainResult, useAccount, useAccounts, useActiveConnector, useApi, useBalance, useBlockNumber, useChain, useChains, useConfig, useConnect, useConnectors, useDisconnect, useEstimatePaymentInfo, useGenesisHash, usePapiSigner, useRuntimeVersion, useSendTransaction, useSendTransactionHash, useSignMessage, useSigner, useSs58Format, useStatus, useSubscription, useSwitchChain };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import W,{useCallback,useEffect,useMemo,useState,useRef,useContext}from'react';import {create}from'zustand';import {isSameAddress,wsProvider,convertAddress,formatBalance}from'@luno-kit/core';export*from'@luno-kit/core';import {LegacyClient}from'dedot';import {jsx}from'react/jsx-runtime';import {useQueryClient,useQuery,useMutation}from'@tanstack/react-query';import {isNumber}from'dedot/utils';var O=(t=>(t.Disconnected="disconnected",t.Connecting="connecting",t.Disconnecting="disconnecting",t.Connected="connected",t))(O||{});var T={LAST_CONNECTOR_ID:"lastConnectorId",LAST_CHAIN_ID:"lastChainId",LAST_SELECTED_ACCOUNT_INFO:"lastSelectedAccountInfo"};var D=async({config:e,chainId:o})=>{let n=e.chains.find(a=>a.genesisHash===o),i=e.transports[o];if(!n||!i)throw new Error(`Configuration missing for chainId: ${o}`);let s={provider:wsProvider(i),cacheMetadata:e.cacheMetadata,metadata:e.metadata,scaledResponses:{...e.scaledResponses,...e.customTypes},runtimeApis:e.runtimeApis,cacheStorage:e.cacheStorage},r=new LegacyClient(s);try{await r.connect();let a=await r.rpc.chain_getBlockHash(0);if(a!==o)throw await r.disconnect(),new Error(`Chain genesis hash mismatch. Expected: ${o}, Got: ${a}. This might indicate connecting to the wrong network or incorrect chain configuration.`);return r}catch(a){throw new Error(`Failed to connect to ${n.name}: ${a?.message||a}`)}};function _(e,o){if(o.type==="Module")try{let n=e.registry.findErrorMeta(o);if(n){let{docs:i,name:t,pallet:s,fields:r,fieldCodecs:a}=n;return `[useSendTransaction]: ${s}.${t} error, ${i.join(" ")}`}return `[useSendTransaction]: Module Error (index: ${o.value.index}, error: ${o.value.error})`}catch(n){let{value:{error:i,index:t}}=o;return `[useSendTransaction]: Module Error (index: ${t}, error: ${i}) - Failed to decode: ${n instanceof Error?n.message:"Unknown error"}`}else if(o.type==="Token")return `[useSendTransaction]: Token Error: ${o.value}`;return "value"in o?`[useSendTransaction]: ${o.type} Error: ${o.value}`:`[useSendTransaction]: Error: ${o.type}`}var $=(e=1e3)=>new Promise(o=>setTimeout(o,e));var M=[],R=()=>{M.forEach(e=>{try{e();}catch(o){console.warn("[LunoStore] Error during listener cleanup:",o);}}),M=[];},B=create((e,o)=>({config:void 0,status:"disconnected",activeConnector:void 0,accounts:[],account:void 0,currentChainId:void 0,currentChain:void 0,currentApi:void 0,isApiReady:false,apiError:null,_setConfig:async n=>{R();let i=null;try{i=await n.storage.getItem(T.LAST_CHAIN_ID);}catch(a){console.warn("[LunoStore] Failed to read stored chain ID from storage:",a);}let t=i?.toLowerCase(),s=t&&n.chains.some(a=>a.genesisHash.toLowerCase()===t)?t:n.chains[0]?.genesisHash,r=s?n.chains.find(a=>a.genesisHash.toLowerCase()===s):void 0;e({config:n,status:"disconnected",activeConnector:void 0,accounts:[],currentChainId:s,currentChain:r});},_setApi:n=>{e({currentApi:n});},_setIsApiReady:n=>{e({isApiReady:n});},setAccount:async n=>{if(!n)return;let{accounts:i,config:t}=o(),s=typeof n=="string"?n.toLowerCase():n.publicKey?.toLowerCase(),r=i.find(a=>a.publicKey?.toLowerCase()===s);if(!r)throw new Error("[LunoStore] setAccount: The provided account or address is not in the current accounts list. Ignored.");if(e({account:r}),t)try{let a={publicKey:r.publicKey,address:r.address,name:r.name,source:r.meta.source};await t.storage.setItem(T.LAST_SELECTED_ACCOUNT_INFO,JSON.stringify(a)),console.log(`[LunoStore] Persisted selected account: ${r.address}`);}catch(a){console.error("[LunoStore] Failed to persist selected account:",a);}},connect:async(n,i)=>{let t=o().config;if(!t)throw e({status:"disconnected"}),new Error("[LunoStore] LunoConfig has not been initialized. Cannot connect.");let s=t.connectors.find(a=>a.id===n);if(!s)throw e({status:"disconnected"}),new Error(`[LunoStore] Connector with ID "${n}" not found in LunoConfig.`);e({status:"connecting"});let r=o().activeConnector;r&&r.id!==s.id?(console.log(`[LunoStore] Switching connector. Cleaning up listeners for old connector: ${r.id}`),R()):r&&r.id===s.id&&(console.log(`[LunoStore] Attempting to reconnect with the same connector: ${s.id}. Cleaning up existing listeners.`),R());try{let a=async p=>{if(console.log(`[LunoStore] accountsChanged event from ${s.name}:`,p),p.length===0){await o().disconnect();return}p.forEach(h=>{h.publicKey||console.warn(`[LunoStore] Account ${h.address} (from ${s.name}) is missing publicKey.`);});let m=p[0];try{let h=await t.storage.getItem(T.LAST_SELECTED_ACCOUNT_INFO);if(h){let f=JSON.parse(h),S=p.find(x=>f.publicKey&&x.publicKey?.toLowerCase()===f.publicKey.toLowerCase()||isSameAddress(x.address,f.address));S&&(m=S);}}catch(h){console.warn("[LunoStore] Failed to restore account during accountsChanged:",h);}e({accounts:p,account:m});},d=()=>{if(console.log(`[LunoStore] disconnect event from ${s.name}`),o().activeConnector?.id===s.id){R();try{t.storage.removeItem(T.LAST_CONNECTOR_ID),t.storage.removeItem(T.LAST_CHAIN_ID),console.log("[LunoStore] Removed persisted connection info from storage due to disconnect event.");}catch(p){console.error("[LunoStore] Failed to remove connection info from storage:",p);}e({status:"disconnected",activeConnector:void 0,accounts:[]});}else console.warn(`[LunoStore] Received disconnect event from an inactive connector ${s.name}. Ignored.`);};s.on("accountsChanged",a),M.push(()=>s.off("accountsChanged",a)),s.on("disconnect",d),M.push(()=>s.off("disconnect",d));let u=i||o().currentChainId||t.chains[0]?.genesisHash,C=await s.connect(t.appName,t.chains,u);C.forEach(p=>{p.publicKey||console.error(`[LunoStore] CRITICAL WARNING: Account ${p.address} from connector ${s.name} was returned without a publicKey! SS58 address formatting will fail.`);});let b=C[0];try{let p=await t.storage.getItem(T.LAST_SELECTED_ACCOUNT_INFO);if(p){let m=JSON.parse(p),h=C.find(f=>m.publicKey&&f.publicKey?.toLowerCase()===m.publicKey.toLowerCase()||isSameAddress(f.address,m.address));h?(b=h,console.log(`[LunoStore] Restored previously selected account: ${b.address}`)):console.log("[LunoStore] Previously selected account not found in current accounts list, using first account");}}catch(p){console.warn("[LunoStore] Failed to restore selected account from storage:",p);}e({activeConnector:s,accounts:C,status:"connected",account:b});try{t.storage.setItem(T.LAST_CONNECTOR_ID,s.id),console.log(`[LunoStore] Persisted connectorId: ${s.id}`);}catch(p){console.error("[LunoStore] Failed to persist connectorId to storage:",p);}let l=o().currentChainId,g=i||l||t.chains[0]?.genesisHash;if(g){let p=t.chains.find(m=>m.genesisHash===g);if(p){(g!==l||!o().currentApi)&&e({currentChainId:g,currentChain:p,currentApi:void 0});try{t.storage.setItem(T.LAST_CHAIN_ID,g),console.log(`[LunoStore] Persisted chainId: ${g}`);}catch(m){console.error("[LunoStore] Failed to persist chainId to storage:",m);}}else console.warn(`[LunoStore] After connection, target chain ID "${g}" was not found in config. Current chain state might not have changed. Not persisting chainId.`);}else console.warn("[LunoStore] Could not determine target chain ID after connection. Please check config.");}catch(a){throw R(),e({status:"disconnected",activeConnector:void 0,accounts:[]}),new Error(`[LunoStore] Error connecting with ${s.name}: ${a?.message||a}`)}},disconnect:async()=>{let{activeConnector:n,status:i,config:t}=o();if(!n||i==="disconnecting"||i==="disconnected"){console.log("[LunoStore] No active connector or already disconnected/disconnecting. Disconnect action aborted.");return}e({status:"disconnecting"});try{if(await n.disconnect(),t)try{console.log("[LunoStore] Attempting to remove persisted connection info due to user disconnect action..."),await t.storage.removeItem(T.LAST_CONNECTOR_ID),await t.storage.removeItem(T.LAST_CHAIN_ID),await t.storage.removeItem(T.LAST_SELECTED_ACCOUNT_INFO),console.log("[LunoStore] Removed persisted connection info from storage.");}catch(s){console.error("[LunoStore] Failed to remove connection info from storage during disconnect action:",s);}R(),e({status:"disconnected",activeConnector:void 0,accounts:[],account:void 0}),o().status!=="disconnected"&&console.warn("[LunoStore] disconnect method called, but status is not yet 'disconnected' (event handler might be delayed or did not fire). Check connector events.");}catch(s){throw e({status:"connected"}),new Error(`[LunoStore] Error disconnecting from ${n.name}: ${s?.message||s}`)}},switchChain:async n=>{let{config:i,currentChainId:t,currentApi:s,activeConnector:r,account:a,accounts:d}=o();if(!i)throw new Error("[LunoStore] LunoConfig has not been initialized. Cannot switch chain.");if(n===t){console.log(`[LunoStore] Already on chain ${n}. No switch needed.`);return}let u=i.chains.find(l=>l.genesisHash===n);if(!u)throw new Error(`[LunoStore] Chain with ID "${n}" not found in LunoConfig.`);let C=d.findIndex(l=>l.address===a.address),b=await r.updateAccountsForChain(n);e({accounts:b,account:b[C]});try{try{s&&s.status==="connected"&&await s.disconnect();}catch(g){console.warn("[LunoStore] Failed to disconnect from previous chain:",g);}console.log(`[LunoStore] Attempting to switch chain to ${u.name} (ID: ${n})`),e({currentChainId:n,currentChain:u,currentApi:void 0,isApiReady:!1,apiError:null});let l=await D({config:i,chainId:n});e({currentApi:l,isApiReady:!0}),await i.storage.setItem(T.LAST_CHAIN_ID,n);}catch(l){e({apiError:l,isApiReady:false});}},_setApiError:n=>{e({apiError:n});}}));var k=W.createContext({});var K=()=>{let e=useRef(false);return {isInitialized:e.current,markAsInitialized:()=>{e.current=true;}}};var ne=({config:e,children:o})=>{let{_setConfig:n,_setApi:i,_setIsApiReady:t,_setApiError:s,setAccount:r,currentChainId:a,config:d,currentApi:u,connect:C,status:b,activeConnector:l,accounts:g,account:p,currentChain:m,isApiReady:h,apiError:f,disconnect:S,switchChain:x}=B(),{markAsInitialized:L,isInitialized:I}=K(),w=useCallback(()=>{i(void 0),t(false);},[i,t]);useEffect(()=>{e&&(console.log("[LunoProvider] Setting config to store:",e),n(e));},[e]),useEffect(()=>{if(I)return;if(!e||!a){u&&u.status==="connected"&&u.disconnect().catch(console.error),w();return}let A=e.chains.find(y=>y.genesisHash===a),E=e.transports[a];if(!A||!E){u&&u.status==="connected"&&u.disconnect().catch(console.error),w();return}u&&u.status==="connected"&&(console.log("[LunoProvider]: Disconnecting API from previous render cycle:",u.runtimeVersion.specName),u.disconnect().catch(y=>console.error("[LunoProvider] Error disconnecting previous API:",y))),w(),D({config:e,chainId:a}).then(y=>{i(y),t(true);}).catch(y=>{w(),s(y);}).finally(()=>L());},[e,a]),useEffect(()=>{e&&(async()=>{if(!e.autoConnect){console.log("[LunoProvider]: AutoConnect disabled or config not set.");return}if(!e.storage){console.warn("[LunoProvider]: AutoConnect Storage not available, cannot auto-connect.");return}try{let E=await e.storage.getItem(T.LAST_CONNECTOR_ID),y=await e.storage.getItem(T.LAST_CHAIN_ID);E&&y?(console.log(`[LunoProvider]: AutoConnect Found persisted session: Connector ID "${E}", Chain ID "${y}"`),await C(E,y)):console.log("[LunoProvider]: AutoConnect No persisted session found or missing data.");}catch(E){console.error("[LunoProvider]: AutoConnect Error during auto-connect process:",E);}})();},[e]),useEffect(()=>{if(h&&u&&m&&m.ss58Format!==void 0&&m.ss58Format!==null)try{let A=u.consts.system.ss58Prefix;A!=null&&A!==m.ss58Format?console.error(`[LunoProvider]: SS58 Format Mismatch for chain "${m.name}" (genesisHash: ${m.genesisHash}):
1
+ import {a,c as c$1,b}from'./chunk-A6LYVRYZ.js';export{a as ConnectionStatus}from'./chunk-62JXEP3B.js';export*from'@luno-kit/core';import Z,{useCallback,useEffect,useMemo,useState,useRef,useContext}from'react';import {isSameAddress,convertAddress,formatBalance,createPapiSigner}from'@luno-kit/core/utils';import {create}from'zustand';import {jsx}from'react/jsx-runtime';import {useQueryClient,useQuery,useMutation}from'@tanstack/react-query';import {isNumber}from'dedot/utils';var C={LAST_CONNECTOR_ID:"lastConnectorId",LAST_CHAIN_ID:"lastChainId",LAST_SELECTED_ACCOUNT_INFO:"lastSelectedAccountInfo"};var K=()=>{let e=useRef(false);return {isInitialized:e.current,markAsInitialized:()=>{e.current=true;}}};var M=[],R=()=>{M.forEach(e=>{try{e();}catch(r){console.warn("[LunoStore] Error during listener cleanup:",r);}}),M=[];},z=create((e,r)=>({config:void 0,status:"disconnected",activeConnector:void 0,accounts:[],account:void 0,currentChainId:void 0,currentChain:void 0,currentApi:void 0,isApiReady:false,apiError:null,_setConfig:async n=>{R();let s=null;try{s=await n.storage.getItem(C.LAST_CHAIN_ID);}catch(a){console.warn("[LunoStore] Failed to read stored chain ID from storage:",a);}let o=s?.toLowerCase(),t=o&&n.chains.some(a=>a.genesisHash.toLowerCase()===o)?o:n.chains[0]?.genesisHash,i=t?n.chains.find(a=>a.genesisHash.toLowerCase()===t):void 0;e({config:n,status:"disconnected",activeConnector:void 0,accounts:[],currentChainId:t,currentChain:i});},_setApi:n=>{e({currentApi:n});},_setIsApiReady:n=>{e({isApiReady:n});},setAccount:async n=>{if(!n)return;let{accounts:s,config:o}=r(),t=typeof n=="string"?n.toLowerCase():n.publicKey?.toLowerCase(),i=s.find(a=>a.publicKey?.toLowerCase()===t);if(!i)throw new Error("[LunoStore] setAccount: The provided account or address is not in the current accounts list. Ignored.");if(e({account:i}),o)try{let a={publicKey:i.publicKey,address:i.address,name:i.name,source:i.meta?.source};await o.storage.setItem(C.LAST_SELECTED_ACCOUNT_INFO,JSON.stringify(a)),console.log(`[LunoStore] Persisted selected account: ${i.address}`);}catch(a){console.error("[LunoStore] Failed to persist selected account:",a);}},connect:async(n,s)=>{let o=r().config;if(!o)throw e({status:"disconnected"}),new Error("[LunoStore] LunoConfig has not been initialized. Cannot connect.");let t=o.connectors.find(a=>a.id===n);if(!t)throw e({status:"disconnected"}),new Error(`[LunoStore] Connector with ID "${n}" not found in LunoConfig.`);e({status:"connecting"});let i=r().activeConnector;i&&i.id!==t.id?(console.log(`[LunoStore] Switching connector. Cleaning up listeners for old connector: ${i.id}`),R()):i&&i.id===t.id&&(console.log(`[LunoStore] Attempting to reconnect with the same connector: ${t.id}. Cleaning up existing listeners.`),R());try{let a=async p=>{if(console.log(`[LunoStore] accountsChanged event from ${t.name}:`,p),p.length===0){await r().disconnect();return}p.forEach(b=>{b.publicKey||console.warn(`[LunoStore] Account ${b.address} (from ${t.name}) is missing publicKey.`);});let m=p[0];try{let b=await o.storage.getItem(C.LAST_SELECTED_ACCOUNT_INFO);if(b){let S=JSON.parse(b),y=p.find(x=>S.publicKey&&x.publicKey?.toLowerCase()===S.publicKey.toLowerCase()||isSameAddress(x.address,S.address));y&&(m=y);}}catch(b){console.warn("[LunoStore] Failed to restore account during accountsChanged:",b);}e({accounts:p,account:m});},d=()=>{if(console.log(`[LunoStore] disconnect event from ${t.name}`),r().activeConnector?.id===t.id){R();try{o.storage.removeItem(C.LAST_CONNECTOR_ID),o.storage.removeItem(C.LAST_CHAIN_ID),console.log("[LunoStore] Removed persisted connection info from storage due to disconnect event.");}catch(p){console.error("[LunoStore] Failed to remove connection info from storage:",p);}e({status:"disconnected",activeConnector:void 0,accounts:[]});}else console.warn(`[LunoStore] Received disconnect event from an inactive connector ${t.name}. Ignored.`);};t.on("accountsChanged",a),M.push(()=>t.off("accountsChanged",a)),t.on("disconnect",d),M.push(()=>t.off("disconnect",d));let u=s||r().currentChainId||o.chains[0]?.genesisHash,f=await t.connect(o.appName,o.chains,u);if(!f||f?.length===0)throw new Error("[LunoStore] No accounts found from wallet");let h=f[0];try{let p=await o.storage.getItem(C.LAST_SELECTED_ACCOUNT_INFO);if(p){let m=JSON.parse(p),b=f.find(S=>m.publicKey&&S.publicKey?.toLowerCase()===m.publicKey.toLowerCase()||isSameAddress(S.address,m.address));b?(h=b,console.log(`[LunoStore] Restored previously selected account: ${h.address}`)):console.log("[LunoStore] Previously selected account not found in current accounts list, using first account");}}catch(p){console.warn("[LunoStore] Failed to restore selected account from storage:",p);}e({activeConnector:t,accounts:f,status:"connected",account:h});try{o.storage.setItem(C.LAST_CONNECTOR_ID,t.id),console.log(`[LunoStore] Persisted connectorId: ${t.id}`);}catch(p){console.error("[LunoStore] Failed to persist connectorId to storage:",p);}let l=r().currentChainId,g=s||l||o.chains[0]?.genesisHash;if(g){let p=o.chains.find(m=>m.genesisHash===g);if(p){(g!==l||!r().currentApi)&&e({currentChainId:g,currentChain:p,currentApi:void 0});try{o.storage.setItem(C.LAST_CHAIN_ID,g),console.log(`[LunoStore] Persisted chainId: ${g}`);}catch(m){console.error("[LunoStore] Failed to persist chainId to storage:",m);}}else console.warn(`[LunoStore] After connection, target chain ID "${g}" was not found in config. Current chain state might not have changed. Not persisting chainId.`);}}catch(a){throw R(),e({status:"disconnected",activeConnector:void 0,accounts:[]}),new Error(`[LunoStore] Error connecting with ${t.name}: ${a?.message||a}`)}},disconnect:async()=>{let{activeConnector:n,status:s,config:o}=r();if(!n||s==="disconnecting"||s==="disconnected"){console.log("[LunoStore] No active connector or already disconnected/disconnecting. Disconnect action aborted.");return}e({status:"disconnecting"});try{if(await n.disconnect(),o)try{console.log("[LunoStore] Attempting to remove persisted connection info due to user disconnect action..."),await o.storage.removeItem(C.LAST_CONNECTOR_ID),await o.storage.removeItem(C.LAST_CHAIN_ID),await o.storage.removeItem(C.LAST_SELECTED_ACCOUNT_INFO),console.log("[LunoStore] Removed persisted connection info from storage.");}catch(t){console.error("[LunoStore] Failed to remove connection info from storage during disconnect action:",t);}R(),e({status:"disconnected",activeConnector:void 0,accounts:[],account:void 0}),r().status!=="disconnected"&&console.warn("[LunoStore] disconnect method called, but status is not yet 'disconnected' (event handler might be delayed or did not fire). Check connector events.");}catch(t){throw e({status:"connected"}),new Error(`[LunoStore] Error disconnecting from ${n.name}: ${t?.message||t}`)}},switchChain:async n=>{let{config:s,currentChainId:o,currentApi:t,activeConnector:i,account:a$1,accounts:d}=r();if(!s)throw new Error("[LunoStore] LunoConfig has not been initialized. Cannot switch chain.");if(n===o){console.log(`[LunoStore] Already on chain ${n}. No switch needed.`);return}let u=s.chains.find(f=>f.genesisHash===n);if(!u)throw new Error(`[LunoStore] Chain with ID "${n}" not found in LunoConfig.`);try{try{t&&t.status==="connected"&&await t.disconnect();}catch(h){console.warn("[LunoStore] Failed to disconnect from previous chain:",h);}console.log(`[LunoStore] Attempting to switch chain to ${u.name} (ID: ${n})`),e({currentChainId:n,currentChain:u,currentApi:void 0,isApiReady:!1,apiError:null});let f=await a({config:s,chainId:n});e({currentApi:f,isApiReady:!0}),await s.storage.setItem(C.LAST_CHAIN_ID,n);}catch(f){e({apiError:f,isApiReady:false});}},_setApiError:n=>{e({apiError:n});}}));var k=Z.createContext({});var te=({config:e,children:r})=>{let{_setConfig:n,_setApi:s,_setIsApiReady:o,_setApiError:t,setAccount:i,currentChainId:a$1,config:d,currentApi:u,connect:f,status:h,activeConnector:l,accounts:g,account:p,currentChain:m,isApiReady:b,apiError:S,disconnect:y,switchChain:x}=z(),{markAsInitialized:E,isInitialized:w}=K(),I=useCallback(()=>{s(void 0),o(false);},[s,o]);useEffect(()=>{e&&(console.log("[LunoProvider] Setting config to store:",e),n(e));},[e]),useEffect(()=>{if(w)return;if(!e||!a$1){u&&u.status==="connected"&&u.disconnect().catch(console.error),I();return}let A=e.chains.find(T=>T.genesisHash===a$1),v=e.transports[a$1];if(!A||!v){u&&u.status==="connected"&&u.disconnect().catch(console.error),I();return}u&&u.status==="connected"&&(console.log("[LunoProvider]: Disconnecting API from previous render cycle:",u.runtimeVersion.specName),u.disconnect().catch(T=>console.error("[LunoProvider] Error disconnecting previous API:",T))),I(),a({config:e,chainId:a$1}).then(T=>{s(T),o(true);}).catch(T=>{I(),t(T);}).finally(()=>E());},[e,a$1]),useEffect(()=>{e&&(async()=>{if(await c$1(500),!e.autoConnect){console.log("[LunoProvider]: AutoConnect disabled or config not set.");return}if(!e.storage){console.warn("[LunoProvider]: AutoConnect Storage not available, cannot auto-connect.");return}try{let v=await e.storage.getItem(C.LAST_CONNECTOR_ID),T=await e.storage.getItem(C.LAST_CHAIN_ID);v?(console.log(`[LunoProvider]: AutoConnect Found persisted session: Connector ID "${v}", Chain ID "${T}"`),await f(v,T||void 0)):console.log("[LunoProvider]: AutoConnect No persisted session found or missing data.");}catch(v){console.error("[LunoProvider]: AutoConnect Error during auto-connect process:",v);}})();},[e]),useEffect(()=>{if(b&&u&&m&&m.ss58Format!==void 0&&m.ss58Format!==null)try{let A=u.consts.system.ss58Prefix;A!=null&&A!==m.ss58Format?console.error(`[LunoProvider]: SS58 Format Mismatch for chain "${m.name}" (genesisHash: ${m.genesisHash}):
2
2
  - Configured SS58Format: ${m.ss58Format}
3
3
  - Node Runtime SS58Format: ${A}
4
- Please verify your Luno configuration for this chain to ensure correct address display and interaction.`):A==null&&console.warn(`[LunoProvider]: Could not determine SS58 format from the API for chain "${m.name}". Cannot validate configured SS58Format (${m.ss58Format}). The application will use the configured value.`);}catch(A){console.error(`[LunoProvider]: Error retrieving SS58 format from API for chain "${m.name}" while attempting validation:`,A);}},[h,u,m]);let N=useMemo(()=>({config:d,status:b,activeConnector:l,accounts:g,account:p,setAccount:r,currentChainId:a,currentChain:m,currentApi:u,isApiReady:h,connect:C,disconnect:S,switchChain:x,apiError:f}),[d,b,l,g,p,a,m,u,h,f,C,S,x,r]);return jsx(k.Provider,{value:N,children:o})};var c=()=>{let e=useContext(k);if(e===void 0)throw new Error("useLuno must be used within a LunoProvider");return e};var bn=()=>{let{currentApi:e,isApiReady:o,apiError:n}=c();return {api:e,isApiReady:o,apiError:n}};var q=()=>{let{account:e,currentChain:o}=c(),n=useMemo(()=>{if(e){if(!o||o?.ss58Format===void 0||!e?.publicKey)return e;try{let i=convertAddress(e.address,o.ss58Format);return {...e,address:i}}catch(i){return console.error(`[useAccount]: Failed to re-format address for account with publicKey ${e.publicKey}:`,i),{...e}}}},[e,o,o?.ss58Format]);return {account:n,address:n?.address}};var In=()=>{let{accounts:e,setAccount:o,currentChain:n}=c();return {accounts:useMemo(()=>!n||n?.ss58Format===void 0?e??[]:(e||[]).map(t=>{if(!t.publicKey)return console.warn(`[useAccounts]: Account ${t.name||t.address} is missing publicKey. Cannot re-format address.`),t;try{let s=convertAddress(t.address,n.ss58Format);return {...t,address:s}}catch(s){return console.error(`[useAccounts]: Failed to re-format address for account with publicKey ${t.publicKey}:`,s),{...t}}}),[e,n,n?.ss58Format]),selectAccount:o}};var Mn=()=>{let{activeConnector:e}=c();return e};var me=e=>e,U=({queryKey:e,factory:o,params:n,options:i={}})=>{let[t,s]=useState(void 0),{currentApi:r,isApiReady:a}=c(),d=useQueryClient(),{enabled:u=true,transform:C=me,defaultValue:b}=i,l=useRef(null),g=useMemo(()=>{if(!(!n||!r||!a))return typeof n=="function"?[n(r)]:n},[n,r,a]),p=useMemo(()=>[e,g,r?.genesisHash],[e,g,r?.genesisHash]);useEffect(()=>{if(l.current&&(l.current(),l.current=null),!(!u||!o||!r||!g||!a)){try{let f=o(r),S=typeof f=="function"?f.bind(r):f,x=L=>{try{let I=C(L);d.setQueryData(p,I),s(void 0);}catch(I){s(new Error(`[useSubscription]: ${I}`));}};S(...g,x).then(L=>{l.current=L;}).catch(L=>{s(new Error(`[useSubscription]: ${L}`));});}catch(f){s(new Error(`[useSubscription]: ${f}`));}return ()=>{l.current&&(l.current(),l.current=null,s(void 0));}}},[JSON.stringify(p),u,d]);let{data:m,isLoading:h}=useQuery({queryKey:p,queryFn:()=>Promise.resolve(b),enabled:false,initialData:b});return {data:m,error:t,isLoading:!!(u&&a&&!m)}};var fe=10,ge=(e,o)=>{let n=e[0],i=e[1],t=n.data.free,s=n.data.reserved,r=n.data.frozen,a=BigInt(t)+BigInt(s),d=t>r?BigInt(t)-BigInt(r):0n;return {free:t,total:a,reserved:s,transferable:d,formattedTransferable:formatBalance(d,o.tokenDecimals),formattedTotal:formatBalance(a,o.tokenDecimals),locks:i.map(u=>({id:u.id,amount:u.amount,reason:u.reasons,lockHuman:formatBalance(u.amount,o.tokenDecimals)}))}},Bn=({address:e})=>{let{currentApi:o,isApiReady:n,currentChain:i}=c();return U({queryKey:"/native-balance",factory:t=>t.queryMulti,params:t=>[{fn:t.query.system.account,args:[e]},{fn:t.query.balances.locks,args:[e]}],options:{enabled:!!o&&n&&!!e,transform:t=>{let s={tokenDecimals:i?.nativeCurrency?.decimals??fe,tokenSymbol:i?.nativeCurrency?.symbol,ss58Format:i?.ss58Format};return ge(t,s)}}})};var Gn=()=>{let{currentApi:e,isApiReady:o}=c();return U({queryKey:"/block-number",factory:i=>i.query.system.number,params:[],options:{enabled:!!e&&o,transform:i=>i}})};var jn=()=>{let{currentChain:e,currentChainId:o}=c();return {chain:e,chainId:o}};var Zn=()=>{let{config:e}=c();return e?.chains?[...e.chains]:[]};var tt=()=>{let{config:e}=c();return e?.connectors?[...e.connectors]:[]};var st=()=>{let{config:e}=c();return e};function v(e,o){let n={};o?.onSuccess&&(n.onSuccess=o.onSuccess),o?.onError&&(n.onError=o.onError),o?.onSettled&&(n.onSettled=o.onSettled);let i=useMutation({mutationFn:e,retry:false,throwOnError:false,...n});return {mutate:(t,s)=>{i.mutate(t,s);},mutateAsync:(t,s)=>i.mutateAsync(t,s),data:i.data,error:i.error,isError:i.isError,isIdle:i.isIdle,isPending:i.isPending,isSuccess:i.isSuccess,reset:i.reset,status:i.status,variables:i.variables}}var pt=e=>{let{connect:o,config:n,activeConnector:i,status:t}=c(),r=v(async a=>{await o(a.connectorId,a.targetChainId),await $();},e);return {connect:r.mutate,connectAsync:r.mutateAsync,connectors:n?.connectors?[...n.connectors]:[],activeConnector:i,status:t,data:r.data,error:r.error,isError:r.isError,isIdle:r.isIdle,isPending:r.isPending,isSuccess:r.isSuccess,reset:r.reset,variables:r.variables}};var St=e=>{let{disconnect:o,status:n}=c(),t=v(async()=>{await o();},e);return {disconnect:s=>t.mutate(void 0,s),disconnectAsync:s=>t.mutateAsync(void 0,s),status:n,data:t.data,error:t.error,isError:t.isError,isIdle:t.isIdle,isPending:t.isPending,isSuccess:t.isSuccess,reset:t.reset,variables:t.variables}};var yt=()=>{let{currentApi:e,currentChainId:o,isApiReady:n}=c(),{data:i,isLoading:t,error:s}=useQuery({queryKey:["/genesis-hash",o],queryFn:async()=>await e.rpc.chain_getBlockHash(0),enabled:!!e&&n&&!!o,staleTime:1/0,gcTime:1/0,retry:false});return {data:i,isLoading:t,error:s}};var Lt=()=>{let{currentApi:e,isApiReady:o,currentChainId:n}=c();return useQuery({queryKey:["luno","runtimeVersion",n],queryFn:async()=>await e.getRuntimeVersion(),enabled:!!e&&o&&!!n})};function Mt(e){let{account:o,activeConnector:n,currentApi:i,isApiReady:t}=c(),[s,r]=useState("idle"),[a,d]=useState("idle"),[u,C]=useState(null),b=useCallback(async g=>{if(!i||!t)throw new Error("[useSendTransaction]: Polkadot API is not ready.");if(!n)throw new Error("[useSendTransaction]: No active connector found.");if(!o||!o.address||!o.meta?.source)throw new Error("[useSendTransaction]: No active account, address, or account metadata (source) found.");if(!g.extrinsic)throw new Error("[useSendTransaction]: No extrinsic provided to send.");let p=await n.getSigner();if(!p)throw new Error("[useSendTransaction]: Could not retrieve signer from the injector.");return r("signing"),d("idle"),new Promise((m,h)=>{let f;g.extrinsic.signAndSend(o.address,{signer:p},({status:S,dispatchError:x,events:L,dispatchInfo:I,txHash:w,txIndex:N})=>{let A=y=>{f&&f(),m(y);},E=y=>{f&&f(),C(y),h(y);};switch(S.type){case "Broadcasting":d("broadcasting");break;case "BestChainBlockIncluded":d("inBlock");break;case "Finalized":r("success"),d("finalized"),A(x?{transactionHash:w,blockHash:S.value?.blockHash,blockNumber:S.value?.blockNumber,events:L,status:"failed",dispatchError:x,errorMessage:_(i,x),dispatchInfo:I}:{transactionHash:w,blockHash:S.value?.blockHash,blockNumber:S.value?.blockNumber,events:L,status:"success",dispatchError:void 0,errorMessage:void 0,dispatchInfo:I});break;case "Invalid":r("failed"),d("invalid"),E(new Error(`Transaction invalid: ${w}`));break;case "Drop":r("failed"),d("dropped"),E(new Error(`Transaction dropped: ${w}`));break}}).then(S=>{f=S;}).catch(S=>{r("failed"),console.error("[useSendTransaction]: Error in signAndSend promise:",S?.message||S),C(S),h(S);});})},[i,t,n,o,r,d]),l=v(b,e);return {sendTransaction:l.mutate,sendTransactionAsync:l.mutateAsync,data:l.data,error:u||l.error,isError:!!u||l.isError,isIdle:l.isIdle,isPending:l.isPending,isSuccess:l.isSuccess,reset:l.reset,status:l.status,variables:l.variables,txStatus:s,detailedStatus:a}}function Ht(e){let{account:o,activeConnector:n,currentApi:i,isApiReady:t}=c(),[s,r]=useState(null),a=useCallback(async u=>{if(!i||!t)throw new Error("[useSendTransactionHash]: Polkadot API is not ready.");if(!n)throw new Error("[useSendTransactionHash]: No active connector found.");if(!o||!o.address||!o.meta?.source)throw new Error("[useSendTransactionHash]: No active account, address, or account metadata (source) found.");if(!u.extrinsic)throw new Error("[useSendTransactionHash]: No extrinsic provided to send.");let C=await n.getSigner();if(!C)throw new Error("[useSendTransactionHash]: Could not retrieve signer from the injector.");try{return await u.extrinsic.signAndSend(o.address,{signer:C}).catch(l=>{throw l})}catch(b){throw r(b),b}},[i,t,n,o]),d=v(a,e);return {sendTransaction:d.mutate,sendTransactionAsync:d.mutateAsync,data:d.data,error:s||d.error,isError:!!s||d.isError,isIdle:d.isIdle,isPending:d.isPending,isSuccess:d.isSuccess,reset:d.reset,status:d.status,variables:d.variables}}function $t(e){let{activeConnector:o,account:n,accounts:i,currentChainId:t}=c(),r=v(async a=>{if(!o)throw new Error("[useSignMessage]: No active connector found to sign the message.");if(!n||!n.address||!n.meta?.source)throw new Error("[useSignMessage]: No address provided for signing.");if(!i.some(u=>u.address===n.address))throw new Error(`[useSignMessage]: Address ${n.address} is not managed by ${o.id}.`);if(!a.message)throw new Error("[useSignMessage]: No message provided for signing.");let d=await o.signMessage(a.message,n.address,t);if(!d)throw new Error("[useSignMessage]: Signature was not obtained. The user may have cancelled the request or the connector failed.");return {signature:d,rawMessage:a.message,addressUsed:n.address}},e);return {signMessage:r.mutate,signMessageAsync:r.mutateAsync,data:r.data,error:r.error,isError:r.isError,isIdle:r.isIdle,isPending:r.isPending,isSuccess:r.isSuccess,reset:r.reset,status:r.status,variables:r.variables}}var Q=42,zt=()=>{let{currentApi:e,isApiReady:o,currentChain:n}=c(),i=n?.ss58Format!==void 0?n.ss58Format:Q;return useMemo(()=>{if(e&&o){let t;try{let s=e.consts.system.ss58Prefix;t=isNumber(s)?s:Q;}catch(s){console.error("[useSs58Format] Error fetching chainSS58:",s),t=i;}return {data:t,isLoading:false}}else return {data:void 0,isLoading:true}},[e,o,i])};var Jt=()=>{let{status:e}=c();return e};var Xt=e=>{let{switchChain:o,config:n,currentChain:i,currentChainId:t}=c(),r=v(async a=>{await o(a.chainId);},e);return {switchChain:r.mutate,switchChainAsync:r.mutateAsync,chains:n?.chains?[...n.chains]:[],currentChain:i,currentChainId:t,data:r.data,error:r.error,isError:r.isError,isIdle:r.isIdle,isPending:r.isPending,isSuccess:r.isSuccess,reset:r.reset,variables:r.variables}};var oo=()=>{let{activeConnector:e}=c(),{account:o}=q(),[n,i]=useState(void 0),[t,s]=useState(false);return useEffect(()=>{if(!e||!o?.address){i(void 0),s(false);return}s(true),e.getSigner().then(r=>i(r)).catch(()=>i(void 0)).finally(()=>s(false));},[e,o?.address]),{data:n,isLoading:t}};export{O as ConnectionStatus,ne as LunoProvider,q as useAccount,In as useAccounts,Mn as useActiveConnector,bn as useApi,Bn as useBalance,Gn as useBlockNumber,jn as useChain,Zn as useChains,st as useConfig,pt as useConnect,tt as useConnectors,St as useDisconnect,yt as useGenesisHash,Lt as useRuntimeVersion,Mt as useSendTransaction,Ht as useSendTransactionHash,$t as useSignMessage,oo as useSigner,zt as useSs58Format,Jt as useStatus,U as useSubscription,Xt as useSwitchChain};//# sourceMappingURL=index.js.map
4
+ Please verify your Luno configuration for this chain to ensure correct address display and interaction.`):A==null&&console.warn(`[LunoProvider]: Could not determine SS58 format from the API for chain "${m.name}". Cannot validate configured SS58Format (${m.ss58Format}). The application will use the configured value.`);}catch(A){console.error(`[LunoProvider]: Error retrieving SS58 format from API for chain "${m.name}" while attempting validation:`,A);}},[b,u,m]);let _=useMemo(()=>({config:d,status:h,activeConnector:l,accounts:g,account:p,setAccount:i,currentChainId:a$1,currentChain:m,currentApi:u,isApiReady:b,connect:f,disconnect:y,switchChain:x,apiError:S}),[d,h,l,g,p,a$1,m,u,b,S,f,y,x,i]);return jsx(k.Provider,{value:_,children:r})};var c=()=>{let e=useContext(k);if(e===void 0)throw new Error("useLuno must be used within a LunoProvider");return e};var D=()=>{let{account:e,currentChain:r}=c(),n=useMemo(()=>{if(e){if(!r||r?.ss58Format===void 0)return e;try{let s=convertAddress(e.address,r.ss58Format);return {...e,address:s}}catch(s){return console.error(`[useAccount]: Failed to re-format address for account ${e.address}:`,s),{...e}}}},[e,r,r?.ss58Format]);return {account:n,address:n?.address}};var pn=()=>{let{accounts:e,setAccount:r,currentChain:n}=c();return {accounts:useMemo(()=>!n||n?.ss58Format===void 0?e??[]:(e||[]).map(o=>{try{let t=convertAddress(o.address,n.ss58Format);return {...o,address:t}}catch(t){return console.error(`[useAccounts]: Failed to re-format address for account ${o.address}:`,t),{...o}}}),[e,n,n?.ss58Format]),selectAccount:r}};var gn=()=>{let{activeConnector:e}=c();return e};var yn=()=>{let{currentApi:e,isApiReady:r,apiError:n}=c();return {api:e,isApiReady:r,apiError:n}};var fe=e=>e,V=({queryKey:e,factory:r,params:n,options:s={}})=>{let[o,t]=useState(void 0),{currentApi:i,isApiReady:a}=c(),d=useQueryClient(),{enabled:u=true,transform:f=fe,defaultValue:h}=s,l=useRef(null),g=useMemo(()=>{if(!(!n||!i||!a))return typeof n=="function"?[n(i)]:n},[n,i,a]),p=useMemo(()=>[e,g,i?.genesisHash],[e,g,i?.genesisHash]);useEffect(()=>{if(l.current&&(l.current(),l.current=null),!(!u||!r||!i||!g||!a)){try{let S=r(i),y=typeof S=="function"?S.bind(i):S,x=E=>{try{let w=f(E);d.setQueryData(p,w),t(void 0);}catch(w){t(new Error(`[useSubscription]: ${w}`));}};y(...g,x).then(E=>{l.current=E;}).catch(E=>{t(new Error(`[useSubscription]: ${E}`));});}catch(S){t(new Error(`[useSubscription]: ${S}`));}return ()=>{l.current&&(l.current(),l.current=null,t(void 0));}}},[JSON.stringify(p),u,d]);let{data:m,isLoading:b}=useQuery({queryKey:p,queryFn:()=>Promise.resolve(h),enabled:false,initialData:h});return {data:m,error:o,isLoading:!!(u&&a&&!m)}};var ge=10,Se=(e,r)=>{let n=e[0],s=e[1],o=n.data.free,t=n.data.reserved,i=n.data.frozen,a=BigInt(o)+BigInt(t),d=o>i?BigInt(o)-BigInt(i):0n;return {free:o,total:a,reserved:t,transferable:d,formattedTransferable:formatBalance(d,r.tokenDecimals),formattedTotal:formatBalance(a,r.tokenDecimals),locks:s.map(u=>({id:u.id,amount:u.amount,reason:u.reasons,lockHuman:formatBalance(u.amount,r.tokenDecimals)}))}},In=({address:e})=>{let{currentApi:r,isApiReady:n,currentChain:s}=c();return V({queryKey:"/native-balance",factory:o=>o.queryMulti,params:o=>[{fn:o.query.system.account,args:[e]},{fn:o.query.balances.locks,args:[e]}],options:{enabled:!!r&&n&&!!e,transform:o=>{let t={tokenDecimals:s?.nativeCurrency?.decimals??ge,tokenSymbol:s?.nativeCurrency?.symbol,ss58Format:s?.ss58Format};return Se(o,t)}}})};var Pn=()=>{let{currentApi:e,isApiReady:r}=c();return V({queryKey:"/block-number",factory:s=>s.query.system.number,params:[],options:{enabled:!!e&&r,transform:s=>s}})};var kn=()=>{let{currentChain:e,currentChainId:r}=c();return {chain:e,chainId:r}};var Hn=()=>{let{config:e}=c();return e?.chains?[...e.chains]:[]};var _n=()=>{let{config:e}=c();return e};function L(e,r){let n={};r?.onSuccess&&(n.onSuccess=r.onSuccess),r?.onError&&(n.onError=r.onError),r?.onSettled&&(n.onSettled=r.onSettled);let s=useMutation({mutationFn:e,retry:false,throwOnError:false,...n});return {mutate:(o,t)=>{s.mutate(o,t);},mutateAsync:(o,t)=>s.mutateAsync(o,t),data:s.data,error:s.error,isError:s.isError,isIdle:s.isIdle,isPending:s.isPending,isSuccess:s.isSuccess,reset:s.reset,status:s.status,variables:s.variables}}var Jn=e=>{let{connect:r,config:n,activeConnector:s,status:o}=c(),i=L(async a=>{await r(a.connectorId,a.targetChainId),await c$1();},e);return {connect:i.mutate,connectAsync:i.mutateAsync,connectors:n?.connectors?[...n.connectors]:[],activeConnector:s,status:o,data:i.data,error:i.error,isError:i.isError,isIdle:i.isIdle,isPending:i.isPending,isSuccess:i.isSuccess,reset:i.reset,variables:i.variables}};var jn=()=>{let{config:e}=c();return e?.connectors?[...e.connectors]:[]};var et=e=>{let{disconnect:r,status:n}=c(),o=L(async()=>{await r();},e);return {disconnect:t=>o.mutate(void 0,t),disconnectAsync:t=>o.mutateAsync(void 0,t),status:n,data:o.data,error:o.error,isError:o.isError,isIdle:o.isIdle,isPending:o.isPending,isSuccess:o.isSuccess,reset:o.reset,variables:o.variables}};function st(){let{account:e,currentChain:r}=c(),[n,s]=useState(null),[o,t]=useState(false),[i,a]=useState(null),d=useCallback(async(u,f)=>{let h=f||e?.address;if(!(!u||!h||!r)){t(true),a(null);try{let l=await u.paymentInfo(h),g=r.nativeCurrency.decimals,p={...l,partialFeeFormatted:formatBalance(l.partialFee,g)};return s(p),p}catch(l){let g=l instanceof Error?l:new Error("Failed to estimate payment info");a(g);}finally{t(false);}}},[e?.address,r]);return {data:n,isLoading:o,error:i,estimate:d}}var ut=()=>{let{currentApi:e,currentChainId:r,isApiReady:n}=c(),{data:s,isLoading:o,error:t}=useQuery({queryKey:["/genesis-hash",r],queryFn:async()=>await e.rpc.chain_getBlockHash(0),enabled:!!e&&n&&!!r,staleTime:1/0,gcTime:1/0,retry:false});return {data:s,isLoading:o,error:t}};var G=()=>{let{activeConnector:e}=c(),{account:r}=D(),[n,s]=useState(void 0),[o,t]=useState(false);return useEffect(()=>{if(!e||!r?.address){s(void 0),t(false);return}t(true),e.getSigner().then(i=>s(i)).catch(()=>s(void 0)).finally(()=>t(false));},[e,r?.address]),{data:n,isLoading:o}};function bt(){let{data:e}=G(),{address:r}=D(),[n,s]=useState(false),[o,t]=useState(void 0);return useEffect(()=>{if(!e||!r){t(void 0),s(false);return}s(true),createPapiSigner(r,e).then(i=>t(i)).catch(()=>t(void 0)).finally(()=>s(false));},[e,r]),{data:o,isLoading:n}}var Lt=()=>{let{currentApi:e,isApiReady:r,currentChainId:n}=c();return useQuery({queryKey:["luno","runtimeVersion",n],queryFn:async()=>await e.getRuntimeVersion(),enabled:!!e&&r&&!!n})};function Dt(e){let{activeConnector:r,currentApi:n,isApiReady:s}=c(),{account:o}=D(),[t,i]=useState("idle"),[a,d]=useState("idle"),[u,f]=useState(null),h=useCallback(async g=>{if(!n||!s)throw new Error("[useSendTransaction]: Polkadot API is not ready.");if(!r)throw new Error("[useSendTransaction]: No active connector found.");if(!o||!o.address||!o.meta?.source)throw new Error("[useSendTransaction]: No active account, address, or account metadata (source) found.");if(!g.extrinsic)throw new Error("[useSendTransaction]: No extrinsic provided to send.");let p=await r.getSigner();if(!p)throw new Error("[useSendTransaction]: Could not retrieve signer from the injector.");return i("signing"),d("idle"),new Promise((m,b$1)=>{let S;g.extrinsic.signAndSend(o.address,{signer:p},({status:y,dispatchError:x,events:E,dispatchInfo:w,txHash:I,txIndex:_})=>{let A=T=>{S&&S(),m(T);},v=T=>{S&&S(),f(T),b$1(T);};switch(y.type){case "Broadcasting":d("broadcasting");break;case "BestChainBlockIncluded":d("inBlock");break;case "Finalized":i("success"),d("finalized"),A(x?{transactionHash:I,blockHash:y.value?.blockHash,blockNumber:y.value?.blockNumber,events:E,status:"failed",dispatchError:x,errorMessage:b(n,x),dispatchInfo:w}:{transactionHash:I,blockHash:y.value?.blockHash,blockNumber:y.value?.blockNumber,events:E,status:"success",dispatchError:void 0,errorMessage:void 0,dispatchInfo:w});break;case "Invalid":i("failed"),d("invalid"),v(new Error(`Transaction invalid: ${I}`));break;case "Drop":i("failed"),d("dropped"),v(new Error(`Transaction dropped: ${I}`));break}}).then(y=>{S=y;}).catch(y=>{i("failed"),console.error("[useSendTransaction]: Error in signAndSend promise:",y?.message||y),f(y),b$1(y);});})},[n,s,r,o,i,d]),l=L(h,e);return {sendTransaction:l.mutate,sendTransactionAsync:l.mutateAsync,data:l.data,error:u||l.error,isError:!!u||l.isError,isIdle:l.isIdle,isPending:l.isPending,isSuccess:l.isSuccess,reset:l.reset,status:l.status,variables:l.variables,txStatus:t,detailedStatus:a}}function Ot(e){let{account:r,activeConnector:n,currentApi:s,isApiReady:o}=c(),[t,i]=useState(null),a=useCallback(async u=>{if(!s||!o)throw new Error("[useSendTransactionHash]: Polkadot API is not ready.");if(!n)throw new Error("[useSendTransactionHash]: No active connector found.");if(!r||!r.address||!r.meta?.source)throw new Error("[useSendTransactionHash]: No active account, address, or account metadata (source) found.");if(!u.extrinsic)throw new Error("[useSendTransactionHash]: No extrinsic provided to send.");let f=await n.getSigner();if(!f)throw new Error("[useSendTransactionHash]: Could not retrieve signer from the injector.");try{return await u.extrinsic.signAndSend(r.address,{signer:f}).catch(l=>{throw l})}catch(h){throw i(h),h}},[s,o,n,r]),d=L(a,e);return {sendTransaction:d.mutate,sendTransactionAsync:d.mutateAsync,data:d.data,error:t||d.error,isError:!!t||d.isError,isIdle:d.isIdle,isPending:d.isPending,isSuccess:d.isSuccess,reset:d.reset,status:d.status,variables:d.variables}}function _t(e){let{activeConnector:r,account:n,accounts:s}=c(),t=L(async i=>{if(!r)throw new Error("[useSignMessage]: No active connector found to sign the message.");if(!n||!n.address||!n.meta?.source)throw new Error("[useSignMessage]: No address provided for signing.");if(!s.some(u=>u.address===n.address))throw new Error(`[useSignMessage]: Address ${n.address} is not managed by ${r.id}.`);if(!i.message)throw new Error("[useSignMessage]: No message provided for signing.");let a=s.find(u=>isSameAddress(u.address,n.address));if(!a)throw new Error("[useSignMessage]: Invalid account address.");let d=await r.signMessage(i.message,a.address);if(!d)throw new Error("[useSignMessage]: Signature was not obtained. The user may have cancelled the request or the connector failed.");return {signature:d,rawMessage:i.message,addressUsed:n.address}},e);return {signMessage:t.mutate,signMessageAsync:t.mutateAsync,data:t.data,error:t.error,isError:t.isError,isIdle:t.isIdle,isPending:t.isPending,isSuccess:t.isSuccess,reset:t.reset,status:t.status,variables:t.variables}}var j=42,zt=()=>{let{currentApi:e,isApiReady:r,currentChain:n}=c(),s=n?.ss58Format!==void 0?n.ss58Format:j;return useMemo(()=>{if(e&&r){let o;try{let t=e.consts.system.ss58Prefix;o=isNumber(t)?t:j;}catch(t){console.error("[useSs58Format] Error fetching chainSS58:",t),o=s;}return {data:o,isLoading:false}}else return {data:void 0,isLoading:true}},[e,r,s])};var Gt=()=>{let{status:e}=c();return e};var Xt=e=>{let{switchChain:r,config:n,currentChain:s,currentChainId:o}=c(),i=L(async a=>{await r(a.chainId);},e);return {switchChain:i.mutate,switchChainAsync:i.mutateAsync,chains:n?.chains?[...n.chains]:[],currentChain:s,currentChainId:o,data:i.data,error:i.error,isError:i.isError,isIdle:i.isIdle,isPending:i.isPending,isSuccess:i.isSuccess,reset:i.reset,variables:i.variables}};export{te as LunoProvider,D as useAccount,pn as useAccounts,gn as useActiveConnector,yn as useApi,In as useBalance,Pn as useBlockNumber,kn as useChain,Hn as useChains,_n as useConfig,Jn as useConnect,jn as useConnectors,et as useDisconnect,st as useEstimatePaymentInfo,ut as useGenesisHash,bt as usePapiSigner,Lt as useRuntimeVersion,Dt as useSendTransaction,Ot as useSendTransactionHash,_t as useSignMessage,G as useSigner,zt as useSs58Format,Gt as useStatus,V as useSubscription,Xt as useSwitchChain};//# sourceMappingURL=index.js.map
5
5
  //# sourceMappingURL=index.js.map