mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 00:37:23 +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
@@ -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"
|
||||
}
|
||||
```
|
||||
Reference in new issue
Block a user