npm package: @hsuite/connect-sdk
Description: > Framework-neutral wallet engine with unified channel protocol, multi-transport communication, and production-ready session orchestration.
Latest version: 2.0.0

# @hsuite/connect-sdk

> Framework-neutral wallet engine with unified channel protocol, multi-transport communication, and production-ready session orchestration.

## Features

- **Channel Protocol** - Unified `hsc:` protocol for dApp-wallet communication via Nostr + P2P
- **WalletConnect v2** - Complete wallet-side integration with session bridge and ledger handlers
- **Secure Key Vault** - Hardware-backed seed storage with BIP-39 mnemonic support
- **Multi-Ledger Support** - Hedera, XRPL, and extensible ledger adapters
- **Transport Layer** - TransportMux with automatic Nostr→P2P upgrade and TURN support
- **Production Logging** - Configurable log levels with scope-based filtering and SOC2 audit trails
- **Portfolio Management** - Token and NFT tracking with price enrichment

## Quick Start

```bash
# Install workspace dependencies
pnpm install

# Build SDK
pnpm --filter @hsuite/connect-sdk build

# Run tests
pnpm --filter @hsuite/connect-sdk test

# Generate API docs
pnpm --filter @hsuite/connect-sdk docs
```

---

## Architecture Overview

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                              SDK Architecture                                │
├─────────────────────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐ │
│  │   Channel   │  │ WalletConnect│  │   Storage   │  │      Security       │ │
│  │  Protocol   │  │     v2      │  │   & Vault   │  │                     │ │
│  ├─────────────┤  ├─────────────┤  ├─────────────┤  ├─────────────────────┤ │
│  │ChannelClient│  │WalletService│  │ KeyVault    │  │ CryptoService       │ │
│  │ ChannelHost │  │SessionBridge│  │ SecureStore │  │ SeedLifecycle       │ │
│  │ChannelIdentity│ │TxHandler    │  │ Recovery    │  │ SecurityState       │ │
│  └──────┬──────┘  └──────┬──────┘  └─────────────┘  └─────────────────────┘ │
│         │                │                                                   │
│  ┌──────┴────────────────┴───────────────────────────────────────────────┐  │
│  │                         TransportMux                                   │  │
│  │    ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐  │  │
│  │    │  NostrTransport │───▶│   P2PTransport  │    │ PostMessageTx   │  │  │
│  │    │    (primary)    │    │   (upgraded)    │    │  (fallback)     │  │  │
│  │    └─────────────────┘    └─────────────────┘    └─────────────────┘  │  │
│  │              │                     │                                   │  │
│  │    ┌─────────┴─────────────────────┴───────────────────────────────┐  │  │
│  │    │              Nostr Relay (nosflare)  +  TURN Server           │  │  │
│  │    └───────────────────────────────────────────────────────────────┘  │  │
│  └───────────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────┘
```

---

## Core Components

### Channel Protocol

The unified `hsc:` channel protocol provides encrypted, persistent communication between dApps and wallets.

#### ChannelClient (dApp Side)

```typescript
import { ChannelClient, encodeChannelInvite } from '@hsuite/connect-sdk';

/**
 * ChannelClient manages the dApp-side of the channel protocol.
 * It handles connection initiation, message sending, and session persistence.
 */
const client = new ChannelClient({
  relayUrl: 'wss://relay.hsuite.io',
  persistence: new LocalStorageAdapter('my-dapp-sessions'),
});

// Connect and generate invite for wallet to scan
const invite = await client.connect({
  type: 'session',
  app: { id: 'my-dapp', name: 'My dApp' },
  context: { ledgerId: 'hedera', networkId: 'hedera:testnet' },
});

// Generate QR code data
const qrData = encodeChannelInvite(invite);
// Result: hsc://invite?key=BASE64&relay=...&app=my-dapp&ledger=hedera&network=testnet
```

#### ChannelHost (Wallet Side)

```typescript
import { ChannelHost, decodeChannelInvite } from '@hsuite/connect-sdk';

/**
 * ChannelHost manages wallet-side channel protocol.
 * It handles incoming connections, RPC routing, and session management.
 */
