# ๐Ÿ’ฐ Wallet Module > **Lightning Network wallet management** with real-time balance updates, payment processing, and comprehensive transaction management integrated with LNbits. ## Table of Contents - [[#Overview]] - [[#Core Features]] - [[#Architecture]] - [[#Real-Time WebSocket Integration]] - [[#Services]] - [[#Components]] - [[#Payment Processing]] - [[#Configuration]] - [[#Development Guide]] ## Overview The Wallet Module provides comprehensive Lightning Network wallet functionality for the Ario application. It integrates with LNbits to handle payments, manage wallet balances, and provide real-time updates through WebSocket connections. ### **Key Capabilities** - **Real-time balance updates** via WebSocket connection to LNbits - **Payment processing** for Lightning invoices, Lightning addresses, and LNURL - **Transaction management** with comprehensive history and status tracking - **Pay link creation** for receiving payments with LNURL and Lightning addresses - **Multi-wallet support** with automatic wallet selection - **Battery optimization** through VisibilityService integration ### **Dependencies** - `['base']` - Requires base module for authentication and core services - **LNbits Server** - External Lightning wallet backend - **PaymentService** - Core payment processing service ## Core Features ### **๐Ÿ”„ Real-Time Balance Updates** Automatic wallet balance synchronization without page refreshes: - **WebSocket Connection** - Direct connection to LNbits WebSocket API - **Instant Updates** - Balance changes reflect immediately in UI - **Smart Unit Conversion** - Handles LNbits sats/millisats conversion differences - **Payment Notifications** - Toast notifications for incoming payments - **Connection Management** - Automatic reconnection with exponential backoff ### **๐Ÿ’ธ Payment Processing** Comprehensive Lightning payment handling: - **Lightning Invoices** - Pay BOLT11 invoices directly - **Lightning Addresses** - Send to Lightning addresses (user@domain.com) - **LNURL Pay** - Support for LNURL payment requests - **Payment Validation** - Pre-flight checks for sufficient balance - **Error Handling** - User-friendly error messages and recovery ### **๐Ÿ“Š Transaction Management** Complete transaction history and tracking: - **Transaction History** - Chronological list of all payments - **Real-time Updates** - New transactions appear instantly - **Transaction Details** - Amount, description, timestamp, fees, status - **Transaction Types** - Sent, received, pending, confirmed, failed - **Search and Filter** - Find specific transactions quickly ### **๐Ÿ”— Payment Links (LNURL)** Create reusable payment endpoints: - **LNURL Generation** - Create payment links for receiving - **Lightning Addresses** - Generate username@domain addresses - **Amount Ranges** - Set minimum and maximum payment amounts - **Comments Support** - Allow payment comments - **Link Management** - Create, view, and delete payment links ## Architecture ### **Service Layer** ``` src/modules/wallet/services/ โ”œโ”€โ”€ WalletService.ts # Core wallet operations โ”œโ”€โ”€ WalletWebSocketService.ts # Real-time balance updates โ””โ”€โ”€ WalletAPI.ts # LNbits API integration ``` ### **Component Layer** ``` src/modules/wallet/components/ โ”œโ”€โ”€ SendDialog.vue # Payment sending interface โ”œโ”€โ”€ ReceiveDialog.vue # Payment receiving interface โ”œโ”€โ”€ TransactionList.vue # Transaction history display โ”œโ”€โ”€ PayLinkManager.vue # LNURL payment link management โ””โ”€โ”€ BalanceDisplay.vue # Wallet balance component ``` ### **Views Layer** ``` src/modules/wallet/views/ โ””โ”€โ”€ WalletPage.vue # Main wallet interface ``` ## Real-Time WebSocket Integration ### **Connection Architecture** The WebSocket service provides seamless real-time updates: ```typescript // WebSocket URL format wss://your-lnbits-server/api/v1/ws/{walletInkey} // Connection lifecycle โ”Œโ”€ Authentication Event โ”€โ”€โ†’ Connect WebSocket โ”œโ”€ Payment Received โ”€โ”€โ”€โ”€โ”€โ†’ Update Balance + Show Toast โ”œโ”€ Payment Sent โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ Update Balance โ”œโ”€ Connection Lost โ”€โ”€โ”€โ”€โ”€โ”€โ†’ Automatic Reconnection โ””โ”€ App Hidden โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ Pause (Battery Optimization) ``` ### **Balance Update Logic** Handles LNbits WebSocket behavior differences: ```typescript // Incoming payments: LNbits sends post-payment balance if (payment.amount > 0) { // Use balance as-is (already includes received amount) updateBalance(websocket_balance) } // Outgoing payments: LNbits sends pre-payment balance if (payment.amount < 0) { // Subtract payment amount from reported balance final_balance = websocket_balance - payment_amount_sats updateBalance(final_balance) } ``` ### **Connection Management** - **Auto-reconnection** with exponential backoff (1s, 2s, 4s, 8s, 16s) - **VisibilityService integration** for battery optimization - **Connection health monitoring** with status indicators - **Graceful disconnection** on logout ### **Error Handling** - Connection failures with retry logic - Invalid wallet credentials handling - Network interruption recovery - WebSocket protocol error handling ## Services ### **WalletService** ๐Ÿฆ **Purpose:** Core wallet operations and transaction management **Location:** `src/modules/wallet/services/WalletService.ts` **Token:** `SERVICE_TOKENS.WALLET_SERVICE` **Key Features:** - Send Lightning payments (invoices, addresses, LNURL) - Create and manage LNURL payment links - Transaction history management - Payment link generation with Lightning addresses **Reactive State:** ```typescript interface WalletService { transactions: ComputedRef // Transaction history payLinks: ComputedRef // Created payment links isCreatingPayLink: ComputedRef // Pay link creation state isSendingPayment: ComputedRef // Payment sending state error: ComputedRef // Error state } ``` **Key Methods:** - `sendPayment(request: SendPaymentRequest)` - Send Lightning payment - `createReceiveAddress(params)` - Create LNURL payment link - `deletePayLink(linkId: string)` - Remove payment link - `refresh()` - Reload transactions and payment links ### **WalletWebSocketService** โšก **Purpose:** Real-time wallet balance updates via WebSocket **Location:** `src/modules/wallet/services/WalletWebSocketService.ts` **Token:** `SERVICE_TOKENS.WALLET_WEBSOCKET_SERVICE` **Key Features:** - WebSocket connection to LNbits - Real-time balance updates - Payment notification handling - Connection health management - Battery optimization via VisibilityService **Reactive State:** ```typescript interface WalletWebSocketService { isConnected: Ref // Connection status connectionStatus: Ref // Connection state } ``` **Connection States:** - `disconnected` - Not connected - `connecting` - Connection in progress - `connected` - Successfully connected - `reconnecting` - Attempting to reconnect - `error` - Connection failed - `failed` - Max reconnection attempts reached **Key Methods:** - `reconnect()` - Manual reconnection trigger - `disconnect()` - Graceful disconnection - `cleanup()` - Service disposal ### **PaymentService Integration** ๐Ÿ’ณ The wallet module integrates with the core PaymentService: **Shared Functionality:** - Wallet balance management via `PaymentService.updateWalletBalance()` - Preferred wallet selection with `PaymentService.getPreferredWallet()` - Admin/invoice key access for API operations - Multi-wallet support with consistent selection logic ## Components ### **SendDialog.vue** ๐Ÿ“ค Payment sending interface with comprehensive validation: **Features:** - Support for Lightning invoices, addresses, and LNURL - Amount validation against available balance - Payment request parsing and validation - Real-time fee estimation - Error handling with user-friendly messages **Form Fields:** - Destination (invoice, address, or LNURL) - Amount (when not specified in invoice) - Comment (for Lightning addresses) ### **ReceiveDialog.vue** ๐Ÿ“ฅ Payment receiving interface for creating payment requests: **Features:** - LNURL payment link creation - Lightning address generation - Customizable amount ranges - Comment support configuration - QR code generation for sharing **Form Fields:** - Description - Minimum amount - Maximum amount - Username (for Lightning address) - Allow comments toggle ### **TransactionList.vue** ๐Ÿ“‹ Comprehensive transaction history display: **Features:** - Chronological transaction listing - Real-time transaction updates - Transaction status indicators - Amount formatting with proper units - Transaction type differentiation (sent/received) - Fee information display ### **BalanceDisplay.vue** ๐Ÿ’ฐ Wallet balance component with real-time updates: **Features:** - Real-time balance updates via WebSocket - Multiple unit display (sats, millisats) - Loading state indicators - Connection status awareness ## Payment Processing ### **Payment Flow Architecture** ``` User Action โ”€โ”€โ†’ Validation โ”€โ”€โ†’ Payment โ”€โ”€โ†’ Confirmation โ”€โ”€โ†’ UI Update โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€ Real-time via WebSocket โ”‚ โ”‚ โ”‚ โ””โ”€ Transaction recorded โ”‚ โ”‚ โ””โ”€ LNbits API call โ”‚ โ””โ”€ Balance check, format validation โ””โ”€ Send/Receive dialog interaction ``` ### **Payment Types Supported** #### **Lightning Invoices (BOLT11)** ```typescript // Direct invoice payment await walletService.sendPayment({ destination: "lnbc1000n1p3xh4v...", amount: 1000 // Optional if invoice has amount }) ``` #### **Lightning Addresses** ```typescript // Lightning address payment await walletService.sendPayment({ destination: "user@stacker.news", amount: 1000, comment: "Great post!" }) ``` #### **LNURL Pay** ```typescript // LNURL payment await walletService.sendPayment({ destination: "LNURL1DP68GURN8GHJ7UM9WFMXJCM99E3K7MF0V9CXJ0M385EKVCENXC6R2C35XVUKXEFCV5MKVV34X5EKZD3EV56NYD3HXQURZEPEXEJXXEPNXSCRVWFNV9NXZCN9XQ6XYEFHVGCXXCMYXYMNSERXFQ5FNS", amount: 1000 }) ``` ### **Error Handling** Comprehensive error handling for payment failures: - **Insufficient balance** - Clear messaging with current balance - **Invalid payment request** - Format validation errors - **Network failures** - Retry options and offline handling - **Payment routing failures** - Lightning network routing errors - **Timeout handling** - Payment timeout with status updates ## Configuration ### **Module Configuration** Configure the wallet module in `src/app.config.ts`: ```typescript modules: { wallet: { enabled: true, config: { // WebSocket configuration websocket: { enabled: true, // Enable real-time updates reconnectDelay: 1000, // Initial reconnection delay (ms) maxReconnectAttempts: 5 // Maximum reconnection attempts }, // Payment configuration payments: { defaultUnit: 'sats', // Default amount unit showFees: true, // Display fee information confirmLarge: 10000 // Confirm payments above this amount }, // UI configuration ui: { showBalance: true, // Display balance in UI showTransactions: true, // Show transaction history transactionLimit: 100 // Max transactions to display } } } } ``` ### **Environment Variables** Required environment setup: ```bash # LNbits server URL VITE_LNBITS_BASE_URL=https://your-lnbits-server.com # Optional: Default wallet configuration VITE_DEFAULT_CURRENCY=sats VITE_PAYMENT_TIMEOUT=30000 ``` ## Development Guide ### **Adding New Payment Types** To add support for new payment methods: 1. **Extend SendPaymentRequest interface:** ```typescript interface SendPaymentRequest { destination: string amount: number comment?: string newPaymentType?: NewPaymentParams // Add new type } ``` 2. **Update WalletService.sendPayment():** ```typescript async sendPayment(request: SendPaymentRequest): Promise { // Add detection logic if (this.isNewPaymentType(request.destination)) { return this.handleNewPaymentType(request) } // ... existing logic } ``` 3. **Add validation and processing:** ```typescript private isNewPaymentType(destination: string): boolean { // Detection logic } private async handleNewPaymentType(request: SendPaymentRequest): Promise { // Processing logic } ``` ### **Extending Transaction Types** To add new transaction types: 1. **Update PaymentTransaction interface:** ```typescript interface PaymentTransaction { // ... existing fields type: 'sent' | 'received' | 'new_type' metadata?: NewTypeMetadata } ``` 2. **Update transaction mapping:** ```typescript private mapPaymentToTransaction(payment: any): PaymentTransaction { // Add new type detection and mapping } ``` ### **Custom WebSocket Handlers** To add custom WebSocket message handling: ```typescript class WalletWebSocketService extends BaseService { private handleMessage(event: MessageEvent): void { const data = JSON.parse(event.data) // Handle existing message types if (data.payment) { this.handlePaymentNotification(data.payment) } // Add custom message handling if (data.custom_event) { this.handleCustomEvent(data.custom_event) } } private handleCustomEvent(event: CustomEvent): void { // Custom event processing } } ``` ### **Testing Wallet Functionality** #### **Unit Tests** ```typescript describe('WalletService', () => { let service: WalletService beforeEach(() => { service = new WalletService() }) it('should send Lightning payment', async () => { const request = { destination: 'lnbc1000n...', amount: 1000 } const result = await service.sendPayment(request) expect(result).toBe(true) }) }) ``` #### **Integration Tests** ```typescript describe('Wallet Integration', () => { it('should update balance after payment', async () => { const websocketService = new WalletWebSocketService() const paymentService = new PaymentService() // Mock payment notification await websocketService.handlePaymentNotification({ amount: 1000, wallet_balance: 5000 }) expect(paymentService.totalBalance).toBe(5000000) // millisats }) }) ``` ## See Also ### Related Documentation - **[[../base-module/index|๐Ÿ—๏ธ Base Module]]** - Authentication and core services - **[[../../03-core-services/payment-service|๐Ÿ’ณ Payment Service]]** - Core payment processing - **[[websocket-integration|โšก WebSocket Integration]]** - Real-time update details - **[[payment-processing|๐Ÿ’ธ Payment Processing]]** - Payment flow documentation ### API References - **[[../../05-api-reference/lnbits-api|โšก LNbits API]]** - Backend API integration - **[[../../05-api-reference/lightning-payments|๐Ÿ’ฐ Lightning Payments]]** - Payment protocol details ### Development Guides - **[[../../04-development/testing|๐Ÿงช Testing Guide]]** - Testing strategies - **[[../../04-development/debugging|๐Ÿ› Debugging]]** - Troubleshooting guide --- **Tags:** #wallet #lightning #payments #websocket #real-time #module **Last Updated:** 2025-09-18 **Author:** Development Team