What are Services?
Services are the core business logic layer in SubWallet Extension. They encapsulate complex functionality, manage state, handle API interactions, and coordinate data flow between different parts of the application. Services provide:- Lifecycle management with init, start, stop methods
- State management through RxJS observables
- Data persistence integration with stores and database
- Event-driven architecture for loosely coupled components
- Cron job support for periodic tasks
Service Interfaces
SubWallet defines several interfaces that services can implement:CoreServiceInterface
The foundation for all services:StoppableServiceInterface
For services that need cleanup:PersistDataServiceInterface
For services that manage persistent data:CronServiceInterface
For services with periodic tasks:Service Statuses
Creating a New Service
Step 1: Define Your Service Structure
Create a new directory inpackages/extension-base/src/services/:
Step 2: Implement the Service Class
Here’s a complete example based on the PriceService:Step 3: Integrate with KoniState
Add your service to the main state handler:Real-World Example: ChainService
The ChainService manages blockchain connections and chain metadata:Service Communication Patterns
Pattern 1: Event-Driven Updates
Pattern 2: Observable State
Pattern 3: Service Dependencies
Best Practices
1. Lazy Initialization
2. Graceful Shutdown
3. Error Handling
4. Memory Management
5. Testing Services
Service Lifecycle
Common Service Types
Data Fetching Services
- PriceService: Fetches and caches token prices
- BalanceService: Manages account balances across chains
- NftService: Handles NFT metadata and ownership
State Management Services
- ChainService: Manages chain configurations and connections
- KeyringService: Handles account keys and signing
- SettingService: Manages user preferences
Background Processing Services
- HistoryService: Processes transaction history
- EarningService: Calculates staking rewards
- NotificationService: Manages in-app notifications