const host = new ChannelHost({
  relayUrl: 'wss://relay.hsuite.io',
  persistence: new LocalStorageAdapter('hsuite-wallet-channels'),
  onSessionRequest: async (request) => {
    // Show approval UI
    return await showApprovalModal(request);
  },
});

// Accept invite from QR scan or deep link
const invite = decodeChannelInvite(scannedData);
await host.acceptInvite(invite, selectedAccounts);
```

#### Channel Identity

```typescript
import { ChannelIdentity } from '@hsuite/connect-sdk';

/**
 * ChannelIdentity provides deterministic key derivation for channel encryption.
 * Uses NaCl box for end-to-end encrypted messaging.
 */
const identity = new ChannelIdentity({
  localContext: 'wallet:0.0.12345',
  sharedKey: invite.key,
});

// Encrypt message for channel
const encrypted = await identity.encrypt(message);

// Decrypt incoming message
const decrypted = await identity.decrypt(encryptedPayload);
```

---

### Transport Layer

The SDK provides a multi-transport architecture with automatic upgrade from Nostr to P2P.

#### TransportMux

```typescript
import { TransportMux, NostrTransport, P2PTransport } from '@hsuite/connect-sdk';

/**
 * TransportMux multiplexes between Nostr (reliable) and P2P (fast).
 * Automatically upgrades to P2P when both sides are ready.
 */
const mux = new TransportMux({
  nostr: new NostrTransport({ relayUrl: 'wss://relay.hsuite.io' }),
  p2p: new P2PTransport({ iceServers: await fetchTurnCredentials() }),
});

// Connect to channel
await mux.connect(invite);

// Messages automatically routed through best available transport
mux.on('message', (msg) => console.log('Received:', msg));
await mux.send({ type: 'rpc', payload: { method: 'session/status' } });
```

#### TURN Credential Service

```typescript
import { fetchTurnCredentials } from '@hsuite/connect-sdk';

/**
 * Fetch short-lived TURN credentials for WebRTC NAT traversal.
 * Credentials are rotated automatically for security.
 */
const iceServers = await fetchTurnCredentials({
  endpoint: 'https://relay.hsuite.io/turn/credentials',
  ttlSeconds: 86400,
});

// Use with P2PTransport
const p2p = new P2PTransport({ iceServers });
```

---

### WalletConnect v2

Complete wallet-side WalletConnect implementation for universal dApp connectivity.

#### WalletConnectWalletService

```typescript
import { WalletConnectWalletService } from '@hsuite/connect-sdk/walletconnect';

/**
 * WalletConnectWalletService wraps Web3Wallet SDK for wallet-side operations.
 * Handles session proposals, requests, and multi-chain support.
 */
const wcWallet = new WalletConnectWalletService();

await wcWallet.initialize({
  projectId: 'YOUR_WALLETCONNECT_PROJECT_ID',
  metadata: {
    name: 'HSuite Wallet',
    description: 'Multi-chain wallet for Hedera & XRPL',
    url: 'https://hsuite.app',
    icons: ['https://hsuite.app/icon.png'],
  },
});

// Handle session proposals
wcWallet.on('session_proposal', async (proposal) => {
  const accounts = await showAccountPicker(proposal);
  await wcWallet.approveSession(proposal.id, accounts);
});

// Handle transaction requests
wcWallet.on('session_request', async (request) => {
  const result = await handleTransaction(request);
  await wcWallet.respondRequest(request.id, result);
});
```

#### WalletConnect Session Bridge

```typescript
import { WalletConnectSessionBridge } from '@hsuite/connect-sdk/walletconnect';

/**
 * WalletConnectSessionBridge coordinates between WalletConnect and SDK session management.
 * Provides unified session handling across protocols.
 */
const bridge = new WalletConnectSessionBridge({
  wcWallet,
  sessionManager,
  onProposal: async (context) => {
    // Show account selection UI
    const accounts = await showAccountPicker();
    await bridge.approveProposal(context.proposal.id, accounts);
  },
});

bridge.on('session:created', (session) => {
  console.log('New session:', session.topic);
});
```

#### WalletConnect Transaction Handler

```typescript
import { WalletConnectTransactionHandler } from '@hsuite/connect-sdk/walletconnect';

/**
 * WalletConnectTransactionHandler orchestrates SDK-level transaction signing.
 * Provides callback-based UI integration for approval and authentication.
 */
