From d0c28b77b80cf280e490397d0641b2506cef293e Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Mon, 20 Oct 2025 13:41:14 -0700 Subject: [PATCH] Docs update for Nutstack wallet integration --- AGENTS.md | 95 ++++++- README.md | 63 ++++- ...P_INTEGRATION.md => WALLET_INTEGRATION.md} | 240 +++++++++++++++++- 3 files changed, 374 insertions(+), 24 deletions(-) rename docs/{CASHU_ZAP_INTEGRATION.md => WALLET_INTEGRATION.md} (60%) diff --git a/AGENTS.md b/AGENTS.md index 519480e..4d6da41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - `/src/components/`: UI components including NostrProvider for Nostr integration - `/src/components/ui/`: shadcn/ui components (48+ components available) - `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.) + - `/src/components/wallet/`: Wallet system components including `CashuWallet` (main wallet interface), `WalletHeader` (balance display and mode toggle), `TransactionCard` (send/receive forms), `MintSelector` (mint management), `TransactionHistory` (unified history) - Zap components: `ZapButton` (unified component with Cashu integration), `LightningWalletModal` for Lightning fallback management - `/src/hooks/`: Custom hooks including: - `useNostr`: Core Nostr protocol integration @@ -34,11 +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 - - `useCashu`: Cashu wallet management (balances, mints, melt quotes) - - `useLightningAddress`: Lightning address validation and LNURL endpoint discovery - - `useWallet`: Unified wallet detection (Cashu + WebLN + NWC) with intelligent payment method selection - - `useNWC`: Nostr Wallet Connect connection management - - `useNWCContext`: Access NWC context provider + - **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) - `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 @@ -142,9 +141,9 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic 1. Edit AGENTS.md directly 2. The changes take effect in the next session -## "Vibed with MKStack" +## "Vibed with NutStack" -When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack +When building the site for the first time, include "Vibed with NutStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack ## Nostr Protocol Integration @@ -770,6 +769,88 @@ function EditProfilePage() { The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically. +### Cashu Token System + +NutStack includes comprehensive Cashu token support using the coco-cashu-core library: + +#### Core Architecture +- **Token Management**: Uses coco-cashu-core for token operations and proof management +- **Mint Operations**: Support for multiple mints with denomination handling +- **Token Encoding**: Built-in token encoding/decoding for secure transfers +- **Proof Storage**: IndexedDB-based proof storage via coco-cashu-indexeddb + +#### Key Hooks +- `useCashu`: Core wallet state, balances, and mint management +- `useMintManager`: Mint addition, removal, and denomination display +- `useWalletTransactions`: Send/receive token operations +- `useHistoryManager`: Transaction history tracking + +#### Npub.cash Integration +- **Hosted Mints**: Automatic mint synchronization with npub.cash +- **Quote Management**: Real-time quote updates and synchronization +- **User Management**: Seamless integration with npub.cash user accounts + +#### Usage Example +```tsx +import { useCashu } from '@/hooks/cashu/useCashu'; + +function WalletComponent() { + const { balances, mints, coco } = useCashu(); + + // Access token balances across all mints + const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0); + + return
Total Balance: {totalBalance} sats
; +} +``` + +### Bitcoin Integration + +NutStack supports on-chain Bitcoin transactions using Taproot addresses derived from Nostr keys: + +#### Address Derivation +- **Taproot P2TR**: Bitcoin addresses generated from Nostr public keys +- **Key Conversion**: Automatic conversion from hex pubkey to Bitcoin Taproot address +- **NIP-19 Support**: Conversion from npub format to Bitcoin address + +#### Core Functions +- `nostrPubkeyToBitcoinAddress()`: Convert Nostr pubkey to Bitcoin Taproot address +- `npubToBitcoinAddress()`: Convert npub to Bitcoin address +- `fetchUTXOs()`: Get unspent transaction outputs via Blockstream API +- `createBitcoinTransaction()`: Build and sign Taproot transactions +- `broadcastTransaction()`: Submit transactions to Bitcoin network + +#### Key Hooks +- `useBitcoinBalance`: Track Bitcoin balance via UTXO fetching +- `useNsecAccess`: Access private key for transaction signing (requires nsec login) + +#### Transaction Flow +1. **Address Generation**: Derive Taproot address from Nostr pubkey +2. **UTXO Fetching**: Get available outputs from Blockstream API +3. **Transaction Building**: Create Taproot transaction with proper fee calculation +4. **Signing**: Sign transaction using private key from nsec +5. **Broadcasting**: Submit signed transaction to Bitcoin network + +#### Usage Example +```tsx +import { useBitcoinBalance, useNsecAccess } from '@/hooks'; +import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin'; + +function BitcoinWallet() { + const { user } = useCurrentUser(); + const { hasNsecAccess, getPrivateKey } = useNsecAccess(); + const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null; + const { data: bitcoinBalance } = useBitcoinBalance(bitcoinAddress); + + return ( +
+

