@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 ADDED
@@ -0,0 +1,92 @@
1
+ Business Source License 1.1
2
+
3
+ License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved.
4
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
5
+
6
+ -----------------------------------------------------------------------------
7
+
8
+ Parameters
9
+
10
+ Licensor: Obelisk Labs
11
+
12
+ Licensed Work: Dubhe
13
+ The Licensed Work is (c) 2023 Obelisk Labs
14
+
15
+ -----------------------------------------------------------------------------
16
+
17
+ Terms
18
+
19
+ The Licensor hereby grants you the right to copy, modify, create derivative
20
+ works, redistribute, and make non-production use of the Licensed Work. The
21
+ Licensor may make an Additional Use Grant, above, permitting limited
22
+ production use.
23
+
24
+ Effective on the Change Date, or the fourth anniversary of the first publicly
25
+ available distribution of a specific version of the Licensed Work under this
26
+ License, whichever comes first, the Licensor hereby grants you rights under
27
+ the terms of the Change License, and the rights granted in the paragraph
28
+ above terminate.
29
+
30
+ If your use of the Licensed Work does not comply with the requirements
31
+ currently in effect as described in this License, you must purchase a
32
+ commercial license from the Licensor, its affiliated entities, or authorized
33
+ resellers, or you must refrain from using the Licensed Work.
34
+
35
+ All copies of the original and modified Licensed Work, and derivative works
36
+ of the Licensed Work, are subject to this License. This License applies
37
+ separately for each version of the Licensed Work and the Change Date may vary
38
+ for each version of the Licensed Work released by Licensor.
39
+
40
+ You must conspicuously display this License on each original or modified copy
41
+ of the Licensed Work. If you receive the Licensed Work in original or
42
+ modified form from a third party, the terms and conditions set forth in this
43
+ License apply to your use of that work.
44
+
45
+ Any use of the Licensed Work in violation of this License will automatically
46
+ terminate your rights under this License for the current and all other
47
+ versions of the Licensed Work.
48
+
49
+ This License does not grant you any right in any trademark or logo of
50
+ Licensor or its affiliates (provided that you may use a trademark or logo of
51
+ Licensor as expressly required by this License).
52
+
53
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
54
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
55
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
56
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
57
+ TITLE.
58
+
59
+ MariaDB hereby grants you permission to use this License’s text to license
60
+ your works, and to refer to it using the trademark "Business Source License",
61
+ as long as you comply with the Covenants of Licensor below.
62
+
63
+ -----------------------------------------------------------------------------
64
+
65
+ Covenants of Licensor
66
+
67
+ In consideration of the right to use this License’s text and the "Business
68
+ Source License" name and trademark, Licensor covenants to MariaDB, and to all
69
+ other recipients of the licensed work to be provided by Licensor:
70
+
71
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
72
+ or a license that is compatible with GPL Version 2.0 or a later version,
73
+ where "compatible" means that software provided under the Change License can
74
+ be included in a program with software provided under GPL Version 2.0 or a
75
+ later version. Licensor may specify additional Change Licenses without
76
+ limitation.
77
+
78
+ 2. To either: (a) specify an additional grant of rights to use that does not
79
+ impose any additional restriction on the right granted in this License, as
80
+ the Additional Use Grant; or (b) insert the text "None".
81
+
82
+ 3. To specify a Change Date.
83
+
84
+ 4. Not to modify this License in any other way.
85
+
86
+ -----------------------------------------------------------------------------
87
+
88
+ Notice
89
+
90
+ The Business Source License (this document, or the "License") is not an Open
91
+ Source license. However, the Licensed Work will eventually be made available
92
+ under an Open Source License, as stated in this License.
package/README.md ADDED
@@ -0,0 +1,564 @@
1
+ # @0xobelisk/react
2
+
3
+ Modern React integration for Dubhe framework with Provider pattern and multi-chain support.
4
+
5
+ ## 🚀 Features
6
+
7
+ - **🎯 Provider Pattern** - Single initialization with React Context sharing
8
+ - **⚡ Performance Optimized** - useRef pattern prevents re-initialization
9
+ - **🛡️ Type Safety** - Complete TypeScript support with strict typing
10
+ - **🌐 Multi-Chain Ready** - Extensible architecture for multiple blockchains
11
+ - **📦 Individual Hooks** - Granular access to specific functionality
12
+ - **🔧 Configuration Driven** - Flexible setup with smart defaults
13
+
14
+ ## 📦 Installation
15
+
16
+ ```bash
17
+ # Core React package
18
+ npm install @0xobelisk/react
19
+
20
+ # Peer dependencies
21
+ npm install react react-dom @0xobelisk/sui-client zod
22
+
23
+ # Optional dependencies for enhanced features
24
+ npm install @0xobelisk/graphql-client @0xobelisk/ecs
25
+ ```
26
+
27
+ ### Requirements
28
+
29
+ - **React**: 18.0.0+ or 19.0.0+
30
+ - **Node.js**: 18.0.0+
31
+ - **TypeScript**: 5.0+ (recommended)
32
+
33
+ ## 🌐 Multi-Chain Support
34
+
35
+ | Blockchain | Status | Import Path |
36
+ |-----------|--------|-------------|
37
+ | **Sui** | ✅ Ready | `@0xobelisk/react/sui` |
38
+ | **Aptos** | 🚧 Coming Soon | `@0xobelisk/react/aptos` |
39
+ | **Initia** | 🚧 Coming Soon | `@0xobelisk/react/initia` |
40
+
41
+ ## 🚀 Quick Start
42
+
43
+ ### Basic Provider Setup
44
+
45
+ ```typescript
46
+ import React from 'react';
47
+ import { DubheProvider, useDubhe } from '@0xobelisk/react/sui';
48
+ import { Transaction } from '@0xobelisk/sui-client';
49
+ import metadata from './contracts/metadata.json';
50
+
51
+ // App root with Provider
52
+ function App() {
53
+ const config = {
54
+ network: 'devnet' as const,
55
+ packageId: process.env.NEXT_PUBLIC_PACKAGE_ID!,
56
+ metadata,
57
+ credentials: {
58
+ secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY // ⚠️ LOCAL DEVELOPMENT ONLY // ⚠️ LOCAL DEVELOPMENT ONLY
59
+ }
60
+ };
61
+
62
+ return (
63
+ <DubheProvider config={config}>
64
+ <MyDApp />
65
+ </DubheProvider>
66
+ );
67
+ }
68
+
69
+ // Component using shared clients
70
+ function MyDApp() {
71
+ const { contract, address, network } = useDubhe();
72
+
73
+ const handleTransaction = async () => {
74
+ try {
75
+ const tx = new Transaction();
76
+ const result = await contract.tx.counter_system.increment({ tx });
77
+ console.log('Success:', result.digest);
78
+ } catch (error) {
79
+ console.error('Transaction failed:', error);
80
+ }
81
+ };
82
+
83
+ return (
84
+ <div>
85
+ <p>Connected: {address}</p>
86
+ <p>Network: {network}</p>
87
+ <button onClick={handleTransaction}>Execute Transaction</button>
88
+ </div>
89
+ );
90
+ }
91
+ ```
92
+
93
+ ## 🎯 Provider Pattern
94
+
95
+ ### DubheProvider Component
96
+
97
+ The `DubheProvider` uses React Context with useRef pattern to ensure single client initialization:
98
+
99
+ ```typescript
100
+ import { DubheProvider } from '@0xobelisk/react/sui';
101
+ import type { DubheConfig } from '@0xobelisk/react/sui';
102
+
103
+ function App() {
104
+ const config: DubheConfig = {
105
+ network: 'devnet',
106
+ packageId: '0x123...',
107
+ metadata: contractMetadata,
108
+ // Optional features
109
+ dubheMetadata: dubheConfigMetadata, // Enables GraphQL + ECS
110
+ credentials: {
111
+ secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY // ⚠️ LOCAL DEVELOPMENT ONLY // ⚠️ LOCAL DEVELOPMENT ONLY
112
+ },
113
+ endpoints: {
114
+ graphql: process.env.NEXT_PUBLIC_GRAPHQL_URL,
115
+ websocket: process.env.NEXT_PUBLIC_GRAPHQL_WS_URL
116
+ },
117
+ options: {
118
+ enableBatchOptimization: true,
119
+ cacheTimeout: 5000,
120
+ debounceMs: 100,
121
+ reconnectOnError: true
122
+ }
123
+ };
124
+
125
+ return (
126
+ <DubheProvider config={config}>
127
+ <YourApp />
128
+ </DubheProvider>
129
+ );
130
+ }
131
+ ```
132
+
133
+ ### Key Benefits of Provider Pattern
134
+
135
+ - **Single Initialization**: Clients created once using useRef
136
+ - **Context Sharing**: All components access same instances
137
+ - **No Re-renders**: useRef prevents unnecessary re-initialization
138
+ - **Type Safety**: Full TypeScript support across the tree
139
+
140
+ ## 🪝 Hook Usage
141
+
142
+ ### Primary Hook: useDubhe()
143
+
144
+ Access all Dubhe features in one hook:
145
+
146
+ ```typescript
147
+ import { useDubhe } from '@0xobelisk/react/sui';
148
+
149
+ function MyComponent() {
150
+ const {
151
+ contract, // Dubhe contract instance
152
+ graphqlClient, // GraphQL client (if dubheMetadata provided)
153
+ ecsWorld, // ECS World (if GraphQL available)
154
+ address, // User address
155
+ network, // Current network
156
+ packageId, // Contract package ID
157
+ metadata // Contract metadata
158
+ } = useDubhe();
159
+
160
+ return (
161
+ <div>
162
+ <p>Contract: {contract ? '✅' : '❌'}</p>
163
+ <p>GraphQL: {graphqlClient ? '✅' : '❌'}</p>
164
+ <p>ECS: {ecsWorld ? '✅' : '❌'}</p>
165
+ </div>
166
+ );
167
+ }
168
+ ```
169
+
170
+ ### Individual Hooks
171
+
172
+ For components that only need specific functionality:
173
+
174
+ ```typescript
175
+ import React, { useEffect } from 'react';
176
+ import {
177
+ useDubheContract,
178
+ useDubheGraphQL,
179
+ useDubheECS
180
+ } from '@0xobelisk/react/sui';
181
+ import { Transaction } from '@0xobelisk/sui-client';
182
+
183
+ // Contract-only component
184
+ function TransactionComponent() {
185
+ const contract = useDubheContract();
186
+
187
+ const executeTransaction = async () => {
188
+ const tx = new Transaction();
189
+ await contract.tx.my_system.my_method({ tx });
190
+ };
191
+
192
+ return <button onClick={executeTransaction}>Execute</button>;
193
+ }
194
+
195
+ // GraphQL-only component
196
+ function DataComponent() {
197
+ const graphqlClient = useDubheGraphQL();
198
+
199
+ useEffect(() => {
200
+ if (graphqlClient) {
201
+ graphqlClient.query({ query: '{ entities { id } }' })
202
+ .then(result => console.log(result));
203
+ }
204
+ }, [graphqlClient]);
205
+
206
+ return <div>Data component</div>;
207
+ }
208
+
209
+ // ECS-only component
210
+ function ECSComponent() {
211
+ const ecsWorld = useDubheECS();
212
+
213
+ useEffect(() => {
214
+ if (ecsWorld) {
215
+ ecsWorld.getComponent('MyComponent')
216
+ .then(components => console.log(components));
217
+ }
218
+ }, [ecsWorld]);
219
+
220
+ return <div>ECS component</div>;
221
+ }
222
+ ```
223
+
224
+ ## ⚙️ Configuration Reference
225
+
226
+ ### DubheConfig Interface
227
+
228
+ ```typescript
229
+ interface DubheConfig {
230
+ /** Network type */
231
+ network: 'mainnet' | 'testnet' | 'devnet' | 'localnet';
232
+
233
+ /** Contract package ID */
234
+ packageId: string;
235
+
236
+ /** Contract metadata (required for contract instantiation) */
237
+ metadata: SuiMoveNormalizedModules;
238
+
239
+ /** Dubhe Schema ID (optional, for enhanced features) */
240
+ dubheSchemaId?: string;
241
+
242
+ /** Dubhe metadata (enables GraphQL/ECS features) */
243
+ dubheMetadata?: any;
244
+
245
+ /** Authentication credentials */
246
+ credentials?: {
247
+ secretKey?: string; // ⚠️ LOCAL DEVELOPMENT ONLY - see security warning below
248
+ mnemonics?: string; // ⚠️ LOCAL DEVELOPMENT ONLY - see security warning below
249
+ };
250
+
251
+ /** Service endpoints configuration */
252
+ endpoints?: {
253
+ graphql?: string; // Default: 'http://localhost:4000/graphql'
254
+ websocket?: string; // Default: 'ws://localhost:4000/graphql'
255
+ };
256
+
257
+ /** Performance and behavior options */
258
+ options?: {
259
+ enableBatchOptimization?: boolean; // Default: true
260
+ cacheTimeout?: number; // Default: 5000ms
261
+ debounceMs?: number; // Default: 100ms
262
+ reconnectOnError?: boolean; // Default: true
263
+ };
264
+ }
265
+ ```
266
+
267
+ ### Environment Variable Configuration
268
+
269
+ ```typescript
270
+ // .env.local
271
+ NEXT_PUBLIC_NETWORK=devnet
272
+ NEXT_PUBLIC_PACKAGE_ID=0x123...
273
+ NEXT_PUBLIC_PRIVATE_KEY=suiprivkey...
274
+ NEXT_PUBLIC_GRAPHQL_URL=http://localhost:4000/graphql
275
+ NEXT_PUBLIC_GRAPHQL_WS_URL=ws://localhost:4000/graphql
276
+
277
+ // App configuration
278
+ function App() {
279
+ const config = {
280
+ network: process.env.NEXT_PUBLIC_NETWORK as NetworkType,
281
+ packageId: process.env.NEXT_PUBLIC_PACKAGE_ID!,
282
+ metadata: contractMetadata,
283
+ credentials: {
284
+ secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY // ⚠️ LOCAL DEVELOPMENT ONLY // ⚠️ LOCAL DEVELOPMENT ONLY
285
+ },
286
+ endpoints: {
287
+ graphql: process.env.NEXT_PUBLIC_GRAPHQL_URL,
288
+ websocket: process.env.NEXT_PUBLIC_GRAPHQL_WS_URL
289
+ }
290
+ };
291
+
292
+ return (
293
+ <DubheProvider config={config}>
294
+ <MyApp />
295
+ </DubheProvider>
296
+ );
297
+ }
298
+ ```
299
+
300
+ ## 🔐 Security Warning
301
+
302
+ > **⚠️ IMPORTANT SECURITY NOTICE**
303
+ >
304
+ > **`secretKey` and `mnemonics` are for LOCAL DEVELOPMENT ONLY!**
305
+ >
306
+ > - ❌ **NEVER use secretKey/mnemonics in production**
307
+ > - ❌ **NEVER commit private keys to version control**
308
+ > - ❌ **NEVER expose private keys in client-side code**
309
+ >
310
+ > **For production applications:**
311
+ > - ✅ Use official wallet providers for transaction signing
312
+ > - ✅ Implement proper wallet integration (Sui Wallet, etc.)
313
+ > - ✅ Let users connect their own wallets securely
314
+ >
315
+ > **Proper wallet integration example:**
316
+ > ```typescript
317
+ > // For production - use wallet providers instead of secretKey
318
+ > const config = {
319
+ > network: 'mainnet',
320
+ > packageId: process.env.NEXT_PUBLIC_PACKAGE_ID!,
321
+ > metadata,
322
+ > // ✅ NO credentials - let wallet handle signing
323
+ > };
324
+ > ```
325
+ >
326
+ > Keep your private keys safe! If compromised, attackers can steal all funds.
327
+
328
+ ## 📚 Practical Examples
329
+
330
+ ### Basic Contract Usage
331
+
332
+ ```typescript
333
+ import React, { useState } from 'react';
334
+ import { DubheProvider, useDubhe } from '@0xobelisk/react/sui';
335
+ import { Transaction } from '@0xobelisk/sui-client';
336
+
337
+ function CounterApp() {
338
+ const { contract, address } = useDubhe();
339
+ const [counter, setCounter] = useState(0);
340
+
341
+ const queryCounter = async () => {
342
+ try {
343
+ const result = await contract.query.counter_system.get({});
344
+ setCounter(result);
345
+ } catch (error) {
346
+ console.error('Query failed:', error);
347
+ }
348
+ };
349
+
350
+ const incrementCounter = async () => {
351
+ try {
352
+ const tx = new Transaction();
353
+ const result = await contract.tx.counter_system.increment({ tx });
354
+ console.log('Transaction:', result.digest);
355
+ await queryCounter(); // Refresh counter
356
+ } catch (error) {
357
+ console.error('Transaction failed:', error);
358
+ }
359
+ };
360
+
361
+ return (
362
+ <div>
363
+ <h1>Counter: {counter}</h1>
364
+ <p>Address: {address}</p>
365
+ <button onClick={queryCounter}>Refresh</button>
366
+ <button onClick={incrementCounter}>Increment</button>
367
+ </div>
368
+ );
369
+ }
370
+ ```
371
+
372
+ ### GraphQL Integration
373
+
374
+ ```typescript
375
+ import React, { useEffect, useState } from 'react';
376
+ import { useDubhe } from '@0xobelisk/react/sui';
377
+
378
+ function DataComponent() {
379
+ const { graphqlClient, ecsWorld } = useDubhe();
380
+ const [entities, setEntities] = useState([]);
381
+
382
+ // Real-time subscription
383
+ useEffect(() => {
384
+ if (graphqlClient) {
385
+ const subscription = graphqlClient.subscribe({
386
+ query: `
387
+ subscription {
388
+ entities {
389
+ id
390
+ components {
391
+ type
392
+ value
393
+ }
394
+ }
395
+ }
396
+ `
397
+ }).subscribe(result => {
398
+ setEntities(result.data.entities);
399
+ });
400
+
401
+ return () => subscription.unsubscribe();
402
+ }
403
+ }, [graphqlClient]);
404
+
405
+ // ECS component queries
406
+ const queryComponents = async () => {
407
+ if (ecsWorld) {
408
+ const components = await ecsWorld.getComponent('CounterComponent');
409
+ console.log('Components:', components);
410
+ }
411
+ };
412
+
413
+ return (
414
+ <div>
415
+ <h2>Real-time Entities: {entities.length}</h2>
416
+ <button onClick={queryComponents}>Query Components</button>
417
+
418
+ {graphqlClient ? (
419
+ <p>✅ GraphQL Connected</p>
420
+ ) : (
421
+ <p>❌ GraphQL Unavailable (add dubheMetadata to config)</p>
422
+ )}
423
+ </div>
424
+ );
425
+ }
426
+ ```
427
+
428
+ ### Error Handling
429
+
430
+ ```typescript
431
+ import React from 'react';
432
+ import { DubheProvider, useDubhe } from '@0xobelisk/react/sui';
433
+
434
+ function ErrorHandlingExample() {
435
+ const { contract } = useDubhe();
436
+
437
+ const handleTransactionWithRetry = async () => {
438
+ const maxRetries = 3;
439
+ let attempt = 0;
440
+
441
+ while (attempt < maxRetries) {
442
+ try {
443
+ const tx = new Transaction();
444
+ const result = await contract.tx.my_system.my_method({ tx });
445
+ console.log('Success:', result.digest);
446
+ return result;
447
+ } catch (error) {
448
+ attempt++;
449
+ console.error(`Attempt ${attempt} failed:`, error);
450
+
451
+ if (attempt === maxRetries) {
452
+ throw error;
453
+ }
454
+
455
+ // Wait before retry
456
+ await new Promise(resolve => setTimeout(resolve, 1000));
457
+ }
458
+ }
459
+ };
460
+
461
+ return (
462
+ <button onClick={handleTransactionWithRetry}>
463
+ Execute with Retry
464
+ </button>
465
+ );
466
+ }
467
+ ```
468
+
469
+ ## 🔧 TypeScript Support
470
+
471
+ ### Type Exports
472
+
473
+ ```typescript
474
+ import type {
475
+ NetworkType,
476
+ DubheConfig,
477
+ DubheReturn,
478
+ ContractReturn // Alias for DubheReturn
479
+ } from '@0xobelisk/react/sui';
480
+ ```
481
+
482
+ ### Type-Safe Configuration
483
+
484
+ ```typescript
485
+ const config: DubheConfig = {
486
+ network: 'devnet', // Type-safe network selection
487
+ packageId: '0x123...',
488
+ metadata: contractMetadata, // Typed metadata
489
+ credentials: {
490
+ secretKey: process.env.NEXT_PUBLIC_PRIVATE_KEY // ⚠️ LOCAL DEVELOPMENT ONLY
491
+ }
492
+ };
493
+
494
+ const result: DubheReturn = useDubhe();
495
+ // Full type safety for all return values
496
+ ```
497
+
498
+ ## 🛠️ Development
499
+
500
+ ```bash
501
+ # Watch mode for development
502
+ npm run watch
503
+
504
+ # Type checking
505
+ npm run type-check
506
+
507
+ # Build package
508
+ npm run build
509
+
510
+ # Run tests
511
+ npm run test
512
+
513
+ # Format code
514
+ npm run format
515
+ ```
516
+
517
+ ## 📖 API Reference
518
+
519
+ ### DubheReturn Interface
520
+
521
+ ```typescript
522
+ interface DubheReturn {
523
+ contract: Dubhe; // Enhanced contract instance
524
+ graphqlClient: DubheGraphqlClient | null; // GraphQL client (if enabled)
525
+ ecsWorld: DubheECSWorld | null; // ECS World (if enabled)
526
+ metadata: SuiMoveNormalizedModules; // Contract metadata
527
+ network: NetworkType; // Current network
528
+ packageId: string; // Package ID
529
+ dubheSchemaId?: string; // Schema ID (if provided)
530
+ address: string; // User address
531
+ options?: DubheOptions; // Configuration options
532
+ metrics?: DubheMetrics; // Performance metrics
533
+ }
534
+ ```
535
+
536
+ ### Available Hooks
537
+
538
+ - `useDubhe()` → `DubheReturn` - Complete Dubhe ecosystem
539
+ - `useDubheContract()` → `Dubhe` - Contract instance only
540
+ - `useDubheGraphQL()` → `DubheGraphqlClient | null` - GraphQL client only
541
+ - `useDubheECS()` → `DubheECSWorld | null` - ECS World only
542
+ - `useContract()` → `DubheReturn` - Alias for `useDubhe()`
543
+
544
+ ## 🚨 Error Handling
545
+
546
+ The package includes comprehensive error handling:
547
+
548
+ ```typescript
549
+ // Configuration validation
550
+ try {
551
+ const { contract } = useDubhe();
552
+ } catch (error) {
553
+ console.error('Configuration error:', error.message);
554
+ }
555
+
556
+ // Provider context validation
557
+ function MyComponent() {
558
+ try {
559
+ const dubhe = useDubhe();
560
+ } catch (error) {
561
+ // Error: useDubhe must be used within a DubheProvider
562
+ }
563
+ }
564
+ ```