@luno-kit/react 0.0.7 → 0.0.9-beta.0

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.
@@ -1,2 +1,2 @@
1
- export*from'@luno-kit/core/types';var o=(n=>(n.Disconnected="disconnected",n.Connecting="connecting",n.Disconnecting="disconnecting",n.Connected="connected",n))(o||{});export{o as a};//# sourceMappingURL=chunk-PCTHAGIZ.js.map
2
- //# sourceMappingURL=chunk-PCTHAGIZ.js.map
1
+ export*from'@luno-kit/core/types';var o=(n=>(n.Disconnected="disconnected",n.Connecting="connecting",n.Disconnecting="disconnecting",n.Connected="connected",n))(o||{});export{o as a};//# sourceMappingURL=chunk-62JXEP3B.js.map
2
+ //# sourceMappingURL=chunk-62JXEP3B.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types/state.ts"],"names":["ConnectionStatus"],"mappings":"kCAIO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAAA,CAAA,aAAe,cAAA,CACfA,CAAAA,CAAA,UAAA,CAAa,YAAA,CACbA,EAAA,aAAA,CAAgB,eAAA,CAChBA,CAAAA,CAAA,SAAA,CAAY,YAJFA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAAA","file":"chunk-62JXEP3B.js","sourcesContent":["import type { HexString } from '@luno-kit/core/types';\nimport type { LegacyClient } from 'dedot';\nimport type { Account, Chain, Config, Connector } from '.';\n\nexport enum ConnectionStatus {\n Disconnected = 'disconnected',\n Connecting = 'connecting',\n Disconnecting = 'disconnecting',\n Connected = 'connected',\n}\n\nexport interface LunoState {\n config?: Config;\n\n status: ConnectionStatus;\n\n activeConnector?: Connector;\n\n accounts: Account[];\n account?: Account;\n setAccount: (accountOrPubkey?: Account | HexString) => Promise<void>;\n\n currentChainId?: string;\n currentChain?: Chain;\n currentApi?: LegacyClient;\n isApiReady: boolean;\n apiError: Error | null;\n\n _setConfig: (config: Config) => Promise<void>;\n\n connect: (connectorId: string, targetChainId?: string) => Promise<void>;\n disconnect: () => Promise<void>;\n\n switchChain: (newChainId: string) => Promise<void>;\n\n _setApi: (api?: LegacyClient) => void;\n\n _setIsApiReady: (isApiReady: boolean) => void;\n _setApiError: (error: Error | null) => void;\n}\n"]}
@@ -1,2 +1,2 @@
1
- export{formatAddress as d,getExplorerUrl as e,getPublicKey as f,isMobileDevice as g,isSameAddress as h,isValidAddress as i,formatBalance as j,getChainToken as k,defineChain as l,convertAddress as m,formatBalanceWithUnit as n}from'@luno-kit/core/utils';import {wsProvider}from'@luno-kit/core';import {LegacyClient}from'dedot';var u=async({config:r,chainId:e})=>{let t=r.chains.find(n=>n.genesisHash===e),o=r.transports[e];if(!t||!o)throw new Error(`Configuration missing for chainId: ${e}`);let s={provider:wsProvider(o),cacheMetadata:r.cacheMetadata,metadata:r.metadata,scaledResponses:{...r.scaledResponses,...r.customTypes},runtimeApis:r.runtimeApis,cacheStorage:r.cacheStorage},i=new LegacyClient(s);try{await i.connect();let n=await i.rpc.chain_getBlockHash(0);if(n!==e)throw await i.disconnect(),new Error(`Chain genesis hash mismatch. Expected: ${e}, Got: ${n}. This might indicate connecting to the wrong network or incorrect chain configuration.`);return i}catch(n){throw new Error(`Failed to connect to ${t.name}: ${n?.message||n}`)}};function g(r,e){if(e.type==="Module")try{let t=r.registry.findErrorMeta(e);if(t){let{docs:o,name:a,pallet:s,fields:i,fieldCodecs:n}=t;return `[useSendTransaction]: ${s}.${a} error, ${o.join(" ")}`}return `[useSendTransaction]: Module Error (index: ${e.value.index}, error: ${e.value.error})`}catch(t){let{value:{error:o,index:a}}=e;return `[useSendTransaction]: Module Error (index: ${a}, error: ${o}) - Failed to decode: ${t instanceof Error?t.message:"Unknown error"}`}else if(e.type==="Token")return `[useSendTransaction]: Token Error: ${e.value}`;return "value"in e?`[useSendTransaction]: ${e.type} Error: ${e.value}`:`[useSendTransaction]: Error: ${e.type}`}var h=(r=1e3)=>new Promise(e=>setTimeout(e,r));export{u as a,g as b,h as c};//# sourceMappingURL=chunk-ARGW3AHU.js.map
2
- //# sourceMappingURL=chunk-ARGW3AHU.js.map
1
+ export{convertAddress as d,defineChain as e,formatAddress as f,formatBalance as g,formatBalanceWithUnit as h,getChainToken as i,getExplorerUrl as j,getPublicKey as k,isMobileDevice as l,isSameAddress as m,isValidAddress as n}from'@luno-kit/core/utils';import {wsProvider}from'@luno-kit/core';import {LegacyClient}from'dedot';var l=async({config:r,chainId:e})=>{let t=r.chains.find(n=>n.genesisHash===e),o=r.transports[e];if(!t||!o)throw new Error(`Configuration missing for chainId: ${e}`);let s={provider:wsProvider(o),cacheMetadata:r.cacheMetadata,metadata:r.metadata,scaledResponses:{...r.scaledResponses,...r.customTypes},runtimeApis:r.runtimeApis,cacheStorage:r.cacheStorage},i=new LegacyClient(s);try{await i.connect();let n=await i.rpc.chain_getBlockHash(0);if(n!==e)throw await i.disconnect(),new Error(`Chain genesis hash mismatch. Expected: ${e}, Got: ${n}. This might indicate connecting to the wrong network or incorrect chain configuration.`);return i}catch(n){throw new Error(`Failed to connect to ${t.name}: ${n?.message||n}`)}};function f(r,e){if(e.type==="Module")try{let t=r.registry.findErrorMeta(e);if(t){let{docs:o,name:a,pallet:s,fields:i,fieldCodecs:n}=t;return `[useSendTransaction]: ${s}.${a} error, ${o.join(" ")}`}return `[useSendTransaction]: Module Error (index: ${e.value.index}, error: ${e.value.error})`}catch(t){let{value:{error:o,index:a}}=e;return `[useSendTransaction]: Module Error (index: ${a}, error: ${o}) - Failed to decode: ${t instanceof Error?t.message:"Unknown error"}`}else if(e.type==="Token")return `[useSendTransaction]: Token Error: ${e.value}`;return "value"in e?`[useSendTransaction]: ${e.type} Error: ${e.value}`:`[useSendTransaction]: Error: ${e.type}`}var y=(r=1e3)=>new Promise(e=>setTimeout(e,r));export{l as a,f as b,y as c};//# sourceMappingURL=chunk-A6LYVRYZ.js.map
2
+ //# sourceMappingURL=chunk-A6LYVRYZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/createApi.ts","../src/utils/dispatchError.ts","../src/utils/sleep.ts"],"names":["createApi","config","chainId","chainConfig","c","transportConfig","apiOptions","wsProvider","newApi","LegacyClient","actualGenesisHash","error","getReadableDispatchError","api","dispatchError","errorMeta","docs","name","pallet","fields","fieldCodecs","e","index","sleep","ms","resolve"],"mappings":"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","file":"chunk-A6LYVRYZ.js","sourcesContent":["import { wsProvider } from '@luno-kit/core';\nimport { type ApiOptions, LegacyClient } from 'dedot';\nimport type { Config } from '../types';\n\ninterface CreateApiOptions {\n config: Config;\n chainId: string;\n}\n\nexport const createApi = async ({ config, chainId }: CreateApiOptions): Promise<LegacyClient> => {\n const chainConfig = config.chains.find((c) => c.genesisHash === chainId);\n const transportConfig = config.transports[chainId];\n\n if (!chainConfig || !transportConfig) {\n throw new Error(`Configuration missing for chainId: ${chainId}`);\n }\n\n const provider = wsProvider(transportConfig);\n\n const apiOptions: ApiOptions = {\n provider,\n cacheMetadata: config.cacheMetadata,\n metadata: config.metadata,\n scaledResponses: {\n ...config.scaledResponses,\n ...config.customTypes,\n },\n runtimeApis: config.runtimeApis,\n cacheStorage: config.cacheStorage,\n };\n\n const newApi = new LegacyClient(apiOptions);\n\n try {\n await newApi.connect();\n\n const actualGenesisHash = await newApi.rpc.chain_getBlockHash(0);\n\n if (actualGenesisHash !== chainId) {\n await newApi.disconnect();\n throw new Error(\n `Chain genesis hash mismatch. Expected: ${chainId}, Got: ${actualGenesisHash}. ` +\n 'This might indicate connecting to the wrong network or incorrect chain configuration.'\n );\n }\n\n return newApi;\n } catch (error: any) {\n throw new Error(`Failed to connect to ${chainConfig.name}: ${error?.message || error}`);\n }\n};\n","import type { LegacyClient } from 'dedot';\nimport type { DispatchError } from 'dedot/codecs';\n\nexport function getReadableDispatchError(api: LegacyClient, dispatchError: DispatchError): string {\n if (dispatchError.type === 'Module') {\n try {\n const errorMeta = api.registry.findErrorMeta(dispatchError);\n if (errorMeta) {\n const { docs, name, pallet, fields, fieldCodecs } = errorMeta;\n return `[useSendTransaction]: ${pallet}.${name} error, ${docs.join(' ')}`;\n }\n\n return `[useSendTransaction]: Module Error (index: ${dispatchError.value.index}, error: ${dispatchError.value.error})`;\n } catch (e) {\n const {\n value: { error, index },\n } = dispatchError;\n\n return `[useSendTransaction]: Module Error (index: ${index}, error: ${error}) - Failed to decode: ${e instanceof Error ? e.message : 'Unknown error'}`;\n }\n } else if (dispatchError.type === 'Token') {\n return `[useSendTransaction]: Token Error: ${dispatchError.value}`;\n }\n\n if ('value' in dispatchError) {\n return `[useSendTransaction]: ${dispatchError.type} Error: ${dispatchError.value}`;\n }\n\n return `[useSendTransaction]: Error: ${dispatchError.type}`;\n}\n","export const sleep = (ms = 1000): Promise<void> => {\n return new Promise((resolve) => setTimeout(resolve, ms));\n};\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var utils=require('@luno-kit/core/utils'),core=require('@luno-kit/core'),dedot=require('dedot');var u=async({config:r,chainId:e})=>{let t=r.chains.find(n=>n.genesisHash===e),o=r.transports[e];if(!t||!o)throw new Error(`Configuration missing for chainId: ${e}`);let s={provider:core.wsProvider(o),cacheMetadata:r.cacheMetadata,metadata:r.metadata,scaledResponses:{...r.scaledResponses,...r.customTypes},runtimeApis:r.runtimeApis,cacheStorage:r.cacheStorage},i=new dedot.LegacyClient(s);try{await i.connect();let n=await i.rpc.chain_getBlockHash(0);if(n!==e)throw await i.disconnect(),new Error(`Chain genesis hash mismatch. Expected: ${e}, Got: ${n}. This might indicate connecting to the wrong network or incorrect chain configuration.`);return i}catch(n){throw new Error(`Failed to connect to ${t.name}: ${n?.message||n}`)}};function g(r,e){if(e.type==="Module")try{let t=r.registry.findErrorMeta(e);if(t){let{docs:o,name:a,pallet:s,fields:i,fieldCodecs:n}=t;return `[useSendTransaction]: ${s}.${a} error, ${o.join(" ")}`}return `[useSendTransaction]: Module Error (index: ${e.value.index}, error: ${e.value.error})`}catch(t){let{value:{error:o,index:a}}=e;return `[useSendTransaction]: Module Error (index: ${a}, error: ${o}) - Failed to decode: ${t instanceof Error?t.message:"Unknown error"}`}else if(e.type==="Token")return `[useSendTransaction]: Token Error: ${e.value}`;return "value"in e?`[useSendTransaction]: ${e.type} Error: ${e.value}`:`[useSendTransaction]: Error: ${e.type}`}var h=(r=1e3)=>new Promise(e=>setTimeout(e,r));Object.defineProperty(exports,"d",{enumerable:true,get:function(){return utils.formatAddress}});Object.defineProperty(exports,"e",{enumerable:true,get:function(){return utils.getExplorerUrl}});Object.defineProperty(exports,"f",{enumerable:true,get:function(){return utils.getPublicKey}});Object.defineProperty(exports,"g",{enumerable:true,get:function(){return utils.isMobileDevice}});Object.defineProperty(exports,"h",{enumerable:true,get:function(){return utils.isSameAddress}});Object.defineProperty(exports,"i",{enumerable:true,get:function(){return utils.isValidAddress}});Object.defineProperty(exports,"j",{enumerable:true,get:function(){return utils.formatBalance}});Object.defineProperty(exports,"k",{enumerable:true,get:function(){return utils.getChainToken}});Object.defineProperty(exports,"l",{enumerable:true,get:function(){return utils.defineChain}});Object.defineProperty(exports,"m",{enumerable:true,get:function(){return utils.convertAddress}});Object.defineProperty(exports,"n",{enumerable:true,get:function(){return utils.formatBalanceWithUnit}});exports.a=u;exports.b=g;exports.c=h;//# sourceMappingURL=chunk-74FF3SAT.cjs.map
2
- //# sourceMappingURL=chunk-74FF3SAT.cjs.map
1
+ 'use strict';var utils=require('@luno-kit/core/utils'),core=require('@luno-kit/core'),dedot=require('dedot');var l=async({config:r,chainId:e})=>{let t=r.chains.find(n=>n.genesisHash===e),o=r.transports[e];if(!t||!o)throw new Error(`Configuration missing for chainId: ${e}`);let s={provider:core.wsProvider(o),cacheMetadata:r.cacheMetadata,metadata:r.metadata,scaledResponses:{...r.scaledResponses,...r.customTypes},runtimeApis:r.runtimeApis,cacheStorage:r.cacheStorage},i=new dedot.LegacyClient(s);try{await i.connect();let n=await i.rpc.chain_getBlockHash(0);if(n!==e)throw await i.disconnect(),new Error(`Chain genesis hash mismatch. Expected: ${e}, Got: ${n}. This might indicate connecting to the wrong network or incorrect chain configuration.`);return i}catch(n){throw new Error(`Failed to connect to ${t.name}: ${n?.message||n}`)}};function f(r,e){if(e.type==="Module")try{let t=r.registry.findErrorMeta(e);if(t){let{docs:o,name:a,pallet:s,fields:i,fieldCodecs:n}=t;return `[useSendTransaction]: ${s}.${a} error, ${o.join(" ")}`}return `[useSendTransaction]: Module Error (index: ${e.value.index}, error: ${e.value.error})`}catch(t){let{value:{error:o,index:a}}=e;return `[useSendTransaction]: Module Error (index: ${a}, error: ${o}) - Failed to decode: ${t instanceof Error?t.message:"Unknown error"}`}else if(e.type==="Token")return `[useSendTransaction]: Token Error: ${e.value}`;return "value"in e?`[useSendTransaction]: ${e.type} Error: ${e.value}`:`[useSendTransaction]: Error: ${e.type}`}var y=(r=1e3)=>new Promise(e=>setTimeout(e,r));Object.defineProperty(exports,"d",{enumerable:true,get:function(){return utils.convertAddress}});Object.defineProperty(exports,"e",{enumerable:true,get:function(){return utils.defineChain}});Object.defineProperty(exports,"f",{enumerable:true,get:function(){return utils.formatAddress}});Object.defineProperty(exports,"g",{enumerable:true,get:function(){return utils.formatBalance}});Object.defineProperty(exports,"h",{enumerable:true,get:function(){return utils.formatBalanceWithUnit}});Object.defineProperty(exports,"i",{enumerable:true,get:function(){return utils.getChainToken}});Object.defineProperty(exports,"j",{enumerable:true,get:function(){return utils.getExplorerUrl}});Object.defineProperty(exports,"k",{enumerable:true,get:function(){return utils.getPublicKey}});Object.defineProperty(exports,"l",{enumerable:true,get:function(){return utils.isMobileDevice}});Object.defineProperty(exports,"m",{enumerable:true,get:function(){return utils.isSameAddress}});Object.defineProperty(exports,"n",{enumerable:true,get:function(){return utils.isValidAddress}});exports.a=l;exports.b=f;exports.c=y;//# sourceMappingURL=chunk-CMKLBFDC.cjs.map
2
+ //# sourceMappingURL=chunk-CMKLBFDC.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/createApi.ts","../src/utils/dispatchError.ts","../src/utils/sleep.ts"],"names":["createApi","config","chainId","chainConfig","c","transportConfig","apiOptions","wsProvider","newApi","LegacyClient","actualGenesisHash","error","getReadableDispatchError","api","dispatchError","errorMeta","docs","name","pallet","fields","fieldCodecs","e","index","sleep","ms","resolve"],"mappings":"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","file":"chunk-CMKLBFDC.cjs","sourcesContent":["import { wsProvider } from '@luno-kit/core';\nimport { type ApiOptions, LegacyClient } from 'dedot';\nimport type { Config } from '../types';\n\ninterface CreateApiOptions {\n config: Config;\n chainId: string;\n}\n\nexport const createApi = async ({ config, chainId }: CreateApiOptions): Promise<LegacyClient> => {\n const chainConfig = config.chains.find((c) => c.genesisHash === chainId);\n const transportConfig = config.transports[chainId];\n\n if (!chainConfig || !transportConfig) {\n throw new Error(`Configuration missing for chainId: ${chainId}`);\n }\n\n const provider = wsProvider(transportConfig);\n\n const apiOptions: ApiOptions = {\n provider,\n cacheMetadata: config.cacheMetadata,\n metadata: config.metadata,\n scaledResponses: {\n ...config.scaledResponses,\n ...config.customTypes,\n },\n runtimeApis: config.runtimeApis,\n cacheStorage: config.cacheStorage,\n };\n\n const newApi = new LegacyClient(apiOptions);\n\n try {\n await newApi.connect();\n\n const actualGenesisHash = await newApi.rpc.chain_getBlockHash(0);\n\n if (actualGenesisHash !== chainId) {\n await newApi.disconnect();\n throw new Error(\n `Chain genesis hash mismatch. Expected: ${chainId}, Got: ${actualGenesisHash}. ` +\n 'This might indicate connecting to the wrong network or incorrect chain configuration.'\n );\n }\n\n return newApi;\n } catch (error: any) {\n throw new Error(`Failed to connect to ${chainConfig.name}: ${error?.message || error}`);\n }\n};\n","import type { LegacyClient } from 'dedot';\nimport type { DispatchError } from 'dedot/codecs';\n\nexport function getReadableDispatchError(api: LegacyClient, dispatchError: DispatchError): string {\n if (dispatchError.type === 'Module') {\n try {\n const errorMeta = api.registry.findErrorMeta(dispatchError);\n if (errorMeta) {\n const { docs, name, pallet, fields, fieldCodecs } = errorMeta;\n return `[useSendTransaction]: ${pallet}.${name} error, ${docs.join(' ')}`;\n }\n\n return `[useSendTransaction]: Module Error (index: ${dispatchError.value.index}, error: ${dispatchError.value.error})`;\n } catch (e) {\n const {\n value: { error, index },\n } = dispatchError;\n\n return `[useSendTransaction]: Module Error (index: ${index}, error: ${error}) - Failed to decode: ${e instanceof Error ? e.message : 'Unknown error'}`;\n }\n } else if (dispatchError.type === 'Token') {\n return `[useSendTransaction]: Token Error: ${dispatchError.value}`;\n }\n\n if ('value' in dispatchError) {\n return `[useSendTransaction]: ${dispatchError.type} Error: ${dispatchError.value}`;\n }\n\n return `[useSendTransaction]: Error: ${dispatchError.type}`;\n}\n","export const sleep = (ms = 1000): Promise<void> => {\n return new Promise((resolve) => setTimeout(resolve, ms));\n};\n"]}
@@ -1,2 +1,2 @@
1
- 'use strict';var types=require('@luno-kit/core/types');var o=(n=>(n.Disconnected="disconnected",n.Connecting="connecting",n.Disconnecting="disconnecting",n.Connected="connected",n))(o||{});exports.a=o;Object.keys(types).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return types[k]}})});//# sourceMappingURL=chunk-FF2XK2NN.cjs.map
2
- //# sourceMappingURL=chunk-FF2XK2NN.cjs.map
1
+ 'use strict';var types=require('@luno-kit/core/types');var o=(n=>(n.Disconnected="disconnected",n.Connecting="connecting",n.Disconnecting="disconnecting",n.Connected="connected",n))(o||{});exports.a=o;Object.keys(types).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return types[k]}})});//# sourceMappingURL=chunk-JJEEWE3N.cjs.map
2
+ //# sourceMappingURL=chunk-JJEEWE3N.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types/state.ts"],"names":["ConnectionStatus"],"mappings":"uDAIO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAAA,CAAA,aAAe,cAAA,CACfA,CAAAA,CAAA,UAAA,CAAa,YAAA,CACbA,EAAA,aAAA,CAAgB,eAAA,CAChBA,CAAAA,CAAA,SAAA,CAAY,YAJFA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAAA","file":"chunk-JJEEWE3N.cjs","sourcesContent":["import type { HexString } from '@luno-kit/core/types';\nimport type { LegacyClient } from 'dedot';\nimport type { Account, Chain, Config, Connector } from '.';\n\nexport enum ConnectionStatus {\n Disconnected = 'disconnected',\n Connecting = 'connecting',\n Disconnecting = 'disconnecting',\n Connected = 'connected',\n}\n\nexport interface LunoState {\n config?: Config;\n\n status: ConnectionStatus;\n\n activeConnector?: Connector;\n\n accounts: Account[];\n account?: Account;\n setAccount: (accountOrPubkey?: Account | HexString) => Promise<void>;\n\n currentChainId?: string;\n currentChain?: Chain;\n currentApi?: LegacyClient;\n isApiReady: boolean;\n apiError: Error | null;\n\n _setConfig: (config: Config) => Promise<void>;\n\n connect: (connectorId: string, targetChainId?: string) => Promise<void>;\n disconnect: () => Promise<void>;\n\n switchChain: (newChainId: string) => Promise<void>;\n\n _setApi: (api?: LegacyClient) => void;\n\n _setIsApiReady: (isApiReady: boolean) => void;\n _setApiError: (error: Error | null) => void;\n}\n"]}
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- 'use strict';var chunk74FF3SAT_cjs=require('./chunk-74FF3SAT.cjs'),chunkFF2XK2NN_cjs=require('./chunk-FF2XK2NN.cjs'),Y=require('react'),zustand=require('zustand'),utils=require('@luno-kit/core/utils'),jsxRuntime=require('react/jsx-runtime'),reactQuery=require('@tanstack/react-query'),utils$1=require('dedot/utils'),core=require('@luno-kit/core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Y__default=/*#__PURE__*/_interopDefault(Y);var T={LAST_CONNECTOR_ID:"lastConnectorId",LAST_CHAIN_ID:"lastChainId",LAST_SELECTED_ACCOUNT_INFO:"lastSelectedAccountInfo"};var M=[],R=()=>{M.forEach(e=>{try{e();}catch(o){console.warn("[LunoStore] Error during listener cleanup:",o);}}),M=[];},B=zustand.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(),r=t&&n.chains.some(a=>a.genesisHash.toLowerCase()===t)?t:n.chains[0]?.genesisHash,s=r?n.chains.find(a=>a.genesisHash.toLowerCase()===r):void 0;e({config:n,status:"disconnected",activeConnector:void 0,accounts:[],currentChainId:r,currentChain:s});},_setApi:n=>{e({currentApi:n});},_setIsApiReady:n=>{e({isApiReady:n});},setAccount:async n=>{if(!n)return;let{accounts:i,config:t}=o(),r=typeof n=="string"?n.toLowerCase():n.publicKey?.toLowerCase(),s=i.find(a=>a.publicKey?.toLowerCase()===r);if(!s)throw new Error("[LunoStore] setAccount: The provided account or address is not in the current accounts list. Ignored.");if(e({account:s}),t)try{let a={publicKey:s.publicKey,address:s.address,name:s.name,source:s.meta.source};await t.storage.setItem(T.LAST_SELECTED_ACCOUNT_INFO,JSON.stringify(a)),console.log(`[LunoStore] Persisted selected account: ${s.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 r=t.connectors.find(a=>a.id===n);if(!r)throw e({status:"disconnected"}),new Error(`[LunoStore] Connector with ID "${n}" not found in LunoConfig.`);e({status:"connecting"});let s=o().activeConnector;s&&s.id!==r.id?(console.log(`[LunoStore] Switching connector. Cleaning up listeners for old connector: ${s.id}`),R()):s&&s.id===r.id&&(console.log(`[LunoStore] Attempting to reconnect with the same connector: ${r.id}. Cleaning up existing listeners.`),R());try{let a=async p=>{if(console.log(`[LunoStore] accountsChanged event from ${r.name}:`,p),p.length===0){await o().disconnect();return}p.forEach(h=>{h.publicKey||console.warn(`[LunoStore] Account ${h.address} (from ${r.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(v=>f.publicKey&&v.publicKey?.toLowerCase()===f.publicKey.toLowerCase()||utils.isSameAddress(v.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 ${r.name}`),o().activeConnector?.id===r.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 ${r.name}. Ignored.`);};r.on("accountsChanged",a),M.push(()=>r.off("accountsChanged",a)),r.on("disconnect",d),M.push(()=>r.off("disconnect",d));let u=i||o().currentChainId||t.chains[0]?.genesisHash,b=await r.connect(t.appName,t.chains,u);b.forEach(p=>{p.publicKey||console.error(`[LunoStore] CRITICAL WARNING: Account ${p.address} from connector ${r.name} was returned without a publicKey! SS58 address formatting will fail.`);});let C=b[0];try{let p=await t.storage.getItem(T.LAST_SELECTED_ACCOUNT_INFO);if(p){let m=JSON.parse(p),h=b.find(f=>m.publicKey&&f.publicKey?.toLowerCase()===m.publicKey.toLowerCase()||utils.isSameAddress(f.address,m.address));h?(C=h,console.log(`[LunoStore] Restored previously selected account: ${C.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:r,accounts:b,status:"connected",account:C});try{t.storage.setItem(T.LAST_CONNECTOR_ID,r.id),console.log(`[LunoStore] Persisted connectorId: ${r.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 ${r.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(r){console.error("[LunoStore] Failed to remove connection info from storage during disconnect action:",r);}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(r){throw e({status:"connected"}),new Error(`[LunoStore] Error disconnecting from ${n.name}: ${r?.message||r}`)}},switchChain:async n=>{let{config:i,currentChainId:t,currentApi:r,activeConnector:s,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 b=d.findIndex(l=>l.address===a.address),C=await s.updateAccountsForChain(n);e({accounts:C,account:C[b]});try{try{r&&r.status==="connected"&&await r.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 chunk74FF3SAT_cjs.a({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 P=Y__default.default.createContext({});var K=()=>{let e=Y.useRef(false);return {isInitialized:e.current,markAsInitialized:()=>{e.current=true;}}};var Z=({config:e,children:o})=>{let{_setConfig:n,_setApi:i,_setIsApiReady:t,_setApiError:r,setAccount:s,currentChainId:a,config:d,currentApi:u,connect:b,status:C,activeConnector:l,accounts:g,account:p,currentChain:m,isApiReady:h,apiError:f,disconnect:S,switchChain:v}=B(),{markAsInitialized:x,isInitialized:I}=K(),w=Y.useCallback(()=>{i(void 0),t(false);},[i,t]);Y.useEffect(()=>{e&&(console.log("[LunoProvider] Setting config to store:",e),n(e));},[e]),Y.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(),chunk74FF3SAT_cjs.a({config:e,chainId:a}).then(y=>{i(y),t(true);}).catch(y=>{w(),r(y);}).finally(()=>x());},[e,a]),Y.useEffect(()=>{e&&(async()=>{if(await chunk74FF3SAT_cjs.c(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 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 b(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]),Y.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}):
2
- - Configured SS58Format: ${m.ss58Format}
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=Y.useMemo(()=>({config:d,status:C,activeConnector:l,accounts:g,account:p,setAccount:s,currentChainId:a,currentChain:m,currentApi:u,isApiReady:h,connect:b,disconnect:S,switchChain:v,apiError:f}),[d,C,l,g,p,a,m,u,h,f,b,S,v,s]);return jsxRuntime.jsx(P.Provider,{value:N,children:o})};var c=()=>{let e=Y.useContext(P);if(e===void 0)throw new Error("useLuno must be used within a LunoProvider");return e};var nn=()=>{let{currentApi:e,isApiReady:o,apiError:n}=c();return {api:e,isApiReady:o,apiError:n}};var q=()=>{let{account:e,currentChain:o}=c(),n=Y.useMemo(()=>{if(e){if(!o||o?.ss58Format===void 0||!e?.publicKey)return e;try{let i=utils.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 ln=()=>{let{accounts:e,setAccount:o,currentChain:n}=c();return {accounts:Y.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 r=utils.convertAddress(t.address,n.ss58Format);return {...t,address:r}}catch(r){return console.error(`[useAccounts]: Failed to re-format address for account with publicKey ${t.publicKey}:`,r),{...t}}}),[e,n,n?.ss58Format]),selectAccount:o}};var fn=()=>{let{activeConnector:e}=c();return e};var le=e=>e,k=({queryKey:e,factory:o,params:n,options:i={}})=>{let[t,r]=Y.useState(void 0),{currentApi:s,isApiReady:a}=c(),d=reactQuery.useQueryClient(),{enabled:u=true,transform:b=le,defaultValue:C}=i,l=Y.useRef(null),g=Y.useMemo(()=>{if(!(!n||!s||!a))return typeof n=="function"?[n(s)]:n},[n,s,a]),p=Y.useMemo(()=>[e,g,s?.genesisHash],[e,g,s?.genesisHash]);Y.useEffect(()=>{if(l.current&&(l.current(),l.current=null),!(!u||!o||!s||!g||!a)){try{let f=o(s),S=typeof f=="function"?f.bind(s):f,v=x=>{try{let I=b(x);d.setQueryData(p,I),r(void 0);}catch(I){r(new Error(`[useSubscription]: ${I}`));}};S(...g,v).then(x=>{l.current=x;}).catch(x=>{r(new Error(`[useSubscription]: ${x}`));});}catch(f){r(new Error(`[useSubscription]: ${f}`));}return ()=>{l.current&&(l.current(),l.current=null,r(void 0));}}},[JSON.stringify(p),u,d]);let{data:m,isLoading:h}=reactQuery.useQuery({queryKey:p,queryFn:()=>Promise.resolve(C),enabled:false,initialData:C});return {data:m,error:t,isLoading:!!(u&&a&&!m)}};var pe=10,me=(e,o)=>{let n=e[0],i=e[1],t=n.data.free,r=n.data.reserved,s=n.data.frozen,a=BigInt(t)+BigInt(r),d=t>s?BigInt(t)-BigInt(s):0n;return {free:t,total:a,reserved:r,transferable:d,formattedTransferable:utils.formatBalance(d,o.tokenDecimals),formattedTotal:utils.formatBalance(a,o.tokenDecimals),locks:i.map(u=>({id:u.id,amount:u.amount,reason:u.reasons,lockHuman:utils.formatBalance(u.amount,o.tokenDecimals)}))}},xn=({address:e})=>{let{currentApi:o,isApiReady:n,currentChain:i}=c();return k({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 r={tokenDecimals:i?.nativeCurrency?.decimals??pe,tokenSymbol:i?.nativeCurrency?.symbol,ss58Format:i?.ss58Format};return me(t,r)}}})};var Dn=()=>{let{currentApi:e,isApiReady:o}=c();return k({queryKey:"/block-number",factory:i=>i.query.system.number,params:[],options:{enabled:!!e&&o,transform:i=>i}})};var Pn=()=>{let{currentChain:e,currentChainId:o}=c();return {chain:e,chainId:o}};var Vn=()=>{let{config:e}=c();return e?.chains?[...e.chains]:[]};var Fn=()=>{let{config:e}=c();return e?.connectors?[...e.connectors]:[]};var Bn=()=>{let{config:e}=c();return e};function L(e,o){let n={};o?.onSuccess&&(n.onSuccess=o.onSuccess),o?.onError&&(n.onError=o.onError),o?.onSettled&&(n.onSettled=o.onSettled);let i=reactQuery.useMutation({mutationFn:e,retry:false,throwOnError:false,...n});return {mutate:(t,r)=>{i.mutate(t,r);},mutateAsync:(t,r)=>i.mutateAsync(t,r),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 Yn=e=>{let{connect:o,config:n,activeConnector:i,status:t}=c(),s=L(async a=>{await o(a.connectorId,a.targetChainId),await chunk74FF3SAT_cjs.c();},e);return {connect:s.mutate,connectAsync:s.mutateAsync,connectors:n?.connectors?[...n.connectors]:[],activeConnector:i,status:t,data:s.data,error:s.error,isError:s.isError,isIdle:s.isIdle,isPending:s.isPending,isSuccess:s.isSuccess,reset:s.reset,variables:s.variables}};var Zn=e=>{let{disconnect:o,status:n}=c(),t=L(async()=>{await o();},e);return {disconnect:r=>t.mutate(void 0,r),disconnectAsync:r=>t.mutateAsync(void 0,r),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 ot=()=>{let{currentApi:e,currentChainId:o,isApiReady:n}=c(),{data:i,isLoading:t,error:r}=reactQuery.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:r}};var ct=()=>{let{currentApi:e,isApiReady:o,currentChainId:n}=c();return reactQuery.useQuery({queryKey:["luno","runtimeVersion",n],queryFn:async()=>await e.getRuntimeVersion(),enabled:!!e&&o&&!!n})};function ft(e){let{account:o,activeConnector:n,currentApi:i,isApiReady:t}=c(),[r,s]=Y.useState("idle"),[a,d]=Y.useState("idle"),[u,b]=Y.useState(null),C=Y.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 s("signing"),d("idle"),new Promise((m,h)=>{let f;g.extrinsic.signAndSend(o.address,{signer:p},({status:S,dispatchError:v,events:x,dispatchInfo:I,txHash:w,txIndex:N})=>{let A=y=>{f&&f(),m(y);},E=y=>{f&&f(),b(y),h(y);};switch(S.type){case "Broadcasting":d("broadcasting");break;case "BestChainBlockIncluded":d("inBlock");break;case "Finalized":s("success"),d("finalized"),A(v?{transactionHash:w,blockHash:S.value?.blockHash,blockNumber:S.value?.blockNumber,events:x,status:"failed",dispatchError:v,errorMessage:chunk74FF3SAT_cjs.b(i,v),dispatchInfo:I}:{transactionHash:w,blockHash:S.value?.blockHash,blockNumber:S.value?.blockNumber,events:x,status:"success",dispatchError:void 0,errorMessage:void 0,dispatchInfo:I});break;case "Invalid":s("failed"),d("invalid"),E(new Error(`Transaction invalid: ${w}`));break;case "Drop":s("failed"),d("dropped"),E(new Error(`Transaction dropped: ${w}`));break}}).then(S=>{f=S;}).catch(S=>{s("failed"),console.error("[useSendTransaction]: Error in signAndSend promise:",S?.message||S),b(S),h(S);});})},[i,t,n,o,s,d]),l=L(C,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:r,detailedStatus:a}}function Ct(e){let{account:o,activeConnector:n,currentApi:i,isApiReady:t}=c(),[r,s]=Y.useState(null),a=Y.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 b=await n.getSigner();if(!b)throw new Error("[useSendTransactionHash]: Could not retrieve signer from the injector.");try{return await u.extrinsic.signAndSend(o.address,{signer:b}).catch(l=>{throw l})}catch(C){throw s(C),C}},[i,t,n,o]),d=L(a,e);return {sendTransaction:d.mutate,sendTransactionAsync:d.mutateAsync,data:d.data,error:r||d.error,isError:!!r||d.isError,isIdle:d.isIdle,isPending:d.isPending,isSuccess:d.isSuccess,reset:d.reset,status:d.status,variables:d.variables}}function Lt(e){let{activeConnector:o,account:n,accounts:i,currentChainId:t}=c(),s=L(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:s.mutate,signMessageAsync:s.mutateAsync,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 Q=42,It=()=>{let{currentApi:e,isApiReady:o,currentChain:n}=c(),i=n?.ss58Format!==void 0?n.ss58Format:Q;return Y.useMemo(()=>{if(e&&o){let t;try{let r=e.consts.system.ss58Prefix;t=utils$1.isNumber(r)?r:Q;}catch(r){console.error("[useSs58Format] Error fetching chainSS58:",r),t=i;}return {data:t,isLoading:false}}else return {data:void 0,isLoading:true}},[e,o,i])};var Ut=()=>{let{status:e}=c();return e};var kt=e=>{let{switchChain:o,config:n,currentChain:i,currentChainId:t}=c(),s=L(async a=>{await o(a.chainId);},e);return {switchChain:s.mutate,switchChainAsync:s.mutateAsync,chains:n?.chains?[...n.chains]:[],currentChain:i,currentChainId:t,data:s.data,error:s.error,isError:s.isError,isIdle:s.isIdle,isPending:s.isPending,isSuccess:s.isSuccess,reset:s.reset,variables:s.variables}};var _t=()=>{let{activeConnector:e}=c(),{account:o}=q(),[n,i]=Y.useState(void 0),[t,r]=Y.useState(false);return Y.useEffect(()=>{if(!e||!o?.address){i(void 0),r(false);return}r(true),e.getSigner().then(s=>i(s)).catch(()=>i(void 0)).finally(()=>r(false));},[e,o?.address]),{data:n,isLoading:t}};Object.defineProperty(exports,"ConnectionStatus",{enumerable:true,get:function(){return chunkFF2XK2NN_cjs.a}});exports.LunoProvider=Z;exports.useAccount=q;exports.useAccounts=ln;exports.useActiveConnector=fn;exports.useApi=nn;exports.useBalance=xn;exports.useBlockNumber=Dn;exports.useChain=Pn;exports.useChains=Vn;exports.useConfig=Bn;exports.useConnect=Yn;exports.useConnectors=Fn;exports.useDisconnect=Zn;exports.useGenesisHash=ot;exports.useRuntimeVersion=ct;exports.useSendTransaction=ft;exports.useSendTransactionHash=Ct;exports.useSignMessage=Lt;exports.useSigner=_t;exports.useSs58Format=It;exports.useStatus=Ut;exports.useSubscription=k;exports.useSwitchChain=kt;Object.keys(core).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return core[k]}})});//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var chunkCMKLBFDC_cjs=require('./chunk-CMKLBFDC.cjs'),chunkJJEEWE3N_cjs=require('./chunk-JJEEWE3N.cjs'),core=require('@luno-kit/core'),Z=require('react'),utils=require('@luno-kit/core/utils'),zustand=require('zustand'),jsxRuntime=require('react/jsx-runtime'),reactQuery=require('@tanstack/react-query'),utils$1=require('dedot/utils');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Z__default=/*#__PURE__*/_interopDefault(Z);var y={LAST_CONNECTOR_ID:"lastConnectorId",LAST_CHAIN_ID:"lastChainId",LAST_SELECTED_ACCOUNT_INFO:"lastSelectedAccountInfo",RECENT_SELECTED_ACCOUNT_INFO:"recentSelectedAccountInfo",RECENT_CONNECTOR_ID:"recentConnectorId"};var $=()=>{let e=Z.useRef(false);return {isInitialized:e.current,markAsInitialized:()=>{e.current=true;}}};var K=[],D=()=>{K.forEach(e=>{try{e();}catch(r){console.warn("[LunoStore] Error during listener cleanup:",r);}}),K=[];},q=zustand.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=>{D();let s=null;try{s=await n.storage.getItem(y.LAST_CHAIN_ID);}catch(a){console.warn("[LunoStore] Failed to read stored chain ID from storage:",a);}let t=s?.toLowerCase(),o=t&&n.chains.some(a=>a.genesisHash.toLowerCase()===t)?t:n.chains[0]?.genesisHash,i=o?n.chains.find(a=>a.genesisHash.toLowerCase()===o):void 0;e({config:n,status:"disconnected",activeConnector:void 0,accounts:[],currentChainId:o,currentChain:i});},_setApi:n=>{e({currentApi:n});},_setIsApiReady:n=>{e({isApiReady:n});},setAccount:async n=>{if(!n)return;let{accounts:s,config:t}=r(),o=typeof n=="string"?n.toLowerCase():n.publicKey?.toLowerCase(),i=s.find(a=>a.publicKey?.toLowerCase()===o);if(!i)throw new Error("[LunoStore] setAccount: The provided account or address is not in the current accounts list. Ignored.");if(e({account:i}),t)try{let a={publicKey:i.publicKey,address:i.address,name:i.name,source:i.meta?.source};await t.storage.setItem(y.LAST_SELECTED_ACCOUNT_INFO,JSON.stringify(a)),await t.storage.setItem(y.RECENT_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 t=r().config;if(!t)throw e({status:"disconnected"}),new Error("[LunoStore] LunoConfig has not been initialized. Cannot connect.");let o=t.connectors.find(a=>a.id===n);if(!o)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!==o.id?(console.log(`[LunoStore] Switching connector. Cleaning up listeners for old connector: ${i.id}`),D()):i&&i.id===o.id&&(console.log(`[LunoStore] Attempting to reconnect with the same connector: ${o.id}. Cleaning up existing listeners.`),D());try{let a=s||r().currentChainId||t.chains[0]?.genesisHash,d=await o.connect(t.appName,t.chains,a);if(!d||d?.length===0)throw new Error("[LunoStore] No accounts found from wallet");let c=d[0];try{let p=await t.storage.getItem(y.LAST_SELECTED_ACCOUNT_INFO),h=await t.storage.getItem(y.RECENT_SELECTED_ACCOUNT_INFO),f=p||h;if(f){let A=JSON.parse(f),C=d.find(S=>utils.isSameAddress(S.address,A.address));C?(c=C,console.log(`[LunoStore] Restored previously selected account: ${c.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:o,accounts:d,status:"connected",account:c});let m={publicKey:c.publicKey,address:c.address,name:c.name,source:c.meta?.source};try{t.storage.setItem(y.LAST_CONNECTOR_ID,o.id),t.storage.setItem(y.RECENT_CONNECTOR_ID,o.id),t.storage.setItem(y.LAST_SELECTED_ACCOUNT_INFO,JSON.stringify(m)),t.storage.setItem(y.RECENT_SELECTED_ACCOUNT_INFO,JSON.stringify(m)),console.log(`[LunoStore] Persisted connectorId: ${o.id}`);}catch(p){console.error("[LunoStore] Failed to persist connectorId to storage:",p);}let g=r().currentChainId,l=s||g||t.chains[0]?.genesisHash;if(l){let p=t.chains.find(h=>h.genesisHash===l);if(p){(l!==g||!r().currentApi)&&e({currentChainId:l,currentChain:p,currentApi:void 0});try{t.storage.setItem(y.LAST_CHAIN_ID,l),console.log(`[LunoStore] Persisted chainId: ${l}`);}catch(h){console.error("[LunoStore] Failed to persist chainId to storage:",h);}}else console.warn(`[LunoStore] After connection, target chain ID "${l}" was not found in config. Current chain state might not have changed. Not persisting chainId.`);}}catch(a){throw D(),e({status:"disconnected",activeConnector:void 0,accounts:[]}),new Error(`[LunoStore] Error connecting with ${o.name}: ${a?.message||a}`)}},disconnect:async()=>{let{activeConnector:n,status:s,config:t}=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(),t)try{console.log("[LunoStore] Attempting to remove persisted connection info due to user disconnect action..."),await t.storage.removeItem(y.LAST_CONNECTOR_ID),await t.storage.removeItem(y.LAST_CHAIN_ID),await t.storage.removeItem(y.LAST_SELECTED_ACCOUNT_INFO),console.log("[LunoStore] Removed persisted connection info from storage.");}catch(o){console.error("[LunoStore] Failed to remove connection info from storage during disconnect action:",o);}D(),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(o){throw e({status:"connected"}),new Error(`[LunoStore] Error disconnecting from ${n.name}: ${o?.message||o}`)}},switchChain:async n=>{let{config:s,currentChainId:t,currentApi:o,activeConnector:i,account:a,accounts:d}=r();if(!s)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 c=s.chains.find(m=>m.genesisHash===n);if(!c)throw new Error(`[LunoStore] Chain with ID "${n}" not found in LunoConfig.`);try{try{o&&o.status==="connected"&&await o.disconnect();}catch(g){console.warn("[LunoStore] Failed to disconnect from previous chain:",g);}console.log(`[LunoStore] Attempting to switch chain to ${c.name} (ID: ${n})`),e({currentChainId:n,currentChain:c,currentApi:void 0,isApiReady:!1,apiError:null});let m=await chunkCMKLBFDC_cjs.a({config:s,chainId:n});e({currentApi:m,isApiReady:!0}),await s.storage.setItem(y.LAST_CHAIN_ID,n);}catch(m){e({apiError:m,isApiReady:false});}},_setApiError:n=>{e({apiError:n});}}));var M=Z__default.default.createContext({});var te=({config:e,children:r})=>{let{_setConfig:n,_setApi:s,_setIsApiReady:t,_setApiError:o,setAccount:i,currentChainId:a,config:d,currentApi:c,connect:m,status:g,activeConnector:l,accounts:p,account:h,currentChain:f,isApiReady:A,apiError:C,disconnect:S,switchChain:v}=q(),{markAsInitialized:x,isInitialized:w}=$(),I=Z.useCallback(()=>{s(void 0),t(false);},[s,t]);Z.useEffect(()=>{e&&(console.log("[LunoProvider] Setting config to store:",e),n(e));},[e]),Z.useEffect(()=>{if(w)return;if(!e||!a){c&&c.status==="connected"&&c.disconnect().catch(console.error),I();return}let b=e.chains.find(L=>L.genesisHash===a),T=e.transports[a];if(!b||!T){c&&c.status==="connected"&&c.disconnect().catch(console.error),I();return}c&&c.status==="connected"&&(console.log("[LunoProvider]: Disconnecting API from previous render cycle:",c.runtimeVersion.specName),c.disconnect().catch(L=>console.error("[LunoProvider] Error disconnecting previous API:",L))),I(),chunkCMKLBFDC_cjs.a({config:e,chainId:a}).then(L=>{s(L),t(true);}).catch(L=>{I(),o(L);}).finally(()=>x());},[e,a]),Z.useEffect(()=>{e&&(async()=>{if(await chunkCMKLBFDC_cjs.c(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 T=await e.storage.getItem(y.LAST_CONNECTOR_ID),L=await e.storage.getItem(y.LAST_CHAIN_ID);T?(console.log(`[LunoProvider]: AutoConnect Found persisted session: Connector ID "${T}", Chain ID "${L}"`),await m(T,L||void 0)):console.log("[LunoProvider]: AutoConnect No persisted session found or missing data.");}catch(T){console.error("[LunoProvider]: AutoConnect Error during auto-connect process:",T);}})();},[e]),Z.useEffect(()=>{if(A&&c&&f&&f.ss58Format!==void 0&&f.ss58Format!==null)try{let b=c.consts.system.ss58Prefix;b!=null&&b!==f.ss58Format?console.error(`[LunoProvider]: SS58 Format Mismatch for chain "${f.name}" (genesisHash: ${f.genesisHash}):
2
+ - Configured SS58Format: ${f.ss58Format}
3
+ - Node Runtime SS58Format: ${b}
4
+ Please verify your Luno configuration for this chain to ensure correct address display and interaction.`):b==null&&console.warn(`[LunoProvider]: Could not determine SS58 format from the API for chain "${f.name}". Cannot validate configured SS58Format (${f.ss58Format}). The application will use the configured value.`);}catch(b){console.error(`[LunoProvider]: Error retrieving SS58 format from API for chain "${f.name}" while attempting validation:`,b);}},[A,c,f]);let P=Z.useMemo(()=>({config:d,status:g,activeConnector:l,accounts:p,account:h,setAccount:i,currentChainId:a,currentChain:f,currentApi:c,isApiReady:A,connect:m,disconnect:S,switchChain:v,apiError:C}),[d,g,l,p,h,a,f,c,A,C,m,S,v,i]);return jsxRuntime.jsx(M.Provider,{value:P,children:r})};var u=()=>{let e=Z.useContext(M);if(e===void 0)throw new Error("useLuno must be used within a LunoProvider");return e};var R=()=>{let{account:e,currentChain:r}=u(),n=Z.useMemo(()=>{if(e){if(!r||r?.ss58Format===void 0)return e;try{let s=utils.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 ln=()=>{let{accounts:e,setAccount:r,currentChain:n}=u();return {accounts:Z.useMemo(()=>!n||n?.ss58Format===void 0?e??[]:(e||[]).map(t=>{try{let o=utils.convertAddress(t.address,n.ss58Format);return {...t,address:o}}catch(o){return console.error(`[useAccounts]: Failed to re-format address for account ${t.address}:`,o),{...t}}}),[e,n,n?.ss58Format]),selectAccount:r}};var fn=()=>{let{activeConnector:e}=u();return e};var hn=()=>{let{currentApi:e,isApiReady:r,apiError:n}=u();return {api:e,isApiReady:r,apiError:n}};var fe=e=>e,k=({queryKey:e,factory:r,params:n,options:s={}})=>{let[t,o]=Z.useState(void 0),{currentApi:i,isApiReady:a}=u(),d=reactQuery.useQueryClient(),{enabled:c=true,transform:m=fe,defaultValue:g}=s,l=Z.useRef(null),p=Z.useMemo(()=>{if(!(!n||!i||!a))return typeof n=="function"?[n(i)]:n},[n,i,a]),h=Z.useMemo(()=>[e,p,i?.genesisHash],[e,p,i?.genesisHash]);Z.useEffect(()=>{if(l.current&&(l.current(),l.current=null),!(!c||!r||!i||!p||!a)){try{let C=r(i),S=typeof C=="function"?C.bind(i):C,v=x=>{try{let w=m(x);d.setQueryData(h,w),o(void 0);}catch(w){o(new Error(`[useSubscription]: ${w}`));}};S(...p,v).then(x=>{l.current=x;}).catch(x=>{o(new Error(`[useSubscription]: ${x}`));});}catch(C){o(new Error(`[useSubscription]: ${C}`));}return ()=>{l.current&&(l.current(),l.current=null,o(void 0));}}},[JSON.stringify(h),c,d]);let{data:f,isLoading:A}=reactQuery.useQuery({queryKey:h,queryFn:()=>Promise.resolve(g),enabled:false,initialData:g});return {data:f,error:t,isLoading:!!(c&&a&&!f)}};var ge=10,Se=(e,r)=>{let n=e[0],s=e[1],t=n.data.free,o=n.data.reserved,i=n.data.frozen,a=BigInt(t)+BigInt(o),d=t>i?BigInt(t)-BigInt(i):0n;return {free:t,total:a,reserved:o,transferable:d,formattedTransferable:utils.formatBalance(d,r.tokenDecimals),formattedTotal:utils.formatBalance(a,r.tokenDecimals),locks:s.map(c=>({id:c.id,amount:c.amount,reason:c.reasons,lockHuman:utils.formatBalance(c.amount,r.tokenDecimals)}))}},In=({address:e})=>{let{currentApi:r,isApiReady:n,currentChain:s}=u();return k({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:!!r&&n&&!!e,transform:t=>{let o={tokenDecimals:s?.nativeCurrency?.decimals??ge,tokenSymbol:s?.nativeCurrency?.symbol,ss58Format:s?.ss58Format};return Se(t,o)}}})};var Dn=()=>{let{currentApi:e,isApiReady:r}=u();return k({queryKey:"/block-number",factory:s=>s.query.system.number,params:[],options:{enabled:!!e&&r,transform:s=>s}})};var On=()=>{let{currentChain:e,currentChainId:r}=u();return {chain:e,chainId:r}};var kn=()=>{let{config:e}=u();return e?.chains?[...e.chains]:[]};var Hn=()=>{let{config:e}=u();return e};function E(e,r){let n={};r?.onSuccess&&(n.onSuccess=r.onSuccess),r?.onError&&(n.onError=r.onError),r?.onSettled&&(n.onSettled=r.onSettled);let s=reactQuery.useMutation({mutationFn:e,retry:false,throwOnError:false,...n});return {mutate:(t,o)=>{s.mutate(t,o);},mutateAsync:(t,o)=>s.mutateAsync(t,o),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 Qn=e=>{let{connect:r,config:n,activeConnector:s,status:t}=u(),i=E(async a=>{await r(a.connectorId,a.targetChainId),await chunkCMKLBFDC_cjs.c();},e);return {connect:i.mutate,connectAsync:i.mutateAsync,connectors:n?.connectors?[...n.connectors]:[],activeConnector:s,status:t,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 Yn=()=>{let{config:e}=u();return e?.connectors?[...e.connectors]:[]};var Zn=e=>{let{disconnect:r,status:n}=u(),t=E(async()=>{await r();},e);return {disconnect:o=>t.mutate(void 0,o),disconnectAsync:o=>t.mutateAsync(void 0,o),status:n,data:t.data,error:t.error,isError:t.isError,isIdle:t.isIdle,isPending:t.isPending,isSuccess:t.isSuccess,reset:t.reset}};function rt(){let{account:e,currentChain:r}=u(),[n,s]=Z.useState(null),[t,o]=Z.useState(false),[i,a]=Z.useState(null),d=Z.useCallback(async(c,m)=>{let g=m||e?.address;if(!(!c||!g||!r)){o(true),a(null);try{let l=await c.paymentInfo(g),p=r.nativeCurrency.decimals,h={...l,partialFeeFormatted:utils.formatBalance(l.partialFee,p)};return s(h),h}catch(l){let p=l instanceof Error?l:new Error("Failed to estimate payment info");a(p);}finally{o(false);}}},[e?.address,r]);return {data:n,isLoading:t,error:i,estimate:d}}var ct=()=>{let{currentApi:e,currentChainId:r,isApiReady:n}=u(),{data:s,isLoading:t,error:o}=reactQuery.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:t,error:o}};var J=()=>{let{activeConnector:e}=u(),{account:r}=R(),[n,s]=Z.useState(void 0),[t,o]=Z.useState(false);return Z.useEffect(()=>{if(!e||!r?.address){s(void 0),o(false);return}o(true),e.getSigner().then(i=>s(i)).catch(()=>s(void 0)).finally(()=>o(false));},[e,r?.address]),{data:n,isLoading:t}};function yt(){let{data:e}=J(),{address:r}=R(),[n,s]=Z.useState(false),[t,o]=Z.useState(void 0);return Z.useEffect(()=>{if(!e||!r){o(void 0),s(false);return}s(true),utils.createPapiSigner(r,e).then(i=>o(i)).catch(()=>o(void 0)).finally(()=>s(false));},[e,r]),{data:t,isLoading:n}}var Et=()=>{let{currentApi:e,isApiReady:r,currentChainId:n}=u();return reactQuery.useQuery({queryKey:["luno","runtimeVersion",n],queryFn:async()=>await e.getRuntimeVersion(),enabled:!!e&&r&&!!n})};function Rt(e){let{activeConnector:r,currentApi:n,isApiReady:s}=u(),{account:t}=R(),[o,i]=Z.useState("idle"),[a,d]=Z.useState("idle"),[c,m]=Z.useState(null),g=Z.useCallback(async p=>{if(!n||!s)throw new Error("[useSendTransaction]: Polkadot API is not ready.");if(!r)throw new Error("[useSendTransaction]: No active connector found.");if(!t||!t.address||!t.meta?.source)throw new Error("[useSendTransaction]: No active account, address, or account metadata (source) found.");if(!p.extrinsic)throw new Error("[useSendTransaction]: No extrinsic provided to send.");let h=await r.getSigner();if(!h)throw new Error("[useSendTransaction]: Could not retrieve signer from the injector.");return i("signing"),d("idle"),new Promise((f,A)=>{let C;p.extrinsic.signAndSend(t.address,{signer:h},({status:S,dispatchError:v,events:x,dispatchInfo:w,txHash:I})=>{let P=T=>{C&&C(),f(T);},b=T=>{C&&C(),m(T),A(T);};switch(S.type){case "Broadcasting":d("broadcasting");break;case "BestChainBlockIncluded":d("inBlock");break;case "Finalized":i("success"),d("finalized"),P(v?{transactionHash:I,blockHash:S.value?.blockHash,blockNumber:S.value?.blockNumber,events:x,status:"failed",dispatchError:v,errorMessage:chunkCMKLBFDC_cjs.b(n,v),dispatchInfo:w}:{transactionHash:I,blockHash:S.value?.blockHash,blockNumber:S.value?.blockNumber,events:x,status:"success",dispatchError:void 0,errorMessage:void 0,dispatchInfo:w});break;case "Invalid":i("failed"),d("invalid"),b(new Error(`Transaction invalid: ${I}`));break;case "Drop":i("failed"),d("dropped"),b(new Error(`Transaction dropped: ${I}`));break}}).then(S=>{C=S;}).catch(S=>{i("failed"),console.error("[useSendTransaction]: Error in signAndSend promise:",S?.message||S),m(S),A(S);});})},[n,s,r,t,i,d]),l=E(g,e);return {sendTransaction:l.mutate,sendTransactionAsync:l.mutateAsync,data:l.data,error:c||l.error,isError:!!c||l.isError,isIdle:l.isIdle,isPending:l.isPending,isSuccess:l.isSuccess,reset:l.reset,status:l.status,variables:l.variables,txStatus:o,detailedStatus:a}}function Mt(e){let{account:r,activeConnector:n,currentApi:s,isApiReady:t}=u(),[o,i]=Z.useState(null),a=Z.useCallback(async c=>{if(!s||!t)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(!c.extrinsic)throw new Error("[useSendTransactionHash]: No extrinsic provided to send.");let m=await n.getSigner();if(!m)throw new Error("[useSendTransactionHash]: Could not retrieve signer from the injector.");try{return await c.extrinsic.signAndSend(r.address,{signer:m}).catch(l=>{throw l})}catch(g){throw i(g),g}},[s,t,n,r]),d=E(a,e);return {sendTransaction:d.mutate,sendTransactionAsync:d.mutateAsync,data:d.data,error:o||d.error,isError:!!o||d.isError,isIdle:d.isIdle,isPending:d.isPending,isSuccess:d.isSuccess,reset:d.reset,status:d.status,variables:d.variables}}function Ht(e){let{activeConnector:r,account:n,accounts:s}=u(),o=E(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(c=>c.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(c=>utils.isSameAddress(c.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:o.mutate,signMessageAsync:o.mutateAsync,data:o.data,error:o.error,isError:o.isError,isIdle:o.isIdle,isPending:o.isPending,isSuccess:o.isSuccess,reset:o.reset,status:o.status,variables:o.variables}}var Y=42,qt=()=>{let{currentApi:e,isApiReady:r,currentChain:n}=u(),s=n?.ss58Format!==void 0?n.ss58Format:Y;return Z.useMemo(()=>{if(e&&r){let t;try{let o=e.consts.system.ss58Prefix;t=utils$1.isNumber(o)?o:Y;}catch(o){console.error("[useSs58Format] Error fetching chainSS58:",o),t=s;}return {data:t,isLoading:false}}else return {data:void 0,isLoading:true}},[e,r,s])};var Jt=()=>{let{status:e}=u();return e};var Wt=e=>{let{switchChain:r,config:n,currentChain:s,currentChainId:t}=u(),i=E(async a=>{await r(a.chainId);},e);return {switchChain:i.mutate,switchChainAsync:i.mutateAsync,chains:n?.chains?[...n.chains]:[],currentChain:s,currentChainId:t,data:i.data,error:i.error,isError:i.isError,isIdle:i.isIdle,isPending:i.isPending,isSuccess:i.isSuccess,reset:i.reset,variables:i.variables}};Object.defineProperty(exports,"ConnectionStatus",{enumerable:true,get:function(){return chunkJJEEWE3N_cjs.a}});exports.LunoProvider=te;exports.useAccount=R;exports.useAccounts=ln;exports.useActiveConnector=fn;exports.useApi=hn;exports.useBalance=In;exports.useBlockNumber=Dn;exports.useChain=On;exports.useChains=kn;exports.useConfig=Hn;exports.useConnect=Qn;exports.useConnectors=Yn;exports.useDisconnect=Zn;exports.useEstimatePaymentInfo=rt;exports.useGenesisHash=ct;exports.usePapiSigner=yt;exports.useRuntimeVersion=Et;exports.useSendTransaction=Rt;exports.useSendTransactionHash=Mt;exports.useSignMessage=Ht;exports.useSigner=J;exports.useSs58Format=qt;exports.useStatus=Jt;exports.useSubscription=k;exports.useSwitchChain=Wt;Object.keys(core).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return core[k]}})});//# sourceMappingURL=index.cjs.map
5
5
  //# sourceMappingURL=index.cjs.map