mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
add agent docs for wallets
This commit is contained in:
1 parent
47492df00e
commit
8cf5391817
10 files changed
+1258
-783
No files matched your search
@@ -35,9 +35,9 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `useZaps`: Lightning zap functionality with Cashu integration and payment processing
|
||||
- **Cashu hooks**: `useCashu` (core wallet management), `useMintManager` (mint operations), `useWalletTransactions` (send/receive), `useHistoryManager` (transaction history)
|
||||
- **Bitcoin hooks**: `useBitcoinBalance` (UTXO tracking), `useNsecAccess` (private key access for signing)
|
||||
- **Integration hooks**: `useNpubCash` (npub.cash API), `useLightningAddress` (Lightning address validation), `useWallet` (unified wallet detection), `useNWC` (Nostr Wallet Connect), `useNWCContext` (NWC context provider)
|
||||
- **Cashu hooks**: `useCashu` (core wallet management), `useMintManager` (mint operations), `useWalletTransactions` (send/receive), `useHistoryManager` (transaction history) - See **`docs/CASHU_WALLET.md`** for comprehensive implementation guide
|
||||
- **Bitcoin hooks**: `useBitcoinBalance` (UTXO tracking), `useNsecAccess` (private key access for signing) - See **`docs/BITCOIN_WALLET.md`** for Bitcoin wallet architecture and operations
|
||||
- **Integration hooks**: `useNpubCash` (npub.cash API), `useLightningAddress` (Lightning address validation), `useWallet` (unified wallet detection), `useNWC` (Nostr Wallet Connect), `useNWCContext` (NWC context provider) - See **`docs/CASHU_WALLET.md`** for integration patterns
|
||||
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
@@ -114,6 +114,10 @@ The project includes a **`docs/`** directory containing specialized documentatio
|
||||
|
||||
- **`docs/NOSTR_DIRECT_MESSAGES.md`**: Read when implementing direct messaging features, building chat interfaces, or working with encrypted peer-to-peer communication (NIP-04 and NIP-17).
|
||||
|
||||
- **`docs/CASHU_WALLET.md`**: Read when implementing Cashu/eCash wallet features, Lightning payments, mint management, token operations, or working with the coco-cashu-core library. This guide covers architecture, component structure, hook patterns, and best practices for the Cashu wallet system.
|
||||
|
||||
- **`docs/BITCOIN_WALLET.md`**: Read when implementing on-chain Bitcoin wallet features, UTXO management, Bitcoin transactions, consolidation, or working with Bitcoin addresses derived from Nostr pubkeys. This guide covers the Bitcoin wallet architecture, transaction flows, and integration patterns.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
@@ -1,22 +1,8 @@
|
||||
# NutStack
|
||||
|
||||
[](https://shakespeare.diy/clone?url=https://gitlab.com/lemonknowsall/nutstack.git)
|
||||
|
||||
## ⚠️ Security Warning
|
||||
|
||||
**This is experimental software. No security audits have been performed. Loss of funds is possible with any AI-coded application using this template.**
|
||||
|
||||
- This software has not been audited for security vulnerabilities
|
||||
- Use at your own risk
|
||||
- Do not store significant amounts of funds in wallets created with this template
|
||||
- Always test with small amounts first
|
||||
- Consider this template for educational and development purposes only
|
||||
|
||||
---
|
||||
# MKStack
|
||||
|
||||
**The Complete Framework for Building Nostr Clients with AI**
|
||||
|
||||
NutStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, NutStack provides everything you need to create decentralized apps on the Nostr protocol.
|
||||
MKStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, MKStack provides everything you need to create decentralized apps on the Nostr protocol.
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
@@ -25,7 +11,7 @@ Build your Nostr app in 3 simple steps:
|
||||
### 1. Install & Create
|
||||
```bash
|
||||
npm install -g @getstacks/stacks
|
||||
stacks nutstack
|
||||
stacks mkstack
|
||||
```
|
||||
|
||||
### 2. Build with AI
|
||||
@@ -40,14 +26,14 @@ npm run deploy
|
||||
# ✅ App deployed to NostrDeploy.com!
|
||||
```
|
||||
|
||||
## ✨ What Makes NutStack Special
|
||||
## ✨ What Makes MKStack Special
|
||||
|
||||
- **🤖 AI-First Development**: Build complete Nostr apps with just one prompt using Dork AI agent
|
||||
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
|
||||
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
|
||||
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
|
||||
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
|
||||
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), on-chain Bitcoin transactions, Wallet Connect (NIP-47), Npub.cash integration
|
||||
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Wallet Connect (NIP-47)
|
||||
- **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included
|
||||
|
||||
## 🛠 Technology Stack
|
||||
@@ -98,7 +84,7 @@ Real Nostr applications built using MKStack:
|
||||
### Nostr Protocol Support
|
||||
- **Social Features**: User profiles (NIP-01), follow lists (NIP-02), reactions (NIP-25), reposts (NIP-18)
|
||||
- **Messaging**: Private DMs (NIP-17), public chat (NIP-28), group chat (NIP-29), encryption (NIP-44)
|
||||
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47), on-chain Bitcoin transactions using Taproot addresses derived from Nostr keys
|
||||
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47)
|
||||
- **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52)
|
||||
|
||||
### Data Management
|
||||
@@ -108,15 +94,6 @@ Real Nostr applications built using MKStack:
|
||||
- Infinite scroll with TanStack Query
|
||||
- Multi-relay support
|
||||
|
||||
### Wallet System
|
||||
- `useCashu` hook for Cashu wallet management
|
||||
- `useMintManager` hook for mint operations
|
||||
- `useWalletTransactions` hook for send/receive operations
|
||||
- `useHistoryManager` hook for transaction history
|
||||
- `useBitcoinBalance` hook for Bitcoin UTXO tracking
|
||||
- `useNsecAccess` hook for private key access (Bitcoin signing)
|
||||
- `useNpubCash` hook for Npub.cash API integration
|
||||
|
||||
### UI Components
|
||||
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
|
||||
- `NoteContent` component for rich text rendering
|
||||
@@ -205,34 +182,6 @@ MKStack includes 48+ shadcn/ui components:
|
||||
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
|
||||
- **Secure authentication**: Use signer interface, never request private keys directly
|
||||
|
||||
## 💰 Unified Wallet System
|
||||
|
||||
NutStack includes a comprehensive three-mode wallet system that supports multiple payment methods:
|
||||
|
||||
### Three Payment Modes
|
||||
|
||||
- **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
|
||||
|
||||
### Key Features
|
||||
|
||||
- **Mode Switching**: Seamless switching between payment methods via UI toggle
|
||||
- **Unified Interface**: Single `CashuWallet` component handles all payment types
|
||||
- **Nostr Integration**: Bitcoin addresses derived from Nostr public keys using Taproot (P2TR)
|
||||
- **Private Key Access**: Bitcoin transactions require nsec login for transaction signing
|
||||
- **Transaction History**: Unified history tracking across all payment methods
|
||||
- **Mobile Optimized**: Responsive design with drawer/modal patterns for mobile
|
||||
|
||||
### Architecture
|
||||
|
||||
The wallet system uses a component-based architecture:
|
||||
- `CashuWallet` - Main wallet interface with mode switching
|
||||
- `WalletHeader` - Balance display and mode toggle
|
||||
- `TransactionCard` - Send/receive forms for each mode
|
||||
- `MintSelector` - Cashu mint management
|
||||
- `TransactionHistory` - Unified transaction history
|
||||
|
||||
## 📱 Responsive Design
|
||||
|
||||
- Mobile-first approach with Tailwind breakpoints
|
||||
@@ -284,6 +233,6 @@ Open source - build amazing Nostr applications and help grow the decentralized w
|
||||
|
||||
---
|
||||
|
||||
**"Vibed with NutStack"** - [Learn more about NutStack](https://soapbox.pub/nutstack)
|
||||
**"Vibed with MKStack"** - [Learn more about MKStack](https://soapbox.pub/mkstack)
|
||||
|
||||
*Build your Nostr app in minutes, not months. Start with AI, deploy instantly.*
|
||||
@@ -0,0 +1,460 @@
|
||||
# Bitcoin Wallet System for AI Agents (NutStack)
|
||||
|
||||
This document explains the Bitcoin wallet system architecture and provides guidance for AI agents to extend, modify, and build upon the existing implementation.
|
||||
|
||||
## Overview
|
||||
|
||||
The Bitcoin wallet system provides on-chain Bitcoin transaction capabilities including:
|
||||
- **Send/Receive**: On-chain Bitcoin transactions using Taproot addresses
|
||||
- **UTXO Management**: View and manage unspent transaction outputs
|
||||
- **UTXO Consolidation**: Combine multiple UTXOs into a single transaction
|
||||
- **Transaction History**: View past Bitcoin transactions with status tracking
|
||||
- **QR Code Support**: Scan Bitcoin addresses and npubs
|
||||
|
||||
The wallet requires nsec login for transaction signing.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Component Hierarchy
|
||||
|
||||
```
|
||||
WalletContainer (parent)
|
||||
└── BitcoinWallet
|
||||
├── WalletHeader (balance, mode toggle, address display)
|
||||
├── PaymentCard (send/receive forms)
|
||||
├── TransactionHistory (transaction list)
|
||||
├── UTXOSelector (UTXO dropdown with consolidation)
|
||||
├── ConsolidationModal (UTXO consolidation confirmation)
|
||||
├── QRScanner (QR code scanning)
|
||||
└── QRModal (address QR code display)
|
||||
```
|
||||
|
||||
### Key Components
|
||||
|
||||
#### `BitcoinWallet.tsx`
|
||||
Main Bitcoin wallet component that orchestrates all Bitcoin operations:
|
||||
- Manages Bitcoin send/receive state
|
||||
- Handles QR scan results
|
||||
- Coordinates UTXO management
|
||||
- Provides action buttons (Send, Receive, Scan, History)
|
||||
|
||||
**Key State:**
|
||||
- `bitcoinAmount`: Amount to send (in sats)
|
||||
- `bitcoinRecipient`: Recipient address or npub
|
||||
- `pendingBitcoinRecipient`: Confirmed recipient after validation
|
||||
- `showSendModal`, `showReceiveModal`, `showHistoryModal`: Drawer visibility
|
||||
|
||||
**Key Props:**
|
||||
- `user`: Current user with pubkey
|
||||
- `toast`: Toast notification function
|
||||
- `generateQRCode`: QR code generation function
|
||||
- `onRequestQRScanner`: Request QR scanner modal
|
||||
- `onQRResult`: Handle QR scan results
|
||||
|
||||
#### `WalletHeader.tsx`
|
||||
Displays wallet balance, mode toggle, and address management:
|
||||
- **Balance Display**: Shows total Bitcoin balance with USD/sats toggle
|
||||
- **Address Display**: Shows Bitcoin address with copy/QR buttons
|
||||
- **UTXO Selector**: Displays UTXO count and consolidation option
|
||||
- **Custody Badge**: Indicates "Self-Custody" for Bitcoin mode
|
||||
|
||||
#### `PaymentCard.tsx`
|
||||
Transaction card for Bitcoin operations:
|
||||
- **Bitcoin Send**: Two-step process (recipient → amount)
|
||||
- **Bitcoin Receive**: Shows address with QR generation
|
||||
- **Send Max**: Toggle for sending all available funds
|
||||
|
||||
**Bitcoin Send Flow:**
|
||||
1. User enters recipient address or npub
|
||||
2. System validates and converts npub to Bitcoin address if needed
|
||||
3. User enters amount (or clicks "Send Max")
|
||||
4. Transaction is created, signed, and broadcast
|
||||
|
||||
#### `TransactionHistory.tsx`
|
||||
Transaction history display:
|
||||
- **Bitcoin Transactions**: On-chain transactions with status
|
||||
- **Transaction Types**: `sent`, `received`, `consolidate`
|
||||
- **Status Display**: `confirmed`, `unconfirmed`, `pending`
|
||||
|
||||
**Bitcoin Transaction Format:**
|
||||
```typescript
|
||||
interface BitcoinTransaction {
|
||||
id: string;
|
||||
txid: string;
|
||||
type: 'sent' | 'received' | 'consolidate';
|
||||
amount: number; // in satoshis
|
||||
fee?: number; // in satoshis
|
||||
address: string;
|
||||
confirmations: number;
|
||||
blockHeight?: number;
|
||||
timestamp: number;
|
||||
status: 'confirmed' | 'unconfirmed' | 'pending';
|
||||
}
|
||||
```
|
||||
|
||||
#### `UTXOSelector.tsx`
|
||||
UTXO management dropdown:
|
||||
- Shows UTXO count and total balance
|
||||
- Lists individual UTXOs with block information
|
||||
- Consolidation button for combining UTXOs
|
||||
- Formatting supports sats/USD display
|
||||
|
||||
#### `ConsolidationModal.tsx`
|
||||
Confirmation modal for UTXO consolidation:
|
||||
- Shows number of UTXOs to be consolidated
|
||||
- Displays total value
|
||||
- Explains benefits (reduced fees, simplified management)
|
||||
- Handles consolidation execution
|
||||
|
||||
#### `QRScanner.tsx`
|
||||
QR code scanning interface:
|
||||
- Camera-based scanning using Html5Qrcode
|
||||
- Paste from clipboard support
|
||||
- Classifies scanned codes (Bitcoin address, npub, etc.)
|
||||
- Handles camera permissions and errors
|
||||
|
||||
### Core Hooks
|
||||
|
||||
#### `useBitcoin.ts`
|
||||
Main Bitcoin operations hook:
|
||||
- **`useBitcoinBalance`**: Fetches UTXOs and calculates balance
|
||||
- **`useBitcoinTransactionHistory`**: Fetches transaction history from Blockstream API
|
||||
- **`useBitcoinOperations`**: Manages send/receive/consolidate operations
|
||||
|
||||
**Key Functions:**
|
||||
```typescript
|
||||
// Fetch UTXOs and balance
|
||||
const { data: bitcoinBalanceData } = useBitcoinBalance(bitcoinAddress);
|
||||
|
||||
// Fetch transaction history
|
||||
const { data: bitcoinTransactions } = useBitcoinTransactionHistory(bitcoinAddress);
|
||||
|
||||
// Get operations hook
|
||||
const {
|
||||
utxos,
|
||||
isConsolidating,
|
||||
bitcoinMaxAmount,
|
||||
fetchBitcoinUtxos,
|
||||
handleSendMax,
|
||||
handleBitcoinSend,
|
||||
handleBitcoinReceive,
|
||||
handleConsolidateUtxos,
|
||||
} = useBitcoinOperations(bitcoinAddress);
|
||||
```
|
||||
|
||||
#### `useNsecAccess.ts`
|
||||
Access to private key for transaction signing:
|
||||
- **`hasNsecAccess`**: Checks if user logged in with nsec
|
||||
- **`getPrivateKey`**: Returns private key in hex format
|
||||
|
||||
**Usage:**
|
||||
```typescript
|
||||
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
|
||||
|
||||
if (!hasNsecAccess) {
|
||||
// Show error: nsec login required
|
||||
return;
|
||||
}
|
||||
|
||||
const privateKey = getPrivateKey();
|
||||
// Use private key for transaction signing
|
||||
```
|
||||
|
||||
#### `useQRCode.ts`
|
||||
QR code generation and scanning:
|
||||
- **`generateQRCode`**: Creates QR code from text
|
||||
- **`startScanning`**: Starts camera scanner
|
||||
- **`stopScanning`**: Stops scanner
|
||||
- **`classifyQRCode`**: Classifies scanned text (Bitcoin address, npub, etc.)
|
||||
|
||||
**QR Code Types:**
|
||||
- `bitcoin_address`: Bitcoin address (bc1..., 1..., 3...)
|
||||
- `npub`: Nostr public key (npub1...)
|
||||
- `unknown`: Unrecognized format
|
||||
|
||||
### Core Libraries
|
||||
|
||||
#### `bitcoin.ts`
|
||||
Bitcoin utility functions:
|
||||
- **Address Derivation**: `nostrPubkeyToBitcoinAddress()`, `npubToBitcoinAddress()`
|
||||
- **Validation**: `isValidBitcoinAddress()`
|
||||
- **UTXO Management**: `fetchUTXOs()`, `calculateMaxSendAmount()`
|
||||
- **Transaction Building**: `createBitcoinTransaction()`, `broadcastTransaction()`
|
||||
- **Fee Estimation**: `getFeeRates()`
|
||||
|
||||
**Key Functions:**
|
||||
```typescript
|
||||
// Convert Nostr pubkey to Bitcoin Taproot address
|
||||
const address = nostrPubkeyToBitcoinAddress(user.pubkey);
|
||||
|
||||
// Fetch UTXOs from Blockstream API
|
||||
const utxos = await fetchUTXOs(address);
|
||||
|
||||
// Get fee rates
|
||||
const feeRates = await getFeeRates();
|
||||
// Returns: { fastestFee, halfHourFee, hourFee, economyFee, minimumFee }
|
||||
|
||||
// Create and sign transaction
|
||||
const { txHex, fee } = await createBitcoinTransaction(
|
||||
privateKeyHex,
|
||||
recipientAddress,
|
||||
amountSats,
|
||||
utxos,
|
||||
feeRates.fastestFee,
|
||||
sendMax // true for send max
|
||||
);
|
||||
|
||||
// Broadcast transaction
|
||||
const txId = await broadcastTransaction(txHex);
|
||||
```
|
||||
|
||||
#### `exchangeRateService.ts`
|
||||
Exchange rate service for BTC/USD conversion:
|
||||
- Fetches rates from Coinbase API
|
||||
- 1-minute caching to reduce API calls
|
||||
- Fallback to cached rate on API failure
|
||||
- Methods: `getBtcUsdRate()`, `satsToUsd()`, `btcToUsd()`, `usdToBtc()`
|
||||
|
||||
## Key Features
|
||||
|
||||
### On-Chain Bitcoin Transactions
|
||||
|
||||
**Address Derivation:**
|
||||
- Bitcoin addresses are derived from Nostr public keys
|
||||
- Uses Taproot (P2TR) addresses (bc1p...)
|
||||
- Supports conversion from npub format
|
||||
|
||||
**Transaction Flow:**
|
||||
1. User enters recipient (Bitcoin address or npub)
|
||||
2. System validates and converts npub if needed
|
||||
3. User enters amount (or selects "Send Max")
|
||||
4. System fetches UTXOs and fee rates
|
||||
5. Transaction is built and signed
|
||||
6. Transaction is broadcast to network
|
||||
7. Balance is refreshed automatically
|
||||
|
||||
**Send Max:**
|
||||
- Calculates maximum sendable amount (total - fees)
|
||||
- No change output (sends all UTXOs)
|
||||
- Useful for consolidating or emptying wallet
|
||||
|
||||
### UTXO Management
|
||||
|
||||
**UTXO Display:**
|
||||
- Shows count and total value
|
||||
- Lists individual UTXOs with block information
|
||||
- Displays confirmation status
|
||||
|
||||
**UTXO Consolidation:**
|
||||
- Combines multiple UTXOs into single transaction
|
||||
- Sends all funds to own address (self-send)
|
||||
- Reduces future transaction fees
|
||||
- Requires nsec login for signing
|
||||
|
||||
**UTXO Selection:**
|
||||
- Automatic selection for transactions
|
||||
- Uses all available UTXOs for send max
|
||||
- Optimizes for fee efficiency
|
||||
|
||||
### Transaction History
|
||||
|
||||
**Data Source:**
|
||||
Blockstream API provides transaction history:
|
||||
- Fetches transaction list from `/address/:address/txs`
|
||||
- Fetches full transaction details for accurate sent/received detection
|
||||
- Calculates transaction amounts and fees
|
||||
|
||||
**Transaction Detection:**
|
||||
- **Received**: Address appears in outputs only
|
||||
- **Sent**: Address appears in input prevouts
|
||||
- **Consolidate**: Self-send where all outputs go to same address
|
||||
|
||||
**Display:**
|
||||
- Transaction type with icon
|
||||
- Amount with direction (sent/received)
|
||||
- Fee information (for sent transactions)
|
||||
- Confirmation count and status
|
||||
- Block height and timestamp
|
||||
|
||||
### QR Code Integration
|
||||
|
||||
**QR Code Generation:**
|
||||
- Bitcoin addresses for receiving payments
|
||||
|
||||
**QR Code Scanning:**
|
||||
- Bitcoin addresses: Auto-fills recipient field
|
||||
- npubs: Converts to Bitcoin address and auto-fills
|
||||
|
||||
**Supported Formats:**
|
||||
- `bc1...` (Taproot addresses)
|
||||
- `1...`, `3...` (Legacy addresses)
|
||||
- `npub1...` (Nostr public keys)
|
||||
|
||||
## State Management
|
||||
|
||||
### Bitcoin State Flow
|
||||
|
||||
```
|
||||
BitcoinWallet Component
|
||||
├── Local State
|
||||
│ ├── bitcoinAmount (send amount)
|
||||
│ ├── bitcoinRecipient (recipient input)
|
||||
│ ├── pendingBitcoinRecipient (validated recipient)
|
||||
│ └── Modal visibility states
|
||||
├── useBitcoinBalance Hook
|
||||
│ ├── Fetches UTXOs from Blockstream API
|
||||
│ ├── Calculates total balance
|
||||
│ └── Auto-refreshes every 30 seconds
|
||||
├── useBitcoinTransactionHistory Hook
|
||||
│ ├── Fetches transaction history
|
||||
│ └── Auto-refreshes every 30 seconds
|
||||
└── useBitcoinOperations Hook
|
||||
├── UTXO management
|
||||
├── Send/receive operations
|
||||
└── Consolidation handling
|
||||
```
|
||||
|
||||
### React Query Integration
|
||||
|
||||
**Bitcoin Balance:**
|
||||
```typescript
|
||||
const { data: bitcoinBalanceData, refetch } = useBitcoinBalance(bitcoinAddress);
|
||||
// Returns: { balance: number, utxos: UTXO[] }
|
||||
```
|
||||
|
||||
**Transaction History:**
|
||||
```typescript
|
||||
const { data: bitcoinTransactions } = useBitcoinTransactionHistory(bitcoinAddress);
|
||||
// Returns: BitcoinTransaction[]
|
||||
```
|
||||
|
||||
**Auto-Refresh:**
|
||||
- Balance: Refetches every 30 seconds
|
||||
- Transactions: Refetches every 30 seconds
|
||||
- Stale time: 10 seconds (data considered fresh for 10s)
|
||||
|
||||
## Extension Points
|
||||
|
||||
### Adding New Features
|
||||
|
||||
#### 1. Custom Fee Selection
|
||||
|
||||
To allow users to select fee rates:
|
||||
|
||||
**Add Fee Selector Component:**
|
||||
```typescript
|
||||
const [selectedFeeRate, setSelectedFeeRate] = useState<'fastest' | 'halfHour' | 'hour' | 'economy'>('fastest');
|
||||
|
||||
const feeRates = await getFeeRates();
|
||||
const feeRate = feeRates[`${selectedFeeRate}Fee`];
|
||||
```
|
||||
|
||||
**Update `PaymentCard.tsx`:**
|
||||
```typescript
|
||||
// Add fee selector dropdown
|
||||
<Select value={selectedFeeRate} onValueChange={setSelectedFeeRate}>
|
||||
<SelectItem value="fastest">Fastest ({feeRates.fastestFee} sat/vB)</SelectItem>
|
||||
<SelectItem value="halfHour">Half Hour ({feeRates.halfHourFee} sat/vB)</SelectItem>
|
||||
// ...
|
||||
</Select>
|
||||
```
|
||||
|
||||
#### 2. Transaction Labels/Notes
|
||||
|
||||
To add labels or notes to transactions:
|
||||
|
||||
**Extend Transaction History:**
|
||||
```typescript
|
||||
interface BitcoinTransaction {
|
||||
// ... existing fields
|
||||
label?: string;
|
||||
notes?: string;
|
||||
}
|
||||
```
|
||||
|
||||
**Store Labels:**
|
||||
- Use local storage or IndexedDB
|
||||
- Key by transaction ID
|
||||
- Display in transaction history
|
||||
|
||||
|
||||
### Modifying Existing Features
|
||||
|
||||
#### Change Address Format
|
||||
|
||||
**Modify `bitcoin.ts`:**
|
||||
```typescript
|
||||
// Change from Taproot to P2WPKH (bc1q...)
|
||||
export function nostrPubkeyToBitcoinAddress(pubkeyHex: string): string {
|
||||
const pubkeyBuffer = Buffer.from(pubkeyHex, 'hex');
|
||||
const { address } = bitcoin.payments.p2wpkh({
|
||||
pubkey: pubkeyBuffer,
|
||||
network: bitcoin.networks.bitcoin,
|
||||
});
|
||||
return address || '';
|
||||
}
|
||||
```
|
||||
|
||||
#### Change Fee Estimation
|
||||
|
||||
**Modify `bitcoin.ts`:**
|
||||
```typescript
|
||||
// Use different API or estimation method
|
||||
export async function getFeeRates() {
|
||||
return {
|
||||
fastestFee: 10,
|
||||
halfHourFee: 5,
|
||||
hourFee: 3,
|
||||
economyFee: 1,
|
||||
minimumFee: 1,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### 1. "Nsec login required" error
|
||||
**Cause**: User not logged in with nsec
|
||||
**Solution**: Check `hasNsecAccess` before showing Bitcoin features
|
||||
|
||||
#### 2. Transaction fails to broadcast
|
||||
**Cause**: Invalid transaction or network error
|
||||
**Solution**: Validate transaction before broadcasting, retry on network errors
|
||||
|
||||
#### 3. UTXOs not updating
|
||||
**Cause**: Blockstream API rate limiting or network issues
|
||||
**Solution**: Implement retry logic, show error to user
|
||||
|
||||
#### 4. Balance incorrect
|
||||
**Cause**: UTXOs not fetched or cached data stale
|
||||
**Solution**: Force refresh balance, check Blockstream API response
|
||||
|
||||
## API Dependencies
|
||||
|
||||
### Blockstream API
|
||||
- **Base URL**: `https://blockstream.info/api`
|
||||
- **Endpoints**:
|
||||
- `/address/:address/utxo` - Fetch UTXOs
|
||||
- `/address/:address/txs` - Fetch transaction list
|
||||
- `/tx/:txid` - Fetch full transaction details
|
||||
- `/fee-estimates` - Get fee rates
|
||||
- `/tx` - Broadcast transaction (POST)
|
||||
|
||||
### Coinbase API
|
||||
- **Base URL**: `https://api.coinbase.com/v2/exchange-rates`
|
||||
- **Endpoint**: `?currency=BTC` - Get BTC/USD exchange rate
|
||||
|
||||
## Dependencies
|
||||
|
||||
Required packages:
|
||||
```json
|
||||
{
|
||||
"bitcoinjs-lib": "^7.x",
|
||||
"@bitcoinerlab/secp256k1": "^1.x",
|
||||
"ecpair": "^2.x",
|
||||
"qrcode": "^1.x",
|
||||
"html5-qrcode": "^2.x"
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,784 @@
|
||||
# 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](#architecture-overview)
|
||||
2. [Component Structure](#component-structure)
|
||||
3. [Hook Patterns](#hook-patterns)
|
||||
4. [Wallet Modes](#wallet-modes)
|
||||
5. [Mint Management](#mint-management)
|
||||
6. [Transaction Operations](#transaction-operations)
|
||||
7. [Integration Points](#integration-points)
|
||||
8. [Extension Guidelines](#extension-guidelines)
|
||||
9. [Best Practices](#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**:
|
||||
```typescript
|
||||
// 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**:
|
||||
```typescript
|
||||
// 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**:
|
||||
```typescript
|
||||
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**:
|
||||
```typescript
|
||||
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**:
|
||||
```typescript
|
||||
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**:
|
||||
```typescript
|
||||
// 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**:
|
||||
```typescript
|
||||
// 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**:
|
||||
```typescript
|
||||
// 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
|
||||
```typescript
|
||||
const token = await coco.wallet.send(activeMintUrl, amount);
|
||||
const encodedToken = getEncodedToken(token);
|
||||
// Show QR code modal with token
|
||||
```
|
||||
|
||||
#### Lightning Invoice Payment
|
||||
```typescript
|
||||
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, invoice);
|
||||
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||
```
|
||||
|
||||
#### Lightning Address Payment
|
||||
```typescript
|
||||
// 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
|
||||
```typescript
|
||||
await coco.wallet.receive(token);
|
||||
// Automatically handles unknown mints
|
||||
```
|
||||
|
||||
#### Lightning Invoice Creation
|
||||
```typescript
|
||||
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**:
|
||||
```typescript
|
||||
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**:
|
||||
```typescript
|
||||
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**:
|
||||
```typescript
|
||||
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
|
||||
```typescript
|
||||
const hasFetchedRef = useRef(false);
|
||||
if (hasFetchedRef.current) return;
|
||||
hasFetchedRef.current = true;
|
||||
```
|
||||
|
||||
2. **Persist important state**: Use `useLocalStorage` for user preferences
|
||||
```typescript
|
||||
const [storedValue, setStoredValue] = useLocalStorage('key', defaultValue);
|
||||
```
|
||||
|
||||
3. **Clean up state on unmount**: Reset state when drawers/modals close
|
||||
```typescript
|
||||
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
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const unsubscribe = coco.on('event', handler);
|
||||
return () => unsubscribe();
|
||||
}, [coco]);
|
||||
```
|
||||
|
||||
2. **Store unsubscribe functions**: Use refs for complex cleanup
|
||||
```typescript
|
||||
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
|
||||
```typescript
|
||||
import type { Manager, HistoryEntry, Mint } from 'coco-cashu-core';
|
||||
```
|
||||
|
||||
2. **Validate inputs**: Check types and values before operations
|
||||
```typescript
|
||||
const amount = parseInt(input);
|
||||
if (isNaN(amount) || amount <= 0) {
|
||||
toast({ variant: 'destructive', title: 'Invalid amount' });
|
||||
return;
|
||||
}
|
||||
```
|
||||
|
||||
## Common Patterns Reference
|
||||
|
||||
### Mint Check Pattern
|
||||
```typescript
|
||||
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
|
||||
```typescript
|
||||
// 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
|
||||
@@ -1,648 +0,0 @@
|
||||
# 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.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 41 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 282 KiB |
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"name": "NutStack",
|
||||
"short_name": "NutStack",
|
||||
"description": "Nostr application with Cashu wallet integration",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#000000",
|
||||
"theme_color": "#000000",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
// public/sw.js
|
||||
|
||||
self.addEventListener("push", (event) => {
|
||||
if (!event.data) return;
|
||||
|
||||
try {
|
||||
const data = event.data.json();
|
||||
|
||||
const title = data.title || "New Notification";
|
||||
const options = {
|
||||
body: data.body,
|
||||
icon: data.icon || "/icon-192.png"
|
||||
// badge: data.badge || "/badge-72x72.png",
|
||||
// data: data.data || {},
|
||||
};
|
||||
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(title, options)
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("Push event error:", err);
|
||||
}
|
||||
});
|
||||
|
||||
self.addEventListener("notificationclick", (event) => {
|
||||
event.notification.close();
|
||||
|
||||
// If you send a `url` in payload.data, open it
|
||||
const url = event.notification.data?.url;
|
||||
if (url) {
|
||||
event.waitUntil(clients.openWindow(url));
|
||||
}
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
interface LoadingScreenProps {
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function LoadingScreen({ isLoading }: LoadingScreenProps) {
|
||||
if (!isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center z-[200]">
|
||||
<Card className="border-0 shadow-lg bg-background">
|
||||
<CardContent className="flex items-center justify-center p-8">
|
||||
<Loader2 className="h-8 w-8 animate-spin mr-3" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user