Files
mkstack/docs/CASHU_WALLET.md

25 KiB

Cashu Wallet Implementation Guide

This document provides comprehensive instructions for AI agents working on the Cashu/Lightning wallet implementation. It covers architecture, patterns, and best practices for extending and maintaining the wallet system.

Table of Contents

  1. Architecture Overview
  2. Component Structure
  3. Hook Patterns
  4. Wallet Modes
  5. Mint Management
  6. Transaction Operations
  7. Integration Points
  8. Extension Guidelines
  9. Best Practices

Architecture Overview

The Cashu wallet is built on a layered architecture with clear separation of concerns:

┌─────────────────────────────────────────────────┐
│         CashuWallet (Orchestrator)              │
│  - Coordinates all operations                   │
│  - Manages UI state and modals                  │
│  - Routes between modes (tokens/lightning)      │
└─────────────────────────────────────────────────┘
                    │
        ┌───────────┼──────────┐
        │           │          │
┌───────▼─────┐ ┌───▼───────┐ ┌▼─────────────┐
│ WalletHeader│ │PaymentCard│ │Modals/Drawers│
│ - Balance   │ │- Send/    │ │ - QRScanner  │
│ - Mint      │ │  Receive  │ │ - History    │
│ - Mode      │ │- Lightning│ │ - Breakdown  │
└─────────────┘ └───────────┘ └──────────────┘
        │
        │
┌───────▼───────────────────────────────────────┐
│              Domain Hooks                     │
│  - useMintManager (mint operations)           │
│  - useTokenOperations (Cashu tokens)          │
│  - useLightningOperations (Lightning)         │
│  - useHistoryManager (transaction history)    │
└───────────────────────────────────────────────┘
        │
        │
┌───────▼───────────────────────────────────────┐
│              Core Hooks                       │
│  - useCashu (coco manager instance)           │
│  - useNpubCash (npub.cash API)                │
│  - useLightningAddress (LNURL resolution)     │
│  - useQRCode (QR generation/scanning)         │
└───────────────────────────────────────────────┘
        │
        │
┌───────▼───────────────────────────────────────┐
│         coco-cashu-core Library               │
│  - Proof management                           │
│  - Mint operations                            │
│  - Quote processing                           │
└───────────────────────────────────────────────┘

Key Principles

  1. Separation of Concerns: UI components are separated from business logic hooks
  2. Single Responsibility: Each hook handles one specific domain (mints, tokens, lightning)
  3. State Management: React state for UI reactivity, coco instance for wallet operations
  4. Error Handling: Centralized error handling with toast notifications
  5. Type Safety: Full TypeScript coverage with proper types from coco-cashu-core

Component Structure

Main Components

CashuWallet.tsx - Main Orchestrator

Purpose: Coordinates all wallet operations and manages global state.

Key Responsibilities:

  • Initializes and manages the coco wallet manager instance
  • Coordinates between mint management, token operations, and lightning operations
  • Manages modal/drawer state (send, receive, history, QR scanner)
  • Handles QR scan results and routes to appropriate handlers
  • Integrates with npub.cash API for Lightning addresses
  • Exposes wallet header props to parent WalletContainer

Key Patterns:

// Core hooks initialized first
const { coco, balances, mints, ... } = useCashu();
const { ... } = useNpubCash();

// Domain hooks use core hooks
const { activeMintUrl, ... } = useMintManager({ coco, mints, ... });
const { sendAmount, ... } = useTokenOperations({ coco, activeMintUrl, ... });

// Combined handlers route to appropriate domain
const handleSend = async () => {
  if (sendAmount && activeMintUrl) {
    return tokenOps.handleTokenSend();
  }
  if (pendingLightningAddress) {
    return lightningOps.handleLightningAddressPayment();
  }
  // ...
};

State Management:

  • Uses refs to track initialization state (hasFetchedUserInfoRef, hasSetMintFromUserInfoRef)
  • Persists active mint URL to localStorage
  • Manages drawer open/close state with cleanup

