@0xobelisk/react 1.2.0-pre.85 → 1.2.0-pre.86

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.
@@ -193,7 +193,7 @@ function DubheProvider({ config, children }) {
193
193
  const graphqlClientRef = useRef(null);
194
194
  const hasInitializedGraphql = useRef(false);
195
195
  const getGraphqlClient = () => {
196
- if (!hasInitializedGraphql.current && finalConfig.dubheMetadata) {
196
+ if (!hasInitializedGraphql.current) {
197
197
  try {
198
198
  console.log("Initializing GraphQL client instance (one-time)");
199
199
  graphqlClientRef.current = createDubheGraphqlClient({
@@ -212,11 +212,11 @@ function DubheProvider({ config, children }) {
212
212
  const grpcClientRef = useRef(null);
213
213
  const hasInitializedGrpc = useRef(false);
214
214
  const getGrpcClient = () => {
215
- if (!hasInitializedGrpc.current && finalConfig.endpoints?.grpc) {
215
+ if (!hasInitializedGrpc.current) {
216
216
  try {
217
217
  console.log("Initializing gRPC client instance (one-time)");
218
218
  grpcClientRef.current = new DubheGrpcClient({
219
- baseUrl: finalConfig.endpoints.grpc
219
+ baseUrl: finalConfig.endpoints?.grpc || "http://localhost:50051"
220
220
  });
221
221
  hasInitializedGrpc.current = true;
222
222
  } catch (error) {
@@ -230,10 +230,11 @@ function DubheProvider({ config, children }) {
230
230
  const hasInitializedEcs = useRef(false);
231
231
  const getEcsWorld = () => {
232
232
  const graphqlClient = getGraphqlClient();
233
- if (!hasInitializedEcs.current && graphqlClient) {
233
+ if (!hasInitializedEcs.current) {
234
234
  try {
235
235
  console.log("Initializing ECS World instance (one-time)");
236
236
  ecsWorldRef.current = createECSWorld(graphqlClient, {
237
+ dubheMetadata: finalConfig.dubheMetadata,
237
238
  queryConfig: {
238
239
  enableBatchOptimization: finalConfig.options?.enableBatchOptimization ?? true,
239
240
  defaultCacheTimeout: finalConfig.options?.cacheTimeout ?? 5e3
@@ -399,43 +400,8 @@ function useDubheFromProvider() {
399
400
  const ecsWorld = context.getEcsWorld();
400
401
  const address = context.getAddress();
401
402
  const metrics = context.getMetrics();
402
- const enhancedContract = contract;
403
- if (!enhancedContract.txWithOptions) {
404
- enhancedContract.txWithOptions = (system, method, options = {}) => {
405
- return async (params) => {
406
- try {
407
- const startTime = performance.now();
408
- const result = await contract.tx[system][method](params);
409
- const executionTime = performance.now() - startTime;
410
- if (process.env.NODE_ENV === "development") {
411
- console.log(
412
- `Transaction ${system}.${method} completed in ${executionTime.toFixed(2)}ms`
413
- );
414
- }
415
- options.onSuccess?.(result);
416
- return result;
417
- } catch (error) {
418
- options.onError?.(error);
419
- throw error;
420
- }
421
- };
422
- };
423
- }
424
- if (!enhancedContract.queryWithOptions) {
425
- enhancedContract.queryWithOptions = (system, method, _options = {}) => {
426
- return async (params) => {
427
- const startTime = performance.now();
428
- const result = await contract.query[system][method](params);
429
- const executionTime = performance.now() - startTime;
430
- if (process.env.NODE_ENV === "development") {
431
- console.log(`Query ${system}.${method} completed in ${executionTime.toFixed(2)}ms`);
432
- }
433
- return result;
434
- };
435
- };
436
- }
437
403
  return {
438
- contract: enhancedContract,
404
+ contract,
439
405
  graphqlClient,
440
406
  grpcClient,
441
407
  ecsWorld,
@@ -497,4 +463,4 @@ export {
497
463
  useDubheConfigUpdate2 as useDubheConfigUpdate,
498
464
  useContract
499
465
  };
500
- //# sourceMappingURL=chunk-RDLQECAX.mjs.map
466
+ //# sourceMappingURL=chunk-GPMPANR4.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sui/config.ts","../src/sui/utils.ts","../src/sui/provider.tsx","../src/sui/hooks.ts"],"sourcesContent":["/**\n * Configuration Management for Dubhe React Integration\n *\n * Features:\n * - Type-safe configuration interface\n * - Configuration validation and error handling\n * - Smart merging of defaults and explicit config\n * - No environment variable handling (developers should handle environment variables themselves)\n */\n\nimport { useMemo } from 'react';\nimport type { DubheConfig } from './types';\nimport { mergeConfigurations, validateConfig } from './utils';\n\n/**\n * Default configuration object with sensible defaults\n */\nexport const DEFAULT_CONFIG: Partial<DubheConfig> = {\n endpoints: {\n graphql: 'http://localhost:4000/graphql',\n websocket: 'ws://localhost:4000/graphql'\n },\n options: {\n enableBatchOptimization: true,\n cacheTimeout: 5000,\n debounceMs: 100,\n reconnectOnError: true\n }\n};\n\n/**\n * Configuration Hook: useDubheConfig\n *\n * Merges defaults with explicit configuration provided by the developer\n *\n * Note: Environment variables should be handled by the developer before passing to this hook\n *\n * @param config - Complete or partial configuration object\n * @returns Complete, validated DubheConfig\n *\n * @example\n * ```typescript\n * // Basic usage with explicit config\n * const config = useDubheConfig({\n * network: 'testnet',\n * packageId: '0x123...',\n * metadata: contractMetadata,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY // Handle env vars yourself\n * }\n * });\n *\n * // With helper function to handle environment variables\n * const getConfigFromEnv = () => ({\n * network: process.env.NEXT_PUBLIC_NETWORK as NetworkType,\n * packageId: process.env.NEXT_PUBLIC_PACKAGE_ID,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY\n * }\n * });\n *\n * const config = useDubheConfig({\n * ...getConfigFromEnv(),\n * metadata: contractMetadata\n * });\n * ```\n */\nexport function useDubheConfig(config: Partial<DubheConfig>): DubheConfig {\n // Memoize the stringified config to detect actual changes\n const configKey = useMemo(() => {\n return JSON.stringify(config);\n }, [config]);\n\n return useMemo(() => {\n // Merge configurations: defaults -> user provided config\n const mergedConfig = mergeConfigurations(DEFAULT_CONFIG, config);\n\n // Validate the final configuration\n const validatedConfig = validateConfig(mergedConfig);\n\n // if (process.env.NODE_ENV === 'development') {\n // console.log('🔧 Dubhe Config:', {\n // ...validatedConfig,\n // credentials: validatedConfig.credentials?.secretKey ? '[REDACTED]' : undefined\n // });\n // }\n\n return validatedConfig;\n }, [configKey]);\n}\n","/**\n * Utility Functions for Dubhe Configuration Management\n *\n * Features:\n * - Configuration validation and error handling\n * - Smart configuration merging with proper type safety\n * - Type-safe configuration validation\n */\n\nimport type { DubheConfig } from './types';\n\n/**\n * Merge multiple configuration objects with proper deep merging\n * Later configurations override earlier ones\n *\n * @param baseConfig - Base configuration (usually defaults)\n * @param overrideConfig - Override configuration (user provided)\n * @returns Merged configuration\n */\nexport function mergeConfigurations(\n baseConfig: Partial<DubheConfig>,\n overrideConfig?: Partial<DubheConfig>\n): Partial<DubheConfig> {\n if (!overrideConfig) {\n return { ...baseConfig };\n }\n\n const result: Partial<DubheConfig> = { ...baseConfig };\n\n // Merge top-level properties\n Object.assign(result, overrideConfig);\n\n // Deep merge nested objects\n if (overrideConfig.credentials || baseConfig.credentials) {\n result.credentials = {\n ...baseConfig.credentials,\n ...overrideConfig.credentials\n };\n }\n\n if (overrideConfig.endpoints || baseConfig.endpoints) {\n result.endpoints = {\n ...baseConfig.endpoints,\n ...overrideConfig.endpoints\n };\n }\n\n if (overrideConfig.options || baseConfig.options) {\n result.options = {\n ...baseConfig.options,\n ...overrideConfig.options\n };\n }\n\n return result;\n}\n\n/**\n * Validate configuration and ensure required fields are present\n * Throws descriptive errors for missing required fields\n *\n * @param config - Configuration to validate\n * @returns Validated and typed configuration\n * @throws Error if required fields are missing or invalid\n */\nexport function validateConfig(config: Partial<DubheConfig>): DubheConfig {\n const errors: string[] = [];\n\n // Check required fields\n if (!config.network) {\n errors.push('network is required');\n }\n\n if (!config.packageId) {\n errors.push('packageId is required');\n }\n\n if (!config.metadata) {\n errors.push('metadata is required');\n } else {\n // Basic metadata validation\n if (typeof config.metadata !== 'object') {\n errors.push('metadata must be an object');\n } else if (Object.keys(config.metadata).length === 0) {\n errors.push('metadata cannot be empty');\n }\n }\n\n // Validate network type\n if (config.network && !['mainnet', 'testnet', 'devnet', 'localnet'].includes(config.network)) {\n errors.push(\n `invalid network: ${config.network}. Must be one of: mainnet, testnet, devnet, localnet`\n );\n }\n\n // Validate package ID format (enhanced check)\n if (config.packageId) {\n if (!config.packageId.startsWith('0x')) {\n errors.push('packageId must start with 0x');\n } else if (config.packageId.length < 3) {\n errors.push('packageId must be longer than 0x');\n } else if (!/^0x[a-fA-F0-9]+$/.test(config.packageId)) {\n errors.push('packageId must contain only hexadecimal characters after 0x');\n }\n }\n\n // Validate dubheMetadata if provided\n if (config.dubheMetadata !== undefined) {\n if (typeof config.dubheMetadata !== 'object' || config.dubheMetadata === null) {\n errors.push('dubheMetadata must be an object');\n } else if (!config.dubheMetadata.components && !config.dubheMetadata.resources) {\n errors.push('dubheMetadata must contain components or resources');\n }\n }\n\n // Validate credentials if provided\n if (config.credentials) {\n if (config.credentials.secretKey && typeof config.credentials.secretKey !== 'string') {\n errors.push('credentials.secretKey must be a string');\n }\n if (config.credentials.mnemonics && typeof config.credentials.mnemonics !== 'string') {\n errors.push('credentials.mnemonics must be a string');\n }\n }\n\n // Validate URLs if provided\n if (config.endpoints?.graphql && !isValidUrl(config.endpoints.graphql)) {\n errors.push('endpoints.graphql must be a valid URL');\n }\n\n if (config.endpoints?.websocket && !isValidUrl(config.endpoints.websocket)) {\n errors.push('endpoints.websocket must be a valid URL');\n }\n\n // Validate numeric options\n if (\n config.options?.cacheTimeout !== undefined &&\n (typeof config.options.cacheTimeout !== 'number' || config.options.cacheTimeout < 0)\n ) {\n errors.push('options.cacheTimeout must be a non-negative number');\n }\n\n if (\n config.options?.debounceMs !== undefined &&\n (typeof config.options.debounceMs !== 'number' || config.options.debounceMs < 0)\n ) {\n errors.push('options.debounceMs must be a non-negative number');\n }\n\n if (errors.length > 0) {\n const errorMessage = `Invalid Dubhe configuration (${errors.length} error${\n errors.length > 1 ? 's' : ''\n }):\\n${errors.map((e) => `- ${e}`).join('\\n')}`;\n console.error('Configuration validation failed:', { errors, config });\n throw new Error(errorMessage);\n }\n\n return config as DubheConfig;\n}\n\n/**\n * Simple URL validation helper\n *\n * @param url - URL string to validate\n * @returns true if URL is valid, false otherwise\n */\nfunction isValidUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Generate a configuration summary for debugging\n * Hides sensitive information like private keys\n *\n * @param config - Configuration to summarize\n * @returns Safe configuration summary\n */\nexport function getConfigSummary(config: DubheConfig): object {\n return {\n network: config.network,\n packageId: config.packageId,\n dubheSchemaId: config.dubheSchemaId,\n hasMetadata: !!config.metadata,\n hasDubheMetadata: !!config.dubheMetadata,\n hasCredentials: !!config.credentials?.secretKey,\n endpoints: config.endpoints,\n options: config.options\n };\n}\n","/**\n * Dubhe Provider - useRef Pattern for Client Management\n *\n * Features:\n * - 🎯 Single client instances across application lifecycle\n * - ⚡ useRef-based storage (no re-initialization on re-renders)\n * - 🔧 Provider pattern for dependency injection\n * - 🛡️ Complete type safety with strict TypeScript\n * - 📦 Context-based client sharing\n */\n\nimport {\n createContext,\n useContext,\n useRef,\n ReactNode,\n useState,\n useCallback,\n useEffect\n} from 'react';\nimport { Dubhe } from '@0xobelisk/sui-client';\nimport { createDubheGraphqlClient, DubheGraphqlClient } from '@0xobelisk/graphql-client';\nimport { createECSWorld, DubheECSWorld } from '@0xobelisk/ecs';\nimport { DubheGrpcClient } from '@0xobelisk/grpc-client';\nimport { useDubheConfig } from './config';\nimport type { DubheConfig, DubheReturn } from './types';\n\n/**\n * Context interface for Dubhe client instances\n * All clients are stored using useRef to ensure single initialization\n */\ninterface DubheContextValue {\n getContract: () => Dubhe;\n getGraphqlClient: () => DubheGraphqlClient;\n getGrpcClient: () => DubheGrpcClient;\n getEcsWorld: () => DubheECSWorld;\n getAddress: () => string;\n getMetrics: () => {\n initTime: number;\n requestCount: number;\n lastActivity: number;\n };\n config: DubheConfig;\n updateConfig: (newConfig: Partial<DubheConfig>) => void;\n resetClients: (options?: {\n resetContract?: boolean;\n resetGraphql?: boolean;\n resetGrpc?: boolean;\n resetEcs?: boolean;\n }) => void;\n}\n\n/**\n * Context for sharing Dubhe clients across the application\n * Uses useRef pattern to ensure clients are created only once\n */\nconst DubheContext = createContext<DubheContextValue | null>(null);\n\n/**\n * Props interface for DubheProvider component\n */\ninterface DubheProviderProps {\n /** Configuration for Dubhe initialization */\n config: Partial<DubheConfig>;\n /** Child components that will have access to Dubhe clients */\n children: ReactNode;\n}\n\n/**\n * DubheProvider Component - useRef Pattern Implementation\n *\n * This Provider uses useRef to store client instances, ensuring they are:\n * 1. Created only once during component lifecycle\n * 2. Persisted across re-renders without re-initialization\n * 3. Shared efficiently via React Context\n *\n * Key advantages over useMemo:\n * - useRef guarantees single initialization (useMemo can re-run on dependency changes)\n * - No dependency array needed (eliminates potential re-initialization bugs)\n * - Better performance for heavy client objects\n * - Clearer separation of concerns via Provider pattern\n *\n * @param props - Provider props containing config and children\n * @returns Provider component wrapping children with Dubhe context\n *\n * @example\n * ```typescript\n * // App root setup\n * function App() {\n * const dubheConfig = {\n * network: 'devnet',\n * packageId: '0x123...',\n * metadata: contractMetadata,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY\n * }\n * };\n *\n * return (\n * <DubheProvider config={dubheConfig}>\n * <MyApplication />\n * </DubheProvider>\n * );\n * }\n * ```\n */\nexport function DubheProvider({ config, children }: DubheProviderProps) {\n // Use state to manage config for dynamic updates with persistence\n const [currentConfig, setCurrentConfig] = useState<Partial<DubheConfig>>(() => {\n // Try to restore config from localStorage\n if (typeof window !== 'undefined') {\n try {\n const saved = localStorage.getItem('dubhe-config');\n if (saved) {\n const parsedConfig = JSON.parse(saved);\n console.log('Restored Dubhe configuration from localStorage');\n return { ...config, ...parsedConfig };\n }\n } catch (error) {\n console.warn('Failed to restore Dubhe configuration from localStorage', error);\n }\n }\n return config;\n });\n\n // Merge configuration with defaults\n const finalConfig = useDubheConfig(currentConfig);\n\n // Track initialization start time (useRef ensures single timestamp)\n const startTimeRef = useRef<number>(performance.now());\n\n // useRef for contract instance - guarantees single initialization\n // Unlike useMemo, useRef.current is never re-calculated\n const contractRef = useRef<Dubhe | undefined>(undefined);\n const getContract = (): Dubhe => {\n if (!contractRef.current) {\n try {\n console.log('Initializing Dubhe contract instance (one-time)');\n contractRef.current = new Dubhe({\n networkType: finalConfig.network,\n packageId: finalConfig.packageId,\n metadata: finalConfig.metadata,\n secretKey: finalConfig.credentials?.secretKey\n });\n } catch (error) {\n console.error('Contract initialization failed:', error);\n throw error;\n }\n }\n return contractRef.current;\n };\n\n // useRef for GraphQL client instance - single initialization guaranteed\n const graphqlClientRef = useRef<DubheGraphqlClient | null>(null);\n const hasInitializedGraphql = useRef(false);\n const getGraphqlClient = (): DubheGraphqlClient => {\n if (!hasInitializedGraphql.current) {\n try {\n console.log('Initializing GraphQL client instance (one-time)');\n graphqlClientRef.current = createDubheGraphqlClient({\n endpoint: finalConfig.endpoints?.graphql || 'http://localhost:4000/graphql',\n subscriptionEndpoint: finalConfig.endpoints?.websocket || 'ws://localhost:4000/graphql',\n dubheMetadata: finalConfig.dubheMetadata\n });\n hasInitializedGraphql.current = true;\n } catch (error) {\n console.error('GraphQL client initialization failed:', error);\n throw error;\n }\n }\n return graphqlClientRef.current!;\n };\n\n // useRef for gRPC client instance - single initialization guaranteed\n const grpcClientRef = useRef<DubheGrpcClient | null>(null);\n const hasInitializedGrpc = useRef(false);\n const getGrpcClient = (): DubheGrpcClient => {\n if (!hasInitializedGrpc.current) {\n try {\n console.log('Initializing gRPC client instance (one-time)');\n grpcClientRef.current = new DubheGrpcClient({\n baseUrl: finalConfig.endpoints?.grpc || 'http://localhost:50051'\n });\n hasInitializedGrpc.current = true;\n } catch (error) {\n console.error('gRPC client initialization failed:', error);\n throw error;\n }\n }\n return grpcClientRef.current!;\n };\n\n // useRef for ECS World instance - depends on GraphQL client\n const ecsWorldRef = useRef<DubheECSWorld | null>(null);\n const hasInitializedEcs = useRef(false);\n const getEcsWorld = (): DubheECSWorld => {\n const graphqlClient = getGraphqlClient();\n if (!hasInitializedEcs.current) {\n try {\n console.log('Initializing ECS World instance (one-time)');\n ecsWorldRef.current = createECSWorld(graphqlClient, {\n dubheMetadata: finalConfig.dubheMetadata,\n queryConfig: {\n enableBatchOptimization: finalConfig.options?.enableBatchOptimization ?? true,\n defaultCacheTimeout: finalConfig.options?.cacheTimeout ?? 5000\n },\n subscriptionConfig: {\n defaultDebounceMs: finalConfig.options?.debounceMs ?? 100,\n reconnectOnError: finalConfig.options?.reconnectOnError ?? true\n }\n });\n hasInitializedEcs.current = true;\n } catch (error) {\n console.error('ECS World initialization failed:', error);\n throw error;\n }\n }\n return ecsWorldRef.current!;\n };\n\n // Address getter - calculated from contract\n const getAddress = (): string => {\n return getContract().getAddress();\n };\n\n // Metrics getter - performance tracking\n const getMetrics = () => ({\n initTime: performance.now() - (startTimeRef.current || 0),\n requestCount: 0, // Can be enhanced with actual tracking\n lastActivity: Date.now()\n });\n\n // Selective reset client instances\n const resetClients = useCallback(\n (options?: {\n resetContract?: boolean;\n resetGraphql?: boolean;\n resetGrpc?: boolean;\n resetEcs?: boolean;\n }) => {\n const opts = {\n resetContract: true,\n resetGraphql: true,\n resetGrpc: true,\n resetEcs: true,\n ...options\n };\n\n console.log('Resetting Dubhe client instances', opts);\n\n if (opts.resetContract) {\n contractRef.current = undefined;\n }\n if (opts.resetGraphql) {\n graphqlClientRef.current = null;\n hasInitializedGraphql.current = false;\n }\n if (opts.resetGrpc) {\n grpcClientRef.current = null;\n hasInitializedGrpc.current = false;\n }\n if (opts.resetEcs) {\n ecsWorldRef.current = null;\n hasInitializedEcs.current = false;\n }\n\n startTimeRef.current = performance.now();\n },\n []\n );\n\n // Update config without resetting clients (reactive update)\n const updateConfig = useCallback((newConfig: Partial<DubheConfig>) => {\n console.log('Updating Dubhe configuration (reactive)');\n setCurrentConfig((prev) => {\n const updated = { ...prev, ...newConfig };\n // Persist to localStorage\n if (typeof window !== 'undefined') {\n try {\n localStorage.setItem('dubhe-config', JSON.stringify(updated));\n console.log('Persisted Dubhe configuration to localStorage');\n } catch (error) {\n console.warn('Failed to persist Dubhe configuration', error);\n }\n }\n return updated;\n });\n }, []);\n\n // Reactive configuration updates via useEffect\n\n // Monitor Contract configuration changes\n useEffect(() => {\n if (contractRef.current) {\n console.log('Contract config dependencies changed, updating...');\n contractRef.current.updateConfig({\n networkType: finalConfig.network,\n packageId: finalConfig.packageId,\n metadata: finalConfig.metadata,\n secretKey: finalConfig.credentials?.secretKey,\n mnemonics: finalConfig.credentials?.mnemonics\n });\n }\n }, [\n finalConfig.network,\n finalConfig.packageId,\n finalConfig.metadata,\n finalConfig.credentials?.secretKey,\n finalConfig.credentials?.mnemonics\n ]);\n\n // Monitor GraphQL endpoint changes\n useEffect(() => {\n if (graphqlClientRef.current) {\n console.log('GraphQL endpoint dependencies changed, updating...');\n graphqlClientRef.current.updateConfig({\n endpoint: finalConfig.endpoints?.graphql,\n subscriptionEndpoint: finalConfig.endpoints?.websocket\n });\n // Reset ECS World when GraphQL endpoints change (needs new connection)\n ecsWorldRef.current = null;\n hasInitializedEcs.current = false;\n }\n }, [finalConfig.endpoints?.graphql, finalConfig.endpoints?.websocket]);\n\n // Monitor GraphQL metadata changes\n useEffect(() => {\n if (graphqlClientRef.current && finalConfig.dubheMetadata) {\n console.log('GraphQL metadata changed, updating...');\n graphqlClientRef.current.updateConfig({\n dubheMetadata: finalConfig.dubheMetadata\n });\n // Note: ECS will handle its own metadata update via its useEffect\n }\n }, [finalConfig.dubheMetadata]);\n\n // Monitor gRPC configuration changes\n useEffect(() => {\n if (grpcClientRef.current && finalConfig.endpoints?.grpc) {\n console.log('gRPC config dependencies changed, updating...');\n grpcClientRef.current.updateConfig({ baseUrl: finalConfig.endpoints.grpc });\n }\n }, [finalConfig.endpoints?.grpc]);\n\n // Monitor ECS configuration changes\n useEffect(() => {\n if (ecsWorldRef.current) {\n console.log('ECS config dependencies changed, updating...');\n ecsWorldRef.current.updateConfig({\n dubheMetadata: finalConfig.dubheMetadata,\n queryConfig: {\n enableBatchOptimization: finalConfig.options?.enableBatchOptimization,\n defaultCacheTimeout: finalConfig.options?.cacheTimeout\n },\n subscriptionConfig: {\n defaultDebounceMs: finalConfig.options?.debounceMs,\n reconnectOnError: finalConfig.options?.reconnectOnError\n }\n });\n }\n }, [\n finalConfig.dubheMetadata,\n finalConfig.options?.enableBatchOptimization,\n finalConfig.options?.cacheTimeout,\n finalConfig.options?.debounceMs,\n finalConfig.options?.reconnectOnError\n ]);\n\n // Context value - stable reference (no re-renders for consumers)\n const contextValue: DubheContextValue = {\n getContract,\n getGraphqlClient,\n getGrpcClient,\n getEcsWorld,\n getAddress,\n getMetrics,\n config: finalConfig,\n updateConfig,\n resetClients\n };\n\n return <DubheContext.Provider value={contextValue}>{children}</DubheContext.Provider>;\n}\n\n/**\n * Custom hook to access Dubhe context\n * Provides type-safe access to all Dubhe client instances\n *\n * @returns DubheContextValue with all client getters and config\n * @throws Error if used outside of DubheProvider\n *\n * @example\n * ```typescript\n * function MyComponent() {\n * const dubheContext = useDubheContext();\n *\n * const contract = dubheContext.getContract();\n * const graphqlClient = dubheContext.getGraphqlClient();\n * const ecsWorld = dubheContext.getEcsWorld();\n * const address = dubheContext.getAddress();\n *\n * return <div>Connected as {address}</div>;\n * }\n * ```\n */\nexport function useDubheContext(): DubheContextValue {\n const context = useContext(DubheContext);\n\n if (!context) {\n throw new Error(\n 'useDubheContext must be used within a DubheProvider. ' +\n 'Make sure to wrap your app with <DubheProvider config={...}>'\n );\n }\n\n return context;\n}\n\n/**\n * Enhanced hook that mimics the original useDubhe API\n * Uses the Provider pattern internally but maintains backward compatibility\n *\n * @returns DubheReturn object with all instances and metadata\n *\n * @example\n * ```typescript\n * function MyComponent() {\n * const { contract, graphqlClient, ecsWorld, address } = useDubheFromProvider();\n *\n * const handleTransaction = async () => {\n * const tx = new Transaction();\n * await contract.tx.my_system.my_method({ tx });\n * };\n *\n * return <button onClick={handleTransaction}>Execute</button>;\n * }\n * ```\n */\nexport function useDubheFromProvider(): DubheReturn {\n const context = useDubheContext();\n\n // Get instances (lazy initialization via getters)\n const contract = context.getContract();\n const graphqlClient = context.getGraphqlClient();\n const grpcClient = context.getGrpcClient();\n const ecsWorld = context.getEcsWorld();\n const address = context.getAddress();\n const metrics = context.getMetrics();\n\n return {\n contract,\n graphqlClient,\n grpcClient,\n ecsWorld,\n metadata: context.config.metadata,\n network: context.config.network,\n packageId: context.config.packageId,\n dubheSchemaId: context.config.dubheSchemaId,\n address,\n options: context.config.options,\n metrics\n };\n}\n\n/**\n * Individual client hooks for components that only need specific instances\n * These are more efficient than useDubheFromProvider for single-client usage\n */\n\n/**\n * Hook for accessing only the Dubhe contract instance\n */\nexport function useDubheContractFromProvider(): Dubhe {\n const { contract } = useDubheFromProvider();\n return contract;\n}\n\n/**\n * Hook for accessing only the GraphQL client instance\n */\nexport function useDubheGraphQLFromProvider(): DubheGraphqlClient {\n const { getGraphqlClient } = useDubheContext();\n return getGraphqlClient();\n}\n\n/**\n * Hook for accessing only the ECS World instance\n */\nexport function useDubheECSFromProvider(): DubheECSWorld {\n const { getEcsWorld } = useDubheContext();\n return getEcsWorld();\n}\n\n/**\n * Hook for accessing only the gRPC client instance\n */\nexport function useDubheGrpcFromProvider(): DubheGrpcClient {\n const { getGrpcClient } = useDubheContext();\n return getGrpcClient();\n}\n\n/**\n * Hook for accessing configuration update methods\n *\n * @returns Object with updateConfig and resetClients methods\n *\n * @example\n * ```typescript\n * function ConfigUpdater() {\n * const { updateConfig, resetClients, config } = useDubheConfigUpdate();\n *\n * const switchNetwork = () => {\n * updateConfig({\n * network: 'testnet',\n * packageId: '0xnew...'\n * });\n * };\n *\n * return (\n * <div>\n * <p>Current network: {config.network}</p>\n * <button onClick={switchNetwork}>Switch to Testnet</button>\n * <button onClick={resetClients}>Reset Clients</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useDubheConfigUpdate() {\n const { updateConfig, resetClients, config } = useDubheContext();\n return { updateConfig, resetClients, config };\n}\n","/**\n * Modern Dubhe React Hooks - Provider Pattern\n *\n * Features:\n * - 🎯 Simple API design with Provider pattern\n * - ⚡ Single client initialization with useRef\n * - 🔧 Configuration-driven setup (developers handle environment variables themselves)\n * - 🛡️ Complete type safety with strict TypeScript\n * - 📦 Context-based client sharing across components\n */\nimport { Dubhe } from '@0xobelisk/sui-client';\nimport type { DubheGraphqlClient } from '@0xobelisk/graphql-client';\nimport type { DubheECSWorld } from '@0xobelisk/ecs';\n\nimport {\n useDubheFromProvider,\n useDubheContractFromProvider,\n useDubheGraphQLFromProvider,\n useDubheECSFromProvider,\n useDubheConfigUpdate as useDubheConfigUpdateFromProvider\n} from './provider';\nimport type { DubheReturn } from './types';\n\n/**\n * Primary Hook: useDubhe\n *\n * Uses Provider pattern to access shared Dubhe clients with guaranteed single initialization.\n * Must be used within a DubheProvider.\n *\n * @returns Complete Dubhe ecosystem with contract, GraphQL, ECS, and metadata\n *\n * @example\n * ```typescript\n * // App setup with Provider\n * function App() {\n * const config = {\n * network: 'devnet',\n * packageId: '0x123...',\n * metadata: contractMetadata,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY\n * }\n * };\n *\n * return (\n * <DubheProvider config={config}>\n * <MyDApp />\n * </DubheProvider>\n * );\n * }\n *\n * // Component usage\n * function MyDApp() {\n * const { contract, address } = useDubhe();\n * return <div>Connected as {address}</div>;\n * }\n * ```\n */\nexport function useDubhe(): DubheReturn {\n return useDubheFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheContract\n *\n * Returns only the Dubhe contract instance from Provider context.\n * More efficient than useDubhe() when only contract access is needed.\n *\n * @returns Dubhe contract instance\n *\n * @example\n * ```typescript\n * function TransactionComponent() {\n * const contract = useDubheContract();\n *\n * const handleTransaction = async () => {\n * const tx = new Transaction();\n * await contract.tx.my_system.my_method({ tx });\n * };\n *\n * return <button onClick={handleTransaction}>Execute</button>;\n * }\n * ```\n */\nexport function useDubheContract(): Dubhe {\n return useDubheContractFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheGraphQL\n *\n * Returns only the GraphQL client from Provider context.\n * More efficient than useDubhe() when only GraphQL access is needed.\n *\n * @returns GraphQL client instance (always available with default localhost endpoint)\n *\n * @example\n * ```typescript\n * function DataComponent() {\n * const graphqlClient = useDubheGraphQL();\n *\n * useEffect(() => {\n * graphqlClient.query({ ... }).then(setData);\n * }, [graphqlClient]);\n *\n * return <div>{data && JSON.stringify(data)}</div>;\n * }\n * ```\n */\nexport function useDubheGraphQL(): DubheGraphqlClient {\n return useDubheGraphQLFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheECS\n *\n * Returns only the ECS World instance from Provider context.\n * More efficient than useDubhe() when only ECS access is needed.\n *\n * @returns ECS World instance (always available, depends on GraphQL client)\n *\n * @example\n * ```typescript\n * function ECSComponent() {\n * const ecsWorld = useDubheECS();\n *\n * useEffect(() => {\n * ecsWorld.getComponent('MyComponent').then(setComponent);\n * }, [ecsWorld]);\n *\n * return <div>ECS Component Data</div>;\n * }\n * ```\n */\nexport function useDubheECS(): DubheECSWorld {\n return useDubheECSFromProvider();\n}\n\n/**\n * Hook for dynamic configuration updates\n *\n * Provides methods to update provider configuration at runtime\n *\n * @returns Object with updateConfig, resetClients methods and current config\n *\n * @example\n * ```typescript\n * function NetworkSwitcher() {\n * const { updateConfig, config } = useDubheConfigUpdate();\n *\n * const switchToTestnet = () => {\n * updateConfig({\n * network: 'testnet',\n * packageId: '0xTestnetPackageId...'\n * });\n * };\n *\n * return (\n * <div>\n * <p>Network: {config.network}</p>\n * <button onClick={switchToTestnet}>Switch to Testnet</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useDubheConfigUpdate() {\n return useDubheConfigUpdateFromProvider();\n}\n\n/**\n * Compatibility alias for useDubhe\n */\nexport const useContract = useDubhe;\n"],"mappings":";AAUA,SAAS,eAAe;;;ACSjB,SAAS,oBACd,YACA,gBACsB;AACtB,MAAI,CAAC,gBAAgB;AACnB,WAAO,EAAE,GAAG,WAAW;AAAA,EACzB;AAEA,QAAM,SAA+B,EAAE,GAAG,WAAW;AAGrD,SAAO,OAAO,QAAQ,cAAc;AAGpC,MAAI,eAAe,eAAe,WAAW,aAAa;AACxD,WAAO,cAAc;AAAA,MACnB,GAAG,WAAW;AAAA,MACd,GAAG,eAAe;AAAA,IACpB;AAAA,EACF;A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AACtC,SAAO,qBAAqB;AAC9B;AAwBO,SAAS,mBAA0B;AACxC,SAAO,6BAA6B;AACtC;AAuBO,SAAS,kBAAsC;AACpD,SAAO,4BAA4B;AACrC;AAuBO,SAAS,cAA6B;AAC3C,SAAO,wBAAwB;AACjC;AA8BO,SAASA,wBAAuB;AACrC,SAAO,qBAAiC;AAC1C;AAKO,IAAM,cAAc;","names":["useDubheConfigUpdate"]}
package/dist/index.js CHANGED
@@ -223,7 +223,7 @@ function DubheProvider({ config, children }) {
223
223
  const graphqlClientRef = (0, import_react2.useRef)(null);
224
224
  const hasInitializedGraphql = (0, import_react2.useRef)(false);
225
225
  const getGraphqlClient = () => {
226
- if (!hasInitializedGraphql.current && finalConfig.dubheMetadata) {
226
+ if (!hasInitializedGraphql.current) {
227
227
  try {
228
228
  console.log("Initializing GraphQL client instance (one-time)");
229
229
  graphqlClientRef.current = (0, import_graphql_client.createDubheGraphqlClient)({
@@ -242,11 +242,11 @@ function DubheProvider({ config, children }) {
242
242
  const grpcClientRef = (0, import_react2.useRef)(null);
243
243
  const hasInitializedGrpc = (0, import_react2.useRef)(false);
244
244
  const getGrpcClient = () => {
245
- if (!hasInitializedGrpc.current && finalConfig.endpoints?.grpc) {
245
+ if (!hasInitializedGrpc.current) {
246
246
  try {
247
247
  console.log("Initializing gRPC client instance (one-time)");
248
248
  grpcClientRef.current = new import_grpc_client.DubheGrpcClient({
249
- baseUrl: finalConfig.endpoints.grpc
249
+ baseUrl: finalConfig.endpoints?.grpc || "http://localhost:50051"
250
250
  });
251
251
  hasInitializedGrpc.current = true;
252
252
  } catch (error) {
@@ -260,10 +260,11 @@ function DubheProvider({ config, children }) {
260
260
  const hasInitializedEcs = (0, import_react2.useRef)(false);
261
261
  const getEcsWorld = () => {
262
262
  const graphqlClient = getGraphqlClient();
263
- if (!hasInitializedEcs.current && graphqlClient) {
263
+ if (!hasInitializedEcs.current) {
264
264
  try {
265
265
  console.log("Initializing ECS World instance (one-time)");
266
266
  ecsWorldRef.current = (0, import_ecs.createECSWorld)(graphqlClient, {
267
+ dubheMetadata: finalConfig.dubheMetadata,
267
268
  queryConfig: {
268
269
  enableBatchOptimization: finalConfig.options?.enableBatchOptimization ?? true,
269
270
  defaultCacheTimeout: finalConfig.options?.cacheTimeout ?? 5e3
@@ -429,43 +430,8 @@ function useDubheFromProvider() {
429
430
  const ecsWorld = context.getEcsWorld();
430
431
  const address = context.getAddress();
431
432
  const metrics = context.getMetrics();
432
- const enhancedContract = contract;
433
- if (!enhancedContract.txWithOptions) {
434
- enhancedContract.txWithOptions = (system, method, options = {}) => {
435
- return async (params) => {
436
- try {
437
- const startTime = performance.now();
438
- const result = await contract.tx[system][method](params);
439
- const executionTime = performance.now() - startTime;
440
- if (process.env.NODE_ENV === "development") {
441
- console.log(
442
- `Transaction ${system}.${method} completed in ${executionTime.toFixed(2)}ms`
443
- );
444
- }
445
- options.onSuccess?.(result);
446
- return result;
447
- } catch (error) {
448
- options.onError?.(error);
449
- throw error;
450
- }
451
- };
452
- };
453
- }
454
- if (!enhancedContract.queryWithOptions) {
455
- enhancedContract.queryWithOptions = (system, method, _options = {}) => {
456
- return async (params) => {
457
- const startTime = performance.now();
458
- const result = await contract.query[system][method](params);
459
- const executionTime = performance.now() - startTime;
460
- if (process.env.NODE_ENV === "development") {
461
- console.log(`Query ${system}.${method} completed in ${executionTime.toFixed(2)}ms`);
462
- }
463
- return result;
464
- };
465
- };
466
- }
467
433
  return {
468
- contract: enhancedContract,
434
+ contract,
469
435
  graphqlClient,
470
436
  grpcClient,
471
437
  ecsWorld,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/sui/config.ts","../src/sui/utils.ts","../src/sui/provider.tsx","../src/sui/hooks.ts"],"sourcesContent":["/**\n * @0xobelisk/react - Modern Dubhe React Integration\n *\n * 🚀 Provides simple, powerful React experience for multi-chain blockchain development\n *\n * Currently supported:\n * - Sui blockchain ✅\n * - Aptos blockchain (coming soon)\n * - Initia blockchain (coming soon)\n */\n\n// Sui integration\nexport * from './sui/index';\n// TODO: Future extensions\n// export * from './aptos/index';\n// export * from './initia/index';\n","/**\n * Configuration Management for Dubhe React Integration\n *\n * Features:\n * - Type-safe configuration interface\n * - Configuration validation and error handling\n * - Smart merging of defaults and explicit config\n * - No environment variable handling (developers should handle environment variables themselves)\n */\n\nimport { useMemo } from 'react';\nimport type { DubheConfig } from './types';\nimport { mergeConfigurations, validateConfig } from './utils';\n\n/**\n * Default configuration object with sensible defaults\n */\nexport const DEFAULT_CONFIG: Partial<DubheConfig> = {\n endpoints: {\n graphql: 'http://localhost:4000/graphql',\n websocket: 'ws://localhost:4000/graphql'\n },\n options: {\n enableBatchOptimization: true,\n cacheTimeout: 5000,\n debounceMs: 100,\n reconnectOnError: true\n }\n};\n\n/**\n * Configuration Hook: useDubheConfig\n *\n * Merges defaults with explicit configuration provided by the developer\n *\n * Note: Environment variables should be handled by the developer before passing to this hook\n *\n * @param config - Complete or partial configuration object\n * @returns Complete, validated DubheConfig\n *\n * @example\n * ```typescript\n * // Basic usage with explicit config\n * const config = useDubheConfig({\n * network: 'testnet',\n * packageId: '0x123...',\n * metadata: contractMetadata,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY // Handle env vars yourself\n * }\n * });\n *\n * // With helper function to handle environment variables\n * const getConfigFromEnv = () => ({\n * network: process.env.NEXT_PUBLIC_NETWORK as NetworkType,\n * packageId: process.env.NEXT_PUBLIC_PACKAGE_ID,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY\n * }\n * });\n *\n * const config = useDubheConfig({\n * ...getConfigFromEnv(),\n * metadata: contractMetadata\n * });\n * ```\n */\nexport function useDubheConfig(config: Partial<DubheConfig>): DubheConfig {\n // Memoize the stringified config to detect actual changes\n const configKey = useMemo(() => {\n return JSON.stringify(config);\n }, [config]);\n\n return useMemo(() => {\n // Merge configurations: defaults -> user provided config\n const mergedConfig = mergeConfigurations(DEFAULT_CONFIG, config);\n\n // Validate the final configuration\n const validatedConfig = validateConfig(mergedConfig);\n\n // if (process.env.NODE_ENV === 'development') {\n // console.log('🔧 Dubhe Config:', {\n // ...validatedConfig,\n // credentials: validatedConfig.credentials?.secretKey ? '[REDACTED]' : undefined\n // });\n // }\n\n return validatedConfig;\n }, [configKey]);\n}\n","/**\n * Utility Functions for Dubhe Configuration Management\n *\n * Features:\n * - Configuration validation and error handling\n * - Smart configuration merging with proper type safety\n * - Type-safe configuration validation\n */\n\nimport type { DubheConfig } from './types';\n\n/**\n * Merge multiple configuration objects with proper deep merging\n * Later configurations override earlier ones\n *\n * @param baseConfig - Base configuration (usually defaults)\n * @param overrideConfig - Override configuration (user provided)\n * @returns Merged configuration\n */\nexport function mergeConfigurations(\n baseConfig: Partial<DubheConfig>,\n overrideConfig?: Partial<DubheConfig>\n): Partial<DubheConfig> {\n if (!overrideConfig) {\n return { ...baseConfig };\n }\n\n const result: Partial<DubheConfig> = { ...baseConfig };\n\n // Merge top-level properties\n Object.assign(result, overrideConfig);\n\n // Deep merge nested objects\n if (overrideConfig.credentials || baseConfig.credentials) {\n result.credentials = {\n ...baseConfig.credentials,\n ...overrideConfig.credentials\n };\n }\n\n if (overrideConfig.endpoints || baseConfig.endpoints) {\n result.endpoints = {\n ...baseConfig.endpoints,\n ...overrideConfig.endpoints\n };\n }\n\n if (overrideConfig.options || baseConfig.options) {\n result.options = {\n ...baseConfig.options,\n ...overrideConfig.options\n };\n }\n\n return result;\n}\n\n/**\n * Validate configuration and ensure required fields are present\n * Throws descriptive errors for missing required fields\n *\n * @param config - Configuration to validate\n * @returns Validated and typed configuration\n * @throws Error if required fields are missing or invalid\n */\nexport function validateConfig(config: Partial<DubheConfig>): DubheConfig {\n const errors: string[] = [];\n\n // Check required fields\n if (!config.network) {\n errors.push('network is required');\n }\n\n if (!config.packageId) {\n errors.push('packageId is required');\n }\n\n if (!config.metadata) {\n errors.push('metadata is required');\n } else {\n // Basic metadata validation\n if (typeof config.metadata !== 'object') {\n errors.push('metadata must be an object');\n } else if (Object.keys(config.metadata).length === 0) {\n errors.push('metadata cannot be empty');\n }\n }\n\n // Validate network type\n if (config.network && !['mainnet', 'testnet', 'devnet', 'localnet'].includes(config.network)) {\n errors.push(\n `invalid network: ${config.network}. Must be one of: mainnet, testnet, devnet, localnet`\n );\n }\n\n // Validate package ID format (enhanced check)\n if (config.packageId) {\n if (!config.packageId.startsWith('0x')) {\n errors.push('packageId must start with 0x');\n } else if (config.packageId.length < 3) {\n errors.push('packageId must be longer than 0x');\n } else if (!/^0x[a-fA-F0-9]+$/.test(config.packageId)) {\n errors.push('packageId must contain only hexadecimal characters after 0x');\n }\n }\n\n // Validate dubheMetadata if provided\n if (config.dubheMetadata !== undefined) {\n if (typeof config.dubheMetadata !== 'object' || config.dubheMetadata === null) {\n errors.push('dubheMetadata must be an object');\n } else if (!config.dubheMetadata.components && !config.dubheMetadata.resources) {\n errors.push('dubheMetadata must contain components or resources');\n }\n }\n\n // Validate credentials if provided\n if (config.credentials) {\n if (config.credentials.secretKey && typeof config.credentials.secretKey !== 'string') {\n errors.push('credentials.secretKey must be a string');\n }\n if (config.credentials.mnemonics && typeof config.credentials.mnemonics !== 'string') {\n errors.push('credentials.mnemonics must be a string');\n }\n }\n\n // Validate URLs if provided\n if (config.endpoints?.graphql && !isValidUrl(config.endpoints.graphql)) {\n errors.push('endpoints.graphql must be a valid URL');\n }\n\n if (config.endpoints?.websocket && !isValidUrl(config.endpoints.websocket)) {\n errors.push('endpoints.websocket must be a valid URL');\n }\n\n // Validate numeric options\n if (\n config.options?.cacheTimeout !== undefined &&\n (typeof config.options.cacheTimeout !== 'number' || config.options.cacheTimeout < 0)\n ) {\n errors.push('options.cacheTimeout must be a non-negative number');\n }\n\n if (\n config.options?.debounceMs !== undefined &&\n (typeof config.options.debounceMs !== 'number' || config.options.debounceMs < 0)\n ) {\n errors.push('options.debounceMs must be a non-negative number');\n }\n\n if (errors.length > 0) {\n const errorMessage = `Invalid Dubhe configuration (${errors.length} error${\n errors.length > 1 ? 's' : ''\n }):\\n${errors.map((e) => `- ${e}`).join('\\n')}`;\n console.error('Configuration validation failed:', { errors, config });\n throw new Error(errorMessage);\n }\n\n return config as DubheConfig;\n}\n\n/**\n * Simple URL validation helper\n *\n * @param url - URL string to validate\n * @returns true if URL is valid, false otherwise\n */\nfunction isValidUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Generate a configuration summary for debugging\n * Hides sensitive information like private keys\n *\n * @param config - Configuration to summarize\n * @returns Safe configuration summary\n */\nexport function getConfigSummary(config: DubheConfig): object {\n return {\n network: config.network,\n packageId: config.packageId,\n dubheSchemaId: config.dubheSchemaId,\n hasMetadata: !!config.metadata,\n hasDubheMetadata: !!config.dubheMetadata,\n hasCredentials: !!config.credentials?.secretKey,\n endpoints: config.endpoints,\n options: config.options\n };\n}\n","/**\n * Dubhe Provider - useRef Pattern for Client Management\n *\n * Features:\n * - 🎯 Single client instances across application lifecycle\n * - ⚡ useRef-based storage (no re-initialization on re-renders)\n * - 🔧 Provider pattern for dependency injection\n * - 🛡️ Complete type safety with strict TypeScript\n * - 📦 Context-based client sharing\n */\n\nimport {\n createContext,\n useContext,\n useRef,\n ReactNode,\n useState,\n useCallback,\n useEffect\n} from 'react';\nimport { Dubhe } from '@0xobelisk/sui-client';\nimport { createDubheGraphqlClient } from '@0xobelisk/graphql-client';\nimport { createECSWorld } from '@0xobelisk/ecs';\nimport { DubheGrpcClient } from '@0xobelisk/grpc-client';\nimport { useDubheConfig } from './config';\nimport type { DubheConfig, DubheReturn } from './types';\n\n/**\n * Context interface for Dubhe client instances\n * All clients are stored using useRef to ensure single initialization\n */\ninterface DubheContextValue {\n getContract: () => Dubhe;\n getGraphqlClient: () => any | null;\n getGrpcClient: () => DubheGrpcClient | null;\n getEcsWorld: () => any | null;\n getAddress: () => string;\n getMetrics: () => {\n initTime: number;\n requestCount: number;\n lastActivity: number;\n };\n config: DubheConfig;\n updateConfig: (newConfig: Partial<DubheConfig>) => void;\n resetClients: (options?: {\n resetContract?: boolean;\n resetGraphql?: boolean;\n resetGrpc?: boolean;\n resetEcs?: boolean;\n }) => void;\n}\n\n/**\n * Context for sharing Dubhe clients across the application\n * Uses useRef pattern to ensure clients are created only once\n */\nconst DubheContext = createContext<DubheContextValue | null>(null);\n\n/**\n * Props interface for DubheProvider component\n */\ninterface DubheProviderProps {\n /** Configuration for Dubhe initialization */\n config: Partial<DubheConfig>;\n /** Child components that will have access to Dubhe clients */\n children: ReactNode;\n}\n\n/**\n * DubheProvider Component - useRef Pattern Implementation\n *\n * This Provider uses useRef to store client instances, ensuring they are:\n * 1. Created only once during component lifecycle\n * 2. Persisted across re-renders without re-initialization\n * 3. Shared efficiently via React Context\n *\n * Key advantages over useMemo:\n * - useRef guarantees single initialization (useMemo can re-run on dependency changes)\n * - No dependency array needed (eliminates potential re-initialization bugs)\n * - Better performance for heavy client objects\n * - Clearer separation of concerns via Provider pattern\n *\n * @param props - Provider props containing config and children\n * @returns Provider component wrapping children with Dubhe context\n *\n * @example\n * ```typescript\n * // App root setup\n * function App() {\n * const dubheConfig = {\n * network: 'devnet',\n * packageId: '0x123...',\n * metadata: contractMetadata,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY\n * }\n * };\n *\n * return (\n * <DubheProvider config={dubheConfig}>\n * <MyApplication />\n * </DubheProvider>\n * );\n * }\n * ```\n */\nexport function DubheProvider({ config, children }: DubheProviderProps) {\n // Use state to manage config for dynamic updates with persistence\n const [currentConfig, setCurrentConfig] = useState<Partial<DubheConfig>>(() => {\n // Try to restore config from localStorage\n if (typeof window !== 'undefined') {\n try {\n const saved = localStorage.getItem('dubhe-config');\n if (saved) {\n const parsedConfig = JSON.parse(saved);\n console.log('Restored Dubhe configuration from localStorage');\n return { ...config, ...parsedConfig };\n }\n } catch (error) {\n console.warn('Failed to restore Dubhe configuration from localStorage', error);\n }\n }\n return config;\n });\n\n // Merge configuration with defaults\n const finalConfig = useDubheConfig(currentConfig);\n\n // Track initialization start time (useRef ensures single timestamp)\n const startTimeRef = useRef<number>(performance.now());\n\n // useRef for contract instance - guarantees single initialization\n // Unlike useMemo, useRef.current is never re-calculated\n const contractRef = useRef<Dubhe | undefined>(undefined);\n const getContract = (): Dubhe => {\n if (!contractRef.current) {\n try {\n console.log('Initializing Dubhe contract instance (one-time)');\n contractRef.current = new Dubhe({\n networkType: finalConfig.network,\n packageId: finalConfig.packageId,\n metadata: finalConfig.metadata,\n secretKey: finalConfig.credentials?.secretKey\n });\n } catch (error) {\n console.error('Contract initialization failed:', error);\n throw error;\n }\n }\n return contractRef.current;\n };\n\n // useRef for GraphQL client instance - single initialization guaranteed\n const graphqlClientRef = useRef<any | null>(null);\n const hasInitializedGraphql = useRef(false);\n const getGraphqlClient = (): any | null => {\n if (!hasInitializedGraphql.current && finalConfig.dubheMetadata) {\n try {\n console.log('Initializing GraphQL client instance (one-time)');\n graphqlClientRef.current = createDubheGraphqlClient({\n endpoint: finalConfig.endpoints?.graphql || 'http://localhost:4000/graphql',\n subscriptionEndpoint: finalConfig.endpoints?.websocket || 'ws://localhost:4000/graphql',\n dubheMetadata: finalConfig.dubheMetadata\n });\n hasInitializedGraphql.current = true;\n } catch (error) {\n console.error('GraphQL client initialization failed:', error);\n throw error;\n }\n }\n return graphqlClientRef.current;\n };\n\n // useRef for gRPC client instance - single initialization guaranteed\n const grpcClientRef = useRef<DubheGrpcClient | null>(null);\n const hasInitializedGrpc = useRef(false);\n const getGrpcClient = (): DubheGrpcClient | null => {\n if (!hasInitializedGrpc.current && finalConfig.endpoints?.grpc) {\n try {\n console.log('Initializing gRPC client instance (one-time)');\n grpcClientRef.current = new DubheGrpcClient({\n baseUrl: finalConfig.endpoints.grpc\n });\n hasInitializedGrpc.current = true;\n } catch (error) {\n console.error('gRPC client initialization failed:', error);\n throw error;\n }\n }\n return grpcClientRef.current;\n };\n\n // useRef for ECS World instance - depends on GraphQL client\n const ecsWorldRef = useRef<any | null>(null);\n const hasInitializedEcs = useRef(false);\n const getEcsWorld = (): any | null => {\n const graphqlClient = getGraphqlClient();\n if (!hasInitializedEcs.current && graphqlClient) {\n try {\n console.log('Initializing ECS World instance (one-time)');\n ecsWorldRef.current = createECSWorld(graphqlClient, {\n queryConfig: {\n enableBatchOptimization: finalConfig.options?.enableBatchOptimization ?? true,\n defaultCacheTimeout: finalConfig.options?.cacheTimeout ?? 5000\n },\n subscriptionConfig: {\n defaultDebounceMs: finalConfig.options?.debounceMs ?? 100,\n reconnectOnError: finalConfig.options?.reconnectOnError ?? true\n }\n });\n hasInitializedEcs.current = true;\n } catch (error) {\n console.error('ECS World initialization failed:', error);\n throw error;\n }\n }\n return ecsWorldRef.current;\n };\n\n // Address getter - calculated from contract\n const getAddress = (): string => {\n return getContract().getAddress();\n };\n\n // Metrics getter - performance tracking\n const getMetrics = () => ({\n initTime: performance.now() - (startTimeRef.current || 0),\n requestCount: 0, // Can be enhanced with actual tracking\n lastActivity: Date.now()\n });\n\n // Selective reset client instances\n const resetClients = useCallback(\n (options?: {\n resetContract?: boolean;\n resetGraphql?: boolean;\n resetGrpc?: boolean;\n resetEcs?: boolean;\n }) => {\n const opts = {\n resetContract: true,\n resetGraphql: true,\n resetGrpc: true,\n resetEcs: true,\n ...options\n };\n\n console.log('Resetting Dubhe client instances', opts);\n\n if (opts.resetContract) {\n contractRef.current = undefined;\n }\n if (opts.resetGraphql) {\n graphqlClientRef.current = null;\n hasInitializedGraphql.current = false;\n }\n if (opts.resetGrpc) {\n grpcClientRef.current = null;\n hasInitializedGrpc.current = false;\n }\n if (opts.resetEcs) {\n ecsWorldRef.current = null;\n hasInitializedEcs.current = false;\n }\n\n startTimeRef.current = performance.now();\n },\n []\n );\n\n // Update config without resetting clients (reactive update)\n const updateConfig = useCallback((newConfig: Partial<DubheConfig>) => {\n console.log('Updating Dubhe configuration (reactive)');\n setCurrentConfig((prev) => {\n const updated = { ...prev, ...newConfig };\n // Persist to localStorage\n if (typeof window !== 'undefined') {\n try {\n localStorage.setItem('dubhe-config', JSON.stringify(updated));\n console.log('Persisted Dubhe configuration to localStorage');\n } catch (error) {\n console.warn('Failed to persist Dubhe configuration', error);\n }\n }\n return updated;\n });\n }, []);\n\n // Reactive configuration updates via useEffect\n\n // Monitor Contract configuration changes\n useEffect(() => {\n if (contractRef.current) {\n console.log('Contract config dependencies changed, updating...');\n contractRef.current.updateConfig({\n networkType: finalConfig.network,\n packageId: finalConfig.packageId,\n metadata: finalConfig.metadata,\n secretKey: finalConfig.credentials?.secretKey,\n mnemonics: finalConfig.credentials?.mnemonics\n });\n }\n }, [\n finalConfig.network,\n finalConfig.packageId,\n finalConfig.metadata,\n finalConfig.credentials?.secretKey,\n finalConfig.credentials?.mnemonics\n ]);\n\n // Monitor GraphQL endpoint changes\n useEffect(() => {\n if (graphqlClientRef.current) {\n console.log('GraphQL endpoint dependencies changed, updating...');\n graphqlClientRef.current.updateConfig({\n endpoint: finalConfig.endpoints?.graphql,\n subscriptionEndpoint: finalConfig.endpoints?.websocket\n });\n // Reset ECS World when GraphQL endpoints change (needs new connection)\n ecsWorldRef.current = null;\n hasInitializedEcs.current = false;\n }\n }, [finalConfig.endpoints?.graphql, finalConfig.endpoints?.websocket]);\n\n // Monitor GraphQL metadata changes\n useEffect(() => {\n if (graphqlClientRef.current && finalConfig.dubheMetadata) {\n console.log('GraphQL metadata changed, updating...');\n graphqlClientRef.current.updateConfig({\n dubheMetadata: finalConfig.dubheMetadata\n });\n // Note: ECS will handle its own metadata update via its useEffect\n }\n }, [finalConfig.dubheMetadata]);\n\n // Monitor gRPC configuration changes\n useEffect(() => {\n if (grpcClientRef.current && finalConfig.endpoints?.grpc) {\n console.log('gRPC config dependencies changed, updating...');\n grpcClientRef.current.updateConfig({ baseUrl: finalConfig.endpoints.grpc });\n }\n }, [finalConfig.endpoints?.grpc]);\n\n // Monitor ECS configuration changes\n useEffect(() => {\n if (ecsWorldRef.current) {\n console.log('ECS config dependencies changed, updating...');\n ecsWorldRef.current.updateConfig({\n dubheMetadata: finalConfig.dubheMetadata,\n queryConfig: {\n enableBatchOptimization: finalConfig.options?.enableBatchOptimization,\n defaultCacheTimeout: finalConfig.options?.cacheTimeout\n },\n subscriptionConfig: {\n defaultDebounceMs: finalConfig.options?.debounceMs,\n reconnectOnError: finalConfig.options?.reconnectOnError\n }\n });\n }\n }, [\n finalConfig.dubheMetadata,\n finalConfig.options?.enableBatchOptimization,\n finalConfig.options?.cacheTimeout,\n finalConfig.options?.debounceMs,\n finalConfig.options?.reconnectOnError\n ]);\n\n // Context value - stable reference (no re-renders for consumers)\n const contextValue: DubheContextValue = {\n getContract,\n getGraphqlClient,\n getGrpcClient,\n getEcsWorld,\n getAddress,\n getMetrics,\n config: finalConfig,\n updateConfig,\n resetClients\n };\n\n return <DubheContext.Provider value={contextValue}>{children}</DubheContext.Provider>;\n}\n\n/**\n * Custom hook to access Dubhe context\n * Provides type-safe access to all Dubhe client instances\n *\n * @returns DubheContextValue with all client getters and config\n * @throws Error if used outside of DubheProvider\n *\n * @example\n * ```typescript\n * function MyComponent() {\n * const dubheContext = useDubheContext();\n *\n * const contract = dubheContext.getContract();\n * const graphqlClient = dubheContext.getGraphqlClient();\n * const ecsWorld = dubheContext.getEcsWorld();\n * const address = dubheContext.getAddress();\n *\n * return <div>Connected as {address}</div>;\n * }\n * ```\n */\nexport function useDubheContext(): DubheContextValue {\n const context = useContext(DubheContext);\n\n if (!context) {\n throw new Error(\n 'useDubheContext must be used within a DubheProvider. ' +\n 'Make sure to wrap your app with <DubheProvider config={...}>'\n );\n }\n\n return context;\n}\n\n/**\n * Enhanced hook that mimics the original useDubhe API\n * Uses the Provider pattern internally but maintains backward compatibility\n *\n * @returns DubheReturn object with all instances and metadata\n *\n * @example\n * ```typescript\n * function MyComponent() {\n * const { contract, graphqlClient, ecsWorld, address } = useDubheFromProvider();\n *\n * const handleTransaction = async () => {\n * const tx = new Transaction();\n * await contract.tx.my_system.my_method({ tx });\n * };\n *\n * return <button onClick={handleTransaction}>Execute</button>;\n * }\n * ```\n */\nexport function useDubheFromProvider(): DubheReturn {\n const context = useDubheContext();\n\n // Get instances (lazy initialization via getters)\n const contract = context.getContract();\n const graphqlClient = context.getGraphqlClient();\n const grpcClient = context.getGrpcClient();\n const ecsWorld = context.getEcsWorld();\n const address = context.getAddress();\n const metrics = context.getMetrics();\n\n // Enhanced contract with additional methods (similar to original implementation)\n const enhancedContract = contract as any;\n\n // Add transaction methods with error handling (if not already added)\n if (!enhancedContract.txWithOptions) {\n enhancedContract.txWithOptions = (system: string, method: string, options: any = {}) => {\n return async (params: any) => {\n try {\n const startTime = performance.now();\n const result = await contract.tx[system][method](params);\n const executionTime = performance.now() - startTime;\n\n if (process.env.NODE_ENV === 'development') {\n console.log(\n `Transaction ${system}.${method} completed in ${executionTime.toFixed(2)}ms`\n );\n }\n\n options.onSuccess?.(result);\n return result;\n } catch (error) {\n options.onError?.(error);\n throw error;\n }\n };\n };\n }\n\n // Add query methods with performance tracking (if not already added)\n if (!enhancedContract.queryWithOptions) {\n enhancedContract.queryWithOptions = (system: string, method: string, _options: any = {}) => {\n return async (params: any) => {\n const startTime = performance.now();\n const result = await contract.query[system][method](params);\n const executionTime = performance.now() - startTime;\n\n if (process.env.NODE_ENV === 'development') {\n console.log(`Query ${system}.${method} completed in ${executionTime.toFixed(2)}ms`);\n }\n\n return result;\n };\n };\n }\n\n return {\n contract: enhancedContract,\n graphqlClient,\n grpcClient,\n ecsWorld,\n metadata: context.config.metadata,\n network: context.config.network,\n packageId: context.config.packageId,\n dubheSchemaId: context.config.dubheSchemaId,\n address,\n options: context.config.options,\n metrics\n };\n}\n\n/**\n * Individual client hooks for components that only need specific instances\n * These are more efficient than useDubheFromProvider for single-client usage\n */\n\n/**\n * Hook for accessing only the Dubhe contract instance\n */\nexport function useDubheContractFromProvider(): Dubhe {\n const { contract } = useDubheFromProvider();\n return contract;\n}\n\n/**\n * Hook for accessing only the GraphQL client instance\n */\nexport function useDubheGraphQLFromProvider(): any | null {\n const { getGraphqlClient } = useDubheContext();\n return getGraphqlClient();\n}\n\n/**\n * Hook for accessing only the ECS World instance\n */\nexport function useDubheECSFromProvider(): any | null {\n const { getEcsWorld } = useDubheContext();\n return getEcsWorld();\n}\n\n/**\n * Hook for accessing only the gRPC client instance\n */\nexport function useDubheGrpcFromProvider(): DubheGrpcClient | null {\n const { getGrpcClient } = useDubheContext();\n return getGrpcClient();\n}\n\n/**\n * Hook for accessing configuration update methods\n *\n * @returns Object with updateConfig and resetClients methods\n *\n * @example\n * ```typescript\n * function ConfigUpdater() {\n * const { updateConfig, resetClients, config } = useDubheConfigUpdate();\n *\n * const switchNetwork = () => {\n * updateConfig({\n * network: 'testnet',\n * packageId: '0xnew...'\n * });\n * };\n *\n * return (\n * <div>\n * <p>Current network: {config.network}</p>\n * <button onClick={switchNetwork}>Switch to Testnet</button>\n * <button onClick={resetClients}>Reset Clients</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useDubheConfigUpdate() {\n const { updateConfig, resetClients, config } = useDubheContext();\n return { updateConfig, resetClients, config };\n}\n","/**\n * Modern Dubhe React Hooks - Provider Pattern\n *\n * Features:\n * - 🎯 Simple API design with Provider pattern\n * - ⚡ Single client initialization with useRef\n * - 🔧 Configuration-driven setup (developers handle environment variables themselves)\n * - 🛡️ Complete type safety with strict TypeScript\n * - 📦 Context-based client sharing across components\n */\nimport { Dubhe } from '@0xobelisk/sui-client';\n\nimport {\n useDubheFromProvider,\n useDubheContractFromProvider,\n useDubheGraphQLFromProvider,\n useDubheECSFromProvider,\n useDubheConfigUpdate as useDubheConfigUpdateFromProvider\n} from './provider';\nimport type { DubheReturn } from './types';\n\n/**\n * Primary Hook: useDubhe\n *\n * Uses Provider pattern to access shared Dubhe clients with guaranteed single initialization.\n * Must be used within a DubheProvider.\n *\n * @returns Complete Dubhe ecosystem with contract, GraphQL, ECS, and metadata\n *\n * @example\n * ```typescript\n * // App setup with Provider\n * function App() {\n * const config = {\n * network: 'devnet',\n * packageId: '0x123...',\n * metadata: contractMetadata,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY\n * }\n * };\n *\n * return (\n * <DubheProvider config={config}>\n * <MyDApp />\n * </DubheProvider>\n * );\n * }\n *\n * // Component usage\n * function MyDApp() {\n * const { contract, address } = useDubhe();\n * return <div>Connected as {address}</div>;\n * }\n * ```\n */\nexport function useDubhe(): DubheReturn {\n return useDubheFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheContract\n *\n * Returns only the Dubhe contract instance from Provider context.\n * More efficient than useDubhe() when only contract access is needed.\n *\n * @returns Dubhe contract instance\n *\n * @example\n * ```typescript\n * function TransactionComponent() {\n * const contract = useDubheContract();\n *\n * const handleTransaction = async () => {\n * const tx = new Transaction();\n * await contract.tx.my_system.my_method({ tx });\n * };\n *\n * return <button onClick={handleTransaction}>Execute</button>;\n * }\n * ```\n */\nexport function useDubheContract(): Dubhe {\n return useDubheContractFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheGraphQL\n *\n * Returns only the GraphQL client from Provider context.\n * More efficient than useDubhe() when only GraphQL access is needed.\n *\n * @returns GraphQL client instance (null if dubheMetadata not provided)\n *\n * @example\n * ```typescript\n * function DataComponent() {\n * const graphqlClient = useDubheGraphQL();\n *\n * useEffect(() => {\n * if (graphqlClient) {\n * graphqlClient.query({ ... }).then(setData);\n * }\n * }, [graphqlClient]);\n *\n * return <div>{data && JSON.stringify(data)}</div>;\n * }\n * ```\n */\nexport function useDubheGraphQL(): any | null {\n return useDubheGraphQLFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheECS\n *\n * Returns only the ECS World instance from Provider context.\n * More efficient than useDubhe() when only ECS access is needed.\n *\n * @returns ECS World instance (null if GraphQL client not available)\n *\n * @example\n * ```typescript\n * function ECSComponent() {\n * const ecsWorld = useDubheECS();\n *\n * useEffect(() => {\n * if (ecsWorld) {\n * ecsWorld.getComponent('MyComponent').then(setComponent);\n * }\n * }, [ecsWorld]);\n *\n * return <div>ECS Component Data</div>;\n * }\n * ```\n */\nexport function useDubheECS(): any | null {\n return useDubheECSFromProvider();\n}\n\n/**\n * Hook for dynamic configuration updates\n *\n * Provides methods to update provider configuration at runtime\n *\n * @returns Object with updateConfig, resetClients methods and current config\n *\n * @example\n * ```typescript\n * function NetworkSwitcher() {\n * const { updateConfig, config } = useDubheConfigUpdate();\n *\n * const switchToTestnet = () => {\n * updateConfig({\n * network: 'testnet',\n * packageId: '0xTestnetPackageId...'\n * });\n * };\n *\n * return (\n * <div>\n * <p>Network: {config.network}</p>\n * <button onClick={switchToTestnet}>Switch to Testnet</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useDubheConfigUpdate() {\n return useDubheConfigUpdateFromProvider();\n}\n\n/**\n * Compatibility alias for useDubhe\n */\nexport const useContract = useDubhe;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,8BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUA,mBAAwB;;;ACSjB,SAAS,oBACd,YACA,gBACsB;AACtB,MAAI,CAAC,gBAAgB;AACnB,WAAO,EAAE,GAAG,WAAW;AAAA,EACzB;AAEA,QAAM,SAA+B,EAAE,GAAG,WAAW;AAGrD,SAAO,OAAO,QAAQ,cAAc;AAGpC,MAAI,eAAe,eAAe,WAAW,aAAa;AACxD,WAAO,cAAc;AAAA,MACnB,GAAG,WAAW;AAAA,MACd,GAAG,eAAe;AAAA,IACpB;AAAA,EACF;AAEA,MAAI,eAAe,aAAa,WAAW,WAAW;AACpD,WAAO,YAAY;AAAA,MACjB,GAAG,WAAW;AAAA,MACd,GAAG,eAAe;AAAA,IACpB;AAAA,EACF;AAEA,MAAI,eAAe,WAAW,WAAW,SAAS;AAChD,WAAO,UAAU;AAAA,MACf,GAAG,WAAW;AAAA,MACd,GAAG,eAAe;AAAA,IACpB;AAAA,EACF;AAEA,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,QAAQ,CAAC,CAAC,IAAI;AAAA,QACpF;AAEA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU,QAAQ,OAAO;AAAA,IACzB,SAAS,QAAQ,OAAO;AAAA,IACxB,WAAW,QAAQ,OAAO;AAAA,IAC1B,eAAe,QAAQ,OAAO;AAAA,IAC9B;AAAA,IACA,SAAS,QAAQ,OAAO;AAAA,IACxB;AAAA,EACF;AACF;AAUO,SAAS,+BAAsC;AACpD,QAAM,EAAE,SAAS,IAAI,qBAAqB;AAC1C,SAAO;AACT;AAKO,SAAS,8BAA0C;AACxD,QAAM,EAAE,iBAAiB,IAAI,gBAAgB;AAC7C,SAAO,iBAAiB;AAC1B;AAKO,SAAS,0BAAsC;AACpD,QAAM,EAAE,YAAY,IAAI,gBAAgB;AACxC,SAAO,YAAY;AACrB;AAqCO,SAAS,uBAAuB;AACrC,QAAM,EAAE,cAAc,cAAc,OAAO,IAAI,gBAAgB;AAC/D,SAAO,EAAE,cAAc,cAAc,OAAO;AAC9C;;;ACvgBO,SAAS,WAAwB;AACtC,SAAO,qBAAqB;AAC9B;AAwBO,SAAS,mBAA0B;AACxC,SAAO,6BAA6B;AACtC;AAyBO,SAAS,kBAA8B;AAC5C,SAAO,4BAA4B;AACrC;AAyBO,SAAS,cAA0B;AACxC,SAAO,wBAAwB;AACjC;AA8BO,SAASC,wBAAuB;AACrC,SAAO,qBAAiC;AAC1C;AAKO,IAAM,cAAc;","names":["useDubheConfigUpdate","import_react","useDubheConfigUpdate"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/sui/config.ts","../src/sui/utils.ts","../src/sui/provider.tsx","../src/sui/hooks.ts"],"sourcesContent":["/**\n * @0xobelisk/react - Modern Dubhe React Integration\n *\n * 🚀 Provides simple, powerful React experience for multi-chain blockchain development\n *\n * Currently supported:\n * - Sui blockchain ✅\n * - Aptos blockchain (coming soon)\n * - Initia blockchain (coming soon)\n */\n\n// Sui integration\nexport * from './sui/index';\n// TODO: Future extensions\n// export * from './aptos/index';\n// export * from './initia/index';\n","/**\n * Configuration Management for Dubhe React Integration\n *\n * Features:\n * - Type-safe configuration interface\n * - Configuration validation and error handling\n * - Smart merging of defaults and explicit config\n * - No environment variable handling (developers should handle environment variables themselves)\n */\n\nimport { useMemo } from 'react';\nimport type { DubheConfig } from './types';\nimport { mergeConfigurations, validateConfig } from './utils';\n\n/**\n * Default configuration object with sensible defaults\n */\nexport const DEFAULT_CONFIG: Partial<DubheConfig> = {\n endpoints: {\n graphql: 'http://localhost:4000/graphql',\n websocket: 'ws://localhost:4000/graphql'\n },\n options: {\n enableBatchOptimization: true,\n cacheTimeout: 5000,\n debounceMs: 100,\n reconnectOnError: true\n }\n};\n\n/**\n * Configuration Hook: useDubheConfig\n *\n * Merges defaults with explicit configuration provided by the developer\n *\n * Note: Environment variables should be handled by the developer before passing to this hook\n *\n * @param config - Complete or partial configuration object\n * @returns Complete, validated DubheConfig\n *\n * @example\n * ```typescript\n * // Basic usage with explicit config\n * const config = useDubheConfig({\n * network: 'testnet',\n * packageId: '0x123...',\n * metadata: contractMetadata,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY // Handle env vars yourself\n * }\n * });\n *\n * // With helper function to handle environment variables\n * const getConfigFromEnv = () => ({\n * network: process.env.NEXT_PUBLIC_NETWORK as NetworkType,\n * packageId: process.env.NEXT_PUBLIC_PACKAGE_ID,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY\n * }\n * });\n *\n * const config = useDubheConfig({\n * ...getConfigFromEnv(),\n * metadata: contractMetadata\n * });\n * ```\n */\nexport function useDubheConfig(config: Partial<DubheConfig>): DubheConfig {\n // Memoize the stringified config to detect actual changes\n const configKey = useMemo(() => {\n return JSON.stringify(config);\n }, [config]);\n\n return useMemo(() => {\n // Merge configurations: defaults -> user provided config\n const mergedConfig = mergeConfigurations(DEFAULT_CONFIG, config);\n\n // Validate the final configuration\n const validatedConfig = validateConfig(mergedConfig);\n\n // if (process.env.NODE_ENV === 'development') {\n // console.log('🔧 Dubhe Config:', {\n // ...validatedConfig,\n // credentials: validatedConfig.credentials?.secretKey ? '[REDACTED]' : undefined\n // });\n // }\n\n return validatedConfig;\n }, [configKey]);\n}\n","/**\n * Utility Functions for Dubhe Configuration Management\n *\n * Features:\n * - Configuration validation and error handling\n * - Smart configuration merging with proper type safety\n * - Type-safe configuration validation\n */\n\nimport type { DubheConfig } from './types';\n\n/**\n * Merge multiple configuration objects with proper deep merging\n * Later configurations override earlier ones\n *\n * @param baseConfig - Base configuration (usually defaults)\n * @param overrideConfig - Override configuration (user provided)\n * @returns Merged configuration\n */\nexport function mergeConfigurations(\n baseConfig: Partial<DubheConfig>,\n overrideConfig?: Partial<DubheConfig>\n): Partial<DubheConfig> {\n if (!overrideConfig) {\n return { ...baseConfig };\n }\n\n const result: Partial<DubheConfig> = { ...baseConfig };\n\n // Merge top-level properties\n Object.assign(result, overrideConfig);\n\n // Deep merge nested objects\n if (overrideConfig.credentials || baseConfig.credentials) {\n result.credentials = {\n ...baseConfig.credentials,\n ...overrideConfig.credentials\n };\n }\n\n if (overrideConfig.endpoints || baseConfig.endpoints) {\n result.endpoints = {\n ...baseConfig.endpoints,\n ...overrideConfig.endpoints\n };\n }\n\n if (overrideConfig.options || baseConfig.options) {\n result.options = {\n ...baseConfig.options,\n ...overrideConfig.options\n };\n }\n\n return result;\n}\n\n/**\n * Validate configuration and ensure required fields are present\n * Throws descriptive errors for missing required fields\n *\n * @param config - Configuration to validate\n * @returns Validated and typed configuration\n * @throws Error if required fields are missing or invalid\n */\nexport function validateConfig(config: Partial<DubheConfig>): DubheConfig {\n const errors: string[] = [];\n\n // Check required fields\n if (!config.network) {\n errors.push('network is required');\n }\n\n if (!config.packageId) {\n errors.push('packageId is required');\n }\n\n if (!config.metadata) {\n errors.push('metadata is required');\n } else {\n // Basic metadata validation\n if (typeof config.metadata !== 'object') {\n errors.push('metadata must be an object');\n } else if (Object.keys(config.metadata).length === 0) {\n errors.push('metadata cannot be empty');\n }\n }\n\n // Validate network type\n if (config.network && !['mainnet', 'testnet', 'devnet', 'localnet'].includes(config.network)) {\n errors.push(\n `invalid network: ${config.network}. Must be one of: mainnet, testnet, devnet, localnet`\n );\n }\n\n // Validate package ID format (enhanced check)\n if (config.packageId) {\n if (!config.packageId.startsWith('0x')) {\n errors.push('packageId must start with 0x');\n } else if (config.packageId.length < 3) {\n errors.push('packageId must be longer than 0x');\n } else if (!/^0x[a-fA-F0-9]+$/.test(config.packageId)) {\n errors.push('packageId must contain only hexadecimal characters after 0x');\n }\n }\n\n // Validate dubheMetadata if provided\n if (config.dubheMetadata !== undefined) {\n if (typeof config.dubheMetadata !== 'object' || config.dubheMetadata === null) {\n errors.push('dubheMetadata must be an object');\n } else if (!config.dubheMetadata.components && !config.dubheMetadata.resources) {\n errors.push('dubheMetadata must contain components or resources');\n }\n }\n\n // Validate credentials if provided\n if (config.credentials) {\n if (config.credentials.secretKey && typeof config.credentials.secretKey !== 'string') {\n errors.push('credentials.secretKey must be a string');\n }\n if (config.credentials.mnemonics && typeof config.credentials.mnemonics !== 'string') {\n errors.push('credentials.mnemonics must be a string');\n }\n }\n\n // Validate URLs if provided\n if (config.endpoints?.graphql && !isValidUrl(config.endpoints.graphql)) {\n errors.push('endpoints.graphql must be a valid URL');\n }\n\n if (config.endpoints?.websocket && !isValidUrl(config.endpoints.websocket)) {\n errors.push('endpoints.websocket must be a valid URL');\n }\n\n // Validate numeric options\n if (\n config.options?.cacheTimeout !== undefined &&\n (typeof config.options.cacheTimeout !== 'number' || config.options.cacheTimeout < 0)\n ) {\n errors.push('options.cacheTimeout must be a non-negative number');\n }\n\n if (\n config.options?.debounceMs !== undefined &&\n (typeof config.options.debounceMs !== 'number' || config.options.debounceMs < 0)\n ) {\n errors.push('options.debounceMs must be a non-negative number');\n }\n\n if (errors.length > 0) {\n const errorMessage = `Invalid Dubhe configuration (${errors.length} error${\n errors.length > 1 ? 's' : ''\n }):\\n${errors.map((e) => `- ${e}`).join('\\n')}`;\n console.error('Configuration validation failed:', { errors, config });\n throw new Error(errorMessage);\n }\n\n return config as DubheConfig;\n}\n\n/**\n * Simple URL validation helper\n *\n * @param url - URL string to validate\n * @returns true if URL is valid, false otherwise\n */\nfunction isValidUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Generate a configuration summary for debugging\n * Hides sensitive information like private keys\n *\n * @param config - Configuration to summarize\n * @returns Safe configuration summary\n */\nexport function getConfigSummary(config: DubheConfig): object {\n return {\n network: config.network,\n packageId: config.packageId,\n dubheSchemaId: config.dubheSchemaId,\n hasMetadata: !!config.metadata,\n hasDubheMetadata: !!config.dubheMetadata,\n hasCredentials: !!config.credentials?.secretKey,\n endpoints: config.endpoints,\n options: config.options\n };\n}\n","/**\n * Dubhe Provider - useRef Pattern for Client Management\n *\n * Features:\n * - 🎯 Single client instances across application lifecycle\n * - ⚡ useRef-based storage (no re-initialization on re-renders)\n * - 🔧 Provider pattern for dependency injection\n * - 🛡️ Complete type safety with strict TypeScript\n * - 📦 Context-based client sharing\n */\n\nimport {\n createContext,\n useContext,\n useRef,\n ReactNode,\n useState,\n useCallback,\n useEffect\n} from 'react';\nimport { Dubhe } from '@0xobelisk/sui-client';\nimport { createDubheGraphqlClient, DubheGraphqlClient } from '@0xobelisk/graphql-client';\nimport { createECSWorld, DubheECSWorld } from '@0xobelisk/ecs';\nimport { DubheGrpcClient } from '@0xobelisk/grpc-client';\nimport { useDubheConfig } from './config';\nimport type { DubheConfig, DubheReturn } from './types';\n\n/**\n * Context interface for Dubhe client instances\n * All clients are stored using useRef to ensure single initialization\n */\ninterface DubheContextValue {\n getContract: () => Dubhe;\n getGraphqlClient: () => DubheGraphqlClient;\n getGrpcClient: () => DubheGrpcClient;\n getEcsWorld: () => DubheECSWorld;\n getAddress: () => string;\n getMetrics: () => {\n initTime: number;\n requestCount: number;\n lastActivity: number;\n };\n config: DubheConfig;\n updateConfig: (newConfig: Partial<DubheConfig>) => void;\n resetClients: (options?: {\n resetContract?: boolean;\n resetGraphql?: boolean;\n resetGrpc?: boolean;\n resetEcs?: boolean;\n }) => void;\n}\n\n/**\n * Context for sharing Dubhe clients across the application\n * Uses useRef pattern to ensure clients are created only once\n */\nconst DubheContext = createContext<DubheContextValue | null>(null);\n\n/**\n * Props interface for DubheProvider component\n */\ninterface DubheProviderProps {\n /** Configuration for Dubhe initialization */\n config: Partial<DubheConfig>;\n /** Child components that will have access to Dubhe clients */\n children: ReactNode;\n}\n\n/**\n * DubheProvider Component - useRef Pattern Implementation\n *\n * This Provider uses useRef to store client instances, ensuring they are:\n * 1. Created only once during component lifecycle\n * 2. Persisted across re-renders without re-initialization\n * 3. Shared efficiently via React Context\n *\n * Key advantages over useMemo:\n * - useRef guarantees single initialization (useMemo can re-run on dependency changes)\n * - No dependency array needed (eliminates potential re-initialization bugs)\n * - Better performance for heavy client objects\n * - Clearer separation of concerns via Provider pattern\n *\n * @param props - Provider props containing config and children\n * @returns Provider component wrapping children with Dubhe context\n *\n * @example\n * ```typescript\n * // App root setup\n * function App() {\n * const dubheConfig = {\n * network: 'devnet',\n * packageId: '0x123...',\n * metadata: contractMetadata,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY\n * }\n * };\n *\n * return (\n * <DubheProvider config={dubheConfig}>\n * <MyApplication />\n * </DubheProvider>\n * );\n * }\n * ```\n */\nexport function DubheProvider({ config, children }: DubheProviderProps) {\n // Use state to manage config for dynamic updates with persistence\n const [currentConfig, setCurrentConfig] = useState<Partial<DubheConfig>>(() => {\n // Try to restore config from localStorage\n if (typeof window !== 'undefined') {\n try {\n const saved = localStorage.getItem('dubhe-config');\n if (saved) {\n const parsedConfig = JSON.parse(saved);\n console.log('Restored Dubhe configuration from localStorage');\n return { ...config, ...parsedConfig };\n }\n } catch (error) {\n console.warn('Failed to restore Dubhe configuration from localStorage', error);\n }\n }\n return config;\n });\n\n // Merge configuration with defaults\n const finalConfig = useDubheConfig(currentConfig);\n\n // Track initialization start time (useRef ensures single timestamp)\n const startTimeRef = useRef<number>(performance.now());\n\n // useRef for contract instance - guarantees single initialization\n // Unlike useMemo, useRef.current is never re-calculated\n const contractRef = useRef<Dubhe | undefined>(undefined);\n const getContract = (): Dubhe => {\n if (!contractRef.current) {\n try {\n console.log('Initializing Dubhe contract instance (one-time)');\n contractRef.current = new Dubhe({\n networkType: finalConfig.network,\n packageId: finalConfig.packageId,\n metadata: finalConfig.metadata,\n secretKey: finalConfig.credentials?.secretKey\n });\n } catch (error) {\n console.error('Contract initialization failed:', error);\n throw error;\n }\n }\n return contractRef.current;\n };\n\n // useRef for GraphQL client instance - single initialization guaranteed\n const graphqlClientRef = useRef<DubheGraphqlClient | null>(null);\n const hasInitializedGraphql = useRef(false);\n const getGraphqlClient = (): DubheGraphqlClient => {\n if (!hasInitializedGraphql.current) {\n try {\n console.log('Initializing GraphQL client instance (one-time)');\n graphqlClientRef.current = createDubheGraphqlClient({\n endpoint: finalConfig.endpoints?.graphql || 'http://localhost:4000/graphql',\n subscriptionEndpoint: finalConfig.endpoints?.websocket || 'ws://localhost:4000/graphql',\n dubheMetadata: finalConfig.dubheMetadata\n });\n hasInitializedGraphql.current = true;\n } catch (error) {\n console.error('GraphQL client initialization failed:', error);\n throw error;\n }\n }\n return graphqlClientRef.current!;\n };\n\n // useRef for gRPC client instance - single initialization guaranteed\n const grpcClientRef = useRef<DubheGrpcClient | null>(null);\n const hasInitializedGrpc = useRef(false);\n const getGrpcClient = (): DubheGrpcClient => {\n if (!hasInitializedGrpc.current) {\n try {\n console.log('Initializing gRPC client instance (one-time)');\n grpcClientRef.current = new DubheGrpcClient({\n baseUrl: finalConfig.endpoints?.grpc || 'http://localhost:50051'\n });\n hasInitializedGrpc.current = true;\n } catch (error) {\n console.error('gRPC client initialization failed:', error);\n throw error;\n }\n }\n return grpcClientRef.current!;\n };\n\n // useRef for ECS World instance - depends on GraphQL client\n const ecsWorldRef = useRef<DubheECSWorld | null>(null);\n const hasInitializedEcs = useRef(false);\n const getEcsWorld = (): DubheECSWorld => {\n const graphqlClient = getGraphqlClient();\n if (!hasInitializedEcs.current) {\n try {\n console.log('Initializing ECS World instance (one-time)');\n ecsWorldRef.current = createECSWorld(graphqlClient, {\n dubheMetadata: finalConfig.dubheMetadata,\n queryConfig: {\n enableBatchOptimization: finalConfig.options?.enableBatchOptimization ?? true,\n defaultCacheTimeout: finalConfig.options?.cacheTimeout ?? 5000\n },\n subscriptionConfig: {\n defaultDebounceMs: finalConfig.options?.debounceMs ?? 100,\n reconnectOnError: finalConfig.options?.reconnectOnError ?? true\n }\n });\n hasInitializedEcs.current = true;\n } catch (error) {\n console.error('ECS World initialization failed:', error);\n throw error;\n }\n }\n return ecsWorldRef.current!;\n };\n\n // Address getter - calculated from contract\n const getAddress = (): string => {\n return getContract().getAddress();\n };\n\n // Metrics getter - performance tracking\n const getMetrics = () => ({\n initTime: performance.now() - (startTimeRef.current || 0),\n requestCount: 0, // Can be enhanced with actual tracking\n lastActivity: Date.now()\n });\n\n // Selective reset client instances\n const resetClients = useCallback(\n (options?: {\n resetContract?: boolean;\n resetGraphql?: boolean;\n resetGrpc?: boolean;\n resetEcs?: boolean;\n }) => {\n const opts = {\n resetContract: true,\n resetGraphql: true,\n resetGrpc: true,\n resetEcs: true,\n ...options\n };\n\n console.log('Resetting Dubhe client instances', opts);\n\n if (opts.resetContract) {\n contractRef.current = undefined;\n }\n if (opts.resetGraphql) {\n graphqlClientRef.current = null;\n hasInitializedGraphql.current = false;\n }\n if (opts.resetGrpc) {\n grpcClientRef.current = null;\n hasInitializedGrpc.current = false;\n }\n if (opts.resetEcs) {\n ecsWorldRef.current = null;\n hasInitializedEcs.current = false;\n }\n\n startTimeRef.current = performance.now();\n },\n []\n );\n\n // Update config without resetting clients (reactive update)\n const updateConfig = useCallback((newConfig: Partial<DubheConfig>) => {\n console.log('Updating Dubhe configuration (reactive)');\n setCurrentConfig((prev) => {\n const updated = { ...prev, ...newConfig };\n // Persist to localStorage\n if (typeof window !== 'undefined') {\n try {\n localStorage.setItem('dubhe-config', JSON.stringify(updated));\n console.log('Persisted Dubhe configuration to localStorage');\n } catch (error) {\n console.warn('Failed to persist Dubhe configuration', error);\n }\n }\n return updated;\n });\n }, []);\n\n // Reactive configuration updates via useEffect\n\n // Monitor Contract configuration changes\n useEffect(() => {\n if (contractRef.current) {\n console.log('Contract config dependencies changed, updating...');\n contractRef.current.updateConfig({\n networkType: finalConfig.network,\n packageId: finalConfig.packageId,\n metadata: finalConfig.metadata,\n secretKey: finalConfig.credentials?.secretKey,\n mnemonics: finalConfig.credentials?.mnemonics\n });\n }\n }, [\n finalConfig.network,\n finalConfig.packageId,\n finalConfig.metadata,\n finalConfig.credentials?.secretKey,\n finalConfig.credentials?.mnemonics\n ]);\n\n // Monitor GraphQL endpoint changes\n useEffect(() => {\n if (graphqlClientRef.current) {\n console.log('GraphQL endpoint dependencies changed, updating...');\n graphqlClientRef.current.updateConfig({\n endpoint: finalConfig.endpoints?.graphql,\n subscriptionEndpoint: finalConfig.endpoints?.websocket\n });\n // Reset ECS World when GraphQL endpoints change (needs new connection)\n ecsWorldRef.current = null;\n hasInitializedEcs.current = false;\n }\n }, [finalConfig.endpoints?.graphql, finalConfig.endpoints?.websocket]);\n\n // Monitor GraphQL metadata changes\n useEffect(() => {\n if (graphqlClientRef.current && finalConfig.dubheMetadata) {\n console.log('GraphQL metadata changed, updating...');\n graphqlClientRef.current.updateConfig({\n dubheMetadata: finalConfig.dubheMetadata\n });\n // Note: ECS will handle its own metadata update via its useEffect\n }\n }, [finalConfig.dubheMetadata]);\n\n // Monitor gRPC configuration changes\n useEffect(() => {\n if (grpcClientRef.current && finalConfig.endpoints?.grpc) {\n console.log('gRPC config dependencies changed, updating...');\n grpcClientRef.current.updateConfig({ baseUrl: finalConfig.endpoints.grpc });\n }\n }, [finalConfig.endpoints?.grpc]);\n\n // Monitor ECS configuration changes\n useEffect(() => {\n if (ecsWorldRef.current) {\n console.log('ECS config dependencies changed, updating...');\n ecsWorldRef.current.updateConfig({\n dubheMetadata: finalConfig.dubheMetadata,\n queryConfig: {\n enableBatchOptimization: finalConfig.options?.enableBatchOptimization,\n defaultCacheTimeout: finalConfig.options?.cacheTimeout\n },\n subscriptionConfig: {\n defaultDebounceMs: finalConfig.options?.debounceMs,\n reconnectOnError: finalConfig.options?.reconnectOnError\n }\n });\n }\n }, [\n finalConfig.dubheMetadata,\n finalConfig.options?.enableBatchOptimization,\n finalConfig.options?.cacheTimeout,\n finalConfig.options?.debounceMs,\n finalConfig.options?.reconnectOnError\n ]);\n\n // Context value - stable reference (no re-renders for consumers)\n const contextValue: DubheContextValue = {\n getContract,\n getGraphqlClient,\n getGrpcClient,\n getEcsWorld,\n getAddress,\n getMetrics,\n config: finalConfig,\n updateConfig,\n resetClients\n };\n\n return <DubheContext.Provider value={contextValue}>{children}</DubheContext.Provider>;\n}\n\n/**\n * Custom hook to access Dubhe context\n * Provides type-safe access to all Dubhe client instances\n *\n * @returns DubheContextValue with all client getters and config\n * @throws Error if used outside of DubheProvider\n *\n * @example\n * ```typescript\n * function MyComponent() {\n * const dubheContext = useDubheContext();\n *\n * const contract = dubheContext.getContract();\n * const graphqlClient = dubheContext.getGraphqlClient();\n * const ecsWorld = dubheContext.getEcsWorld();\n * const address = dubheContext.getAddress();\n *\n * return <div>Connected as {address}</div>;\n * }\n * ```\n */\nexport function useDubheContext(): DubheContextValue {\n const context = useContext(DubheContext);\n\n if (!context) {\n throw new Error(\n 'useDubheContext must be used within a DubheProvider. ' +\n 'Make sure to wrap your app with <DubheProvider config={...}>'\n );\n }\n\n return context;\n}\n\n/**\n * Enhanced hook that mimics the original useDubhe API\n * Uses the Provider pattern internally but maintains backward compatibility\n *\n * @returns DubheReturn object with all instances and metadata\n *\n * @example\n * ```typescript\n * function MyComponent() {\n * const { contract, graphqlClient, ecsWorld, address } = useDubheFromProvider();\n *\n * const handleTransaction = async () => {\n * const tx = new Transaction();\n * await contract.tx.my_system.my_method({ tx });\n * };\n *\n * return <button onClick={handleTransaction}>Execute</button>;\n * }\n * ```\n */\nexport function useDubheFromProvider(): DubheReturn {\n const context = useDubheContext();\n\n // Get instances (lazy initialization via getters)\n const contract = context.getContract();\n const graphqlClient = context.getGraphqlClient();\n const grpcClient = context.getGrpcClient();\n const ecsWorld = context.getEcsWorld();\n const address = context.getAddress();\n const metrics = context.getMetrics();\n\n return {\n contract,\n graphqlClient,\n grpcClient,\n ecsWorld,\n metadata: context.config.metadata,\n network: context.config.network,\n packageId: context.config.packageId,\n dubheSchemaId: context.config.dubheSchemaId,\n address,\n options: context.config.options,\n metrics\n };\n}\n\n/**\n * Individual client hooks for components that only need specific instances\n * These are more efficient than useDubheFromProvider for single-client usage\n */\n\n/**\n * Hook for accessing only the Dubhe contract instance\n */\nexport function useDubheContractFromProvider(): Dubhe {\n const { contract } = useDubheFromProvider();\n return contract;\n}\n\n/**\n * Hook for accessing only the GraphQL client instance\n */\nexport function useDubheGraphQLFromProvider(): DubheGraphqlClient {\n const { getGraphqlClient } = useDubheContext();\n return getGraphqlClient();\n}\n\n/**\n * Hook for accessing only the ECS World instance\n */\nexport function useDubheECSFromProvider(): DubheECSWorld {\n const { getEcsWorld } = useDubheContext();\n return getEcsWorld();\n}\n\n/**\n * Hook for accessing only the gRPC client instance\n */\nexport function useDubheGrpcFromProvider(): DubheGrpcClient {\n const { getGrpcClient } = useDubheContext();\n return getGrpcClient();\n}\n\n/**\n * Hook for accessing configuration update methods\n *\n * @returns Object with updateConfig and resetClients methods\n *\n * @example\n * ```typescript\n * function ConfigUpdater() {\n * const { updateConfig, resetClients, config } = useDubheConfigUpdate();\n *\n * const switchNetwork = () => {\n * updateConfig({\n * network: 'testnet',\n * packageId: '0xnew...'\n * });\n * };\n *\n * return (\n * <div>\n * <p>Current network: {config.network}</p>\n * <button onClick={switchNetwork}>Switch to Testnet</button>\n * <button onClick={resetClients}>Reset Clients</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useDubheConfigUpdate() {\n const { updateConfig, resetClients, config } = useDubheContext();\n return { updateConfig, resetClients, config };\n}\n","/**\n * Modern Dubhe React Hooks - Provider Pattern\n *\n * Features:\n * - 🎯 Simple API design with Provider pattern\n * - ⚡ Single client initialization with useRef\n * - 🔧 Configuration-driven setup (developers handle environment variables themselves)\n * - 🛡️ Complete type safety with strict TypeScript\n * - 📦 Context-based client sharing across components\n */\nimport { Dubhe } from '@0xobelisk/sui-client';\nimport type { DubheGraphqlClient } from '@0xobelisk/graphql-client';\nimport type { DubheECSWorld } from '@0xobelisk/ecs';\n\nimport {\n useDubheFromProvider,\n useDubheContractFromProvider,\n useDubheGraphQLFromProvider,\n useDubheECSFromProvider,\n useDubheConfigUpdate as useDubheConfigUpdateFromProvider\n} from './provider';\nimport type { DubheReturn } from './types';\n\n/**\n * Primary Hook: useDubhe\n *\n * Uses Provider pattern to access shared Dubhe clients with guaranteed single initialization.\n * Must be used within a DubheProvider.\n *\n * @returns Complete Dubhe ecosystem with contract, GraphQL, ECS, and metadata\n *\n * @example\n * ```typescript\n * // App setup with Provider\n * function App() {\n * const config = {\n * network: 'devnet',\n * packageId: '0x123...',\n * metadata: contractMetadata,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY\n * }\n * };\n *\n * return (\n * <DubheProvider config={config}>\n * <MyDApp />\n * </DubheProvider>\n * );\n * }\n *\n * // Component usage\n * function MyDApp() {\n * const { contract, address } = useDubhe();\n * return <div>Connected as {address}</div>;\n * }\n * ```\n */\nexport function useDubhe(): DubheReturn {\n return useDubheFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheContract\n *\n * Returns only the Dubhe contract instance from Provider context.\n * More efficient than useDubhe() when only contract access is needed.\n *\n * @returns Dubhe contract instance\n *\n * @example\n * ```typescript\n * function TransactionComponent() {\n * const contract = useDubheContract();\n *\n * const handleTransaction = async () => {\n * const tx = new Transaction();\n * await contract.tx.my_system.my_method({ tx });\n * };\n *\n * return <button onClick={handleTransaction}>Execute</button>;\n * }\n * ```\n */\nexport function useDubheContract(): Dubhe {\n return useDubheContractFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheGraphQL\n *\n * Returns only the GraphQL client from Provider context.\n * More efficient than useDubhe() when only GraphQL access is needed.\n *\n * @returns GraphQL client instance (always available with default localhost endpoint)\n *\n * @example\n * ```typescript\n * function DataComponent() {\n * const graphqlClient = useDubheGraphQL();\n *\n * useEffect(() => {\n * graphqlClient.query({ ... }).then(setData);\n * }, [graphqlClient]);\n *\n * return <div>{data && JSON.stringify(data)}</div>;\n * }\n * ```\n */\nexport function useDubheGraphQL(): DubheGraphqlClient {\n return useDubheGraphQLFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheECS\n *\n * Returns only the ECS World instance from Provider context.\n * More efficient than useDubhe() when only ECS access is needed.\n *\n * @returns ECS World instance (always available, depends on GraphQL client)\n *\n * @example\n * ```typescript\n * function ECSComponent() {\n * const ecsWorld = useDubheECS();\n *\n * useEffect(() => {\n * ecsWorld.getComponent('MyComponent').then(setComponent);\n * }, [ecsWorld]);\n *\n * return <div>ECS Component Data</div>;\n * }\n * ```\n */\nexport function useDubheECS(): DubheECSWorld {\n return useDubheECSFromProvider();\n}\n\n/**\n * Hook for dynamic configuration updates\n *\n * Provides methods to update provider configuration at runtime\n *\n * @returns Object with updateConfig, resetClients methods and current config\n *\n * @example\n * ```typescript\n * function NetworkSwitcher() {\n * const { updateConfig, config } = useDubheConfigUpdate();\n *\n * const switchToTestnet = () => {\n * updateConfig({\n * network: 'testnet',\n * packageId: '0xTestnetPackageId...'\n * });\n * };\n *\n * return (\n * <div>\n * <p>Network: {config.network}</p>\n * <button onClick={switchToTestnet}>Switch to Testnet</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useDubheConfigUpdate() {\n return useDubheConfigUpdateFromProvider();\n}\n\n/**\n * Compatibility alias for useDubhe\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QAAQ,OAAO;AAAA,IACxB;AAAA,EACF;AACF;AAUO,SAAS,+BAAsC;AACpD,QAAM,EAAE,SAAS,IAAI,qBAAqB;AAC1C,SAAO;AACT;AAKO,SAAS,8BAAkD;AAChE,QAAM,EAAE,iBAAiB,IAAI,gBAAgB;AAC7C,SAAO,iBAAiB;AAC1B;AAKO,SAAS,0BAAyC;AACvD,QAAM,EAAE,YAAY,IAAI,gBAAgB;AACxC,SAAO,YAAY;AACrB;AAqCO,SAAS,uBAAuB;AACrC,QAAM,EAAE,cAAc,cAAc,OAAO,IAAI,gBAAgB;AAC/D,SAAO,EAAE,cAAc,cAAc,OAAO;AAC9C;;;ACzdO,SAAS,WAAwB;AACtC,SAAO,qBAAqB;AAC9B;AAwBO,SAAS,mBAA0B;AACxC,SAAO,6BAA6B;AACtC;AAuBO,SAAS,kBAAsC;AACpD,SAAO,4BAA4B;AACrC;AAuBO,SAAS,cAA6B;AAC3C,SAAO,wBAAwB;AACjC;AA8BO,SAASC,wBAAuB;AACrC,SAAO,qBAAiC;AAC1C;AAKO,IAAM,cAAc;","names":["useDubheConfigUpdate","import_react","useDubheConfigUpdate"]}
package/dist/index.mjs CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  useDubheECS,
12
12
  useDubheGraphQL,
13
13
  validateConfig
14
- } from "./chunk-RDLQECAX.mjs";
14
+ } from "./chunk-GPMPANR4.mjs";
15
15
  export {
16
16
  DEFAULT_CONFIG,
17
17
  DubheProvider,
@@ -9,6 +9,8 @@
9
9
  * - 📦 Context-based client sharing across components
10
10
  */
11
11
  import { Dubhe } from '@0xobelisk/sui-client';
12
+ import type { DubheGraphqlClient } from '@0xobelisk/graphql-client';
13
+ import type { DubheECSWorld } from '@0xobelisk/ecs';
12
14
  import type { DubheReturn } from './types';
13
15
  /**
14
16
  * Primary Hook: useDubhe
@@ -75,7 +77,7 @@ export declare function useDubheContract(): Dubhe;
75
77
  * Returns only the GraphQL client from Provider context.
76
78
  * More efficient than useDubhe() when only GraphQL access is needed.
77
79
  *
78
- * @returns GraphQL client instance (null if dubheMetadata not provided)
80
+ * @returns GraphQL client instance (always available with default localhost endpoint)
79
81
  *
80
82
  * @example
81
83
  * ```typescript
@@ -83,23 +85,21 @@ export declare function useDubheContract(): Dubhe;
83
85
  * const graphqlClient = useDubheGraphQL();
84
86
  *
85
87
  * useEffect(() => {
86
- * if (graphqlClient) {
87
- * graphqlClient.query({ ... }).then(setData);
88
- * }
88
+ * graphqlClient.query({ ... }).then(setData);
89
89
  * }, [graphqlClient]);
90
90
  *
91
91
  * return <div>{data && JSON.stringify(data)}</div>;
92
92
  * }
93
93
  * ```
94
94
  */
95
- export declare function useDubheGraphQL(): any | null;
95
+ export declare function useDubheGraphQL(): DubheGraphqlClient;
96
96
  /**
97
97
  * Individual Instance Hook: useDubheECS
98
98
  *
99
99
  * Returns only the ECS World instance from Provider context.
100
100
  * More efficient than useDubhe() when only ECS access is needed.
101
101
  *
102
- * @returns ECS World instance (null if GraphQL client not available)
102
+ * @returns ECS World instance (always available, depends on GraphQL client)
103
103
  *
104
104
  * @example
105
105
  * ```typescript
@@ -107,16 +107,14 @@ export declare function useDubheGraphQL(): any | null;
107
107
  * const ecsWorld = useDubheECS();
108
108
  *
109
109
  * useEffect(() => {
110
- * if (ecsWorld) {
111
- * ecsWorld.getComponent('MyComponent').then(setComponent);
112
- * }
110
+ * ecsWorld.getComponent('MyComponent').then(setComponent);
113
111
  * }, [ecsWorld]);
114
112
  *
115
113
  * return <div>ECS Component Data</div>;
116
114
  * }
117
115
  * ```
118
116
  */
119
- export declare function useDubheECS(): any | null;
117
+ export declare function useDubheECS(): DubheECSWorld;
120
118
  /**
121
119
  * Hook for dynamic configuration updates
122
120
  *