const handler = new WalletConnectTransactionHandler({
  walletCore,
  onApproval: async (request) => {
    // Show transaction approval UI
    return await showApprovalModal(request);
  },
  onAuthentication: async () => {
    // Prompt for PIN/biometric
    return await promptPinOrBiometric();
  },
  onTransactionParsed: (parsed) => {
    // Display human-readable transaction details
    console.log('Transaction:', parsed.description);
  },
});

const result = await handler.handleRequest(request, { dappName, dappUrl });
```

#### Ledger Handlers

```typescript
import { 
  HederaWalletHandler, 
  XrplWalletHandler,
  HEDERA_METHODS,
  XRPL_METHODS,
} from '@hsuite/connect-sdk/walletconnect';

/**
 * Ledger-specific handlers for WalletConnect method routing.
 */

// Hedera methods
// - hedera_signTransaction
// - hedera_signAndExecuteTransaction
// - hedera_signMessage

// XRPL methods
// - xrpl_signTransaction
// - xrpl_signAndSubmit
// - xrpl_signMessage
```

---

### Session Management

#### ChannelSessionManager (UnifiedSessionManager)

```typescript
import { ChannelSessionManager } from '@hsuite/connect-sdk';

/**
 * ChannelSessionManager provides unified session tracking for both
 * native channel sessions and WalletConnect sessions.
 */
const sessionManager = new ChannelSessionManager({
  storageAdapter: new LocalStorageAdapter('sessions'),
});

// Create native session
const session = sessionManager.create({
  appId: 'my-dapp',
  appName: 'My dApp',
  ledgerId: 'hedera',
  networkId: 'hedera:testnet',
  accounts: ['0.0.12345'],
});

// Create WalletConnect session
const wcSession = sessionManager.createWalletConnectSession({
  topic: 'abc123',
  dappName: 'My dApp',
  ledgerId: 'hedera',
  networkId: 'hedera:testnet',
  expiry: Date.now() + 86400000,
});

// List all active sessions
const sessions = sessionManager.getActiveSessions();

// Terminate session
await sessionManager.terminate(session.sessionId);
```

---

### Storage & Security

#### KeyVaultService

```typescript
import { KeyVaultService } from '@hsuite/connect-sdk';

/**
 * KeyVaultService provides encrypted seed storage with hardware/biometric protection.
 * Supports multiple protection modes and recovery bundle export.
 */
const keyVault = new KeyVaultService({
  storage: secureStorage,
  encoder: cryptoEncoder,
  auditTrail: auditLogger,
});

// Store seed with biometric protection
await keyVault.storeSeed({
  seedId: 'primary',
  mnemonic: 'word1 word2 ... word24',
  protection: 'biometric',
});

// Retrieve seed (requires authentication)
const seed = await keyVault.getSeed('primary', { biometricToken });

// Create recovery bundle
const bundle = await keyVault.exportRecoveryBundle('primary');
```

#### Session Storage Adapters

```typescript
import { 
  LocalStorageAdapter,
  MemoryStorageAdapter,
  NoopSessionStorageAdapter,
} from '@hsuite/connect-sdk';

// Browser localStorage (recommended for web wallets)
const browserAdapter = new LocalStorageAdapter('my-app.sessions');

// In-memory for testing or ephemeral sessions
const memoryAdapter = new MemoryStorageAdapter();

// No-op for when persistence isn't needed
const noopAdapter = new NoopSessionStorageAdapter();
```

---

### Production Logging

```typescript
import { configureLogger, createChainedAuditTrail } from '@hsuite/connect-sdk';

/**
 * Configure structured logging with scope-based filtering.
 * Supports SOC2 CC7.1 compliant audit trails.
 */

// Production configuration
configureLogger({
  environment: 'production',
  minLevel: 'warn',
  scopeLevels: {
    'WalletConnect': 'error',
    'ChannelProtocol': 'warn',
    'Security': 'info',
  },
});

// SOC2 compliant audit trail
const auditTrail = createChainedAuditTrail({
  storage: new IndexedDbAuditStorage('audit-logs'),
  retentionDays: 90,
  hashChainEnabled: true,
});