WalletHeader.tsx - Balance and Controls

Purpose: Displays wallet balance, mode switching, and mint/address selectors.

Key Features:

  • Toggle between sats and USD display
  • Mode switching button (tokens → lightning → bitcoin → tokens)
  • Mint selector dropdown (when mode is tokens/lightning)
  • Lightning address display (when mode is lightning)
  • Bitcoin address display (when mode is bitcoin)
  • Seed phrase display (when mode is tokens)

Key Patterns:

  • Uses exchangeRateService for BTC/USD conversion
  • Conditional rendering based on mode prop
  • Copy-to-clipboard functionality with visual feedback
  • QR code generation for addresses

PaymentCard.tsx - Send/Receive Interface

Purpose: Unified interface for all send/receive operations.

Modes Supported:

  • Send: Token send, Lightning invoice payment, Lightning address payment, Bitcoin send, reverse swap
  • Receive: Token receive, Lightning invoice creation, Bitcoin address display

Key Patterns:

  • Single component handles multiple operation types
  • Uses operation prop ('send' | 'receive') to determine UI
  • Uses mode prop ('tokens' | 'lightning' | 'bitcoin') for context
  • Progressive disclosure: shows pending state (e.g., "Sending to: address") before amount input
  • Input validation with error messages

State Flow:

// Send flow
1. User enters invoice/address → detectAndHandleLightningInput()
2. Sets pending state (pendingInvoice, pendingLightningAddress)
3. Shows confirmation UI with amount
4. User confirms → handleConfirmInvoicePayment() or handleLightningAddressPayment()

// Receive flow
1. User enters amount → handleLightningReceive()
2. Creates mint quote → shows invoice modal
3. Waits for payment via mint-quote:redeemed event

MintSelector.tsx - Mint Dropdown

Purpose: Select and manage Cashu mints.

Features:

  • Dropdown showing all trusted mints with balances
  • Add new mint input
  • Remove mint button (with confirmation modal)
  • Active mint indicator
  • Denomination breakdown button

Key Patterns:

  • Uses DropdownMenu from shadcn/ui
  • Filters mints to only show trusted mints
  • Format balance with sats/USD toggle
  • Inline input for adding mints

Modal Components

QRScanner.tsx

  • Camera-based QR code scanning
  • Paste from clipboard support
  • Classifies QR codes (invoice, address, token, etc.)
  • Uses html5-qrcode library

ProofBreakdownModal.tsx

  • Shows token denomination breakdown for a mint
  • Displays total balance and count of each denomination
  • Useful for debugging payment issues

RemoveMintModal.tsx

  • Confirmation dialog for removing mints
  • Warns about data loss
  • Shows mint name/URL

SeedPhraseModal.tsx

  • Input for restoring tokens from seed phrase
  • Validates mnemonic format
  • Shows active mint context

TransactionHistory.tsx

  • Displays transaction history from coco
  • Filters out unpaid quotes (only shows completed)
  • Supports both Cashu and Bitcoin transactions
  • Shows transaction type, amount, timestamp, mint info

Hook Patterns

Core Hooks

useCashu.ts - Wallet Manager

Purpose: Manages the coco wallet manager instance and core wallet state.

Key Features:

  • Singleton pattern to prevent multiple initializations
  • Mnemonic generation and validation
  • Balance and mint state management
  • Event listeners for automatic balance updates
  • Repository access for direct proof operations

Usage Pattern:

const { 
  coco,           // Manager instance (null until initialized)
  repositories,   // Direct repository access
  balances,       // Reactive balance state
  mints,          // Reactive mint list
  isInitialized,  // Initialization status
  isLoading,      // Loading state
  error,          // Error state
  mnemonic,       // Current mnemonic
  refreshMints    // Refresh mint list
} = useCashu();

