forked from zer0-os/zOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopusdocs-complete.patch
More file actions
10886 lines (10886 loc) · 398 KB
/
opusdocs-complete.patch
File metadata and controls
10886 lines (10886 loc) · 398 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..7d62a24d
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,120 @@
+# CLAUDE.md
+
+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+
+## Development Commands
+
+### Build and Run
+- **Development**: `npm start` - Runs the app with Vite
+- **Build**: `npm run build` - TypeScript check and Vite build
+- **Legacy Builds**: `npm run start:legacy` or `npm run build:legacy` - Uses craco with OpenSSL legacy provider
+
+### Testing
+- **Jest Tests**: `npm test` - Runs Jest tests (*.test.tsx, *.test.ts)
+- **Vitest Tests**: `npm run test:vitest` - Runs Vitest tests (*.vitest.tsx, *.vitest.ts)
+- **Single Test**: `npm test -- --testNamePattern="test name"`
+
+### Code Quality
+- **Lint**: `npm run lint` - ESLint check
+- **Lint Fix**: `npm run lint:fix` - Auto-fix ESLint issues
+- **Format**: `npm run code-format:fix` - Prettier formatting
+- **Format Check**: `npm run code-format:validate` - Check Prettier formatting
+
+### Mock Generation
+- **Generate Mocks**: `BUILD_MOCKS=true npm test -- --watchAll=false src/app-sandbox/index.test.tsx`
+
+## Architecture Overview
+
+### Redux-Based Architecture
+The application follows a Redux-Saga architecture with normalized state management:
+- **Components**: Presentational React components in `/src/components/`
+- **Connected Components**: Container components with Redux connections
+- **Redux Store**: State management in `/src/store/` with feature-based organization
+- **Sagas**: Side effects handled by redux-saga
+- **Normalizr**: Entity normalization for consistent state shape
+
+### Key Directories
+- **`/src/apps/`**: Core application modules (feed, messenger, wallet, staking, etc.)
+- **`/src/store/`**: Redux state management, organized by feature
+- **`/src/lib/`**: Shared utilities and hooks
+- **`/src/components/`**: Reusable UI components
+- **`/src/authentication/`**: Auth flows and components
+
+### External App Integration
+Apps can be integrated as external components using the ExternalApp wrapper:
+1. Create folder in `/src/apps/your-app/`
+2. Add to AppRouter in `/src/apps/app-router.tsx`
+3. Add navigation in AppBar component
+
+### Matrix Integration
+The app uses Matrix for chat functionality:
+- Matrix client configuration in `/src/lib/chat/matrix/`
+- Home server URL configured via `REACT_APP_MATRIX_HOME_SERVER_URL`
+- Sliding sync support for improved performance
+
+### Web3 Integration
+- **Wagmi & RainbowKit**: Wallet connection and management
+- **Thirdweb**: Additional Web3 functionality
+- **Chains**: Multi-chain support configured in `/src/lib/web3/`
+
+### Testing Approach
+- **Jest**: Used for unit tests with Enzyme (legacy)
+- **Vitest**: Modern test runner for newer tests
+- **Test Utils**: Testing utilities in `/src/test-utils.tsx`
+- **Redux Testing**: redux-saga-test-plan for saga testing
+
+### Build Configuration
+- **Vite**: Primary build tool with React SWC plugin
+- **Craco**: Legacy build support for compatibility
+- **Environment Variables**: Prefixed with `REACT_APP_`
+- **Node Polyfills**: Enabled for Web3 compatibility
+
+## Key Patterns
+
+### Component Structure
+```typescript
+// Presentational component
+const Component = ({ prop }) => <div>{prop}</div>;
+
+// Connected component (container)
+const Container = connect(mapStateToProps, mapDispatchToProps)(Component);
+```
+
+### Redux-Saga Pattern
+```typescript
+function* saga() {
+ yield takeEvery(ACTION_TYPE, function* (action) {
+ try {
+ const result = yield call(api.method, action.payload);
+ yield put(successAction(result));
+ } catch (error) {
+ yield put(errorAction(error));
+ }
+ });
+}
+```
+
+### Normalized State
+Entities are normalized using normalizr schemas for consistent access patterns.
+
+### Module CSS
+Components use CSS modules (*.module.scss) for scoped styling.
+
+## Agent Communication Guidelines
+
+### Inter-Agent Communication
+- **`./agents-only/`**: Designated directory for semaphores, control flows, job requests, and any form of inter-agent communication
+- **Flexibility**: Agents are free to create any necessary communication artifacts in this directory, including codes.
+
+## Deliverables Management
+- **Opus Docs Location**: Use `./opusdocs/` as the production location for deliverables
+- **Named Versions**: Multiple named versions of files are permitted
+
+## Development Naming Conventions
+- Don't capitalize filenames, use standard naming conventions
+- Always use lowercase for file and directory names
+- Prefer kebab-case or snake_case for multi-word filenames
+
+## Workspace Guides
+- **Opus Docs Usage**:
+ - USE `./opusdocs/new-recruits/` to generate necessary and requested files (documentation, prompts, notes, dev-logs) for new developers who are already coding full stack web apps
diff --git a/opusdocs/architecture-overview.md b/opusdocs/architecture-overview.md
new file mode 100644
index 00000000..b756a084
--- /dev/null
+++ b/opusdocs/architecture-overview.md
@@ -0,0 +1,414 @@
+# zOS Architecture Overview
+
+## System Overview
+
+zOS (Zero Operating System) is a sophisticated web application built around a **Redux-Saga-Normalizr** pattern that creates a decentralized, Matrix-protocol-based social platform with Web3 integration. The architecture prioritizes real-time communication, normalized data management, and modular application design.
+
+### High-Level Architecture
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ zOS Application │
+├─────────────────────────────────────────────────────────────────┤
+│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐│
+│ │ Feed │ │ Messenger │ │ Wallet │ │ Staking ││
+│ │ App │ │ App │ │ App │ │ App ││
+│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘│
+├─────────────────────────────────────────────────────────────────┤
+│ App Router │
+├─────────────────────────────────────────────────────────────────┤
+│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐│
+│ │ Redux │ │ Sagas │ │ Normalized │ │ Matrix ││
+│ │ Store │ │ Middleware │ │ State │ │ Client ││
+│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘│
+├─────────────────────────────────────────────────────────────────┤
+│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐│
+│ │ Matrix │ │ Web3 │ │ Cloudinary │ │ Thirdweb ││
+│ │ Protocol │ │ Wallets │ │ Images │ │ APIs ││
+│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘│
+└─────────────────────────────────────────────────────────────────┘
+```
+
+### Core Technology Stack
+
+- **Frontend Framework**: React 18 with TypeScript
+- **State Management**: Redux Toolkit + Redux-Saga
+- **Data Normalization**: Normalizr for entity management
+- **Real-time Communication**: Matrix Protocol (matrix-js-sdk)
+- **Web3 Integration**: Wagmi + RainbowKit + Thirdweb
+- **Styling**: SCSS with CSS Modules
+- **Build Tool**: Vite
+- **Testing**: Vitest + Jest
+
+## Main Architectural Patterns
+
+### 1. Redux-Saga-Normalizr Pattern
+
+The application follows a sophisticated state management pattern that combines:
+
+- **Redux Toolkit**: Modern Redux with createSlice for reducers
+- **Redux-Saga**: Side effect management for async operations
+- **Normalizr**: Entity normalization for relational data
+
+#### Why This Pattern?
+
+- **Redux-Saga over alternatives**: Provides powerful async flow control with cancellation, racing, and complex orchestration
+- **Normalized state benefits**: Eliminates data duplication, ensures consistency, and simplifies updates
+- **Matrix protocol integration**: Sagas handle complex Matrix event flows and real-time synchronization
+
+### 2. Modular Application Architecture
+
+Each major feature is organized as a self-contained "app" within the `/src/apps/` directory:
+
+```
+apps/
+├── feed/ # Social media feed functionality
+├── messenger/ # Real-time chat application
+├── wallet/ # Web3 wallet management
+├── staking/ # DeFi staking interface
+├── profile/ # User profile management
+├── notifications/ # Notification system
+└── explorer/ # External app integration
+```
+
+## Data Flow Architecture
+
+### Redux Store Structure
+
+```
+rootState: {
+ // Core entities (normalized)
+ normalized: {
+ users: { [id]: User },
+ channels: { [id]: Channel },
+ messages: { [id]: Message }
+ },
+
+ // Feature slices
+ authentication: AuthState,
+ chat: ChatState,
+ web3: Web3State,
+ posts: PostsState,
+
+ // UI state
+ panels: PanelsState,
+ dialogs: DialogsState,
+ background: BackgroundState
+}
+```
+
+### Saga Flow Pattern
+
+```mermaid
+graph TD
+ A[UI Action] --> B[Saga Watcher]
+ B --> C[Saga Worker]
+ C --> D[Matrix API Call]
+ C --> E[REST API Call]
+ C --> F[Web3 Transaction]
+ D --> G[Normalize Response]
+ E --> G
+ F --> G
+ G --> H[Dispatch to Store]
+ H --> I[UI Update]
+```
+
+### Normalizr Entity Management
+
+The application uses Normalizr to manage relational data:
+
+```typescript
+// Schema definitions
+const userSchema = new schema.Entity('users');
+const channelSchema = new schema.Entity('channels');
+const messageSchema = new schema.Entity('messages', {
+ sender: userSchema,
+ channel: channelSchema
+});
+
+// Normalization happens in sagas
+const normalizedData = normalize(apiResponse, [messageSchema]);
+dispatch(receive(normalizedData.entities));
+```
+
+## Matrix Protocol Integration
+
+### Architecture Overview
+
+zOS is built on the Matrix protocol for decentralized communication:
+
+```
+┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
+│ zOS Client │◄──►│ Matrix Client │◄──►│ Matrix Server │
+│ │ │ (matrix-js-sdk)│ │ (Homeserver) │
+└─────────────────┘ └──────────────────┘ └─────────────────┘
+ │ │ │
+ │ │ │
+ ┌────▼────┐ ┌────▼────┐ ┌────▼────┐
+ │ Redux │ │ Event │ │ Room │
+ │ Sagas │ │Handler │ │ State │
+ └─────────┘ └─────────┘ └─────────┘
+```
+
+### Key Matrix Integration Points
+
+1. **Authentication**: JWT-based login with Matrix homeserver
+2. **Real-time Events**: Matrix events flow through sagas to Redux store
+3. **End-to-End Encryption**: Built-in E2EE with key backup/restore
+4. **Room Management**: Channels are Matrix rooms with custom metadata
+5. **File Uploads**: Encrypted file handling through Matrix media API
+
+### Matrix Client Wrapper
+
+The `MatrixClient` class (`/src/lib/chat/matrix-client.ts`) provides:
+
+- Connection management and authentication
+- Event processing and normalization
+- Message sending/receiving with encryption
+- Room creation and management
+- File upload/download with caching
+
+## Module Architecture
+
+### App Module Structure
+
+Each app follows a consistent structure:
+
+```
+apps/[app-name]/
+├── index.tsx # Main app component
+├── components/ # App-specific components
+├── lib/ # Business logic and hooks
+│ ├── types.ts # TypeScript interfaces
+│ ├── useAppLogic.ts # Custom hooks
+│ └── utils.ts # Utility functions
+└── styles.module.scss # Scoped styles
+```
+
+### Component Hierarchy
+
+```
+App
+├── AppRouter # Route-based app switching
+│ ├── MessengerApp # Real-time chat
+│ ├── FeedApp # Social media feed
+│ ├── WalletApp # Web3 wallet
+│ └── [Other Apps]
+├── AppBar # Global navigation
+├── DialogManager # Modal management
+└── Sidekick # Context-aware sidebar
+```
+
+### State Management Per Feature
+
+Each feature manages its state through:
+
+1. **Slice**: Redux slice with actions and reducers
+2. **Saga**: Side effect management and async operations
+3. **Selectors**: Memoized state access patterns
+4. **Hooks**: React hooks for component integration
+
+Example pattern:
+```typescript
+// Slice (actions + reducer)
+const slice = createSlice({
+ name: 'feature',
+ initialState,
+ reducers: { /* sync actions */ }
+});
+
+// Saga (async operations)
+function* featureSaga() {
+ yield takeEvery('feature/action', handleAction);
+}
+
+// Selectors (memoized state access)
+const selectFeatureData = createSelector(
+ (state) => state.feature,
+ (feature) => feature.data
+);
+```
+
+## Web3 Architecture
+
+### Integration Strategy
+
+zOS integrates Web3 functionality through multiple layers:
+
+1. **Wagmi**: React hooks for Ethereum interaction
+2. **RainbowKit**: Wallet connection UI
+3. **Thirdweb**: Additional Web3 utilities and APIs
+4. **Custom Hooks**: App-specific Web3 logic
+
+### Web3 State Management
+
+```typescript
+interface Web3State {
+ status: ConnectionStatus;
+ value: {
+ chainId: number;
+ address: string;
+ connectorId: string;
+ error: string;
+ };
+}
+```
+
+### Wallet Integration Points
+
+- **Authentication**: Web3 login alongside Matrix authentication
+- **Staking**: DeFi protocol interactions
+- **NFT Management**: Token display and transfers
+- **Transaction History**: On-chain activity tracking
+
+## Essential Concepts for Developers
+
+### 1. Why Redux-Saga?
+
+**Advantages:**
+- **Testability**: Sagas are pure functions, easy to test
+- **Cancellation**: Built-in support for cancelling async operations
+- **Flow Control**: Complex async orchestration with racing, forking
+- **Integration**: Perfect for handling Matrix protocol events
+
+**Common Pattern:**
+```typescript
+function* handleMessageSend(action) {
+ try {
+ // Send via Matrix
+ const result = yield call(matrixClient.sendMessage, action.payload);
+
+ // Update optimistic message
+ yield put(updateOptimisticMessage(result));
+
+ // Record analytics
+ yield fork(recordMessageSent, result);
+ } catch (error) {
+ yield put(setError(error));
+ }
+}
+```
+
+### 2. Normalized State Benefits
+
+**Problem Solved:**
+- Data duplication across components
+- Inconsistent updates
+- Complex nested state updates
+
+**Solution:**
+```typescript
+// Instead of nested data
+{
+ channels: [
+ { id: 1, name: "General", messages: [/* full message objects */] }
+ ]
+}
+
+// Use normalized structure
+{
+ channels: { 1: { id: 1, name: "General", messageIds: [101, 102] } },
+ messages: {
+ 101: { id: 101, text: "Hello", senderId: 5 },
+ 102: { id: 102, text: "World", senderId: 3 }
+ },
+ users: {
+ 3: { id: 3, name: "Alice" },
+ 5: { id: 5, name: "Bob" }
+ }
+}
+```
+
+### 3. Matrix Protocol Benefits
+
+**Decentralization**: No single point of failure
+**Interoperability**: Standards-based communication
+**Security**: End-to-end encryption by default
+**Scalability**: Federation across multiple servers
+
+### 4. Component Integration Patterns
+
+**Using Selectors:**
+```typescript
+const MyComponent = () => {
+ const messages = useSelector(selectChannelMessages(channelId));
+ const users = useSelector(selectUsers);
+
+ return (
+ <div>
+ {messages.map(message => (
+ <Message
+ key={message.id}
+ message={message}
+ user={users[message.senderId]}
+ />
+ ))}
+ </div>
+ );
+};
+```
+
+**Dispatching Actions:**
+```typescript
+const dispatch = useDispatch();
+
+const handleSendMessage = (text: string) => {
+ dispatch(sendMessage({
+ channelId,
+ text,
+ optimisticId: generateId()
+ }));
+};
+```
+
+## Common Pitfalls and Solutions
+
+### 1. **Async State Race Conditions**
+**Problem**: Multiple async operations updating the same state
+**Solution**: Use saga patterns like `takeLatest` or request cancellation
+
+### 2. **Normalized State Complexity**
+**Problem**: Difficulty accessing related entities
+**Solution**: Use memoized selectors to join normalized data
+
+### 3. **Matrix Event Ordering**
+**Problem**: Out-of-order event processing
+**Solution**: Event sequencing in sagas with proper error handling
+
+### 4. **Memory Leaks in Real-time Apps**
+**Problem**: Event listeners not cleaned up
+**Solution**: Proper cleanup in useEffect hooks and saga cancellation
+
+## Getting Started: Developer Mental Model
+
+### 1. **Data Flow Understanding**
+1. User interacts with UI component
+2. Component dispatches Redux action
+3. Saga intercepts action and handles side effects
+4. API responses are normalized and stored
+5. Selectors provide normalized data to components
+6. UI updates reactively
+
+### 2. **Adding New Features**
+1. Define normalized schema if needed
+2. Create Redux slice with actions
+3. Implement saga for async operations
+4. Create selectors for data access
+5. Build UI components with hooks
+6. Connect everything through the app router
+
+### 3. **Matrix Integration**
+1. Understand rooms as channels
+2. Events flow through the MatrixClient wrapper
+3. Sagas process Matrix events into Redux actions
+4. UI components react to normalized state changes
+
+### 4. **Web3 Integration**
+1. Use Wagmi hooks for blockchain interactions
+2. Handle wallet connection state
+3. Integrate with existing Redux patterns
+4. Consider gas optimization and error handling
+
+---
+
+This architecture enables zOS to be a scalable, real-time, decentralized social platform that seamlessly integrates Web3 functionality while maintaining a clean separation of concerns and robust state management.
\ No newline at end of file
diff --git a/opusdocs/blockchain-integration.md b/opusdocs/blockchain-integration.md
new file mode 100644
index 00000000..70799559
--- /dev/null
+++ b/opusdocs/blockchain-integration.md
@@ -0,0 +1,872 @@
+# Blockchain Integration Guide for zOS
+
+This guide provides comprehensive patterns and examples for integrating blockchain functionality into zOS applications, with special focus on wallet connections, transactions, and smart contract interactions that support Haven Protocol's creator economy features.
+
+## Table of Contents
+
+1. [Architecture Overview](#architecture-overview)
+2. [Wallet Connection Patterns](#wallet-connection-patterns)
+3. [Transaction Handling](#transaction-handling)
+4. [Smart Contract Interactions](#smart-contract-interactions)
+5. [State Management Integration](#state-management-integration)
+6. [Error Handling & User Experience](#error-handling--user-experience)
+7. [Security Best Practices](#security-best-practices)
+8. [Creator Economy Patterns](#creator-economy-patterns)
+9. [Testing Strategies](#testing-strategies)
+10. [Troubleshooting](#troubleshooting)
+
+## Architecture Overview
+
+zOS uses a modern Web3 stack built around **RainbowKit**, **Wagmi**, and **Viem** for blockchain interactions. The architecture separates concerns between UI components, Redux state management, and blockchain operations.
+
+### Core Technologies
+
+- **RainbowKit**: Wallet connection UI and management
+- **Wagmi**: React hooks for Ethereum interactions
+- **Viem**: TypeScript library for Ethereum operations
+- **React Query**: Caching and synchronization for blockchain data
+- **Redux Toolkit**: Global state management for Web3 state
+
+### Supported Networks
+
+```typescript
+// From /src/lib/web3/wagmi-config.ts
+const supportedChains = [
+ 1, // Ethereum Mainnet
+ 11155111, // Sepolia Testnet
+ 43113, // Avalanche Fuji Testnet
+ 1417429182 // Zephyr Test Net (custom chain)
+];
+```
+
+## Wallet Connection Patterns
+
+### Basic Wallet Provider Setup
+
+The foundation of zOS's Web3 integration starts with the `RainbowKitProvider`:
+
+```tsx
+// /src/lib/web3/rainbowkit/provider.tsx
+import { WagmiProvider } from 'wagmi';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { RainbowKitProvider as RKProvider, darkTheme } from '@rainbow-me/rainbowkit';
+import { getWagmiConfig } from '../wagmi-config';
+
+const queryClient = new QueryClient();
+
+export const RainbowKitProvider = ({ children }) => {
+ return (
+ <WagmiProvider config={getWagmiConfig()}>
+ <QueryClientProvider client={queryClient}>
+ <RKProvider theme={darkTheme()} modalSize='compact'>
+ {children}
+ </RKProvider>
+ </QueryClientProvider>
+ </WagmiProvider>
+ );
+};
+```
+
+### Connection State Management
+
+zOS implements a comprehensive connection monitoring system:
+
+```tsx
+// /src/lib/web3/rainbowkit/connect.tsx
+import { watchAccount } from '@wagmi/core';
+import { ConnectionStatus } from '..';
+
+export class Container extends React.Component<Properties> {
+ watchConnection() {
+ this.unwatch = watchAccount(getWagmiConfig(), {
+ onChange: (account, prevAccount) => {
+ this.props.setChain(account.chainId);
+
+ if (!account.isConnected) {
+ this.props.setConnectionStatus(ConnectionStatus.Disconnected);
+ } else if (!this.isSupportedChain(account.chainId)) {
+ this.props.setConnectionStatus(ConnectionStatus.NetworkNotSupported);
+ } else {
+ this.props.setConnectionStatus(ConnectionStatus.Connected);
+
+ // Handle address changes for wallet switching
+ if (account.address && prevAccount?.address !== account.address) {
+ this.props.setAddress(account.address);
+ }
+ }
+ },
+ });
+ }
+
+ isSupportedChain(chainId: number | undefined): boolean {
+ if (!chainId) return false;
+ const supportedChains = [1, 11155111, 43113]; // mainnet, sepolia, avalanche fuji
+ return supportedChains.includes(chainId);
+ }
+}
+```
+
+### Connection State in Redux
+
+```typescript
+// /src/store/web3/index.ts
+export enum ConnectionStatus {
+ Disconnected = 'disconnected',
+ Connected = 'connected',
+ NetworkNotSupported = 'network-not-supported'
+}
+
+export interface Web3State {
+ status: ConnectionStatus;
+ value: {
+ chainId: Chains;
+ address: string;
+ connectorId: Connector['id'] | '';
+ error: string;
+ };
+}
+```
+
+### User Authentication with Web3
+
+zOS integrates Web3 authentication seamlessly with traditional auth:
+
+```tsx
+// /src/authentication/web3-login/index.tsx
+export class Web3Login extends React.Component<Web3LoginProperties> {
+ render() {
+ const { error, isConnecting, isWalletConnected, onSelect } = this.props;
+
+ return (
+ <div>
+ <RainbowKitConnectButton isDisabled={isConnecting} />
+ {isWalletConnected && (
+ <Button isDisabled={isConnecting} onPress={onSelect}>
+ Sign In
+ </Button>
+ )}
+ {error && (
+ <Alert variant='error'>
+ {error === Web3LoginErrors.PROFILE_NOT_FOUND
+ ? 'The wallet you connected is not associated with a ZERO account'
+ : error}
+ </Alert>
+ )}
+ </div>
+ );
+ }
+}
+```
+
+## Transaction Handling
+
+### Token Transfer Pattern
+
+zOS uses a hybrid approach combining client-side preparation with server-side execution for security:
+
+```typescript
+// /src/apps/wallet/queries/transferTokenRequest.ts
+export const transferTokenRequest = async (
+ address: string,
+ to: string,
+ amount: string,
+ tokenAddress: string
+): Promise<TransferTokenResponse> => {
+ const response = await post(`/api/wallet/${address}/transactions/transfer-token`).send({
+ to,
+ amount,
+ tokenAddress,
+ });
+
+ return response.body as TransferTokenResponse;
+};
+```
+
+### NFT Transfer Implementation
+
+```typescript
+// /src/apps/wallet/queries/transferNFTRequest.ts
+export const transferNFTRequest = async (
+ address: string,
+ to: string,
+ tokenId: string,
+ nftAddress: string
+): Promise<TransferNFTResponse> => {
+ const response = await post(`/api/wallet/${address}/transactions/transfer-nft`).send({
+ to,
+ tokenId,
+ nftAddress,
+ });
+
+ return response.body as TransferNFTResponse;
+};
+```
+
+### Transaction Receipt Monitoring
+
+```typescript
+// Pattern for monitoring transaction status
+const waitForTransactionReceipt = async (hash: string) => {
+ const receiptResponse = await get(`/api/wallet/transaction/${hash}/receipt`).send();
+
+ if (receiptResponse.body.status === 'confirmed') {
+ return { success: true, receipt: receiptResponse.body };
+ } else if (receiptResponse.body.status === 'failed') {
+ throw new Error('Transaction failed');
+ }
+
+ // Continue polling for pending transactions
+ return null;
+};
+```
+
+## Smart Contract Interactions
+
+### Staking Contract Integration
+
+zOS implements a comprehensive staking system with proper error handling and state management:
+
+```typescript
+// /src/apps/staking/lib/useStaking.ts
+export const useStaking = () => {
+ const { address: userAddress } = useSelector(selectedWalletSelector);
+ const queryClient = useQueryClient();
+
+ const mutation = useMutation({
+ mutationFn: async ({ poolAddress, amount, lockDuration }: StakingParams) => {
+ if (!userAddress) {
+ throw new Error('User not connected');
+ }
+
+ let response;
+ try {
+ response = await post(`/api/wallet/${userAddress}/transactions/stake${lockDuration ? '-with-lock' : ''}`).send({
+ poolAddress,
+ amount,
+ lockDuration,
+ });
+ } catch (e) {
+ console.error(e);
+ throw new Error('Failed to stake tokens, please try again.');
+ }
+
+ if (response.body?.transactionHash) {
+ const receiptResponse = await get(`/api/wallet/transaction/${response.body.transactionHash}/receipt`).send();
+
+ if (receiptResponse.body.status === 'confirmed') {
+ return { success: true, hash: response.body.transactionHash, receipt: receiptResponse.body };
+ } else {
+ throw new Error('Transaction failed');
+ }
+ }
+ },
+ onSuccess: (_, { poolAddress }) => {
+ // Invalidate relevant queries to refresh UI
+ queryClient.invalidateQueries({
+ queryKey: ['userStakingBalance'],
+ });
+ queryClient.invalidateQueries({
+ queryKey: ['userStakingInfo', poolAddress],
+ });
+ },
+ });
+
+ const executeStake = async (poolAddress: string, amount: string, lockDuration?: string) => {
+ try {
+ const result = await mutation.mutateAsync({ poolAddress, amount, lockDuration });
+ return result;
+ } catch (err: any) {
+ const errorMessage = err.message || 'Staking failed';
+ return { success: false, error: errorMessage };
+ }
+ };
+
+ return {
+ stakeWithLock: (poolAddress: string, amount: string, lockDuration: string) =>
+ executeStake(poolAddress, amount, lockDuration),
+ stakeWithoutLock: (poolAddress: string, amount: string) =>
+ executeStake(poolAddress, amount),
+ isStaking: mutation.isPending,
+ error: mutation.error?.message || null,
+ };
+};
+```
+
+### Token Approval Pattern
+
+```typescript
+// /src/apps/staking/lib/useTokenApproval.ts
+export const useTokenApproval = () => {
+ const { address: userAddress } = useSelector(selectedWalletSelector);
+
+ const mutation = useMutation({
+ mutationFn: async ({ tokenAddress, spender, amount }: ApprovalParams) => {
+ if (!userAddress) {
+ throw new Error('User not connected');
+ }
+
+ const response = await post(`/api/wallet/${userAddress}/transactions/approve`).send({
+ tokenAddress,
+ spender,
+ amount,
+ });
+
+ if (response.body?.transactionHash) {
+ // Wait for confirmation
+ const receiptResponse = await get(`/api/wallet/transaction/${response.body.transactionHash}/receipt`).send();
+
+ if (receiptResponse.body.status === 'confirmed') {
+ return { success: true, hash: response.body.transactionHash };
+ } else {
+ throw new Error('Approval transaction failed');
+ }
+ }
+ },
+ });
+
+ return {
+ approveToken: mutation.mutateAsync,
+ isApproving: mutation.isPending,
+ error: mutation.error?.message || null,
+ };
+};
+```
+
+## State Management Integration
+
+### Web3 State Structure
+
+```typescript
+// /src/store/web3/index.ts
+export interface Web3State {
+ status: ConnectionStatus;
+ value: {
+ chainId: Chains;
+ address: string;
+ connectorId: Connector['id'] | '';
+ error: string;
+ };
+}
+
+const slice = createSlice({
+ name: 'web3',
+ initialState,
+ reducers: {
+ setConnectionStatus: (state, action: PayloadAction<ConnectionStatus>) => {
+ state.status = action.payload;
+ },
+ setWalletAddress: (state, action: PayloadAction<string>) => {
+ state.value.address = action.payload;
+ },
+ setChain: (state, action: PayloadAction<Chains>) => {
+ state.value.chainId = action.payload;
+ },
+ setWalletConnectionError: (state, action: PayloadAction<string>) => {
+ state.value.error = action.payload;
+ },
+ },
+});
+```
+
+### Wallet State Management
+
+```typescript
+// /src/store/wallet/selectors.ts
+export const selectedWalletSelector = (state: RootState) => {
+ return {
+ address: state.web3.value.address,
+ chainId: state.web3.value.chainId,
+ status: state.web3.status,
+ connectorId: state.web3.value.connectorId,
+ };
+};
+```
+
+## Error Handling & User Experience
+
+### Connection Error Handling
+
+```typescript
+// Comprehensive error handling pattern
+const handleWeb3Error = (error: Error): string => {
+ if (error.message.includes('User denied transaction')) {
+ return 'Transaction was cancelled by user';
+ }
+
+ if (error.message.includes('insufficient funds')) {
+ return 'Insufficient funds for transaction';
+ }
+
+ if (error.message.includes('network')) {
+ return 'Network error. Please check your connection and try again';
+ }
+
+ return 'An unexpected error occurred. Please try again';
+};
+```
+
+### Loading States and User Feedback
+
+```tsx
+// Pattern for showing transaction progress
+const TransactionButton = ({ onExecute, children }) => {
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const handleClick = async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ await onExecute();
+ } catch (err) {
+ setError(handleWeb3Error(err as Error));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <>
+ <Button
+ isLoading={isLoading}
+ onPress={handleClick}
+ isDisabled={isLoading}
+ >
+ {children}
+ </Button>
+ {error && <Alert variant="error">{error}</Alert>}
+ </>
+ );
+};
+```
+
+## Security Best Practices
+
+### 1. Address Validation
+