auditTrail.log({
  action: 'session.approved',
  actor: 'user',
  target: 'session-123',
  metadata: { dappName: 'My dApp' },
});
```

---

## Module Reference

| Module | Purpose | Key Exports |
|--------|---------|-------------|
| `core/` | Wallet lifecycle primitives | `WalletCore`, `SessionManager`, `LedgerRegistry`, `EventBus` |
| `channel/` | Unified channel protocol | `ChannelClient`, `ChannelHost`, `ChannelIdentity`, `ChannelPersistence` |
| `transport/` | Multi-transport communication | `TransportMux`, `NostrTransport`, `P2PTransport`, `PostMessageTransport` |
| `walletconnect/` | WalletConnect v2 integration | `WalletConnectWalletService`, `SessionBridge`, `TransactionHandler` |
| `session/` | Session management | `ChannelSessionManager`, `SessionFlowController`, `SecureMemory` |
| `storage/` | Secure storage & vault | `KeyVaultService`, `SecureStore`, `PersistentCacheService` |
| `security/` | Cryptographic utilities | `CryptoService`, `SeedLifecycleController`, `SecurityStateController` |
| `ledger/` | Ledger services | `PortfolioService`, `TransactionOrchestrator`, `AccountLabelManager` |
| `protocol/` | RPC implementation | `RpcClient`, `RpcServer`, `RpcRouter`, `RpcCodec` |
| `telemetry/` | Observability | `BaseTelemetryClient`, `PersistentAuditTrail`, `ConsoleMetrics` |
| `logging/` | Structured logging | `configureLogger`, `ChainedAuditTrail`, `LogSanitizer` |
| `pricing/` | Token pricing | `PriceService`, `SUPPORTED_CURRENCIES` |
| `preferences/` | User preferences | `CurrencyPreferences`, `NetworkPreferences` |
| `multisig/` | Multi-signature support | `MultisigExtension`, `SignatureAggregator` |
| `asset-metadata/` | NFT/token metadata | `AssetMetadataCache`, `NftMetadataResolver`, `TokenImageResolver` |

---

## Development

### Directory Structure

```
src/
├── channel/           # Unified channel protocol (hsc:)
├── core/              # WalletCore, SessionManager, LedgerRegistry, EventBus
├── ledger/            # Portfolio, transactions, account labels, token discovery
├── logging/           # Logger, audit trail, log sanitizer
├── multisig/          # Multi-signature extension
├── preferences/       # Currency and network preferences
├── presentation/      # Asset presentation utilities
├── pricing/           # CoinGecko price service
├── protocol/          # RPC client/server/router/codec
├── security/          # Crypto, seed lifecycle, security state (50+ files)
├── session/           # Session management, secure memory
├── storage/           # KeyVault, SecureStore, persistence
├── telemetry/         # Audit trails, metrics
├── transport/         # TransportMux, Nostr, P2P, PostMessage, TURN
├── utils/             # Shared utilities
└── walletconnect/     # WalletConnect v2 integration
```

### Scripts

| Command | Description |
|---------|-------------|
| `pnpm build` | Build package to `dist/` |
| `pnpm test` | Run Vitest suite |
| `pnpm test -- --coverage` | Run with coverage report |
| `pnpm docs` | Generate Compodoc API documentation |
| `pnpm lint` | Lint TypeScript sources |

### Test Statistics

- **3,453+ passing tests** across 109 test files
- **80%+ statement coverage**
- **< 5 seconds** execution time

---

## Documentation

📚 **Full Documentation**: [docs/packages/native-wallet-sdk.md](../../docs/packages/native-wallet-sdk.md)

For comprehensive guides including:
- Core capabilities and architecture
- Channel protocol deep dive
- WalletConnect integration guide
- Compose → Sign → Submit workflows
- Transport layer configuration
- Session management patterns
- Testing strategies

### Related Documentation

- [Main README](../../readme.md) - Project overview
- [Documentation Index](../../docs/readme.md) - All documentation
- [Channel Protocol](../../docs/native-wallet-sdk/channel-protocol.md) - Protocol specification
- [Transport Architecture](../../docs/native-wallet-sdk/transports.md) - Transport layer
- [Session Management](../../docs/architecture/session-management.md) - Session design

---

**Status:** ✅ Production Ready | **Coverage:** 80%+ | **Tests:** 3,453+ passing | **Modules:** 15+