Important Notes:

  • coco is null until wallet is initialized
  • Always check isInitialized before using coco
  • Balance updates automatically via event listeners
  • Repositories provide direct access to proofs, mints, history

useNpubCash.ts - npub.cash Integration

Purpose: Integrates with npub.cash API for Lightning addresses and quote sync.

Key Features:

  • NIP-98 authentication with Nostr signer
  • User info fetching (mint URL, Lightning address)
  • Quote synchronization with wallet
  • Real-time quote updates via WebSocket
  • Automatic mint addition for quotes

Usage Pattern:

const {
  setMint,              // Set mint URL in npub.cash
  getUserInfo,          // Get user info (mint URL, name)
  syncQuotesWithWallet, // Subscribe to quote updates
  isLoggedIn,           // Login status
  isLoading,            // Loading state
  error                 // Error state
} = useNpubCash();

Quote Sync Flow:

  1. On login, syncQuotesWithWallet() is called
  2. Fetches all quotes from npub.cash
  3. Adds mints if needed (auto-trusts)
  4. Adds quotes to wallet via coco.quotes.addMintQuote()
  5. Subscribes to real-time updates
  6. On quote update, fetches newer quotes and syncs

useLightningAddress.ts - LNURL Resolution

Purpose: Resolves Lightning addresses to invoices using LNURL-pay protocol.

Key Features:

  • Two-step LNURL-pay resolution
  • Amount validation (min/max)
  • Comment support
  • Error handling with descriptive messages

Usage Pattern:

const { getInvoice, isLoading, error } = useLightningAddress();

const invoice = await getInvoice({
  lightningAddress: '[email protected]',
  amountSats: 1000,
  comment: 'Optional comment'
});

Resolution Flow:

  1. Parse Lightning address → https://domain/.well-known/lnurlp/username
  2. Fetch LNURL-pay info (min/max, callback URL)
  3. Validate amount against bounds
  4. Request invoice from callback URL with amount
  5. Return BOLT11 invoice

Domain Hooks

useMintManager.ts - Mint Operations

Purpose: Manages mint selection, adding, removing, and denomination display.

Key Features:

  • Active mint selection with npub.cash sync
  • Mint addition with auto-trust
  • Mint removal with confirmation
  • Denomination breakdown calculation
  • Mint URL normalization

Key Functions:

  • handleSetActiveMint() - Set active mint, optionally sync to npub.cash
  • handleAddMint() - Add new mint with validation
  • handleRemoveMintClick() - Show removal confirmation
  • handleConfirmRemoveMint() - Remove mint and switch active mint
  • handleShowDenominations() - Calculate and show token breakdown

Important Patterns:

// Always check if mint exists before adding
const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());

if (isKnown) {
  // Ensure trusted
  const isTrusted = await coco.mint.isTrustedMint(mintUrl);
  if (!isTrusted) {
    await coco.mint.trustMint(mintUrl);
  }
} else {
  // Add with trusted flag
  await coco.mint.addMint(mintUrl, { trusted: true });
}

useTokenOperations.ts - Cashu Token Operations

Purpose: Handles sending and receiving Cashu tokens.

Key Features:

  • Token send with amount validation
  • Token receive with unknown mint handling
  • QR code generation for sent tokens
  • Automatic mint addition for unknown mints

Key Functions:

  • handleTokenSend() - Send tokens, generate QR code
  • handleTokenReceive() - Receive tokens, handle unknown mints
  • handleUnknownMintError() - Add unknown mint and retry

Error Handling:

  • Detects UnknownMintError from coco
  • Extracts mint URL from error message
  • Automatically adds and trusts the mint
  • Retries the receive operation

useLightningOperations.ts - Lightning Operations

Purpose: Handles Lightning invoice creation, payment, and address resolution.

Key Features:

  • Lightning invoice creation (mint quotes)
  • Invoice payment (melt quotes)
  • Lightning address payment flow
  • Invoice amount decoding
  • Real-time payment tracking

