@0xobelisk/react 1.2.0-pre.94 → 1.2.0-pre.96
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-Q5VWR7TU.mjs → chunk-R3BJRALM.mjs} +7 -4
- package/dist/chunk-R3BJRALM.mjs.map +1 -0
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/sui/index.d.mts +2 -0
- package/dist/sui/index.d.ts +2 -0
- package/dist/sui/index.js +6 -3
- package/dist/sui/index.js.map +1 -1
- package/dist/sui/index.mjs +1 -1
- package/dist/sui/types.d.ts +2 -0
- package/package.json +6 -6
- package/src/sui/provider.tsx +6 -3
- package/src/sui/types.ts +2 -0
- package/dist/chunk-Q5VWR7TU.mjs.map +0 -1
|
@@ -199,7 +199,8 @@ function DubheProvider({ config, children }) {
|
|
|
199
199
|
metadata: finalConfig.metadata,
|
|
200
200
|
secretKey: finalConfig.credentials?.secretKey,
|
|
201
201
|
mnemonics: finalConfig.credentials?.mnemonics,
|
|
202
|
-
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls
|
|
202
|
+
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,
|
|
203
|
+
channelUrl: finalConfig.endpoints?.channelUrl
|
|
203
204
|
});
|
|
204
205
|
} catch (error) {
|
|
205
206
|
console.error("Contract initialization failed:", error);
|
|
@@ -332,7 +333,8 @@ function DubheProvider({ config, children }) {
|
|
|
332
333
|
metadata: finalConfig.metadata,
|
|
333
334
|
secretKey: finalConfig.credentials?.secretKey,
|
|
334
335
|
mnemonics: finalConfig.credentials?.mnemonics,
|
|
335
|
-
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls
|
|
336
|
+
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,
|
|
337
|
+
channelUrl: finalConfig.endpoints?.channelUrl
|
|
336
338
|
});
|
|
337
339
|
}
|
|
338
340
|
}, [
|
|
@@ -341,7 +343,8 @@ function DubheProvider({ config, children }) {
|
|
|
341
343
|
finalConfig.metadata,
|
|
342
344
|
finalConfig.credentials?.secretKey,
|
|
343
345
|
finalConfig.credentials?.mnemonics,
|
|
344
|
-
finalConfig.endpoints?.fullnodeUrls
|
|
346
|
+
finalConfig.endpoints?.fullnodeUrls,
|
|
347
|
+
finalConfig.endpoints?.channelUrl
|
|
345
348
|
]);
|
|
346
349
|
useEffect(() => {
|
|
347
350
|
if (graphqlClientRef.current) {
|
|
@@ -483,4 +486,4 @@ export {
|
|
|
483
486
|
useDubheConfigUpdate2 as useDubheConfigUpdate,
|
|
484
487
|
useContract
|
|
485
488
|
};
|
|
486
|
-
//# sourceMappingURL=chunk-
|
|
489
|
+
//# sourceMappingURL=chunk-R3BJRALM.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 if (config.endpoints?.grpc && !isValidUrl(config.endpoints.grpc)) {\n errors.push('endpoints.grpc must be a valid URL');\n }\n\n // Validate fullnodeUrls if provided\n if (config.endpoints?.fullnodeUrls) {\n if (!Array.isArray(config.endpoints.fullnodeUrls)) {\n errors.push('endpoints.fullnodeUrls must be an array');\n } else if (config.endpoints.fullnodeUrls.length === 0) {\n errors.push('endpoints.fullnodeUrls cannot be empty if provided');\n } else {\n config.endpoints.fullnodeUrls.forEach((url, index) => {\n if (!isValidUrl(url)) {\n errors.push(`endpoints.fullnodeUrls[${index}] must be a valid URL: ${url}`);\n }\n });\n }\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 // Important: Explicit config takes precedence over localStorage\n return { ...parsedConfig, ...config };\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 mnemonics: finalConfig.credentials?.mnemonics,\n fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,\n channelUrl: finalConfig.endpoints?.channelUrl\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:8080'\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 fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,\n channelUrl: finalConfig.endpoints?.channelUrl\n });\n }\n }, [\n finalConfig.network,\n finalConfig.packageId,\n finalConfig.metadata,\n finalConfig.credentials?.secretKey,\n finalConfig.credentials?.mnemonics,\n finalConfig.endpoints?.fullnodeUrls,\n finalConfig.endpoints?.channelUrl\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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@ -229,7 +229,8 @@ function DubheProvider({ config, children }) {
|
|
|
229
229
|
metadata: finalConfig.metadata,
|
|
230
230
|
secretKey: finalConfig.credentials?.secretKey,
|
|
231
231
|
mnemonics: finalConfig.credentials?.mnemonics,
|
|
232
|
-
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls
|
|
232
|
+
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,
|
|
233
|
+
channelUrl: finalConfig.endpoints?.channelUrl
|
|
233
234
|
});
|
|
234
235
|
} catch (error) {
|
|
235
236
|
console.error("Contract initialization failed:", error);
|
|
@@ -362,7 +363,8 @@ function DubheProvider({ config, children }) {
|
|
|
362
363
|
metadata: finalConfig.metadata,
|
|
363
364
|
secretKey: finalConfig.credentials?.secretKey,
|
|
364
365
|
mnemonics: finalConfig.credentials?.mnemonics,
|
|
365
|
-
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls
|
|
366
|
+
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,
|
|
367
|
+
channelUrl: finalConfig.endpoints?.channelUrl
|
|
366
368
|
});
|
|
367
369
|
}
|
|
368
370
|
}, [
|
|
@@ -371,7 +373,8 @@ function DubheProvider({ config, children }) {
|
|
|
371
373
|
finalConfig.metadata,
|
|
372
374
|
finalConfig.credentials?.secretKey,
|
|
373
375
|
finalConfig.credentials?.mnemonics,
|
|
374
|
-
finalConfig.endpoints?.fullnodeUrls
|
|
376
|
+
finalConfig.endpoints?.fullnodeUrls,
|
|
377
|
+
finalConfig.endpoints?.channelUrl
|
|
375
378
|
]);
|
|
376
379
|
(0, import_react2.useEffect)(() => {
|
|
377
380
|
if (graphqlClientRef.current) {
|
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 if (config.endpoints?.grpc && !isValidUrl(config.endpoints.grpc)) {\n errors.push('endpoints.grpc must be a valid URL');\n }\n\n // Validate fullnodeUrls if provided\n if (config.endpoints?.fullnodeUrls) {\n if (!Array.isArray(config.endpoints.fullnodeUrls)) {\n errors.push('endpoints.fullnodeUrls must be an array');\n } else if (config.endpoints.fullnodeUrls.length === 0) {\n errors.push('endpoints.fullnodeUrls cannot be empty if provided');\n } else {\n config.endpoints.fullnodeUrls.forEach((url, index) => {\n if (!isValidUrl(url)) {\n errors.push(`endpoints.fullnodeUrls[${index}] must be a valid URL: ${url}`);\n }\n });\n }\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 // Important: Explicit config takes precedence over localStorage\n return { ...parsedConfig, ...config };\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 mnemonics: finalConfig.credentials?.mnemonics,\n fullnodeUrls: finalConfig.endpoints?.fullnodeUrls\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:8080'\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 fullnodeUrls: finalConfig.endpoints?.fullnodeUrls\n });\n }\n }, [\n finalConfig.network,\n finalConfig.packageId,\n finalConfig.metadata,\n finalConfig.credentials?.secretKey,\n finalConfig.credentials?.mnemonics,\n finalConfig.endpoints?.fullnodeUrls\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":";;;;;;;;;;;;;;;;;;;;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,W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AA,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;;;AC9dO,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"]}
|
|
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 if (config.endpoints?.grpc && !isValidUrl(config.endpoints.grpc)) {\n errors.push('endpoints.grpc must be a valid URL');\n }\n\n // Validate fullnodeUrls if provided\n if (config.endpoints?.fullnodeUrls) {\n if (!Array.isArray(config.endpoints.fullnodeUrls)) {\n errors.push('endpoints.fullnodeUrls must be an array');\n } else if (config.endpoints.fullnodeUrls.length === 0) {\n errors.push('endpoints.fullnodeUrls cannot be empty if provided');\n } else {\n config.endpoints.fullnodeUrls.forEach((url, index) => {\n if (!isValidUrl(url)) {\n errors.push(`endpoints.fullnodeUrls[${index}] must be a valid URL: ${url}`);\n }\n });\n }\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 // Important: Explicit config takes precedence over localStorage\n return { ...parsedConfig, ...config };\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 mnemonics: finalConfig.credentials?.mnemonics,\n fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,\n channelUrl: finalConfig.endpoints?.channelUrl\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:8080'\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 fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,\n channelUrl: finalConfig.endpoints?.channelUrl\n });\n }\n }, [\n finalConfig.network,\n finalConfig.packageId,\n finalConfig.metadata,\n finalConfig.credentials?.secretKey,\n finalConfig.credentials?.mnemonics,\n finalConfig.endpoints?.fullnodeUrls,\n finalConfig.endpoints?.channelUrl\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":";;;;;;;;;;;;;;;;;;;;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,SAAO;AACT;AAUO,SAAS,eAAe,QAA2C;AACxE,QAAM,SAAmB,CAAC;AAG1B,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,KAAK,qBAAqB;AAAA,EACnC;AAEA,MAAI,CAAC,OAAO,WAAW;AACrB,WAAO,KAA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O,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;;;ACjeO,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
package/dist/sui/index.d.mts
CHANGED
package/dist/sui/index.d.ts
CHANGED
package/dist/sui/index.js
CHANGED
|
@@ -229,7 +229,8 @@ function DubheProvider({ config, children }) {
|
|
|
229
229
|
metadata: finalConfig.metadata,
|
|
230
230
|
secretKey: finalConfig.credentials?.secretKey,
|
|
231
231
|
mnemonics: finalConfig.credentials?.mnemonics,
|
|
232
|
-
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls
|
|
232
|
+
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,
|
|
233
|
+
channelUrl: finalConfig.endpoints?.channelUrl
|
|
233
234
|
});
|
|
234
235
|
} catch (error) {
|
|
235
236
|
console.error("Contract initialization failed:", error);
|
|
@@ -362,7 +363,8 @@ function DubheProvider({ config, children }) {
|
|
|
362
363
|
metadata: finalConfig.metadata,
|
|
363
364
|
secretKey: finalConfig.credentials?.secretKey,
|
|
364
365
|
mnemonics: finalConfig.credentials?.mnemonics,
|
|
365
|
-
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls
|
|
366
|
+
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,
|
|
367
|
+
channelUrl: finalConfig.endpoints?.channelUrl
|
|
366
368
|
});
|
|
367
369
|
}
|
|
368
370
|
}, [
|
|
@@ -371,7 +373,8 @@ function DubheProvider({ config, children }) {
|
|
|
371
373
|
finalConfig.metadata,
|
|
372
374
|
finalConfig.credentials?.secretKey,
|
|
373
375
|
finalConfig.credentials?.mnemonics,
|
|
374
|
-
finalConfig.endpoints?.fullnodeUrls
|
|
376
|
+
finalConfig.endpoints?.fullnodeUrls,
|
|
377
|
+
finalConfig.endpoints?.channelUrl
|
|
375
378
|
]);
|
|
376
379
|
(0, import_react2.useEffect)(() => {
|
|
377
380
|
if (graphqlClientRef.current) {
|
package/dist/sui/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sui/index.ts","../../src/sui/config.ts","../../src/sui/utils.ts","../../src/sui/provider.tsx","../../src/sui/hooks.ts"],"sourcesContent":["/**\n * @0xobelisk/react/sui - Modern Dubhe React Integration\n *\n * 🚀 Simple, powerful, type-safe Sui blockchain development experience\n *\n * Features:\n * - ⚡ Auto-initialization with environment variable support\n * - 🔧 Configuration-driven setup with smart defaults\n * - 🛡️ Complete type safety with strict TypeScript\n * - 📦 Direct instance access without connection state management\n * - 🎯 Intuitive API design following React best practices\n */\n\n// ============ Type Exports ============\nexport type { NetworkType, DubheConfig, ClientConfig, DubheReturn, ContractReturn } from './types';\n\n// ============ Configuration Management ============\nexport { useDubheConfig, DEFAULT_CONFIG } from './config';\n\nexport { mergeConfigurations, validateConfig, getConfigSummary } from './utils';\n\n// ============ Provider Component ============\nexport { DubheProvider } from './provider';\n\n// ============ Modern React Hooks ============\nexport {\n // Primary Hook - Provider pattern\n useDubhe,\n\n // Compatibility alias\n useContract,\n\n // Individual Instance Hooks - optimized for specific use cases\n useDubheContract,\n useDubheGraphQL,\n useDubheECS,\n\n // Configuration Update Hook - for dynamic config changes\n useDubheConfigUpdate\n} from './hooks';\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 if (config.endpoints?.grpc && !isValidUrl(config.endpoints.grpc)) {\n errors.push('endpoints.grpc must be a valid URL');\n }\n\n // Validate fullnodeUrls if provided\n if (config.endpoints?.fullnodeUrls) {\n if (!Array.isArray(config.endpoints.fullnodeUrls)) {\n errors.push('endpoints.fullnodeUrls must be an array');\n } else if (config.endpoints.fullnodeUrls.length === 0) {\n errors.push('endpoints.fullnodeUrls cannot be empty if provided');\n } else {\n config.endpoints.fullnodeUrls.forEach((url, index) => {\n if (!isValidUrl(url)) {\n errors.push(`endpoints.fullnodeUrls[${index}] must be a valid URL: ${url}`);\n }\n });\n }\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 // Important: Explicit config takes precedence over localStorage\n return { ...parsedConfig, ...config };\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 mnemonics: finalConfig.credentials?.mnemonics,\n fullnodeUrls: finalConfig.endpoints?.fullnodeUrls\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:8080'\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 fullnodeUrls: finalConfig.endpoints?.fullnodeUrls\n });\n }\n }, [\n finalConfig.network,\n finalConfig.packageId,\n finalConfig.metadata,\n finalConfig.credentials?.secretKey,\n finalConfig.credentials?.mnemonics,\n finalConfig.endpoints?.fullnodeUrls\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":";;;;;;;;;;;;;;;;;;;;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,SAAO;AACT;AAUO,SAAS,eAAe,QAA2C;AACxE,QAAM,SAAmB,CAAC;AAG1B,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,KAAK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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;;;AC9dO,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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sui/index.ts","../../src/sui/config.ts","../../src/sui/utils.ts","../../src/sui/provider.tsx","../../src/sui/hooks.ts"],"sourcesContent":["/**\n * @0xobelisk/react/sui - Modern Dubhe React Integration\n *\n * 🚀 Simple, powerful, type-safe Sui blockchain development experience\n *\n * Features:\n * - ⚡ Auto-initialization with environment variable support\n * - 🔧 Configuration-driven setup with smart defaults\n * - 🛡️ Complete type safety with strict TypeScript\n * - 📦 Direct instance access without connection state management\n * - 🎯 Intuitive API design following React best practices\n */\n\n// ============ Type Exports ============\nexport type { NetworkType, DubheConfig, ClientConfig, DubheReturn, ContractReturn } from './types';\n\n// ============ Configuration Management ============\nexport { useDubheConfig, DEFAULT_CONFIG } from './config';\n\nexport { mergeConfigurations, validateConfig, getConfigSummary } from './utils';\n\n// ============ Provider Component ============\nexport { DubheProvider } from './provider';\n\n// ============ Modern React Hooks ============\nexport {\n // Primary Hook - Provider pattern\n useDubhe,\n\n // Compatibility alias\n useContract,\n\n // Individual Instance Hooks - optimized for specific use cases\n useDubheContract,\n useDubheGraphQL,\n useDubheECS,\n\n // Configuration Update Hook - for dynamic config changes\n useDubheConfigUpdate\n} from './hooks';\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 if (config.endpoints?.grpc && !isValidUrl(config.endpoints.grpc)) {\n errors.push('endpoints.grpc must be a valid URL');\n }\n\n // Validate fullnodeUrls if provided\n if (config.endpoints?.fullnodeUrls) {\n if (!Array.isArray(config.endpoints.fullnodeUrls)) {\n errors.push('endpoints.fullnodeUrls must be an array');\n } else if (config.endpoints.fullnodeUrls.length === 0) {\n errors.push('endpoints.fullnodeUrls cannot be empty if provided');\n } else {\n config.endpoints.fullnodeUrls.forEach((url, index) => {\n if (!isValidUrl(url)) {\n errors.push(`endpoints.fullnodeUrls[${index}] must be a valid URL: ${url}`);\n }\n });\n }\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 // Important: Explicit config takes precedence over localStorage\n return { ...parsedConfig, ...config };\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 mnemonics: finalConfig.credentials?.mnemonics,\n fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,\n channelUrl: finalConfig.endpoints?.channelUrl\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:8080'\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 fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,\n channelUrl: finalConfig.endpoints?.channelUrl\n });\n }\n }, [\n finalConfig.network,\n finalConfig.packageId,\n finalConfig.metadata,\n finalConfig.credentials?.secretKey,\n finalConfig.credentials?.mnemonics,\n finalConfig.endpoints?.fullnodeUrls,\n finalConfig.endpoints?.channelUrl\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":";;;;;;;;;;;;;;;;;;;;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;AA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AAO;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;;;ACjeO,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/sui/index.mjs
CHANGED
package/dist/sui/types.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0xobelisk/react",
|
|
3
|
-
"version": "1.2.0-pre.
|
|
3
|
+
"version": "1.2.0-pre.96",
|
|
4
4
|
"description": "React integration for Dubhe framework with Sui blockchain support",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dubhe",
|
|
@@ -41,10 +41,10 @@
|
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"@nanostores/react": "^0.8.0",
|
|
43
43
|
"nanostores": "^0.11.4",
|
|
44
|
-
"@0xobelisk/graphql-client": "1.2.0-pre.
|
|
45
|
-
"@0xobelisk/
|
|
46
|
-
"@0xobelisk/grpc-client": "1.2.0-pre.
|
|
47
|
-
"@0xobelisk/
|
|
44
|
+
"@0xobelisk/graphql-client": "1.2.0-pre.96",
|
|
45
|
+
"@0xobelisk/sui-client": "1.2.0-pre.96",
|
|
46
|
+
"@0xobelisk/grpc-client": "1.2.0-pre.96",
|
|
47
|
+
"@0xobelisk/ecs": "1.2.0-pre.96"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
50
|
"@types/node": "^20.8.7",
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"react": "^18.0.0 || ^19.0.0",
|
|
66
66
|
"react-dom": "^18.0.0 || ^19.0.0",
|
|
67
67
|
"zod": "^3.25.0 || ^4.0.0",
|
|
68
|
-
"@0xobelisk/sui-client": "1.2.0-pre.
|
|
68
|
+
"@0xobelisk/sui-client": "1.2.0-pre.96"
|
|
69
69
|
},
|
|
70
70
|
"peerDependenciesMeta": {
|
|
71
71
|
"@0xobelisk/sui-client": {
|
package/src/sui/provider.tsx
CHANGED
|
@@ -143,7 +143,8 @@ export function DubheProvider({ config, children }: DubheProviderProps) {
|
|
|
143
143
|
metadata: finalConfig.metadata,
|
|
144
144
|
secretKey: finalConfig.credentials?.secretKey,
|
|
145
145
|
mnemonics: finalConfig.credentials?.mnemonics,
|
|
146
|
-
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls
|
|
146
|
+
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,
|
|
147
|
+
channelUrl: finalConfig.endpoints?.channelUrl
|
|
147
148
|
});
|
|
148
149
|
} catch (error) {
|
|
149
150
|
console.error('Contract initialization failed:', error);
|
|
@@ -302,7 +303,8 @@ export function DubheProvider({ config, children }: DubheProviderProps) {
|
|
|
302
303
|
metadata: finalConfig.metadata,
|
|
303
304
|
secretKey: finalConfig.credentials?.secretKey,
|
|
304
305
|
mnemonics: finalConfig.credentials?.mnemonics,
|
|
305
|
-
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls
|
|
306
|
+
fullnodeUrls: finalConfig.endpoints?.fullnodeUrls,
|
|
307
|
+
channelUrl: finalConfig.endpoints?.channelUrl
|
|
306
308
|
});
|
|
307
309
|
}
|
|
308
310
|
}, [
|
|
@@ -311,7 +313,8 @@ export function DubheProvider({ config, children }: DubheProviderProps) {
|
|
|
311
313
|
finalConfig.metadata,
|
|
312
314
|
finalConfig.credentials?.secretKey,
|
|
313
315
|
finalConfig.credentials?.mnemonics,
|
|
314
|
-
finalConfig.endpoints?.fullnodeUrls
|
|
316
|
+
finalConfig.endpoints?.fullnodeUrls,
|
|
317
|
+
finalConfig.endpoints?.channelUrl
|
|
315
318
|
]);
|
|
316
319
|
|
|
317
320
|
// Monitor GraphQL endpoint changes
|
package/src/sui/types.ts
CHANGED
|
@@ -1 +0,0 @@
|
|
|
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 if (config.endpoints?.grpc && !isValidUrl(config.endpoints.grpc)) {\n errors.push('endpoints.grpc must be a valid URL');\n }\n\n // Validate fullnodeUrls if provided\n if (config.endpoints?.fullnodeUrls) {\n if (!Array.isArray(config.endpoints.fullnodeUrls)) {\n errors.push('endpoints.fullnodeUrls must be an array');\n } else if (config.endpoints.fullnodeUrls.length === 0) {\n errors.push('endpoints.fullnodeUrls cannot be empty if provided');\n } else {\n config.endpoints.fullnodeUrls.forEach((url, index) => {\n if (!isValidUrl(url)) {\n errors.push(`endpoints.fullnodeUrls[${index}] must be a valid URL: ${url}`);\n }\n });\n }\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 // Important: Explicit config takes precedence over localStorage\n return { ...parsedConfig, ...config };\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 mnemonics: finalConfig.credentials?.mnemonics,\n fullnodeUrls: finalConfig.endpoints?.fullnodeUrls\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:8080'\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 fullnodeUrls: finalConfig.endpoints?.fullnodeUrls\n });\n }\n }, [\n finalConfig.network,\n finalConfig.packageId,\n finalConfig.metadata,\n finalConfig.credentials?.secretKey,\n finalConfig.credentials?.mnemonics,\n finalConfig.endpoints?.fullnodeUrls\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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