What are Stores?
Stores are data persistence layers in SubWallet Extension that handle saving and retrieving data from Chrome’s local storage. They provide a clean abstraction over the browser storage API and enable reactive data patterns through RxJS subjects. Stores are essential for:- Persisting user data across browser sessions
- Reactive data flow through observable patterns
- Type-safe storage with TypeScript interfaces
- Namespaced data to avoid key conflicts
Store Architecture
SubWallet implements two types of stores:BaseStore
The foundation class that provides basic CRUD operations with Chrome storage:- Prefix-based namespacing to avoid storage key collisions
- Callback-based async operations
- Automatic error handling via
chrome.runtime.lastError
SubscribableStore
ExtendsBaseStore with reactive capabilities using RxJS:
- RxJS Subject emits on every data change
- Promise-based
asyncGetfor modern async/await syntax - Automatic notification to all subscribers when data changes
Creating a New Store
Step 1: Define Your Store Class
Create a new file inpackages/extension-base/src/stores/:
- Use
SubscribableStoreif you need reactive updates - Use
BaseStorefor simple key-value storage - Always prefix with
EXTENSION_PREFIXfor namespace isolation - Use descriptive, unique keys for your store
Step 2: Define the Data Type
Ensure your data type is defined in the appropriate types file:Step 3: Integrate into KoniState
Add your store to the state management class:Step 4: Export Your Store
Add your store to the index file:Real-World Example: SettingsStore
Here’s how the SettingsStore is implemented:Best Practices
1. Choose the Right Base Class
- Use
SubscribableStorewhen:- UI needs real-time updates
- Multiple components depend on the data
- Data changes frequently
- Use
BaseStorewhen:- Data is read once at startup
- Simple configuration storage
- No need for reactive updates
2. Storage Keys
3. Type Safety
Always define proper TypeScript interfaces:4. Ready State Pattern
Implement ready flags to prevent redundant storage reads:5. Event Emission
Emit events when data changes to trigger dependent systems:6. Error Handling
BaseStore automatically logs errors, but add application-level handling:Common Patterns
Pattern 1: Cache with Store Backup
Pattern 2: Subscribe with Initial Value
Pattern 3: Batch Updates
Debugging Stores
View Storage Contents
In Chrome DevTools:- Open Developer Tools > Application > Local Storage
- Look for keys prefixed with your
EXTENSION_PREFIX - Inspect values (stored as JSON)