Key Functions:

  • handleLightningReceive() - Create mint quote, show invoice modal
  • detectAndHandleLightningInput() - Classify input (invoice vs address)
  • handleLightningAddressPayment() - Resolve address, create invoice, pay
  • handleConfirmInvoicePayment() - Pay pending invoice

Payment Flow:

// Receive flow
1. User enters amount → handleLightningReceive()
2. coco.quotes.createMintQuote(mintUrl, amount)
3. Generate QR code for invoice
4. Show invoice modal
5. Listen for 'mint-quote:redeemed' event
6. On payment, close modal and show success

// Send flow (invoice)
1. User enters invoice → detectAndHandleLightningInput()
2. Decode amount from invoice
3. Set pendingInvoice state
4. User confirms → handleConfirmInvoicePayment()
5. coco.quotes.createMeltQuote() + payMeltQuote()

// Send flow (address)
1. User enters address → detectAndHandleLightningInput()
2. Set pendingLightningAddress state
3. User enters amount → handleLightningAddressPayment()
4. Resolve address to invoice → createMeltQuote() + payMeltQuote()

useHistoryManager.ts - Transaction History

Purpose: Manages transaction history loading and filtering.

Key Features:

  • Paginated history loading
  • Filters out unpaid quotes (only completed transactions)
  • Auto-refresh on wallet events
  • Event listeners for history updates

Filtering Logic:

  • Mint quotes: only show state === 'ISSUED' (completed)
  • Melt quotes: only show state === 'PAID' (completed)
  • Send/Receive: show all (no state field)

Event Listeners:

  • history:updated - General history updates
  • melt-quote:created - Melt quote created (coco bug workaround)
  • melt-quote:paid - Melt quote paid
  • mint-quote:redeemed - Mint quote redeemed (invoice paid)

useQRCode.ts - QR Code Operations

Purpose: Generates QR codes and scans QR codes with camera.

Key Features:

  • QR code generation with qrcode library
  • Camera-based scanning with html5-qrcode
  • QR code classification (invoice, address, token, npub, Bitcoin address)
  • Paste from clipboard support
  • Error handling for camera permissions

Classification Logic:

// Lightning invoice: lnbc... or lightning:lnbc...
// Lightning address: [email protected] or lightning:[email protected]
// Cashu token: cashu...
// Bitcoin address: bc1..., 1..., 3...
// Nostr npub: npub1... or nostr:npub1...

Wallet Modes

The wallet supports three modes, each with different UI and operations:

Mode: 'tokens' (Cashu)

Purpose: Direct Cashu token operations.

Features:

  • Mint selector for choosing active mint
  • Send tokens (generates Cashu token)
  • Receive tokens (redeems Cashu token)
  • Seed phrase display
  • Token denomination breakdown

Operations:

  • Send: coco.wallet.send(mintUrl, amount) → generates token
  • Receive: coco.wallet.receive(token) → redeems token

Mode: 'lightning'

Purpose: Lightning Network operations via Cashu mints.

Features:

  • Lightning address display (from npub.cash)
  • Send: Pay Lightning invoices or addresses
  • Receive: Create Lightning invoices (mint quotes)
  • Mint selector for choosing active mint
  • Reverse swap support (on-chain to Lightning)

Operations:

  • Send: createMeltQuote() + payMeltQuote() to pay invoice
  • Receive: createMintQuote() → generates Lightning invoice → wait for payment

Mode: 'bitcoin'

Purpose: On-chain Bitcoin operations.

Features:

  • Bitcoin address display (derived from Nostr pubkey)
  • UTXO selector for managing UTXOs
  • Send Bitcoin on-chain
  • Receive Bitcoin on-chain
  • Consolidation support

Note: Bitcoin mode is handled by BitcoinWallet component (not shown in attached files reference BITCOIN_WALLET.md for more information).

