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
- Architecture Overview
- Component Structure
- Hook Patterns
- Wallet Modes
- Mint Management
- Transaction Operations
- Integration Points
- Extension Guidelines
- 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
- Separation of Concerns: UI components are separated from business logic hooks
- Single Responsibility: Each hook handles one specific domain (mints, tokens, lightning)
- State Management: React state for UI reactivity, coco instance for wallet operations
- Error Handling: Centralized error handling with toast notifications
- 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
cocowallet 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
exchangeRateServicefor BTC/USD conversion - Conditional rendering based on
modeprop - 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
operationprop ('send' | 'receive') to determine UI - Uses
modeprop ('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
DropdownMenufrom 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-qrcodelibrary
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:
cocoisnulluntil wallet is initialized- Always check
isInitializedbefore usingcoco - 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:
- On login,
syncQuotesWithWallet()is called - Fetches all quotes from npub.cash
- Adds mints if needed (auto-trusts)
- Adds quotes to wallet via
coco.quotes.addMintQuote() - Subscribes to real-time updates
- 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:
- Parse Lightning address →
https://domain/.well-known/lnurlp/username - Fetch LNURL-pay info (min/max, callback URL)
- Validate amount against bounds
- Request invoice from callback URL with amount
- 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.cashhandleAddMint()- Add new mint with validationhandleRemoveMintClick()- Show removal confirmationhandleConfirmRemoveMint()- Remove mint and switch active minthandleShowDenominations()- 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 codehandleTokenReceive()- Receive tokens, handle unknown mintshandleUnknownMintError()- Add unknown mint and retry
Error Handling:
- Detects
UnknownMintErrorfrom 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 modaldetectAndHandleLightningInput()- Classify input (invoice vs address)handleLightningAddressPayment()- Resolve address, create invoice, payhandleConfirmInvoicePayment()- 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 updatesmelt-quote:created- Melt quote created (coco bug workaround)melt-quote:paid- Melt quote paidmint-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
qrcodelibrary - 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
- Add Mint: User enters URL →
coco.mint.addMint(url, { trusted: true }) - Trust Mint: Automatically trusted when added (or via
coco.mint.trustMint()) - Select Mint: Set as active mint →
setActiveMintUrl(url) - 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:
- User logs in with Nostr →
useNIP98provides signer useNpubCashcreatesNPCClientwith JWT auth- On login, fetch user info → get mint URL and Lightning address
- Set mint URL as active mint (if not already set)
- Subscribe to quote updates → sync quotes to wallet
Key Files:
useNpubCash.ts- API client and sync logicuseNIP98.ts- NIP-98 authentication (not shown, but referenced)
QR Code Integration
Flow:
- User clicks scan button → opens
QRScannermodal - Camera starts →
html5-qrcodescans - QR code detected →
classifyQRCode()classifies type - Result routed to appropriate handler:
lightning_invoice→handleQRResult()→ sets invoicelightning_address→handleQRResult()→ sets addresscashu_token→handleQRResult()→ sets token inputbitcoin_address→ handled by BitcoinWalletnpub→ 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
-
Use refs for initialization tracking: Prevents duplicate requests
const hasFetchedRef = useRef(false); if (hasFetchedRef.current) return; hasFetchedRef.current = true; -
Persist important state: Use
useLocalStoragefor user preferencesconst [storedValue, setStoredValue] = useLocalStorage('key', defaultValue); -
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
-
Always unsubscribe: Clean up event listeners in useEffect return
useEffect(() => { const unsubscribe = coco.on('event', handler); return () => unsubscribe(); }, [coco]); -
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
-
Use types from coco-cashu-core: Import types from the library
import type { Manager, HistoryEntry, Mint } from 'coco-cashu-core'; -
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