npm package: @pioneer-platform/pioneer-subscriptions
Description: Session-based blockchain address subscription manager for real-time payment notifications
Author: highlander
Latest version: 3.0.6

# @pioneer-platform/pioneer-subscriptions

Session-based blockchain address subscription manager for real-time payment notifications.

## Features

- 🔔 **Real-time notifications** - Receive instant alerts when addresses receive payments
- 🔄 **Session-based** - Subscriptions automatically tied to client connection lifecycle
- 🧹 **Auto-cleanup** - Subscriptions removed when clients disconnect
- ⛓️ **Multi-chain** - Support for all blockbook-enabled blockchains (BTC, LTC, DOGE, DASH, etc.)
- 🎯 **Event-driven** - Simple callback API for handling payment notifications
- 📊 **Statistics** - Track active subscriptions and sessions

## Installation

```bash
pnpm add @pioneer-platform/pioneer-subscriptions
```

## Usage

### Basic Setup

```typescript
import { SubscriptionManager } from '@pioneer-platform/pioneer-subscriptions';

// Initialize
const manager = new SubscriptionManager();
await manager.init();

// Register callback for payment notifications
manager.onPayment((notification) => {
  console.log('Payment received:', notification);
  // {
  //   sessionId: 'socket-123',
  //   username: 'user1',
  //   coin: 'BTC',
  //   address: 'bc1q...',
  //   txid: 'abc123...',
  //   amount: '50000',
  //   confirmations: 0,
  //   timestamp: 1234567890
  // }
  
  // Push to client via WebSocket
  io.to(notification.sessionId).emit('payment:notification', notification);
});
```

### Subscribe to Addresses

```typescript
// When client connects and sends addresses to monitor
const result = await manager.subscribe({
  sessionId: socket.id,
  username: 'user123',
  coin: 'BTC',
  addresses: [
    'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
    '3J98t1WpEZ73CNmYviecrnyiWrnqRhWNLy'
  ]
});

console.log(result);
// { success: true, message: 'Subscribed to 2 addresses on BTC' }
```

### Unsubscribe on Disconnect

```typescript
// When client disconnects
socket.on('disconnect', async () => {
  await manager.unsubscribe(socket.id);
  console.log('Session cleaned up');
});
```

### Get Statistics

```typescript
const stats = manager.getStats();
console.log(stats);
// {
//   totalSessions: 5,
//   totalAddresses: 12,
//   sessionsByUsername: { 'user1': 2, 'user2': 3 },
//   addressesByCoin: { 'BTC': 8, 'LTC': 4 },
//   sessions: [...]
// }
```

## WebSocket Integration Example

```typescript
import { SubscriptionManager } from '@pioneer-platform/pioneer-subscriptions';
import { Server } from 'socket.io';

const io = new Server(server);
const subscriptionManager = new SubscriptionManager();
await subscriptionManager.init();

// Setup payment notification forwarding
subscriptionManager.onPayment((notification) => {
  // Send to specific session
  io.to(notification.sessionId).emit('payment', notification);
  
  // Also log for monitoring
  console.log(`💰 Payment: ${notification.amount} ${notification.coin} to ${notification.address}`);
});

// Handle client connections
io.on('connection', (socket) => {
  console.log('Client connected:', socket.id);
  
  // Client sends addresses to monitor
  socket.on('subscribe_addresses', async (data) => {
    const { coin, addresses } = data;
    const username = socket.data.username; // From auth
    
    const result = await subscriptionManager.subscribe({
      sessionId: socket.id,
      username,
      coin,
      addresses
    });
    
    socket.emit('subscribe_result', result);
  });
  
  // Cleanup on disconnect
  socket.on('disconnect', async () => {
    await subscriptionManager.unsubscribe(socket.id);
    console.log('Client disconnected and unsubscribed:', socket.id);
  });
});
```

## API

### `SubscriptionManager`

#### Methods

- **`init(): Promise<void>`** - Initialize the manager and connect to blockbook
- **`subscribe(request): Promise<{success, message}>`** - Subscribe a session to addresses
- **`unsubscribe(sessionId): Promise<void>`** - Unsubscribe a session and cleanup
- **`onPayment(callback): void`** - Register a payment notification callback
- **`offPayment(callback): void`** - Remove a payment callback
- **`getStats(): SubscriptionStats`** - Get subscription statistics
- **`getAvailableCoins(): string[]`** - Get list of supported coins
- **`isReady(): boolean`** - Check if manager is initialized
- **`shutdown(): Promise<void>`** - Cleanup and shutdown

#### Types

```typescript
interface SubscriptionRequest {
  sessionId: string;    // Unique session/socket ID
  username: string;     // Username for tracking
  coin: string;         // Coin symbol (BTC, LTC, etc.)
  addresses: string[];  // Array of addresses to monitor
}

interface PaymentNotification {
  sessionId: string;
  username: string;
  coin: string;
  address: string;
  txid: string;
  amount: string;       // In satoshis/smallest unit
  confirmations: number;
  timestamp: number;
}

interface SubscriptionStats {
  totalSessions: number;
  totalAddresses: number;
  sessionsByUsername: Record<string, number>;
  addressesByCoin: Record<string, number>;
  sessions: SessionSubscription[];
}
```

## Architecture

```
┌─────────────┐
│   Client    │
│  (Browser)  │
└──────┬──────┘
       │ WebSocket
       │ subscribe_addresses
       ▼
┌─────────────────┐
│   WebSocket     │
│    Server       │
└────────┬────────┘
         │
         │ manager.subscribe()
         ▼
┌─────────────────────┐
│ SubscriptionManager │
│                     │
│  - Sessions Map     │
│  - Address Map      │
│  - Callbacks        │
└──────────┬──────────┘
           │
           │ subscribeAddresses()
           ▼
┌─────────────────────┐
│   Blockbook WS      │
│   (per chain)       │
└──────────┬──────────┘
           │
           │ TX notifications
           ▼
┌─────────────────────┐
│  Blockchain Node    │
└─────────────────────┘
```

## Testing

```bash
pnpm run build
pnpm test
```

## License

MIT