Mint Management

Mint Lifecycle

  1. Add Mint: User enters URL → coco.mint.addMint(url, { trusted: true })
  2. Trust Mint: Automatically trusted when added (or via coco.mint.trustMint())
  3. Select Mint: Set as active mint → setActiveMintUrl(url)
  4. Remove Mint: Delete from repository → repositories.mintRepository.deleteMint(url)

Mint States

  • Known: Mint exists in repository (from getAllMints())
  • Trusted: Mint is trusted (from isTrustedMint())
  • Active: Currently selected mint (stored in state and localStorage)

Mint Synchronization

  • When user logs into npub.cash, mint URL is fetched and set as active
  • When user manually selects a mint, it's synced to npub.cash (if logged in)
  • Active mint URL is persisted to localStorage

Transaction Operations

Send Operations

Token Send

const token = await coco.wallet.send(activeMintUrl, amount);
const encodedToken = getEncodedToken(token);
// Show QR code modal with token

Lightning Invoice Payment

const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, invoice);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);

Lightning Address Payment

// 1. Resolve address to invoice
const invoice = await getLightningInvoice({ lightningAddress, amountSats });
// 2. Pay invoice
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, invoice);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);

Receive Operations

Token Receive

await coco.wallet.receive(token);
// Automatically handles unknown mints

Lightning Invoice Creation

const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
// quote.request is the Lightning invoice
// Show QR code modal
// Listen for 'mint-quote:redeemed' event

Integration Points

npub.cash Integration

Purpose: Provides Lightning addresses and quote synchronization.

Flow:

  1. User logs in with Nostr → useNIP98 provides signer
  2. useNpubCash creates NPCClient with JWT auth
  3. On login, fetch user info → get mint URL and Lightning address
  4. Set mint URL as active mint (if not already set)
  5. Subscribe to quote updates → sync quotes to wallet

Key Files:

  • useNpubCash.ts - API client and sync logic
  • useNIP98.ts - NIP-98 authentication (not shown, but referenced)

QR Code Integration

Flow:

  1. User clicks scan button → opens QRScanner modal
  2. Camera starts → html5-qrcode scans
  3. QR code detected → classifyQRCode() classifies type
  4. Result routed to appropriate handler:
    • lightning_invoice → handleQRResult() → sets invoice
    • lightning_address → handleQRResult() → sets address
    • cashu_token → handleQRResult() → sets token input
    • bitcoin_address → handled by BitcoinWallet
    • npub → handled by BitcoinWallet

Exchange Rate Service

Purpose: Provides BTC/USD conversion for balance display.

Usage:

import { exchangeRateService } from '@/lib/exchangeRateService';

const rate = await exchangeRateService.getBtcUsdRate();
const usdAmount = await exchangeRateService.satsToUsd(sats);

Features:

  • 1-minute cache to avoid excessive API calls
  • Fallback to stale cache on error
  • Coinbase API integration

Extension Guidelines

Error Handling Patterns

Toast Notifications:

try {
  await operation();
  toast({
    title: 'Success',
    description: 'Operation completed successfully',
  });
} catch (err) {
  toast({
    variant: 'destructive',
    title: 'Error',
    description: err instanceof Error ? err.message : 'Unknown error',
  });
}

Unknown Mint Handling:

try {
  await coco.wallet.receive(token);
} catch (err) {
  if (isUnknownMintError(err)) {
    const mintUrl = extractMintUrlFromError(err);
    if (mintUrl) {
      await coco.mint.addMint(mintUrl, { trusted: true });
      await coco.wallet.receive(token); // Retry
    }
  }
}

Best Practices

