Files
mkstack/docs/WALLET_INTEGRATION.md
T

649 lines
19 KiB
Markdown

# Unified Wallet System for AI Agents (NutStack)
This document explains how AI agents can easily integrate intelligent Lightning zaps and comprehensive wallet functionality into Nostr clients using the unified NutStack wallet system.
## Overview
NutStack includes a comprehensive three-mode wallet system that supports multiple payment methods:
- **Tokens Mode**: Cashu token operations with mint management
- **Lightning Mode**: Lightning invoice payments, Lightning address support, and zaps
- **Bitcoin Mode**: On-chain Bitcoin transactions using Taproot addresses
The `CashuWallet` component provides a complete standalone wallet interface with seamless mode switching, while the `ZapButton` component offers intelligent Lightning zaps with Cashu integration for content feeds.
## File Hierarchy
Understanding the wallet system requires familiarity with these key directories and files:
### Core Components
- **`src/components/wallet/CashuWallet.tsx`** - Main three-mode wallet interface (Tokens/Lightning/Bitcoin)
- **`src/components/ZapButton.tsx`** - Intelligent zap button for content feeds
### Context & State Management
- **`src/contexts/CashuContext.tsx`** - Required context provider for Cashu wallet state
- **`src/hooks/useNpubCash.ts`** - Main hook for npub.cash integration and wallet operations
### Cashu-Specific Hooks
- **`src/hooks/cashu/useCashu.ts`** - Core Cashu wallet functionality and balance management
- **`src/hooks/cashu/useMintManager.ts`** - Mint URL management and switching
- **`src/hooks/cashu/useWalletTransactions.ts`** - Transaction history and tracking
### Lightning Integration
- **`src/hooks/useLightningAddress.ts`** - Lightning address resolution and invoice handling
- **`src/lib/bolt11Decoder.ts`** - Lightning invoice parsing and validation
### Bitcoin Integration
- **`src/lib/bitcoin.ts`** - Bitcoin address derivation, UTXO management, transaction building
- **`src/hooks/useBitcoinBalance.ts`** - Bitcoin balance fetching and UTXO management
- **`src/hooks/useNsecAccess.ts`** - Private key access for Bitcoin transaction signing
### Utility Functions
- **`src/lib/nostr.ts`** - Nostr key utilities and address derivation
- **`src/lib/lightning.ts`** - Lightning payment processing and WebLN integration
### Key Integration Points
- **`src/hooks/useZaps.ts`** - Zap data fetching and management
- **`src/components/TransactionHistory.tsx`** - Unified transaction history display
- **`src/components/MintSelector.tsx`** - Cashu mint management interface
### Three-Mode Architecture
**Tokens Mode**:
- Cashu token send/receive operations
- Multiple mint management
- Token encoding/decoding
- Transaction history tracking
**Lightning Mode**:
- Lightning invoice payment processing
- Lightning address support
- NIP-57 compliant zaps
- WebLN/NWC integration
**Bitcoin Mode**:
- On-chain Bitcoin transactions using Taproot addresses
- UTXO management via Blockstream API
- Fee estimation and transaction building
- Requires nsec login for transaction signing
## Key Features
- **Three-Mode Wallet**: Complete wallet system supporting Cashu tokens, Lightning, and Bitcoin
- **Mode Switching**: Seamless switching between payment methods via UI toggle
- **Unified Interface**: Single `CashuWallet` component handles all payment types
- **Intelligent Zap Integration**: `ZapButton` automatically prioritizes Cashu balances for zaps
- **Nostr Integration**: Bitcoin addresses derived from Nostr public keys using Taproot (P2TR)
- **Mobile Optimized**: Responsive design with drawer/modal patterns
- **Transaction History**: Unified history tracking across all payment methods
- **NIP-57 Compliant**: Full compliance with Lightning zap standards
- **Zero Configuration**: Works out of the box with existing Nostr infrastructure
## Basic Usage
### Simple Integration
```tsx
import { ZapButton } from '@/components/ZapButton';
import type { Event } from 'nostr-tools';
function PostCard({ event }: { event: Event }) {
return (
<div className="post-card">
<p>{event.content}</p>
<ZapButton target={event} showCount={true} />
</div>
);
}
```
### With Custom Styling
```tsx
<ZapButton
target={event}
className="text-sm hover:text-yellow-500 transition-colors"
showCount={true}
/>
```
## Component Props
```tsx
interface ZapButtonProps {
target: Event; // Required: The Nostr event to zap
className?: string; // Optional: CSS classes for styling
showCount?: boolean; // Optional: Show zap count (default: true)
zapData?: { // Optional: External zap data to avoid refetching
count: number;
totalSats: number;
isLoading?: boolean;
};
}
```
## How It Works
### Automatic Wallet Detection
The `ZapButton` automatically detects if the user has:
1. A Cashu wallet with available balance
2. Traditional Lightning wallet (WebLN/NWC)
### Payment Flow
The unified `ZapButton` uses an intelligent payment selection system:
1. **Cashu Available & Sufficient**: Uses Cashu tokens → Lightning invoice conversion
2. **Cashu Insufficient/Unavailable**: Falls back to WebLN payment
3. **WebLN Unavailable**: Falls back to NWC payment
4. **NWC Unavailable**: Shows manual Lightning invoice with QR code
### Cashu Integration Details
When Cashu wallet is available and has sufficient balance:
- Creates a NIP-57 compliant zap request
- Gets Lightning invoice from recipient's zap endpoint
- Uses `createMeltQuote()` to convert Cashu tokens to Lightning payment
- Uses `payMeltQuote()` to execute the payment
- Burns Cashu tokens and sends Lightning payment
## Required Dependencies
**CRITICAL**: The `useCashu` hook MUST be wrapped in a Context Provider to avoid infinite loops!
### Bitcoin Dependencies
Add these packages for Bitcoin functionality:
```bash
npm install bitcoinjs-lib @bitcoinerlab/secp256k1 ecpair
```
### Cashu Dependencies
Add these packages for Cashu token functionality:
```bash
npm install coco-cashu-core coco-cashu-indexeddb @scure/bip39
```
### Npub.cash Dependencies
Add these packages for npub.cash integration:
```bash
npm install npubcash-sdk npubcash-types
```
### Setup CashuContext (Required!)
Create `src/contexts/CashuContext.tsx`:
```tsx
import { createContext, useContext, ReactNode } from 'react';
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/useCashu';
const CashuContext = createContext<UseCashuReturn | null>(null);
export function CashuProvider({ children }: { children: ReactNode }) {
const cashu = useCashuHook();
return (
<CashuContext.Provider value={cashu}>
{children}
</CashuContext.Provider>
);
}
export function useCashu(): UseCashuReturn {
const context = useContext(CashuContext);
if (!context) {
throw new Error('useCashu must be used within a CashuProvider');
}
return context;
}
```
### Wrap Your App
Add `CashuProvider` to your App.tsx:
```tsx
import { CashuProvider } from '@/contexts/CashuContext';
export function App() {
return (
<SomeProvider>
<CashuProvider>
{/* Your app */}
</CashuProvider>
</SomeProvider>
);
}
```
### Import from Context
**Always** import from the context, not the hook:
```tsx
// ✅ CORRECT
import { useCashu } from '@/contexts/CashuContext';
// ❌ WRONG - Will cause infinite loops!
import { useCashu } from '@/hooks/useCashu';
```
This ensures all components share the same Cashu wallet instance, preventing:
- Multiple wallet initializations
- Infinite refresh loops
- Performance issues
## Architecture Overview
**IMPORTANT**: The Cashu integration uses a **two-component architecture**:
1. **`CashuWallet`** - Standalone wallet management interface (separate page/route)
2. **`ZapButton`** - Integrated zap functionality within content feeds
### Component Separation
The `CashuWallet` component is designed as a **standalone wallet management interface** and should remain separate from content feeds. This separation provides:
- **Clean UX**: Users manage their wallet separately from consuming content
- **Performance**: Wallet operations don't interfere with feed rendering
- **Security**: Sensitive wallet operations are isolated
- **Mobile Optimization**: Wallet can use full-screen layouts on mobile
### Integration Pattern
```tsx
// ✅ CORRECT: Separate wallet management
function App() {
return (
<Router>
<Routes>
<Route path="/wallet" element={<CashuWallet />} />
<Route path="/" element={<FeedPage />} />
</Routes>
</Router>
);
}
// ✅ CORRECT: ZapButton integrated in content
function FeedPage() {
return (
<div className="posts">
{events.map(event => (
<div key={event.id} className="post">
<p>{event.content}</p>
<ZapButton target={event} showCount={true} />
</div>
))}
</div>
);
}
// ❌ INCORRECT: Don't embed CashuWallet in content feeds
function FeedPage() {
return (
<div className="posts">
<CashuWallet /> {/* Don't do this */}
{events.map(event => (
<div key={event.id} className="post">
<p>{event.content}</p>
<ZapButton target={event} showCount={true} />
</div>
))}
</div>
);
}
```
## Complete Example
```tsx
import { ZapButton } from '@/components/ZapButton';
import { CashuWallet } from '@/components/CashuWallet';
import type { Event } from 'nostr-tools';
function NostrApp() {
return (
<div className="app">
{/* Cashu wallet for balance management */}
<CashuWallet />
{/* Posts with zap buttons */}
<div className="posts">
{events.map(event => (
<div key={event.id} className="post">
<p>{event.content}</p>
<ZapButton target={event} showCount={true} />
</div>
))}
</div>
</div>
);
}
```
## Advanced Usage
### Custom Zap Data
If you're already fetching zap data elsewhere, pass it to avoid duplicate requests:
```tsx
const zapData = useZaps(event);
<ZapButton
target={event}
zapData={zapData}
showCount={true}
/>
```
### Conditional Rendering
The component automatically handles visibility based on:
- User login status
- Author Lightning address availability
- Cashu wallet availability
```tsx
// Only shows if user can zap
<ZapButton target={event} />
```
## CashuWallet Component
The `CashuWallet` component provides a complete standalone wallet interface supporting all three payment modes:
### Basic Implementation
```tsx
import { CashuWallet } from '@/components/wallet/CashuWallet';
function App() {
return (
<Router>
<Routes>
<Route path="/wallet" element={<CashuWallet />} />
<Route path="/" element={<FeedPage />} />
</Routes>
</Router>
);
}
```
### Three-Mode System
The wallet automatically handles mode switching between:
```tsx
// Mode state management
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
// Mode-specific operations
if (mode === 'bitcoin') {
// Bitcoin transaction handling
} else if (mode === 'tokens') {
// Cashu token operations
} else {
// Lightning operations
}
```
### Component Architecture
- **WalletHeader**: Balance display, mode toggle, mint selector
- **TransactionCard**: Send/receive forms for each mode
- **TransactionHistory**: Unified transaction history
- **MintSelector**: Cashu mint management
### Props and State
The component manages comprehensive state for all three modes:
```tsx
// Bitcoin state
const [bitcoinAmount, setBitcoinAmount] = useState('');
const [bitcoinRecipient, setBitcoinRecipient] = useState('');
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
// Cashu state
const { balances, mints, coco } = useCashu();
const { activeMintUrl, setActiveMintUrl } = useMintManager();
// Lightning state
const { getInvoice: getLightningInvoice } = useLightningAddress();
```
## Error Handling
The component handles common error scenarios:
- Insufficient Cashu balance
- Lightning address not found
- Zap endpoint unavailable
- Payment failures
## Bitcoin Mode
NutStack supports on-chain Bitcoin transactions using Taproot addresses derived from Nostr keys:
### Nsec Requirement
Bitcoin transactions require nsec login to access the private key for transaction signing:
```tsx
import { useNsecAccess } from '@/hooks/useNsecAccess';
function BitcoinTransaction() {
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
if (!hasNsecAccess) {
return <div>Please login with nsec to use Bitcoin features</div>;
}
const privateKey = getPrivateKey();
// Use private key for transaction signing
}
```
### Address Derivation
Bitcoin addresses are automatically derived from Nostr public keys:
```tsx
import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress } from '@/lib/bitcoin';
// From hex pubkey
const bitcoinAddress = nostrPubkeyToBitcoinAddress(user.pubkey);
// From npub format
const bitcoinAddress = npubToBitcoinAddress('npub1...');
```
### Send/Receive Flow
```tsx
import { useBitcoinBalance } from '@/hooks/useBitcoinBalance';
import { fetchUTXOs, createBitcoinTransaction, broadcastTransaction } from '@/lib/bitcoin';
function BitcoinSend() {
const { data: bitcoinBalance, refetch } = useBitcoinBalance(bitcoinAddress);
const handleSend = async (amount: number, recipient: string) => {
// Fetch UTXOs and fee rates
const [utxos, feeRates] = await Promise.all([
fetchUTXOs(bitcoinAddress),
getFeeRates()
]);
// Create and sign transaction
const { txHex, fee } = await createBitcoinTransaction(
privateKey,
recipient,
amount,
utxos,
feeRates.fastestFee
);
// Broadcast transaction
const txId = await broadcastTransaction(txHex);
// Refresh balance
refetch();
};
}
```
### UTXO Management
The system automatically handles UTXO selection and fee calculation:
- **UTXO Fetching**: Uses Blockstream API to get unspent outputs
- **Fee Estimation**: Dynamic fee calculation based on network conditions
- **Change Handling**: Automatic change output creation when needed
- **Dust Limit**: Respects Bitcoin dust limit (546 sats)
### Blockstream API Integration
```tsx
// Fetch UTXOs
const utxos = await fetchUTXOs(address);
// Get fee rates
const feeRates = await getFeeRates();
// Returns: { fastestFee, halfHourFee, hourFee, economyFee, minimumFee }
// Broadcast transaction
const txId = await broadcastTransaction(txHex);
```
## Mobile Optimization
The component automatically uses:
- **Desktop**: Modal dialog
- **Mobile**: Bottom drawer
No additional configuration needed.
## Testing
The component includes test IDs for easy testing:
```tsx
// Unified zap modal
data-testid="zap-modal"
```
## Best Practices for AI Agents
1. **Maintain Component Separation**: Keep `CashuWallet` as a standalone page/route, not embedded in content feeds
2. **Always include CashuWallet**: Provide a dedicated route/page for wallet management
3. **Use consistent styling**: Apply your app's design system
4. **Handle loading states**: The component manages its own loading states
5. **Trust the intelligence**: The component handles payment method selection automatically
6. **Test all scenarios**: Ensure Cashu, WebLN, NWC, and manual zaps all work
7. **Follow the architecture**: Use `ZapButton` for content integration, `CashuWallet` for wallet management
8. **Avoid Infinite Loops**: The `useCashu` hook includes throttling and deep comparison to prevent infinite refresh loops. Do NOT:
- Call `refreshBalances()` in `useEffect` that depends on `balances`
- Create circular dependencies between state updates and effects
- Override the built-in throttling mechanisms
## Troubleshooting
### ZapButton Not Showing
- Check if user is logged in
- Verify author has Lightning address (lud06/lud16)
- Ensure Cashu wallet is initialized
### Cashu Zaps Not Working
- Verify Cashu wallet has sufficient balance
- Check mint connectivity
- Ensure Lightning invoice is valid
### Payment Method Fallbacks Not Working
- Verify WebLN/NWC connection
- Check Lightning wallet availability
- Ensure zap endpoint is accessible
- Test manual QR code fallback
### Infinite Loop: `refreshBalances` Repeatedly Called
If you see continuous console logs like `🔄 refreshBalances: Getting balances from wallet...`, the issue is likely:
**Root Cause #1 (MOST COMMON)**: Multiple components are calling `useCashu()` directly from the hook instead of from the Context Provider. This creates multiple wallet instances that all try to initialize and refresh balances.
**Solution**: Ensure you:
1. Created `CashuContext.tsx` as shown in the Required Dependencies section
2. Wrapped your app with `<CashuProvider>`
3. Import `useCashu` from `@/contexts/CashuContext` in ALL components (not from `@/hooks/useCashu`)
**Root Cause #2**: A `useEffect` that depends on `balances` is triggering `refreshBalances()`, creating a circular dependency.
**Built-in Protections**: The `useCashu` hook includes:
- **Throttling**: Prevents calls more than once every 500ms
- **Deep Comparison**: Only updates state if balance values actually changed
- **Stable References**: Returns the same object reference when values are unchanged
**Common Mistakes to Avoid**:
```tsx
// ❌ INCORRECT: Creates infinite loop
useEffect(() => {
refreshBalances();
}, [balances, refreshBalances]);
// ❌ INCORRECT: Calls refreshBalances on every balance change
useEffect(() => {
if (balances) {
refreshBalances();
}
}, [balances]);
// ✅ CORRECT: Only call on mount or user action
useEffect(() => {
refreshBalances(); // Called once on mount
}, []); // Empty dependency array
// ✅ CORRECT: Call on user action
<Button onClick={() => refreshBalances()}>
Refresh
</Button>
```
**If Issue Persists**: Check your implementation for:
1. Effects that call `refreshBalances` and depend on `balances`
2. Custom hooks that wrap `useCashu` and create circular dependencies
3. Component re-renders that trigger unintended effect runs
## Integration Checklist
- [ ] **CRITICAL**: Create `CashuContext.tsx` with `CashuProvider` (see Required Dependencies)
- [ ] **CRITICAL**: Wrap app with `<CashuProvider>` in App.tsx
- [ ] **CRITICAL**: Import `useCashu` from `@/contexts/CashuContext` in ALL components
- [ ] **Bitcoin Setup**:
- [ ] Install Bitcoin dependencies: `bitcoinjs-lib`, `@bitcoinerlab/secp256k1`, `ecpair`
- [ ] Import Bitcoin utility functions from `@/lib/bitcoin`
- [ ] Ensure user login with nsec for Bitcoin features
- [ ] Test Bitcoin send/receive with Taproot addresses
- [ ] Verify UTXO fetching and balance display
- [ ] **Cashu Setup**:
- [ ] Install Cashu dependencies: `coco-cashu-core`, `coco-cashu-indexeddb`, `@scure/bip39`
- [ ] Initialize coco-cashu-core with mnemonic
- [ ] Add mint management UI
- [ ] Test token send/receive flows
- [ ] Verify npub.cash integration (optional)
- [ ] Import unified `ZapButton` component
- [ ] Create dedicated route/page for `CashuWallet` (don't embed in content feeds)
- [ ] Test all payment methods: Cashu → WebLN → NWC → Manual QR
- [ ] Verify mobile responsiveness
- [ ] Test error handling scenarios
- [ ] Verify component separation (wallet management vs content integration)
- [ ] Check console for infinite `refreshBalances` loops (should see throttling logs if working correctly)
This unified integration provides a seamless, intelligent wallet experience that automatically selects the best available payment method while leveraging the benefits of Cashu tokens, Lightning payments, and on-chain Bitcoin transactions.