Bitcoin Address: {bitcoinAddress}

+

Balance: {bitcoinBalance?.balance || 0} sats

+
+ ); +} +``` + ### Uploading Files on Nostr Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags. diff --git a/README.md b/README.md index e7e5690..30e5397 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,20 @@ -# MKStack +# NutStack + +## ⚠️ 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 + +--- **The Complete Framework for Building Nostr Clients with AI** -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. +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. ## 🚀 Quick Start @@ -11,7 +23,7 @@ Build your Nostr app in 3 simple steps: ### 1. Install & Create ```bash npm install -g @getstacks/stacks -stacks mkstack +stacks nutstack ``` ### 2. Build with AI @@ -26,14 +38,14 @@ npm run deploy # ✅ App deployed to NostrDeploy.com! ``` -## ✨ What Makes MKStack Special +## ✨ What Makes NutStack 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), Wallet Connect (NIP-47) +- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), on-chain Bitcoin transactions, Wallet Connect (NIP-47), Npub.cash integration - **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included ## 🛠 Technology Stack @@ -84,7 +96,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) +- **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 - **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52) ### Data Management @@ -94,6 +106,15 @@ 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 @@ -182,6 +203,34 @@ 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 @@ -233,6 +282,6 @@ Open source - build amazing Nostr applications and help grow the decentralized w --- -**"Vibed with MKStack"** - [Learn more about MKStack](https://soapbox.pub/mkstack) +**"Vibed with NutStack"** - [Learn more about NutStack](https://soapbox.pub/nutstack) *Build your Nostr app in minutes, not months. Start with AI, deploy instantly.* \ No newline at end of file diff --git a/docs/CASHU_ZAP_INTEGRATION.md b/docs/WALLET_INTEGRATION.md similarity index 60% rename from docs/CASHU_ZAP_INTEGRATION.md rename to docs/WALLET_INTEGRATION.md index 4ecea0d..f492442 100644 --- a/docs/CASHU_ZAP_INTEGRATION.md +++ b/docs/WALLET_INTEGRATION.md @@ -1,20 +1,48 @@ -# Unified ZapButton for AI Agents +# Unified Wallet System for AI Agents (NutStack) -This document explains how AI agents can easily integrate intelligent Lightning zaps into Nostr clients using the unified MKStack `ZapButton` component. +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 -The `ZapButton` component automatically prioritizes Cashu wallet balances for NIP-57 Lightning zaps when available, with intelligent fallback to traditional Lightning payments (WebLN → NWC → Manual QR). This provides a seamless user experience where users can zap directly from their Cashu token balance or use traditional Lightning methods. +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. + +### 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 -- **Unified Component**: Single `ZapButton` handles all zap scenarios -- **Intelligent Payment Selection**: Automatically chooses the best available payment method -- **Cashu Integration**: Uses Cashu wallet balance when available and sufficient -- **Smart Fallbacks**: Falls back to WebLN → NWC → Manual QR code +- **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 -- **Mobile Optimized**: Responsive design with drawer/modal patterns ## Basic Usage @@ -89,6 +117,30 @@ When Cashu wallet is available and has sufficient balance: **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`: @@ -271,6 +323,70 @@ The component automatically handles visibility based on: ``` +## 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 ( + + + } /> + } /> + + + ); +} +``` + +### 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: @@ -279,7 +395,99 @@ The component handles common error scenarios: - Zap endpoint unavailable - Payment failures -All errors are displayed via toast notifications. +## 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
Please login with nsec to use Bitcoin features
; + } + + 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 @@ -382,6 +590,18 @@ useEffect(() => { - [ ] **CRITICAL**: Create `CashuContext.tsx` with `CashuProvider` (see Required Dependencies) - [ ] **CRITICAL**: Wrap app with `` 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 @@ -390,4 +610,4 @@ useEffect(() => { - [ ] 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 zap experience that automatically selects the best available payment method while leveraging the benefits of both Cashu tokens and Lightning payments. +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.