State Management

  1. Use refs for initialization tracking: Prevents duplicate requests

    const hasFetchedRef = useRef(false);
    if (hasFetchedRef.current) return;
    hasFetchedRef.current = true;
    
  2. Persist important state: Use useLocalStorage for user preferences

    const [storedValue, setStoredValue] = useLocalStorage('key', defaultValue);
    
  3. Clean up state on unmount: Reset state when drawers/modals close

    const handleClose = (open: boolean) => {
      setModalOpen(open);
      if (!open) {
        // Reset all related state
        setInput('');
        setPending(null);
      }
    };
    

Event Listeners

  1. Always unsubscribe: Clean up event listeners in useEffect return

    useEffect(() => {
      const unsubscribe = coco.on('event', handler);
      return () => unsubscribe();
    }, [coco]);
    
  2. Store unsubscribe functions: Use refs for complex cleanup

    const unsubscribeRef = useRef<(() => void) | null>(null);
    
    useEffect(() => {
      unsubscribeRef.current = coco.on('event', handler);
      return () => {
        if (unsubscribeRef.current) {
          unsubscribeRef.current();
        }
      };
    }, [coco]);
    

Type Safety

  1. Use types from coco-cashu-core: Import types from the library

    import type { Manager, HistoryEntry, Mint } from 'coco-cashu-core';
    
  2. Validate inputs: Check types and values before operations

    const amount = parseInt(input);
    if (isNaN(amount) || amount <= 0) {
      toast({ variant: 'destructive', title: 'Invalid amount' });
      return;
    }
    

Common Patterns Reference

Mint Check Pattern

const allMints = await coco.mint.getAllMints();
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());

if (isKnown) {
  const isTrusted = await coco.mint.isTrustedMint(mintUrl);
  if (!isTrusted) {
    await coco.mint.trustMint(mintUrl);
  }
} else {
  await coco.mint.addMint(mintUrl, { trusted: true });
}

Quote Sync Pattern

// Group quotes by mint
const quotesByMint = quotes.reduce((acc, quote) => {
  if (!acc[quote.mintUrl]) {
    acc[quote.mintUrl] = [];
  }
  acc[quote.mintUrl].push(quote);
  return acc;
}, {} as Record<string, typeof quotes>);

// Process each mint
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
  // Ensure mint exists and is trusted
  // Add quotes
  coco.quotes.addMintQuote(mintUrl, mintQuotes.map(q => ({
    ...q,
    expiry: q.expiresAt,
    quote: q.quoteId,
    state: "PAID",
    unit: "sat",
  })));
}

File Organization

src/
├── components/
│   └── wallet/
│       ├── CashuWallet.tsx          # Main orchestrator
│       ├── WalletHeader.tsx          # Balance and controls
│       ├── PaymentCard.tsx           # Send/receive UI
│       ├── MintSelector.tsx          # Mint dropdown
│       ├── TransactionHistory.tsx    # History display
│       ├── ProofBreakdownModal.tsx   # Token breakdown
│       ├── RemoveMintModal.tsx       # Mint removal confirmation
│       ├── SeedPhraseModal.tsx       # Seed phrase restore
│       └── QRScanner.tsx              # QR code scanner
├── hooks/
│   └── wallet/
│       ├── useCashu.ts               # Core wallet manager
│       ├── useMintManager.ts         # Mint operations
│       ├── useTokenOperations.ts     # Token send/receive
│       ├── useLightningOperations.ts # Lightning operations
│       ├── useLightningAddress.ts    # LNURL resolution
│       ├── useNpubCash.ts            # npub.cash API
│       ├── useQRCode.ts              # QR code operations
│       ├── useHistoryManager.ts      # Transaction history
│       └── useSeedPhraseRestore.ts   # Seed phrase restore
└── lib/
    ├── bolt11Decoder.ts             # Lightning invoice decoding
    └── exchangeRateService.ts       # BTC/USD exchange rates

Additional Resources

  • coco-cashu-core: Main Cashu library documentation
  • npubcash-sdk: npub.cash API SDK documentation
  • LNURL-pay: Lightning address protocol specification
  • BOLT11: Lightning invoice format specification