@0xobelisk/react 1.2.0-pre.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,374 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ DEFAULT_CONFIG: () => DEFAULT_CONFIG,
24
+ DubheProvider: () => DubheProvider,
25
+ getConfigSummary: () => getConfigSummary,
26
+ mergeConfigurations: () => mergeConfigurations,
27
+ useContract: () => useContract,
28
+ useDubhe: () => useDubhe,
29
+ useDubheConfig: () => useDubheConfig,
30
+ useDubheContract: () => useDubheContract,
31
+ useDubheECS: () => useDubheECS,
32
+ useDubheGraphQL: () => useDubheGraphQL,
33
+ validateConfig: () => validateConfig
34
+ });
35
+ module.exports = __toCommonJS(src_exports);
36
+
37
+ // src/sui/config.ts
38
+ var import_react = require("react");
39
+
40
+ // src/sui/utils.ts
41
+ function mergeConfigurations(baseConfig, overrideConfig) {
42
+ if (!overrideConfig) {
43
+ return { ...baseConfig };
44
+ }
45
+ const result = { ...baseConfig };
46
+ Object.assign(result, overrideConfig);
47
+ if (overrideConfig.credentials || baseConfig.credentials) {
48
+ result.credentials = {
49
+ ...baseConfig.credentials,
50
+ ...overrideConfig.credentials
51
+ };
52
+ }
53
+ if (overrideConfig.endpoints || baseConfig.endpoints) {
54
+ result.endpoints = {
55
+ ...baseConfig.endpoints,
56
+ ...overrideConfig.endpoints
57
+ };
58
+ }
59
+ if (overrideConfig.options || baseConfig.options) {
60
+ result.options = {
61
+ ...baseConfig.options,
62
+ ...overrideConfig.options
63
+ };
64
+ }
65
+ return result;
66
+ }
67
+ function validateConfig(config) {
68
+ const errors = [];
69
+ if (!config.network) {
70
+ errors.push("network is required");
71
+ }
72
+ if (!config.packageId) {
73
+ errors.push("packageId is required");
74
+ }
75
+ if (!config.metadata) {
76
+ errors.push("metadata is required");
77
+ } else {
78
+ if (typeof config.metadata !== "object") {
79
+ errors.push("metadata must be an object");
80
+ } else if (Object.keys(config.metadata).length === 0) {
81
+ errors.push("metadata cannot be empty");
82
+ }
83
+ }
84
+ if (config.network && !["mainnet", "testnet", "devnet", "localnet"].includes(config.network)) {
85
+ errors.push(
86
+ `invalid network: ${config.network}. Must be one of: mainnet, testnet, devnet, localnet`
87
+ );
88
+ }
89
+ if (config.packageId) {
90
+ if (!config.packageId.startsWith("0x")) {
91
+ errors.push("packageId must start with 0x");
92
+ } else if (config.packageId.length < 3) {
93
+ errors.push("packageId must be longer than 0x");
94
+ } else if (!/^0x[a-fA-F0-9]+$/.test(config.packageId)) {
95
+ errors.push("packageId must contain only hexadecimal characters after 0x");
96
+ }
97
+ }
98
+ if (config.dubheMetadata !== void 0) {
99
+ if (typeof config.dubheMetadata !== "object" || config.dubheMetadata === null) {
100
+ errors.push("dubheMetadata must be an object");
101
+ } else if (!config.dubheMetadata.components && !config.dubheMetadata.resources) {
102
+ errors.push("dubheMetadata must contain components or resources");
103
+ }
104
+ }
105
+ if (config.credentials) {
106
+ if (config.credentials.secretKey && typeof config.credentials.secretKey !== "string") {
107
+ errors.push("credentials.secretKey must be a string");
108
+ }
109
+ if (config.credentials.mnemonics && typeof config.credentials.mnemonics !== "string") {
110
+ errors.push("credentials.mnemonics must be a string");
111
+ }
112
+ }
113
+ if (config.endpoints?.graphql && !isValidUrl(config.endpoints.graphql)) {
114
+ errors.push("endpoints.graphql must be a valid URL");
115
+ }
116
+ if (config.endpoints?.websocket && !isValidUrl(config.endpoints.websocket)) {
117
+ errors.push("endpoints.websocket must be a valid URL");
118
+ }
119
+ if (config.options?.cacheTimeout !== void 0 && (typeof config.options.cacheTimeout !== "number" || config.options.cacheTimeout < 0)) {
120
+ errors.push("options.cacheTimeout must be a non-negative number");
121
+ }
122
+ if (config.options?.debounceMs !== void 0 && (typeof config.options.debounceMs !== "number" || config.options.debounceMs < 0)) {
123
+ errors.push("options.debounceMs must be a non-negative number");
124
+ }
125
+ if (errors.length > 0) {
126
+ const errorMessage = `Invalid Dubhe configuration (${errors.length} error${errors.length > 1 ? "s" : ""}):
127
+ ${errors.map((e) => `- ${e}`).join("\n")}`;
128
+ console.error("Configuration validation failed:", { errors, config });
129
+ throw new Error(errorMessage);
130
+ }
131
+ return config;
132
+ }
133
+ function isValidUrl(url) {
134
+ try {
135
+ new URL(url);
136
+ return true;
137
+ } catch {
138
+ return false;
139
+ }
140
+ }
141
+ function getConfigSummary(config) {
142
+ return {
143
+ network: config.network,
144
+ packageId: config.packageId,
145
+ dubheSchemaId: config.dubheSchemaId,
146
+ hasMetadata: !!config.metadata,
147
+ hasDubheMetadata: !!config.dubheMetadata,
148
+ hasCredentials: !!config.credentials?.secretKey,
149
+ endpoints: config.endpoints,
150
+ options: config.options
151
+ };
152
+ }
153
+
154
+ // src/sui/config.ts
155
+ var DEFAULT_CONFIG = {
156
+ endpoints: {
157
+ graphql: "http://localhost:4000/graphql",
158
+ websocket: "ws://localhost:4000/graphql"
159
+ },
160
+ options: {
161
+ enableBatchOptimization: true,
162
+ cacheTimeout: 5e3,
163
+ debounceMs: 100,
164
+ reconnectOnError: true
165
+ }
166
+ };
167
+ function useDubheConfig(config) {
168
+ const configKey = (0, import_react.useMemo)(() => {
169
+ return JSON.stringify(config);
170
+ }, [config]);
171
+ return (0, import_react.useMemo)(() => {
172
+ const mergedConfig = mergeConfigurations(DEFAULT_CONFIG, config);
173
+ const validatedConfig = validateConfig(mergedConfig);
174
+ return validatedConfig;
175
+ }, [configKey]);
176
+ }
177
+
178
+ // src/sui/provider.tsx
179
+ var import_react2 = require("react");
180
+ var import_sui_client = require("@0xobelisk/sui-client");
181
+ var import_graphql_client = require("@0xobelisk/graphql-client");
182
+ var import_ecs = require("@0xobelisk/ecs");
183
+ var import_jsx_runtime = require("react/jsx-runtime");
184
+ var DubheContext = (0, import_react2.createContext)(null);
185
+ function DubheProvider({ config, children }) {
186
+ const finalConfig = useDubheConfig(config);
187
+ const startTimeRef = (0, import_react2.useRef)(performance.now());
188
+ const contractRef = (0, import_react2.useRef)(void 0);
189
+ const getContract = () => {
190
+ if (!contractRef.current) {
191
+ try {
192
+ console.log("Initializing Dubhe contract instance (one-time)");
193
+ contractRef.current = new import_sui_client.Dubhe({
194
+ networkType: finalConfig.network,
195
+ packageId: finalConfig.packageId,
196
+ metadata: finalConfig.metadata,
197
+ secretKey: finalConfig.credentials?.secretKey
198
+ });
199
+ } catch (error) {
200
+ console.error("Contract initialization failed:", error);
201
+ throw error;
202
+ }
203
+ }
204
+ return contractRef.current;
205
+ };
206
+ const graphqlClientRef = (0, import_react2.useRef)(null);
207
+ const hasInitializedGraphql = (0, import_react2.useRef)(false);
208
+ const getGraphqlClient = () => {
209
+ if (!hasInitializedGraphql.current && finalConfig.dubheMetadata) {
210
+ try {
211
+ console.log("Initializing GraphQL client instance (one-time)");
212
+ graphqlClientRef.current = (0, import_graphql_client.createDubheGraphqlClient)({
213
+ endpoint: finalConfig.endpoints?.graphql || "http://localhost:4000/graphql",
214
+ subscriptionEndpoint: finalConfig.endpoints?.websocket || "ws://localhost:4000/graphql",
215
+ dubheMetadata: finalConfig.dubheMetadata
216
+ });
217
+ hasInitializedGraphql.current = true;
218
+ } catch (error) {
219
+ console.error("GraphQL client initialization failed:", error);
220
+ throw error;
221
+ }
222
+ }
223
+ return graphqlClientRef.current;
224
+ };
225
+ const ecsWorldRef = (0, import_react2.useRef)(null);
226
+ const hasInitializedEcs = (0, import_react2.useRef)(false);
227
+ const getEcsWorld = () => {
228
+ const graphqlClient = getGraphqlClient();
229
+ if (!hasInitializedEcs.current && graphqlClient) {
230
+ try {
231
+ console.log("Initializing ECS World instance (one-time)");
232
+ ecsWorldRef.current = (0, import_ecs.createECSWorld)(graphqlClient, {
233
+ queryConfig: {
234
+ enableBatchOptimization: finalConfig.options?.enableBatchOptimization ?? true,
235
+ defaultCacheTimeout: finalConfig.options?.cacheTimeout ?? 5e3
236
+ },
237
+ subscriptionConfig: {
238
+ defaultDebounceMs: finalConfig.options?.debounceMs ?? 100,
239
+ reconnectOnError: finalConfig.options?.reconnectOnError ?? true
240
+ }
241
+ });
242
+ hasInitializedEcs.current = true;
243
+ } catch (error) {
244
+ console.error("ECS World initialization failed:", error);
245
+ throw error;
246
+ }
247
+ }
248
+ return ecsWorldRef.current;
249
+ };
250
+ const getAddress = () => {
251
+ return getContract().getAddress();
252
+ };
253
+ const getMetrics = () => ({
254
+ initTime: performance.now() - (startTimeRef.current || 0),
255
+ requestCount: 0,
256
+ // Can be enhanced with actual tracking
257
+ lastActivity: Date.now()
258
+ });
259
+ const contextValue = {
260
+ getContract,
261
+ getGraphqlClient,
262
+ getEcsWorld,
263
+ getAddress,
264
+ getMetrics,
265
+ config: finalConfig
266
+ };
267
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DubheContext.Provider, { value: contextValue, children });
268
+ }
269
+ function useDubheContext() {
270
+ const context = (0, import_react2.useContext)(DubheContext);
271
+ if (!context) {
272
+ throw new Error(
273
+ "useDubheContext must be used within a DubheProvider. Make sure to wrap your app with <DubheProvider config={...}>"
274
+ );
275
+ }
276
+ return context;
277
+ }
278
+ function useDubheFromProvider() {
279
+ const context = useDubheContext();
280
+ const contract = context.getContract();
281
+ const graphqlClient = context.getGraphqlClient();
282
+ const ecsWorld = context.getEcsWorld();
283
+ const address = context.getAddress();
284
+ const metrics = context.getMetrics();
285
+ const enhancedContract = contract;
286
+ if (!enhancedContract.txWithOptions) {
287
+ enhancedContract.txWithOptions = (system, method, options = {}) => {
288
+ return async (params) => {
289
+ try {
290
+ const startTime = performance.now();
291
+ const result = await contract.tx[system][method](params);
292
+ const executionTime = performance.now() - startTime;
293
+ if (process.env.NODE_ENV === "development") {
294
+ console.log(
295
+ `Transaction ${system}.${method} completed in ${executionTime.toFixed(2)}ms`
296
+ );
297
+ }
298
+ options.onSuccess?.(result);
299
+ return result;
300
+ } catch (error) {
301
+ options.onError?.(error);
302
+ throw error;
303
+ }
304
+ };
305
+ };
306
+ }
307
+ if (!enhancedContract.queryWithOptions) {
308
+ enhancedContract.queryWithOptions = (system, method, options = {}) => {
309
+ return async (params) => {
310
+ const startTime = performance.now();
311
+ const result = await contract.query[system][method](params);
312
+ const executionTime = performance.now() - startTime;
313
+ if (process.env.NODE_ENV === "development") {
314
+ console.log(`Query ${system}.${method} completed in ${executionTime.toFixed(2)}ms`);
315
+ }
316
+ return result;
317
+ };
318
+ };
319
+ }
320
+ return {
321
+ contract: enhancedContract,
322
+ graphqlClient,
323
+ ecsWorld,
324
+ metadata: context.config.metadata,
325
+ network: context.config.network,
326
+ packageId: context.config.packageId,
327
+ dubheSchemaId: context.config.dubheSchemaId,
328
+ address,
329
+ options: context.config.options,
330
+ metrics
331
+ };
332
+ }
333
+ function useDubheContractFromProvider() {
334
+ const { contract } = useDubheFromProvider();
335
+ return contract;
336
+ }
337
+ function useDubheGraphQLFromProvider() {
338
+ const { getGraphqlClient } = useDubheContext();
339
+ return getGraphqlClient();
340
+ }
341
+ function useDubheECSFromProvider() {
342
+ const { getEcsWorld } = useDubheContext();
343
+ return getEcsWorld();
344
+ }
345
+
346
+ // src/sui/hooks.ts
347
+ function useDubhe() {
348
+ return useDubheFromProvider();
349
+ }
350
+ function useDubheContract() {
351
+ return useDubheContractFromProvider();
352
+ }
353
+ function useDubheGraphQL() {
354
+ return useDubheGraphQLFromProvider();
355
+ }
356
+ function useDubheECS() {
357
+ return useDubheECSFromProvider();
358
+ }
359
+ var useContract = useDubhe;
360
+ // Annotate the CommonJS export names for ESM import in node:
361
+ 0 && (module.exports = {
362
+ DEFAULT_CONFIG,
363
+ DubheProvider,
364
+ getConfigSummary,
365
+ mergeConfigurations,
366
+ useContract,
367
+ useDubhe,
368
+ useDubheConfig,
369
+ useDubheContract,
370
+ useDubheECS,
371
+ useDubheGraphQL,
372
+ validateConfig
373
+ });
374
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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, NetworkType } 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, NetworkType } from './types';\n\n/**\n * Merge multiple configuration objects with proper deep merging\n * Later configurations override earlier ones\n *\n * @param baseConfig - Base configuration (usually defaults)\n * @param overrideConfig - Override configuration (user provided)\n * @returns Merged configuration\n */\nexport function mergeConfigurations(\n baseConfig: Partial<DubheConfig>,\n overrideConfig?: Partial<DubheConfig>\n): Partial<DubheConfig> {\n if (!overrideConfig) {\n return { ...baseConfig };\n }\n\n const result: Partial<DubheConfig> = { ...baseConfig };\n\n // Merge top-level properties\n Object.assign(result, overrideConfig);\n\n // Deep merge nested objects\n if (overrideConfig.credentials || baseConfig.credentials) {\n result.credentials = {\n ...baseConfig.credentials,\n ...overrideConfig.credentials\n };\n }\n\n if (overrideConfig.endpoints || baseConfig.endpoints) {\n result.endpoints = {\n ...baseConfig.endpoints,\n ...overrideConfig.endpoints\n };\n }\n\n if (overrideConfig.options || baseConfig.options) {\n result.options = {\n ...baseConfig.options,\n ...overrideConfig.options\n };\n }\n\n return result;\n}\n\n/**\n * Validate configuration and ensure required fields are present\n * Throws descriptive errors for missing required fields\n *\n * @param config - Configuration to validate\n * @returns Validated and typed configuration\n * @throws Error if required fields are missing or invalid\n */\nexport function validateConfig(config: Partial<DubheConfig>): DubheConfig {\n const errors: string[] = [];\n\n // Check required fields\n if (!config.network) {\n errors.push('network is required');\n }\n\n if (!config.packageId) {\n errors.push('packageId is required');\n }\n\n if (!config.metadata) {\n errors.push('metadata is required');\n } else {\n // Basic metadata validation\n if (typeof config.metadata !== 'object') {\n errors.push('metadata must be an object');\n } else if (Object.keys(config.metadata).length === 0) {\n errors.push('metadata cannot be empty');\n }\n }\n\n // Validate network type\n if (config.network && !['mainnet', 'testnet', 'devnet', 'localnet'].includes(config.network)) {\n errors.push(\n `invalid network: ${config.network}. Must be one of: mainnet, testnet, devnet, localnet`\n );\n }\n\n // Validate package ID format (enhanced check)\n if (config.packageId) {\n if (!config.packageId.startsWith('0x')) {\n errors.push('packageId must start with 0x');\n } else if (config.packageId.length < 3) {\n errors.push('packageId must be longer than 0x');\n } else if (!/^0x[a-fA-F0-9]+$/.test(config.packageId)) {\n errors.push('packageId must contain only hexadecimal characters after 0x');\n }\n }\n\n // Validate dubheMetadata if provided\n if (config.dubheMetadata !== undefined) {\n if (typeof config.dubheMetadata !== 'object' || config.dubheMetadata === null) {\n errors.push('dubheMetadata must be an object');\n } else if (!config.dubheMetadata.components && !config.dubheMetadata.resources) {\n errors.push('dubheMetadata must contain components or resources');\n }\n }\n\n // Validate credentials if provided\n if (config.credentials) {\n if (config.credentials.secretKey && typeof config.credentials.secretKey !== 'string') {\n errors.push('credentials.secretKey must be a string');\n }\n if (config.credentials.mnemonics && typeof config.credentials.mnemonics !== 'string') {\n errors.push('credentials.mnemonics must be a string');\n }\n }\n\n // Validate URLs if provided\n if (config.endpoints?.graphql && !isValidUrl(config.endpoints.graphql)) {\n errors.push('endpoints.graphql must be a valid URL');\n }\n\n if (config.endpoints?.websocket && !isValidUrl(config.endpoints.websocket)) {\n errors.push('endpoints.websocket must be a valid URL');\n }\n\n // Validate numeric options\n if (\n config.options?.cacheTimeout !== undefined &&\n (typeof config.options.cacheTimeout !== 'number' || config.options.cacheTimeout < 0)\n ) {\n errors.push('options.cacheTimeout must be a non-negative number');\n }\n\n if (\n config.options?.debounceMs !== undefined &&\n (typeof config.options.debounceMs !== 'number' || config.options.debounceMs < 0)\n ) {\n errors.push('options.debounceMs must be a non-negative number');\n }\n\n if (errors.length > 0) {\n const errorMessage = `Invalid Dubhe configuration (${errors.length} error${errors.length > 1 ? 's' : ''}):\\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 React, { createContext, useContext, useRef, ReactNode } from 'react';\nimport { Dubhe } from '@0xobelisk/sui-client';\nimport { createDubheGraphqlClient } from '@0xobelisk/graphql-client';\nimport { createECSWorld } from '@0xobelisk/ecs';\nimport { useDubheConfig } from './config';\nimport type { DubheConfig, DubheReturn } from './types';\n\n/**\n * Context interface for Dubhe client instances\n * All clients are stored using useRef to ensure single initialization\n */\ninterface DubheContextValue {\n getContract: () => Dubhe;\n getGraphqlClient: () => any | null;\n getEcsWorld: () => any | null;\n getAddress: () => string;\n getMetrics: () => {\n initTime: number;\n requestCount: number;\n lastActivity: number;\n };\n config: DubheConfig;\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 // Merge configuration with defaults (only runs once)\n const finalConfig = useDubheConfig(config);\n\n // Track initialization start time (useRef ensures single timestamp)\n const startTimeRef = useRef<number>(performance.now());\n\n // useRef for contract instance - guarantees single initialization\n // Unlike useMemo, useRef.current is never re-calculated\n const contractRef = useRef<Dubhe | undefined>(undefined);\n const getContract = (): Dubhe => {\n if (!contractRef.current) {\n try {\n console.log('Initializing Dubhe contract instance (one-time)');\n contractRef.current = new Dubhe({\n networkType: finalConfig.network,\n packageId: finalConfig.packageId,\n metadata: finalConfig.metadata,\n secretKey: finalConfig.credentials?.secretKey\n });\n } catch (error) {\n console.error('Contract initialization failed:', error);\n throw error;\n }\n }\n return contractRef.current;\n };\n\n // useRef for GraphQL client instance - single initialization guaranteed\n const graphqlClientRef = useRef<any | null>(null);\n const hasInitializedGraphql = useRef(false);\n const getGraphqlClient = (): any | null => {\n if (!hasInitializedGraphql.current && finalConfig.dubheMetadata) {\n try {\n console.log('Initializing GraphQL client instance (one-time)');\n graphqlClientRef.current = createDubheGraphqlClient({\n endpoint: finalConfig.endpoints?.graphql || 'http://localhost:4000/graphql',\n subscriptionEndpoint: finalConfig.endpoints?.websocket || 'ws://localhost:4000/graphql',\n dubheMetadata: finalConfig.dubheMetadata\n });\n hasInitializedGraphql.current = true;\n } catch (error) {\n console.error('GraphQL client initialization failed:', error);\n throw error;\n }\n }\n return graphqlClientRef.current;\n };\n\n // useRef for ECS World instance - depends on GraphQL client\n const ecsWorldRef = useRef<any | null>(null);\n const hasInitializedEcs = useRef(false);\n const getEcsWorld = (): any | null => {\n const graphqlClient = getGraphqlClient();\n if (!hasInitializedEcs.current && graphqlClient) {\n try {\n console.log('Initializing ECS World instance (one-time)');\n ecsWorldRef.current = createECSWorld(graphqlClient, {\n queryConfig: {\n enableBatchOptimization: finalConfig.options?.enableBatchOptimization ?? true,\n defaultCacheTimeout: finalConfig.options?.cacheTimeout ?? 5000\n },\n subscriptionConfig: {\n defaultDebounceMs: finalConfig.options?.debounceMs ?? 100,\n reconnectOnError: finalConfig.options?.reconnectOnError ?? true\n }\n });\n hasInitializedEcs.current = true;\n } catch (error) {\n console.error('ECS World initialization failed:', error);\n throw error;\n }\n }\n return ecsWorldRef.current;\n };\n\n // Address getter - calculated from contract\n const getAddress = (): string => {\n return getContract().getAddress();\n };\n\n // Metrics getter - performance tracking\n const getMetrics = () => ({\n initTime: performance.now() - (startTimeRef.current || 0),\n requestCount: 0, // Can be enhanced with actual tracking\n lastActivity: Date.now()\n });\n\n // Context value - stable reference (no re-renders for consumers)\n const contextValue: DubheContextValue = {\n getContract,\n getGraphqlClient,\n getEcsWorld,\n getAddress,\n getMetrics,\n config: finalConfig\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 ecsWorld = context.getEcsWorld();\n const address = context.getAddress();\n const metrics = context.getMetrics();\n\n // Enhanced contract with additional methods (similar to original implementation)\n const enhancedContract = contract as any;\n\n // Add transaction methods with error handling (if not already added)\n if (!enhancedContract.txWithOptions) {\n enhancedContract.txWithOptions = (system: string, method: string, options: any = {}) => {\n return async (params: any) => {\n try {\n const startTime = performance.now();\n const result = await contract.tx[system][method](params);\n const executionTime = performance.now() - startTime;\n\n if (process.env.NODE_ENV === 'development') {\n console.log(\n `Transaction ${system}.${method} completed in ${executionTime.toFixed(2)}ms`\n );\n }\n\n options.onSuccess?.(result);\n return result;\n } catch (error) {\n options.onError?.(error);\n throw error;\n }\n };\n };\n }\n\n // Add query methods with performance tracking (if not already added)\n if (!enhancedContract.queryWithOptions) {\n enhancedContract.queryWithOptions = (system: string, method: string, options: any = {}) => {\n return async (params: any) => {\n const startTime = performance.now();\n const result = await contract.query[system][method](params);\n const executionTime = performance.now() - startTime;\n\n if (process.env.NODE_ENV === 'development') {\n console.log(`Query ${system}.${method} completed in ${executionTime.toFixed(2)}ms`);\n }\n\n return result;\n };\n };\n }\n\n return {\n contract: enhancedContract,\n graphqlClient,\n ecsWorld,\n metadata: context.config.metadata,\n network: context.config.network,\n packageId: context.config.packageId,\n dubheSchemaId: context.config.dubheSchemaId,\n address,\n options: context.config.options,\n metrics\n };\n}\n\n/**\n * Individual client hooks for components that only need specific instances\n * These are more efficient than useDubheFromProvider for single-client usage\n */\n\n/**\n * Hook for accessing only the Dubhe contract instance\n */\nexport function useDubheContractFromProvider(): Dubhe {\n const { contract } = useDubheFromProvider();\n return contract;\n}\n\n/**\n * Hook for accessing only the GraphQL client instance\n */\nexport function useDubheGraphQLFromProvider(): any | null {\n const { getGraphqlClient } = useDubheContext();\n return getGraphqlClient();\n}\n\n/**\n * Hook for accessing only the ECS World instance\n */\nexport function useDubheECSFromProvider(): any | null {\n const { getEcsWorld } = useDubheContext();\n return getEcsWorld();\n}\n","/**\n * Modern Dubhe React Hooks - Provider Pattern\n *\n * Features:\n * - 🎯 Simple API design with Provider pattern\n * - ⚡ Single client initialization with useRef\n * - 🔧 Configuration-driven setup (developers handle environment variables themselves)\n * - 🛡️ Complete type safety with strict TypeScript\n * - 📦 Context-based client sharing across components\n */\nimport { Dubhe } from '@0xobelisk/sui-client';\n\nimport {\n useDubheContext,\n useDubheFromProvider,\n useDubheContractFromProvider,\n useDubheGraphQLFromProvider,\n useDubheECSFromProvider\n} from './provider';\nimport type { DubheConfig, DubheReturn } from './types';\n\n/**\n * Primary Hook: useDubhe\n *\n * Uses Provider pattern to access shared Dubhe clients with guaranteed single initialization.\n * Must be used within a DubheProvider.\n *\n * @returns Complete Dubhe ecosystem with contract, GraphQL, ECS, and metadata\n *\n * @example\n * ```typescript\n * // App setup with Provider\n * function App() {\n * const config = {\n * network: 'devnet',\n * packageId: '0x123...',\n * metadata: contractMetadata,\n * credentials: {\n * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY\n * }\n * };\n *\n * return (\n * <DubheProvider config={config}>\n * <MyDApp />\n * </DubheProvider>\n * );\n * }\n *\n * // Component usage\n * function MyDApp() {\n * const { contract, address } = useDubhe();\n * return <div>Connected as {address}</div>;\n * }\n * ```\n */\nexport function useDubhe(): DubheReturn {\n return useDubheFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheContract\n *\n * Returns only the Dubhe contract instance from Provider context.\n * More efficient than useDubhe() when only contract access is needed.\n *\n * @returns Dubhe contract instance\n *\n * @example\n * ```typescript\n * function TransactionComponent() {\n * const contract = useDubheContract();\n *\n * const handleTransaction = async () => {\n * const tx = new Transaction();\n * await contract.tx.my_system.my_method({ tx });\n * };\n *\n * return <button onClick={handleTransaction}>Execute</button>;\n * }\n * ```\n */\nexport function useDubheContract(): Dubhe {\n return useDubheContractFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheGraphQL\n *\n * Returns only the GraphQL client from Provider context.\n * More efficient than useDubhe() when only GraphQL access is needed.\n *\n * @returns GraphQL client instance (null if dubheMetadata not provided)\n *\n * @example\n * ```typescript\n * function DataComponent() {\n * const graphqlClient = useDubheGraphQL();\n *\n * useEffect(() => {\n * if (graphqlClient) {\n * graphqlClient.query({ ... }).then(setData);\n * }\n * }, [graphqlClient]);\n *\n * return <div>{data && JSON.stringify(data)}</div>;\n * }\n * ```\n */\nexport function useDubheGraphQL(): any | null {\n return useDubheGraphQLFromProvider();\n}\n\n/**\n * Individual Instance Hook: useDubheECS\n *\n * Returns only the ECS World instance from Provider context.\n * More efficient than useDubhe() when only ECS access is needed.\n *\n * @returns ECS World instance (null if GraphQL client not available)\n *\n * @example\n * ```typescript\n * function ECSComponent() {\n * const ecsWorld = useDubheECS();\n *\n * useEffect(() => {\n * if (ecsWorld) {\n * ecsWorld.getComponent('MyComponent').then(setComponent);\n * }\n * }, [ecsWorld]);\n *\n * return <div>ECS Component Data</div>;\n * }\n * ```\n */\nexport function useDubheECS(): any | null {\n return useDubheECSFromProvider();\n}\n\n/**\n * Compatibility alias for useDubhe\n */\nexport const useContract = useDubhe;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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;AAA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,SAAO,6BAA6B;AACtC;AAyBO,SAAS,kBAA8B;AAC5C,SAAO,4BAA4B;AACrC;AAyBO,SAAS,cAA0B;AACxC,SAAO,wBAAwB;AACjC;AAKO,IAAM,cAAc;","names":["import_react"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,27 @@
1
+ import {
2
+ DEFAULT_CONFIG,
3
+ DubheProvider,
4
+ getConfigSummary,
5
+ mergeConfigurations,
6
+ useContract,
7
+ useDubhe,
8
+ useDubheConfig,
9
+ useDubheContract,
10
+ useDubheECS,
11
+ useDubheGraphQL,
12
+ validateConfig
13
+ } from "./chunk-XI35QBSQ.mjs";
14
+ export {
15
+ DEFAULT_CONFIG,
16
+ DubheProvider,
17
+ getConfigSummary,
18
+ mergeConfigurations,
19
+ useContract,
20
+ useDubhe,
21
+ useDubheConfig,
22
+ useDubheContract,
23
+ useDubheECS,
24
+ useDubheGraphQL,
25
+ validateConfig
26
+ };
27
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Configuration Management for Dubhe React Integration
3
+ *
4
+ * Features:
5
+ * - Type-safe configuration interface
6
+ * - Configuration validation and error handling
7
+ * - Smart merging of defaults and explicit config
8
+ * - No environment variable handling (developers should handle environment variables themselves)
9
+ */
10
+ import type { DubheConfig } from './types';
11
+ /**
12
+ * Default configuration object with sensible defaults
13
+ */
14
+ export declare const DEFAULT_CONFIG: Partial<DubheConfig>;
15
+ /**
16
+ * Configuration Hook: useDubheConfig
17
+ *
18
+ * Merges defaults with explicit configuration provided by the developer
19
+ *
20
+ * Note: Environment variables should be handled by the developer before passing to this hook
21
+ *
22
+ * @param config - Complete or partial configuration object
23
+ * @returns Complete, validated DubheConfig
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * // Basic usage with explicit config
28
+ * const config = useDubheConfig({
29
+ * network: 'testnet',
30
+ * packageId: '0x123...',
31
+ * metadata: contractMetadata,
32
+ * credentials: {
33
+ * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY // Handle env vars yourself
34
+ * }
35
+ * });
36
+ *
37
+ * // With helper function to handle environment variables
38
+ * const getConfigFromEnv = () => ({
39
+ * network: process.env.NEXT_PUBLIC_NETWORK as NetworkType,
40
+ * packageId: process.env.NEXT_PUBLIC_PACKAGE_ID,
41
+ * credentials: {
42
+ * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY
43
+ * }
44
+ * });
45
+ *
46
+ * const config = useDubheConfig({
47
+ * ...getConfigFromEnv(),
48
+ * metadata: contractMetadata
49
+ * });
50
+ * ```
51
+ */
52
+ export declare function useDubheConfig(config: Partial<DubheConfig>): DubheConfig;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Modern Dubhe React Hooks - Provider Pattern
3
+ *
4
+ * Features:
5
+ * - 🎯 Simple API design with Provider pattern
6
+ * - ⚡ Single client initialization with useRef
7
+ * - 🔧 Configuration-driven setup (developers handle environment variables themselves)
8
+ * - 🛡️ Complete type safety with strict TypeScript
9
+ * - 📦 Context-based client sharing across components
10
+ */
11
+ import { Dubhe } from '@0xobelisk/sui-client';
12
+ import type { DubheReturn } from './types';
13
+ /**
14
+ * Primary Hook: useDubhe
15
+ *
16
+ * Uses Provider pattern to access shared Dubhe clients with guaranteed single initialization.
17
+ * Must be used within a DubheProvider.
18
+ *
19
+ * @returns Complete Dubhe ecosystem with contract, GraphQL, ECS, and metadata
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * // App setup with Provider
24
+ * function App() {
25
+ * const config = {
26
+ * network: 'devnet',
27
+ * packageId: '0x123...',
28
+ * metadata: contractMetadata,
29
+ * credentials: {
30
+ * secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY
31
+ * }
32
+ * };
33
+ *
34
+ * return (
35
+ * <DubheProvider config={config}>
36
+ * <MyDApp />
37
+ * </DubheProvider>
38
+ * );
39
+ * }
40
+ *
41
+ * // Component usage
42
+ * function MyDApp() {
43
+ * const { contract, address } = useDubhe();
44
+ * return <div>Connected as {address}</div>;
45
+ * }
46
+ * ```
47
+ */
48
+ export declare function useDubhe(): DubheReturn;
49
+ /**
50
+ * Individual Instance Hook: useDubheContract
51
+ *
52
+ * Returns only the Dubhe contract instance from Provider context.
53
+ * More efficient than useDubhe() when only contract access is needed.
54
+ *
55
+ * @returns Dubhe contract instance
56
+ *
57
+ * @example
58
+ * ```typescript
59
+ * function TransactionComponent() {
60
+ * const contract = useDubheContract();
61
+ *
62
+ * const handleTransaction = async () => {
63
+ * const tx = new Transaction();
64
+ * await contract.tx.my_system.my_method({ tx });
65
+ * };
66
+ *
67
+ * return <button onClick={handleTransaction}>Execute</button>;
68
+ * }
69
+ * ```
70
+ */
71
+ export declare function useDubheContract(): Dubhe;
72
+ /**
73
+ * Individual Instance Hook: useDubheGraphQL
74
+ *
75
+ * Returns only the GraphQL client from Provider context.
76
+ * More efficient than useDubhe() when only GraphQL access is needed.
77
+ *
78
+ * @returns GraphQL client instance (null if dubheMetadata not provided)
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * function DataComponent() {
83
+ * const graphqlClient = useDubheGraphQL();
84
+ *
85
+ * useEffect(() => {
86
+ * if (graphqlClient) {
87
+ * graphqlClient.query({ ... }).then(setData);
88
+ * }
89
+ * }, [graphqlClient]);
90
+ *
91
+ * return <div>{data && JSON.stringify(data)}</div>;
92
+ * }
93
+ * ```
94
+ */
95
+ export declare function useDubheGraphQL(): any | null;
96
+ /**
97
+ * Individual Instance Hook: useDubheECS
98
+ *
99
+ * Returns only the ECS World instance from Provider context.
100
+ * More efficient than useDubhe() when only ECS access is needed.
101
+ *
102
+ * @returns ECS World instance (null if GraphQL client not available)
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * function ECSComponent() {
107
+ * const ecsWorld = useDubheECS();
108
+ *
109
+ * useEffect(() => {
110
+ * if (ecsWorld) {
111
+ * ecsWorld.getComponent('MyComponent').then(setComponent);
112
+ * }
113
+ * }, [ecsWorld]);
114
+ *
115
+ * return <div>ECS Component Data</div>;
116
+ * }
117
+ * ```
118
+ */
119
+ export declare function useDubheECS(): any | null;
120
+ /**
121
+ * Compatibility alias for useDubhe
122
+ */
123
+ export declare const useContract: typeof useDubhe;