@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/LICENSE +92 -0
- package/README.md +564 -0
- package/dist/chunk-2WEYKH27.mjs +344 -0
- package/dist/chunk-2WEYKH27.mjs.map +1 -0
- package/dist/chunk-LQ3XXOG4.mjs +342 -0
- package/dist/chunk-LQ3XXOG4.mjs.map +1 -0
- package/dist/chunk-TTYSS65P.mjs +345 -0
- package/dist/chunk-TTYSS65P.mjs.map +1 -0
- package/dist/chunk-XI35QBSQ.mjs +338 -0
- package/dist/chunk-XI35QBSQ.mjs.map +1 -0
- package/dist/index.d.mts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +374 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +27 -0
- package/dist/index.mjs.map +1 -0
- package/dist/sui/config.d.ts +52 -0
- package/dist/sui/hooks.d.ts +123 -0
- package/dist/sui/index.d.mts +353 -0
- package/dist/sui/index.d.ts +353 -0
- package/dist/sui/index.js +374 -0
- package/dist/sui/index.js.map +1 -0
- package/dist/sui/index.mjs +27 -0
- package/dist/sui/index.mjs.map +1 -0
- package/dist/sui/provider.d.ts +137 -0
- package/dist/sui/types.d.ts +87 -0
- package/dist/sui/utils.d.ts +35 -0
- package/package.json +103 -0
- package/src/index.ts +16 -0
- package/src/sui/config.ts +90 -0
- package/src/sui/hooks.ts +144 -0
- package/src/sui/index.ts +37 -0
- package/src/sui/provider.tsx +341 -0
- package/src/sui/types.ts +99 -0
- package/src/sui/utils.ts +192 -0
|
@@ -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/sui/index.ts
|
|
21
|
+
var sui_exports = {};
|
|
22
|
+
__export(sui_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(sui_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/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, 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} 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, 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;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KO,SAAS,8BAA0C;AACxD,QAAM,EAAE,iBAAiB,IAAI,gBAAgB;AAC7C,SAAO,iBAAiB;AAC1B;AAKO,SAAS,0BAAsC;AACpD,QAAM,EAAE,YAAY,IAAI,gBAAgB;AACxC,SAAO,YAAY;AACrB;;;AC5RO,SAAS,WAAwB;AACtC,SAAO,qBAAqB;AAC9B;AAwBO,SAAS,mBAA0B;AACxC,SAAO,6BAA6B;AACtC;AAyBO,SAAS,kBAA8B;AAC5C,SAAO,4BAA4B;AACrC;AAyBO,SAAS,cAA0B;AACxC,SAAO,wBAAwB;AACjC;AAKO,IAAM,cAAc;","names":["import_react"]}
|
|
@@ -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,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dubhe Provider - useRef Pattern for Client Management
|
|
3
|
+
*
|
|
4
|
+
* Features:
|
|
5
|
+
* - 🎯 Single client instances across application lifecycle
|
|
6
|
+
* - ⚡ useRef-based storage (no re-initialization on re-renders)
|
|
7
|
+
* - 🔧 Provider pattern for dependency injection
|
|
8
|
+
* - 🛡️ Complete type safety with strict TypeScript
|
|
9
|
+
* - 📦 Context-based client sharing
|
|
10
|
+
*/
|
|
11
|
+
import { ReactNode } from 'react';
|
|
12
|
+
import { Dubhe } from '@0xobelisk/sui-client';
|
|
13
|
+
import type { DubheConfig, DubheReturn } from './types';
|
|
14
|
+
/**
|
|
15
|
+
* Context interface for Dubhe client instances
|
|
16
|
+
* All clients are stored using useRef to ensure single initialization
|
|
17
|
+
*/
|
|
18
|
+
interface DubheContextValue {
|
|
19
|
+
getContract: () => Dubhe;
|
|
20
|
+
getGraphqlClient: () => any | null;
|
|
21
|
+
getEcsWorld: () => any | null;
|
|
22
|
+
getAddress: () => string;
|
|
23
|
+
getMetrics: () => {
|
|
24
|
+
initTime: number;
|
|
25
|
+
requestCount: number;
|
|
26
|
+
lastActivity: number;
|
|
27
|
+
};
|
|
28
|
+
config: DubheConfig;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Props interface for DubheProvider component
|
|
32
|
+
*/
|
|
33
|
+
interface DubheProviderProps {
|
|
34
|
+
/** Configuration for Dubhe initialization */
|
|
35
|
+
config: Partial<DubheConfig>;
|
|
36
|
+
/** Child components that will have access to Dubhe clients */
|
|
37
|
+
children: ReactNode;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* DubheProvider Component - useRef Pattern Implementation
|
|
41
|
+
*
|
|
42
|
+
* This Provider uses useRef to store client instances, ensuring they are:
|
|
43
|
+
* 1. Created only once during component lifecycle
|
|
44
|
+
* 2. Persisted across re-renders without re-initialization
|
|
45
|
+
* 3. Shared efficiently via React Context
|
|
46
|
+
*
|
|
47
|
+
* Key advantages over useMemo:
|
|
48
|
+
* - useRef guarantees single initialization (useMemo can re-run on dependency changes)
|
|
49
|
+
* - No dependency array needed (eliminates potential re-initialization bugs)
|
|
50
|
+
* - Better performance for heavy client objects
|
|
51
|
+
* - Clearer separation of concerns via Provider pattern
|
|
52
|
+
*
|
|
53
|
+
* @param props - Provider props containing config and children
|
|
54
|
+
* @returns Provider component wrapping children with Dubhe context
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```typescript
|
|
58
|
+
* // App root setup
|
|
59
|
+
* function App() {
|
|
60
|
+
* const dubheConfig = {
|
|
61
|
+
* network: 'devnet',
|
|
62
|
+
* packageId: '0x123...',
|
|
63
|
+
* metadata: contractMetadata,
|
|
64
|
+
* credentials: {
|
|
65
|
+
* secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY
|
|
66
|
+
* }
|
|
67
|
+
* };
|
|
68
|
+
*
|
|
69
|
+
* return (
|
|
70
|
+
* <DubheProvider config={dubheConfig}>
|
|
71
|
+
* <MyApplication />
|
|
72
|
+
* </DubheProvider>
|
|
73
|
+
* );
|
|
74
|
+
* }
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
export declare function DubheProvider({ config, children }: DubheProviderProps): import("react/jsx-runtime").JSX.Element;
|
|
78
|
+
/**
|
|
79
|
+
* Custom hook to access Dubhe context
|
|
80
|
+
* Provides type-safe access to all Dubhe client instances
|
|
81
|
+
*
|
|
82
|
+
* @returns DubheContextValue with all client getters and config
|
|
83
|
+
* @throws Error if used outside of DubheProvider
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```typescript
|
|
87
|
+
* function MyComponent() {
|
|
88
|
+
* const dubheContext = useDubheContext();
|
|
89
|
+
*
|
|
90
|
+
* const contract = dubheContext.getContract();
|
|
91
|
+
* const graphqlClient = dubheContext.getGraphqlClient();
|
|
92
|
+
* const ecsWorld = dubheContext.getEcsWorld();
|
|
93
|
+
* const address = dubheContext.getAddress();
|
|
94
|
+
*
|
|
95
|
+
* return <div>Connected as {address}</div>;
|
|
96
|
+
* }
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
export declare function useDubheContext(): DubheContextValue;
|
|
100
|
+
/**
|
|
101
|
+
* Enhanced hook that mimics the original useDubhe API
|
|
102
|
+
* Uses the Provider pattern internally but maintains backward compatibility
|
|
103
|
+
*
|
|
104
|
+
* @returns DubheReturn object with all instances and metadata
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* ```typescript
|
|
108
|
+
* function MyComponent() {
|
|
109
|
+
* const { contract, graphqlClient, ecsWorld, address } = useDubheFromProvider();
|
|
110
|
+
*
|
|
111
|
+
* const handleTransaction = async () => {
|
|
112
|
+
* const tx = new Transaction();
|
|
113
|
+
* await contract.tx.my_system.my_method({ tx });
|
|
114
|
+
* };
|
|
115
|
+
*
|
|
116
|
+
* return <button onClick={handleTransaction}>Execute</button>;
|
|
117
|
+
* }
|
|
118
|
+
* ```
|
|
119
|
+
*/
|
|
120
|
+
export declare function useDubheFromProvider(): DubheReturn;
|
|
121
|
+
/**
|
|
122
|
+
* Individual client hooks for components that only need specific instances
|
|
123
|
+
* These are more efficient than useDubheFromProvider for single-client usage
|
|
124
|
+
*/
|
|
125
|
+
/**
|
|
126
|
+
* Hook for accessing only the Dubhe contract instance
|
|
127
|
+
*/
|
|
128
|
+
export declare function useDubheContractFromProvider(): Dubhe;
|
|
129
|
+
/**
|
|
130
|
+
* Hook for accessing only the GraphQL client instance
|
|
131
|
+
*/
|
|
132
|
+
export declare function useDubheGraphQLFromProvider(): any | null;
|
|
133
|
+
/**
|
|
134
|
+
* Hook for accessing only the ECS World instance
|
|
135
|
+
*/
|
|
136
|
+
export declare function useDubheECSFromProvider(): any | null;
|
|
137
|
+
export {};
|