mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 08:23:35 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c4c73f8ef | ||
|
|
d0c28b77b8 | ||
|
|
1c991e3185 | ||
|
|
24920117ae | ||
|
|
722b1a743f | ||
|
|
617edd1784 |
No files matched your search
@@ -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 components including NostrProvider for Nostr integration
|
||||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
- `/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
|
- Zap components: `ZapButton` (unified component with Cashu integration), `LightningWalletModal` for Lightning fallback management
|
||||||
- `/src/hooks/`: Custom hooks including:
|
- `/src/hooks/`: Custom hooks including:
|
||||||
- `useNostr`: Core Nostr protocol integration
|
- `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
|
- `useLoginActions`: Authentication actions
|
||||||
- `useIsMobile`: Responsive design helper
|
- `useIsMobile`: Responsive design helper
|
||||||
- `useZaps`: Lightning zap functionality with Cashu integration and payment processing
|
- `useZaps`: Lightning zap functionality with Cashu integration and payment processing
|
||||||
- `useCashu`: Cashu wallet management (balances, mints, melt quotes)
|
- **Cashu hooks**: `useCashu` (core wallet management), `useMintManager` (mint operations), `useWalletTransactions` (send/receive), `useHistoryManager` (transaction history)
|
||||||
- `useLightningAddress`: Lightning address validation and LNURL endpoint discovery
|
- **Bitcoin hooks**: `useBitcoinBalance` (UTXO tracking), `useNsecAccess` (private key access for signing)
|
||||||
- `useWallet`: Unified wallet detection (Cashu + WebLN + NWC) with intelligent payment method selection
|
- **Integration hooks**: `useNpubCash` (npub.cash API), `useLightningAddress` (Lightning address validation), `useWallet` (unified wallet detection), `useNWC` (Nostr Wallet Connect), `useNWCContext` (NWC context provider)
|
||||||
- `useNWC`: Nostr Wallet Connect connection management
|
|
||||||
- `useNWCContext`: Access NWC context provider
|
|
||||||
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
||||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||||
- `/src/lib/`: Utility functions and shared logic
|
- `/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
|
1. Edit AGENTS.md directly
|
||||||
2. The changes take effect in the next session
|
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
|
## 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.
|
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 <div>Total Balance: {totalBalance} sats</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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 (
|
||||||
|
<div>
|
||||||
|
<p>Bitcoin Address: {bitcoinAddress}</p>
|
||||||
|
<p>Balance: {bitcoinBalance?.balance || 0} sats</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Uploading Files on Nostr
|
### 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.
|
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||||
|
|||||||
@@ -1,8 +1,22 @@
|
|||||||
# MKStack
|
# 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
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
**The Complete Framework for Building Nostr Clients with AI**
|
**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
|
## 🚀 Quick Start
|
||||||
|
|
||||||
@@ -11,7 +25,7 @@ Build your Nostr app in 3 simple steps:
|
|||||||
### 1. Install & Create
|
### 1. Install & Create
|
||||||
```bash
|
```bash
|
||||||
npm install -g @getstacks/stacks
|
npm install -g @getstacks/stacks
|
||||||
stacks mkstack
|
stacks nutstack
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Build with AI
|
### 2. Build with AI
|
||||||
@@ -26,14 +40,14 @@ npm run deploy
|
|||||||
# ✅ App deployed to NostrDeploy.com!
|
# ✅ 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
|
- **🤖 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
|
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
|
||||||
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
|
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
|
||||||
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
|
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
|
||||||
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
|
- **🔐 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
|
- **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included
|
||||||
|
|
||||||
## 🛠 Technology Stack
|
## 🛠 Technology Stack
|
||||||
@@ -84,7 +98,7 @@ Real Nostr applications built using MKStack:
|
|||||||
### Nostr Protocol Support
|
### Nostr Protocol Support
|
||||||
- **Social Features**: User profiles (NIP-01), follow lists (NIP-02), reactions (NIP-25), reposts (NIP-18)
|
- **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)
|
- **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)
|
- **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52)
|
||||||
|
|
||||||
### Data Management
|
### Data Management
|
||||||
@@ -94,6 +108,15 @@ Real Nostr applications built using MKStack:
|
|||||||
- Infinite scroll with TanStack Query
|
- Infinite scroll with TanStack Query
|
||||||
- Multi-relay support
|
- 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
|
### UI Components
|
||||||
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
|
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
|
||||||
- `NoteContent` component for rich text rendering
|
- `NoteContent` component for rich text rendering
|
||||||
@@ -182,6 +205,34 @@ MKStack includes 48+ shadcn/ui components:
|
|||||||
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
|
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
|
||||||
- **Secure authentication**: Use signer interface, never request private keys directly
|
- **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
|
## 📱 Responsive Design
|
||||||
|
|
||||||
- Mobile-first approach with Tailwind breakpoints
|
- Mobile-first approach with Tailwind breakpoints
|
||||||
@@ -233,6 +284,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.*
|
*Build your Nostr app in minutes, not months. Start with AI, deploy instantly.*
|
||||||
@@ -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
|
## 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
|
## Key Features
|
||||||
|
|
||||||
- **Unified Component**: Single `ZapButton` handles all zap scenarios
|
- **Three-Mode Wallet**: Complete wallet system supporting Cashu tokens, Lightning, and Bitcoin
|
||||||
- **Intelligent Payment Selection**: Automatically chooses the best available payment method
|
- **Mode Switching**: Seamless switching between payment methods via UI toggle
|
||||||
- **Cashu Integration**: Uses Cashu wallet balance when available and sufficient
|
- **Unified Interface**: Single `CashuWallet` component handles all payment types
|
||||||
- **Smart Fallbacks**: Falls back to WebLN → NWC → Manual QR code
|
- **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
|
- **NIP-57 Compliant**: Full compliance with Lightning zap standards
|
||||||
- **Zero Configuration**: Works out of the box with existing Nostr infrastructure
|
- **Zero Configuration**: Works out of the box with existing Nostr infrastructure
|
||||||
- **Mobile Optimized**: Responsive design with drawer/modal patterns
|
|
||||||
|
|
||||||
## Basic Usage
|
## 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!
|
**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!)
|
### Setup CashuContext (Required!)
|
||||||
|
|
||||||
Create `src/contexts/CashuContext.tsx`:
|
Create `src/contexts/CashuContext.tsx`:
|
||||||
@@ -271,6 +323,70 @@ The component automatically handles visibility based on:
|
|||||||
<ZapButton target={event} />
|
<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
|
## Error Handling
|
||||||
|
|
||||||
The component handles common error scenarios:
|
The component handles common error scenarios:
|
||||||
@@ -279,7 +395,99 @@ The component handles common error scenarios:
|
|||||||
- Zap endpoint unavailable
|
- Zap endpoint unavailable
|
||||||
- Payment failures
|
- 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 <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
|
## Mobile Optimization
|
||||||
|
|
||||||
@@ -382,6 +590,18 @@ useEffect(() => {
|
|||||||
- [ ] **CRITICAL**: Create `CashuContext.tsx` with `CashuProvider` (see Required Dependencies)
|
- [ ] **CRITICAL**: Create `CashuContext.tsx` with `CashuProvider` (see Required Dependencies)
|
||||||
- [ ] **CRITICAL**: Wrap app with `<CashuProvider>` in App.tsx
|
- [ ] **CRITICAL**: Wrap app with `<CashuProvider>` in App.tsx
|
||||||
- [ ] **CRITICAL**: Import `useCashu` from `@/contexts/CashuContext` in ALL components
|
- [ ] **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
|
- [ ] Import unified `ZapButton` component
|
||||||
- [ ] Create dedicated route/page for `CashuWallet` (don't embed in content feeds)
|
- [ ] Create dedicated route/page for `CashuWallet` (don't embed in content feeds)
|
||||||
- [ ] Test all payment methods: Cashu → WebLN → NWC → Manual QR
|
- [ ] Test all payment methods: Cashu → WebLN → NWC → Manual QR
|
||||||
@@ -390,4 +610,4 @@ useEffect(() => {
|
|||||||
- [ ] Verify component separation (wallet management vs content integration)
|
- [ ] Verify component separation (wallet management vs content integration)
|
||||||
- [ ] Check console for infinite `refreshBalances` loops (should see throttling logs if working correctly)
|
- [ ] 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.
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 41 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 282 KiB |
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// 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));
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -15,10 +15,10 @@ const Slider = React.forwardRef<
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
|
<SliderPrimitive.Track className="relative h-12 w-full grow overflow-hidden rounded-full bg-secondary">
|
||||||
<SliderPrimitive.Range className="absolute h-full bg-primary" />
|
<SliderPrimitive.Range className="absolute h-full bg-primary" />
|
||||||
</SliderPrimitive.Track>
|
</SliderPrimitive.Track>
|
||||||
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
|
<SliderPrimitive.Thumb className="block h-10 w-10 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
|
||||||
</SliderPrimitive.Root>
|
</SliderPrimitive.Root>
|
||||||
))
|
))
|
||||||
Slider.displayName = SliderPrimitive.Root.displayName
|
Slider.displayName = SliderPrimitive.Root.displayName
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
|||||||
import { useMintManager } from '@/hooks/cashu/useMintManager';
|
import { useMintManager } from '@/hooks/cashu/useMintManager';
|
||||||
import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
|
import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
|
||||||
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
||||||
|
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
||||||
|
import { useBitcoinBalance } from '@/hooks/useBitcoinBalance';
|
||||||
|
import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress, fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction } from '@/lib/bitcoin';
|
||||||
import { QRModal } from '@/components/ui/qr-modal';
|
import { QRModal } from '@/components/ui/qr-modal';
|
||||||
import { WalletHeader } from './WalletHeader';
|
import { WalletHeader } from './WalletHeader';
|
||||||
import { TransactionCard } from './PaymentCard';
|
import { TransactionCard } from './PaymentCard';
|
||||||
@@ -44,6 +47,11 @@ export function CashuWallet() {
|
|||||||
const { generateQRCode } = useQRCode();
|
const { generateQRCode } = useQRCode();
|
||||||
const { copy: copyToClipboard } = useCopyToClipboard();
|
const { copy: copyToClipboard } = useCopyToClipboard();
|
||||||
|
|
||||||
|
// Bitcoin hooks
|
||||||
|
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
|
||||||
|
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
|
||||||
|
const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading, refetch: refetchBitcoinBalance } = useBitcoinBalance(bitcoinAddress);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
setMint: setNpubCashMint,
|
setMint: setNpubCashMint,
|
||||||
getUserInfo: getNpubCashUserInfo,
|
getUserInfo: getNpubCashUserInfo,
|
||||||
@@ -111,6 +119,10 @@ export function CashuWallet() {
|
|||||||
setLightningAddressAmount,
|
setLightningAddressAmount,
|
||||||
pendingLightningAddress,
|
pendingLightningAddress,
|
||||||
setPendingLightningAddress,
|
setPendingLightningAddress,
|
||||||
|
decodedInvoiceAmount,
|
||||||
|
setDecodedInvoiceAmount,
|
||||||
|
pendingInvoice,
|
||||||
|
setPendingInvoice,
|
||||||
sentToken,
|
sentToken,
|
||||||
setSentToken,
|
setSentToken,
|
||||||
sentTokenQRCode,
|
sentTokenQRCode,
|
||||||
@@ -120,6 +132,7 @@ export function CashuWallet() {
|
|||||||
setCurrentInvoice,
|
setCurrentInvoice,
|
||||||
handleReceive,
|
handleReceive,
|
||||||
handleSend,
|
handleSend,
|
||||||
|
handleConfirmInvoicePayment,
|
||||||
mintQuoteUnsubscribeRef,
|
mintQuoteUnsubscribeRef,
|
||||||
} = useWalletTransactions({
|
} = useWalletTransactions({
|
||||||
coco,
|
coco,
|
||||||
@@ -147,7 +160,7 @@ export function CashuWallet() {
|
|||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
const [showSats, setShowSats] = useState(true);
|
const [showSats, setShowSats] = useState(true);
|
||||||
const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens');
|
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
|
||||||
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
|
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
|
||||||
const [proofBreakdown, setProofBreakdown] = useState<{
|
const [proofBreakdown, setProofBreakdown] = useState<{
|
||||||
mintUrl: string;
|
mintUrl: string;
|
||||||
@@ -163,14 +176,146 @@ export function CashuWallet() {
|
|||||||
const [showReceiveModal, setShowReceiveModal] = useState(false);
|
const [showReceiveModal, setShowReceiveModal] = useState(false);
|
||||||
const [showHistoryModal, setShowHistoryModal] = useState(false);
|
const [showHistoryModal, setShowHistoryModal] = useState(false);
|
||||||
|
|
||||||
|
// Bitcoin state
|
||||||
|
const [bitcoinAmount, setBitcoinAmount] = useState('');
|
||||||
|
const [bitcoinRecipient, setBitcoinRecipient] = useState('');
|
||||||
|
const [pendingBitcoinRecipient, setPendingBitcoinRecipient] = useState<string | null>(null);
|
||||||
|
const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false);
|
||||||
|
const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState('');
|
||||||
|
|
||||||
|
// Handle drawer close with state reset
|
||||||
|
const handleSendDrawerClose = (open: boolean) => {
|
||||||
|
setShowSendModal(open);
|
||||||
|
if (!open) {
|
||||||
|
// Reset all send-related state when drawer closes
|
||||||
|
setSendAmount('');
|
||||||
|
setLightningInvoice('');
|
||||||
|
setLightningAddressInput('');
|
||||||
|
setLightningAddressAmount('');
|
||||||
|
setPendingLightningAddress(null);
|
||||||
|
setDecodedInvoiceAmount(null);
|
||||||
|
setPendingInvoice(null);
|
||||||
|
// Reset Bitcoin state
|
||||||
|
setBitcoinAmount('');
|
||||||
|
setBitcoinRecipient('');
|
||||||
|
setPendingBitcoinRecipient(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleReceiveDrawerClose = (open: boolean) => {
|
||||||
|
setShowReceiveModal(open);
|
||||||
|
if (!open) {
|
||||||
|
// Reset all receive-related state when drawer closes
|
||||||
|
setTokenInput('');
|
||||||
|
setQuoteAmount('');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Ref to track if we've fetched npub.cash user info
|
// Ref to track if we've fetched npub.cash user info
|
||||||
const hasCheckedNpubCashRef = useRef(false);
|
const hasCheckedNpubCashRef = useRef(false);
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// BITCOIN HANDLERS
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
const handleBitcoinSend = async () => {
|
||||||
|
if (!hasNsecAccess || !bitcoinAmount || !pendingBitcoinRecipient || !bitcoinAddress) {
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Bitcoin Send Error",
|
||||||
|
description: "Missing required information for Bitcoin transaction",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const privateKey = getPrivateKey();
|
||||||
|
if (!privateKey) {
|
||||||
|
throw new Error('Unable to access private key');
|
||||||
|
}
|
||||||
|
|
||||||
|
const amountSats = parseInt(bitcoinAmount);
|
||||||
|
if (isNaN(amountSats) || amountSats <= 0) {
|
||||||
|
throw new Error('Invalid amount');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine if the recipient is a Bitcoin address or npub
|
||||||
|
let recipientAddress: string;
|
||||||
|
if (pendingBitcoinRecipient.startsWith('bc1') || pendingBitcoinRecipient.startsWith('1') || pendingBitcoinRecipient.startsWith('3')) {
|
||||||
|
// It's already a Bitcoin address
|
||||||
|
recipientAddress = pendingBitcoinRecipient;
|
||||||
|
} else if (pendingBitcoinRecipient.startsWith('npub')) {
|
||||||
|
// It's an npub, convert to Bitcoin address
|
||||||
|
recipientAddress = npubToBitcoinAddress(pendingBitcoinRecipient);
|
||||||
|
} else {
|
||||||
|
// Assume it's a hex pubkey
|
||||||
|
recipientAddress = nostrPubkeyToBitcoinAddress(pendingBitcoinRecipient);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch UTXOs and fee rates
|
||||||
|
const [utxos, feeRates] = await Promise.all([
|
||||||
|
fetchUTXOs(bitcoinAddress),
|
||||||
|
getFeeRates()
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Create and sign transaction
|
||||||
|
const { txHex, fee } = await createBitcoinTransaction(
|
||||||
|
privateKey,
|
||||||
|
recipientAddress,
|
||||||
|
amountSats,
|
||||||
|
utxos,
|
||||||
|
feeRates.fastestFee
|
||||||
|
);
|
||||||
|
|
||||||
|
// Broadcast transaction
|
||||||
|
const txId = await broadcastTransaction(txHex);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Bitcoin Sent!",
|
||||||
|
description: `Transaction ${txId.slice(0, 8)}... confirmed`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Reset form and refresh balance
|
||||||
|
setBitcoinAmount('');
|
||||||
|
setBitcoinRecipient('');
|
||||||
|
setPendingBitcoinRecipient(null);
|
||||||
|
refetchBitcoinBalance();
|
||||||
|
setShowSendModal(false);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Bitcoin send error:', error);
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Bitcoin Send Failed",
|
||||||
|
description: error instanceof Error ? error.message : 'Unknown error occurred',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleBitcoinReceive = async () => {
|
||||||
|
if (!bitcoinAddress) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const qr = await generateQRCode(bitcoinAddress);
|
||||||
|
setBitcoinAddressQRCode(qr);
|
||||||
|
setShowBitcoinAddressQR(true);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('QR generation error:', error);
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "QR Code Error",
|
||||||
|
description: "Failed to generate QR code",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// COMPUTED VALUES
|
// COMPUTED VALUES
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
|
const totalBalance: number = mode === 'bitcoin'
|
||||||
|
? (bitcoinBalanceData?.balance || 0)
|
||||||
|
: (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// EFFECTS - Error Handling
|
// EFFECTS - Error Handling
|
||||||
@@ -293,6 +438,10 @@ export function CashuWallet() {
|
|||||||
setLightningAddressQRCode(qr);
|
setLightningAddressQRCode(qr);
|
||||||
setShowLightningAddressQR(true);
|
setShowLightningAddressQR(true);
|
||||||
}}
|
}}
|
||||||
|
onShowBitcoinAddressQR={(qr) => {
|
||||||
|
setBitcoinAddressQRCode(qr);
|
||||||
|
setShowBitcoinAddressQR(true);
|
||||||
|
}}
|
||||||
generateQRCode={generateQRCode}
|
generateQRCode={generateQRCode}
|
||||||
// MintSelector props
|
// MintSelector props
|
||||||
activeMintUrl={activeMintUrl}
|
activeMintUrl={activeMintUrl}
|
||||||
@@ -374,8 +523,8 @@ export function CashuWallet() {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Bottom Drawer Modals */}
|
{/* Bottom Drawer Modals */}
|
||||||
<Drawer open={showSendModal} onOpenChange={setShowSendModal}>
|
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
|
||||||
<DrawerContent className="h-[50vh] max-w-4xl mx-auto">
|
<DrawerContent className="h-[40vh] max-w-4xl mx-auto">
|
||||||
<DrawerHeader>
|
<DrawerHeader>
|
||||||
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
|
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
|
||||||
</DrawerHeader>
|
</DrawerHeader>
|
||||||
@@ -393,28 +542,49 @@ export function CashuWallet() {
|
|||||||
setLightningAddressAmount={setLightningAddressAmount}
|
setLightningAddressAmount={setLightningAddressAmount}
|
||||||
pendingLightningAddress={pendingLightningAddress}
|
pendingLightningAddress={pendingLightningAddress}
|
||||||
setPendingLightningAddress={setPendingLightningAddress}
|
setPendingLightningAddress={setPendingLightningAddress}
|
||||||
|
decodedInvoiceAmount={decodedInvoiceAmount}
|
||||||
|
setDecodedInvoiceAmount={setDecodedInvoiceAmount}
|
||||||
|
pendingInvoice={pendingInvoice}
|
||||||
|
setPendingInvoice={setPendingInvoice}
|
||||||
tokenInput=""
|
tokenInput=""
|
||||||
setTokenInput={() => {}}
|
setTokenInput={() => {}}
|
||||||
quoteAmount=""
|
quoteAmount=""
|
||||||
setQuoteAmount={() => {}}
|
setQuoteAmount={() => {}}
|
||||||
activeMintUrl={activeMintUrl}
|
activeMintUrl={activeMintUrl}
|
||||||
onSend={() => {
|
onSend={() => {
|
||||||
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
|
if (mode === 'bitcoin') {
|
||||||
handleSend();
|
handleBitcoinSend();
|
||||||
if (mode === 'tokens' || wasPendingBefore) {
|
} else {
|
||||||
setShowSendModal(false);
|
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
|
||||||
|
handleSend();
|
||||||
|
if (mode === 'tokens' || wasPendingBefore) {
|
||||||
|
setShowSendModal(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
onReceive={() => {}}
|
onReceive={() => {}}
|
||||||
|
onConfirmInvoice={() => {
|
||||||
|
handleConfirmInvoicePayment();
|
||||||
|
setShowSendModal(false);
|
||||||
|
}}
|
||||||
isResolvingAddress={isResolvingAddress}
|
isResolvingAddress={isResolvingAddress}
|
||||||
isLoading={isLoading || isNpubCashLoading}
|
isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading}
|
||||||
|
// Bitcoin props
|
||||||
|
bitcoinAddress={bitcoinAddress || ''}
|
||||||
|
bitcoinAmount={bitcoinAmount}
|
||||||
|
setBitcoinAmount={setBitcoinAmount}
|
||||||
|
bitcoinRecipient={bitcoinRecipient}
|
||||||
|
setBitcoinRecipient={setBitcoinRecipient}
|
||||||
|
pendingBitcoinRecipient={pendingBitcoinRecipient}
|
||||||
|
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
|
||||||
|
hasNsecAccess={hasNsecAccess}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</DrawerContent>
|
</DrawerContent>
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|
||||||
<Drawer open={showReceiveModal} onOpenChange={setShowReceiveModal}>
|
<Drawer open={showReceiveModal} onOpenChange={handleReceiveDrawerClose}>
|
||||||
<DrawerContent className="h-[50vh] max-w-4xl mx-auto">
|
<DrawerContent className="h-[40vh] max-w-4xl mx-auto">
|
||||||
<DrawerHeader>
|
<DrawerHeader>
|
||||||
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
|
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
|
||||||
</DrawerHeader>
|
</DrawerHeader>
|
||||||
@@ -432,6 +602,10 @@ export function CashuWallet() {
|
|||||||
setLightningAddressAmount={() => {}}
|
setLightningAddressAmount={() => {}}
|
||||||
pendingLightningAddress={null}
|
pendingLightningAddress={null}
|
||||||
setPendingLightningAddress={() => {}}
|
setPendingLightningAddress={() => {}}
|
||||||
|
decodedInvoiceAmount={null}
|
||||||
|
setDecodedInvoiceAmount={() => {}}
|
||||||
|
pendingInvoice={null}
|
||||||
|
setPendingInvoice={() => {}}
|
||||||
tokenInput={tokenInput}
|
tokenInput={tokenInput}
|
||||||
setTokenInput={setTokenInput}
|
setTokenInput={setTokenInput}
|
||||||
quoteAmount={quoteAmount}
|
quoteAmount={quoteAmount}
|
||||||
@@ -439,22 +613,36 @@ export function CashuWallet() {
|
|||||||
activeMintUrl={activeMintUrl}
|
activeMintUrl={activeMintUrl}
|
||||||
onSend={() => {}}
|
onSend={() => {}}
|
||||||
onReceive={() => {
|
onReceive={() => {
|
||||||
handleReceive();
|
if (mode === 'bitcoin') {
|
||||||
setShowReceiveModal(false);
|
handleBitcoinReceive();
|
||||||
|
setShowReceiveModal(false);
|
||||||
|
} else {
|
||||||
|
handleReceive();
|
||||||
|
setShowReceiveModal(false);
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
isResolvingAddress={false}
|
isResolvingAddress={false}
|
||||||
isLoading={isLoading || isNpubCashLoading}
|
isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading}
|
||||||
|
// Bitcoin props
|
||||||
|
bitcoinAddress={bitcoinAddress || ''}
|
||||||
|
bitcoinAmount=""
|
||||||
|
setBitcoinAmount={() => {}}
|
||||||
|
bitcoinRecipient=""
|
||||||
|
setBitcoinRecipient={() => {}}
|
||||||
|
pendingBitcoinRecipient={null}
|
||||||
|
setPendingBitcoinRecipient={() => {}}
|
||||||
|
hasNsecAccess={hasNsecAccess}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</DrawerContent>
|
</DrawerContent>
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|
||||||
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
|
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
|
||||||
<DrawerContent className="max-h-[90vh] max-w-4xl mx-auto">
|
<DrawerContent className="max-h-[80vh] max-w-4xl mx-auto">
|
||||||
<DrawerHeader>
|
<DrawerHeader>
|
||||||
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
|
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
|
||||||
</DrawerHeader>
|
</DrawerHeader>
|
||||||
<ScrollArea className="h-[90vh] px-4 pb-4">
|
<ScrollArea className="h-[80vh] px-4 pb-4">
|
||||||
<TransactionHistory
|
<TransactionHistory
|
||||||
entries={historyEntries}
|
entries={historyEntries}
|
||||||
isLoading={isLoadingHistory}
|
isLoading={isLoadingHistory}
|
||||||
@@ -462,6 +650,17 @@ export function CashuWallet() {
|
|||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
</DrawerContent>
|
</DrawerContent>
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|
||||||
|
{/* Bitcoin Address QR Modal */}
|
||||||
|
<QRModal
|
||||||
|
isOpen={showBitcoinAddressQR}
|
||||||
|
onClose={() => setShowBitcoinAddressQR(false)}
|
||||||
|
title="Bitcoin Address"
|
||||||
|
description="Scan this QR code to send Bitcoin to your address"
|
||||||
|
qrCodeUrl={bitcoinAddressQRCode}
|
||||||
|
content={bitcoinAddress || ''}
|
||||||
|
icon="qr"
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -93,49 +93,51 @@ export function MintSelector({
|
|||||||
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
|
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none">
|
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none max-h-[200px] overflow-hidden">
|
||||||
{mints
|
<div className="max-h-[120px] overflow-y-auto">
|
||||||
.filter((mint) => mint.url)
|
{mints
|
||||||
.map((mint, index) => {
|
.filter((mint) => mint.url)
|
||||||
const isActive = activeMintUrl === mint.url;
|
.map((mint, index) => {
|
||||||
const balance = balances[mint.url] || 0;
|
const isActive = activeMintUrl === mint.url;
|
||||||
|
const balance = balances[mint.url] || 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
key={`mint-${mint.url || `unknown-${index}`}`}
|
key={`mint-${mint.url || `unknown-${index}`}`}
|
||||||
onClick={() => setActiveMintUrl(mint.url)}
|
onClick={() => setActiveMintUrl(mint.url)}
|
||||||
className="flex items-center justify-between p-3 text-base"
|
className="flex items-center justify-between p-3 text-base"
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-3 flex-1 min-w-0">
|
<div className="flex items-center gap-3 flex-1 min-w-0">
|
||||||
{isActive && (
|
{isActive && (
|
||||||
<div className="flex-shrink-0">
|
<div className="flex-shrink-0">
|
||||||
<Check className="h-5 w-5 text-primary" />
|
<Check className="h-5 w-5 text-primary" />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="font-medium truncate">
|
<div className="font-medium truncate">
|
||||||
{getCleanMintLabel(mint)}
|
{getCleanMintLabel(mint)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div className="flex items-center gap-2 flex-shrink-0">
|
||||||
<div className="flex items-center gap-2 flex-shrink-0">
|
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
|
||||||
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
|
{formatBalance(balance)}
|
||||||
{formatBalance(balance)}
|
</span>
|
||||||
</span>
|
<button
|
||||||
<button
|
onClick={(e) => {
|
||||||
onClick={(e) => {
|
e.stopPropagation();
|
||||||
e.stopPropagation();
|
onRemoveMint(mint);
|
||||||
onRemoveMint(mint);
|
}}
|
||||||
}}
|
className="p-1 rounded hover:bg-destructive hover:text-destructive-foreground transition-colors"
|
||||||
className="p-1 rounded hover:bg-destructive hover:text-destructive-foreground transition-colors"
|
title="Remove mint"
|
||||||
title="Remove mint"
|
>
|
||||||
>
|
<X className="h-4 w-4" />
|
||||||
<X className="h-4 w-4" />
|
</button>
|
||||||
</button>
|
</div>
|
||||||
</div>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuItem>
|
);
|
||||||
);
|
})}
|
||||||
})}
|
</div>
|
||||||
{mints.length > 0 && <DropdownMenuSeparator />}
|
{mints.length > 0 && <DropdownMenuSeparator />}
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<div className="flex gap-2 p-2">
|
<div className="flex gap-2 p-2">
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Send, Download, Zap, Loader2, X } from 'lucide-react';
|
import { Slider } from '@/components/ui/slider';
|
||||||
|
import { Send, Download, ArrowRight, Zap, Loader2, X } from 'lucide-react';
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
interface TransactionCardProps {
|
interface TransactionCardProps {
|
||||||
mode: 'tokens' | 'lightning';
|
mode: 'tokens' | 'lightning' | 'bitcoin';
|
||||||
operation: 'send' | 'receive';
|
operation: 'send' | 'receive';
|
||||||
// Send props
|
// Send props
|
||||||
sendAmount: string;
|
sendAmount: string;
|
||||||
@@ -16,6 +18,10 @@ interface TransactionCardProps {
|
|||||||
setLightningAddressAmount: (value: string) => void;
|
setLightningAddressAmount: (value: string) => void;
|
||||||
pendingLightningAddress: string | null;
|
pendingLightningAddress: string | null;
|
||||||
setPendingLightningAddress: (value: string | null) => void;
|
setPendingLightningAddress: (value: string | null) => void;
|
||||||
|
decodedInvoiceAmount: number | null;
|
||||||
|
setDecodedInvoiceAmount: (value: number | null) => void;
|
||||||
|
pendingInvoice: string | null;
|
||||||
|
setPendingInvoice: (value: string | null) => void;
|
||||||
// Receive props
|
// Receive props
|
||||||
tokenInput: string;
|
tokenInput: string;
|
||||||
setTokenInput: (value: string) => void;
|
setTokenInput: (value: string) => void;
|
||||||
@@ -25,8 +31,18 @@ interface TransactionCardProps {
|
|||||||
activeMintUrl: string | null;
|
activeMintUrl: string | null;
|
||||||
onSend: () => void;
|
onSend: () => void;
|
||||||
onReceive: () => void;
|
onReceive: () => void;
|
||||||
|
onConfirmInvoice?: () => void;
|
||||||
isResolvingAddress: boolean;
|
isResolvingAddress: boolean;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
|
// Bitcoin props
|
||||||
|
bitcoinAddress?: string;
|
||||||
|
bitcoinAmount?: string;
|
||||||
|
setBitcoinAmount?: (value: string) => void;
|
||||||
|
bitcoinRecipient?: string;
|
||||||
|
setBitcoinRecipient?: (value: string) => void;
|
||||||
|
pendingBitcoinRecipient?: string | null;
|
||||||
|
setPendingBitcoinRecipient?: (value: string | null) => void;
|
||||||
|
hasNsecAccess?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TransactionCard({
|
export function TransactionCard({
|
||||||
@@ -42,6 +58,10 @@ export function TransactionCard({
|
|||||||
setLightningAddressAmount,
|
setLightningAddressAmount,
|
||||||
pendingLightningAddress,
|
pendingLightningAddress,
|
||||||
setPendingLightningAddress,
|
setPendingLightningAddress,
|
||||||
|
decodedInvoiceAmount,
|
||||||
|
setDecodedInvoiceAmount,
|
||||||
|
pendingInvoice,
|
||||||
|
setPendingInvoice,
|
||||||
tokenInput,
|
tokenInput,
|
||||||
setTokenInput,
|
setTokenInput,
|
||||||
quoteAmount,
|
quoteAmount,
|
||||||
@@ -49,9 +69,90 @@ export function TransactionCard({
|
|||||||
activeMintUrl,
|
activeMintUrl,
|
||||||
onSend,
|
onSend,
|
||||||
onReceive,
|
onReceive,
|
||||||
|
onConfirmInvoice,
|
||||||
isResolvingAddress,
|
isResolvingAddress,
|
||||||
isLoading,
|
isLoading,
|
||||||
|
bitcoinAddress,
|
||||||
|
bitcoinAmount,
|
||||||
|
setBitcoinAmount,
|
||||||
|
bitcoinRecipient,
|
||||||
|
setBitcoinRecipient,
|
||||||
|
pendingBitcoinRecipient,
|
||||||
|
setPendingBitcoinRecipient,
|
||||||
|
hasNsecAccess,
|
||||||
}: TransactionCardProps) {
|
}: TransactionCardProps) {
|
||||||
|
// Slider state for confirmation
|
||||||
|
const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]);
|
||||||
|
const [addressSliderValue, setAddressSliderValue] = useState([0]);
|
||||||
|
const [bitcoinSliderValue, setBitcoinSliderValue] = useState([0]);
|
||||||
|
|
||||||
|
// State to track which slider is being actively held
|
||||||
|
const [activeSlider, setActiveSlider] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Handle slider value changes and auto-submit at 100%
|
||||||
|
const handleInvoiceSliderChange = (value: number[]) => {
|
||||||
|
setInvoiceSliderValue(value);
|
||||||
|
if (value[0] === 100 && onConfirmInvoice) {
|
||||||
|
onConfirmInvoice();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddressSliderChange = (value: number[]) => {
|
||||||
|
setAddressSliderValue(value);
|
||||||
|
if (value[0] === 100) {
|
||||||
|
onSend();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleBitcoinSliderChange = (value: number[]) => {
|
||||||
|
setBitcoinSliderValue(value);
|
||||||
|
if (value[0] === 100) {
|
||||||
|
onSend();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Reset sliders when states change
|
||||||
|
const resetSliders = () => {
|
||||||
|
setInvoiceSliderValue([0]);
|
||||||
|
setAddressSliderValue([0]);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle slider release (reset on mouse/touch up)
|
||||||
|
const handleSliderMouseUp = (sliderId: string) => {
|
||||||
|
setActiveSlider(null);
|
||||||
|
// Reset the slider if it hasn't reached 100
|
||||||
|
if (sliderId === 'invoice' && invoiceSliderValue[0] !== 100) {
|
||||||
|
setInvoiceSliderValue([0]);
|
||||||
|
} else if (sliderId === 'address' && addressSliderValue[0] !== 100) {
|
||||||
|
setAddressSliderValue([0]);
|
||||||
|
} else if (sliderId === 'bitcoin' && bitcoinSliderValue[0] !== 100) {
|
||||||
|
setBitcoinSliderValue([0]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSliderMouseDown = (sliderId: string) => {
|
||||||
|
setActiveSlider(sliderId);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Reset sliders when pending states change
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pendingInvoice) {
|
||||||
|
setInvoiceSliderValue([0]);
|
||||||
|
}
|
||||||
|
}, [pendingInvoice]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pendingLightningAddress) {
|
||||||
|
setAddressSliderValue([0]);
|
||||||
|
}
|
||||||
|
}, [pendingLightningAddress]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!pendingBitcoinRecipient) {
|
||||||
|
setBitcoinSliderValue([0]);
|
||||||
|
}
|
||||||
|
}, [pendingBitcoinRecipient]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
{/* Title */}
|
{/* Title */}
|
||||||
@@ -60,23 +161,58 @@ export function TransactionCard({
|
|||||||
{operation === 'send' ? (
|
{operation === 'send' ? (
|
||||||
mode === 'tokens'
|
mode === 'tokens'
|
||||||
? 'Generate Cashu token to send'
|
? 'Generate Cashu token to send'
|
||||||
: pendingLightningAddress ? (
|
: mode === 'bitcoin' && !pendingBitcoinRecipient
|
||||||
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
|
? 'Send Bitcoin on-chain'
|
||||||
<span className="font-bold text-primary">Sending to:</span>{' '}
|
: mode === 'bitcoin' && pendingBitcoinRecipient
|
||||||
<span className="font-semibold text-foreground">{pendingLightningAddress}</span>
|
? ''
|
||||||
</span>
|
: pendingInvoice && decodedInvoiceAmount ? (
|
||||||
|
<div className="flex items-center justify-center gap-2">
|
||||||
|
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
|
||||||
|
<span className="font-bold text-primary">Sending:</span>{' '}
|
||||||
|
<span className="font-semibold text-foreground">{decodedInvoiceAmount} sats</span>
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setPendingInvoice(null);
|
||||||
|
setDecodedInvoiceAmount(null);
|
||||||
|
}}
|
||||||
|
className="p-1.5 rounded-full hover:bg-muted transition-colors"
|
||||||
|
title="Cancel"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : pendingLightningAddress ? (
|
||||||
|
<div className="flex items-center justify-center gap-2">
|
||||||
|
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
|
||||||
|
<span className="font-bold text-primary">Sending:</span>{' '}
|
||||||
|
<span className="font-semibold text-foreground">{pendingLightningAddress}</span>
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setPendingLightningAddress(null);
|
||||||
|
setLightningAddressAmount('');
|
||||||
|
}}
|
||||||
|
className="p-1.5 rounded-full hover:bg-muted transition-colors"
|
||||||
|
title="Cancel"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
) : 'Pay invoices or addresses'
|
) : 'Pay invoices or addresses'
|
||||||
) : (
|
) : (
|
||||||
mode === 'tokens'
|
mode === 'tokens'
|
||||||
? 'Enter Cashu token to redeem'
|
? 'Enter Cashu token to redeem'
|
||||||
|
: mode === 'bitcoin'
|
||||||
|
? 'Receive Bitcoin on-chain'
|
||||||
: 'Deposit funds with Lightning'
|
: 'Deposit funds with Lightning'
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Content */}
|
{/* Content */}
|
||||||
<div className="space-y-4">
|
<div className="space-y-8">
|
||||||
{!activeMintUrl && (
|
{!activeMintUrl && mode !== 'bitcoin' && (
|
||||||
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
|
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
|
||||||
{operation === 'send'
|
{operation === 'send'
|
||||||
? (mode === 'tokens' ? 'Select a mint to send tokens' : 'Select a mint to pay Lightning invoices')
|
? (mode === 'tokens' ? 'Select a mint to send tokens' : 'Select a mint to pay Lightning invoices')
|
||||||
@@ -87,9 +223,105 @@ export function TransactionCard({
|
|||||||
|
|
||||||
{operation === 'send' ? (
|
{operation === 'send' ? (
|
||||||
// Send Mode
|
// Send Mode
|
||||||
mode === 'tokens' ? (
|
mode === 'bitcoin' ? (
|
||||||
|
// Bitcoin Send
|
||||||
|
<div className="space-y-8">
|
||||||
|
{!hasNsecAccess ? (
|
||||||
|
<div className="flex justify-center items-center h-32">
|
||||||
|
<div className="text-sm text-destructive bg-destructive/10 border border-destructive/20 p-3 rounded text-center">
|
||||||
|
⚠️ Login with nsec required to send Bitcoin
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : pendingBitcoinRecipient ? (
|
||||||
|
// Step 2: Amount Input with Slider
|
||||||
|
<div className="space-y-8">
|
||||||
|
<div className="flex items-center justify-center gap-2">
|
||||||
|
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
|
||||||
|
<span className="font-bold text-primary">Sending to:</span>{' '}
|
||||||
|
<span className="font-semibold text-foreground">{pendingBitcoinRecipient}</span>
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setPendingBitcoinRecipient?.(null);
|
||||||
|
setBitcoinAmount?.('');
|
||||||
|
}}
|
||||||
|
className="p-1.5 rounded-full hover:bg-muted transition-colors"
|
||||||
|
title="Cancel"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
placeholder="Amount (sats)"
|
||||||
|
type="number"
|
||||||
|
value={bitcoinAmount || ''}
|
||||||
|
onChange={(e) => setBitcoinAmount?.(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' && bitcoinAmount && pendingBitcoinRecipient && !isLoading) {
|
||||||
|
onSend();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
|
||||||
|
/>
|
||||||
|
<div className="mt-6">
|
||||||
|
<div className="relative w-full">
|
||||||
|
<div
|
||||||
|
onMouseDown={() => handleSliderMouseDown('bitcoin')}
|
||||||
|
onMouseUp={() => handleSliderMouseUp('bitcoin')}
|
||||||
|
onMouseLeave={() => handleSliderMouseUp('bitcoin')}
|
||||||
|
onTouchEnd={() => handleSliderMouseUp('bitcoin')}
|
||||||
|
>
|
||||||
|
<Slider
|
||||||
|
value={bitcoinSliderValue}
|
||||||
|
onValueChange={handleBitcoinSliderChange}
|
||||||
|
max={100}
|
||||||
|
step={1}
|
||||||
|
className="w-full h-12"
|
||||||
|
disabled={!bitcoinAmount || isLoading}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||||
|
<span className="text-sm font-medium text-muted-foreground">
|
||||||
|
{bitcoinSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
// Step 1: Recipient Input
|
||||||
|
<div className="space-y-8">
|
||||||
|
<Input
|
||||||
|
placeholder="Bitcoin address or npub..."
|
||||||
|
value={bitcoinRecipient || ''}
|
||||||
|
onChange={(e) => setBitcoinRecipient?.(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' && bitcoinRecipient && !isLoading) {
|
||||||
|
setPendingBitcoinRecipient?.(bitcoinRecipient);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
||||||
|
/>
|
||||||
|
<div className="flex justify-center mt-6">
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
if (bitcoinRecipient) {
|
||||||
|
setPendingBitcoinRecipient?.(bitcoinRecipient);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={!bitcoinRecipient || isLoading}
|
||||||
|
className="h-12 px-12 rounded-full"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
<ArrowRight className="h-5 w-5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : mode === 'tokens' ? (
|
||||||
// Cashu Token Send
|
// Cashu Token Send
|
||||||
<div className="space-y-3">
|
<div className="space-y-8">
|
||||||
<Input
|
<Input
|
||||||
placeholder="Amount (sats)"
|
placeholder="Amount (sats)"
|
||||||
type="number"
|
type="number"
|
||||||
@@ -103,7 +335,7 @@ export function TransactionCard({
|
|||||||
disabled={!activeMintUrl}
|
disabled={!activeMintUrl}
|
||||||
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
|
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
|
||||||
/>
|
/>
|
||||||
<div className="flex justify-center mt-4">
|
<div className="flex justify-center mt-6">
|
||||||
<Button
|
<Button
|
||||||
onClick={onSend}
|
onClick={onSend}
|
||||||
disabled={!sendAmount || !activeMintUrl || isLoading}
|
disabled={!sendAmount || !activeMintUrl || isLoading}
|
||||||
@@ -114,9 +346,37 @@ export function TransactionCard({
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
) : pendingInvoice && decodedInvoiceAmount ? (
|
||||||
|
// Lightning Invoice Confirmation (with slider)
|
||||||
|
<div className="space-y-8">
|
||||||
|
<div className="mt-6">
|
||||||
|
<div className="relative">
|
||||||
|
<div
|
||||||
|
onMouseDown={() => handleSliderMouseDown('invoice')}
|
||||||
|
onMouseUp={() => handleSliderMouseUp('invoice')}
|
||||||
|
onMouseLeave={() => handleSliderMouseUp('invoice')}
|
||||||
|
onTouchEnd={() => handleSliderMouseUp('invoice')}
|
||||||
|
>
|
||||||
|
<Slider
|
||||||
|
value={invoiceSliderValue}
|
||||||
|
onValueChange={handleInvoiceSliderChange}
|
||||||
|
max={100}
|
||||||
|
step={1}
|
||||||
|
className="w-full h-12"
|
||||||
|
disabled={!activeMintUrl || isLoading}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||||
|
<span className="text-sm font-medium text-muted-foreground">
|
||||||
|
{invoiceSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
) : pendingLightningAddress ? (
|
) : pendingLightningAddress ? (
|
||||||
// Lightning Address Amount Input
|
// Lightning Address Amount Input with Slider
|
||||||
<div className="space-y-3">
|
<div className="space-y-8">
|
||||||
<Input
|
<Input
|
||||||
placeholder="Amount (sats)"
|
placeholder="Amount (sats)"
|
||||||
type="number"
|
type="number"
|
||||||
@@ -130,36 +390,34 @@ export function TransactionCard({
|
|||||||
disabled={!activeMintUrl}
|
disabled={!activeMintUrl}
|
||||||
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
|
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
|
||||||
/>
|
/>
|
||||||
<div className="flex justify-center gap-2 mt-4">
|
<div className="mt-6">
|
||||||
<Button
|
<div className="relative w-full">
|
||||||
onClick={onSend}
|
<div
|
||||||
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
|
onMouseDown={() => handleSliderMouseDown('address')}
|
||||||
className="h-12 px-12 rounded-full"
|
onMouseUp={() => handleSliderMouseUp('address')}
|
||||||
size="lg"
|
onMouseLeave={() => handleSliderMouseUp('address')}
|
||||||
>
|
onTouchEnd={() => handleSliderMouseUp('address')}
|
||||||
{isResolvingAddress ? (
|
>
|
||||||
<Loader2 className="h-5 w-5 animate-spin" />
|
<Slider
|
||||||
) : (
|
value={addressSliderValue}
|
||||||
<Zap className="h-5 w-5" />
|
onValueChange={handleAddressSliderChange}
|
||||||
)}
|
max={100}
|
||||||
</Button>
|
step={1}
|
||||||
<Button
|
className="w-full h-12"
|
||||||
variant="outline"
|
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
|
||||||
size="icon"
|
/>
|
||||||
onClick={() => {
|
</div>
|
||||||
setPendingLightningAddress(null);
|
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||||
setLightningAddressAmount('');
|
<span className="text-sm font-medium text-muted-foreground">
|
||||||
}}
|
{addressSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
|
||||||
className="h-12 w-12 rounded-full"
|
</span>
|
||||||
title="Cancel"
|
</div>
|
||||||
>
|
</div>
|
||||||
<X className="h-5 w-5" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
// Lightning Invoice/Address Input
|
// Lightning Invoice/Address Input
|
||||||
<div className="space-y-3">
|
<div className="space-y-8">
|
||||||
<Input
|
<Input
|
||||||
placeholder="lnbc... or [email protected]"
|
placeholder="lnbc... or [email protected]"
|
||||||
value={lightningInvoice || lightningAddressInput}
|
value={lightningInvoice || lightningAddressInput}
|
||||||
@@ -181,23 +439,42 @@ export function TransactionCard({
|
|||||||
disabled={!activeMintUrl}
|
disabled={!activeMintUrl}
|
||||||
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
||||||
/>
|
/>
|
||||||
<div className="flex justify-center mt-4">
|
<div className="flex justify-center mt-6">
|
||||||
<Button
|
<Button
|
||||||
onClick={onSend}
|
onClick={onSend}
|
||||||
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
|
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
|
||||||
className="h-12 px-12 rounded-full"
|
className="h-12 px-12 rounded-full"
|
||||||
size="lg"
|
size="lg"
|
||||||
>
|
>
|
||||||
<Zap className="h-5 w-5" />
|
<ArrowRight className="h-5 w-5" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
) : (
|
) : (
|
||||||
// Receive Mode
|
// Receive Mode
|
||||||
mode === 'tokens' ? (
|
mode === 'bitcoin' ? (
|
||||||
|
// Bitcoin Receive
|
||||||
|
<div className="space-y-8">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="font-mono text-sm bg-muted p-3 rounded border break-all">
|
||||||
|
{bitcoinAddress}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-center mt-6">
|
||||||
|
<Button
|
||||||
|
onClick={onReceive}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="h-12 px-12 rounded-full"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
<Download className="h-5 w-5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : mode === 'tokens' ? (
|
||||||
// Cashu Token Receive
|
// Cashu Token Receive
|
||||||
<div className="space-y-3">
|
<div className="space-y-8">
|
||||||
<Input
|
<Input
|
||||||
placeholder="cashuBo2Ft..."
|
placeholder="cashuBo2Ft..."
|
||||||
value={tokenInput}
|
value={tokenInput}
|
||||||
@@ -210,7 +487,7 @@ export function TransactionCard({
|
|||||||
disabled={!activeMintUrl}
|
disabled={!activeMintUrl}
|
||||||
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
||||||
/>
|
/>
|
||||||
<div className="flex justify-center mt-4">
|
<div className="flex justify-center mt-6">
|
||||||
<Button
|
<Button
|
||||||
onClick={onReceive}
|
onClick={onReceive}
|
||||||
disabled={!tokenInput.trim() || !activeMintUrl || isLoading}
|
disabled={!tokenInput.trim() || !activeMintUrl || isLoading}
|
||||||
@@ -223,7 +500,7 @@ export function TransactionCard({
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
// Lightning Invoice Receive
|
// Lightning Invoice Receive
|
||||||
<div className="space-y-3">
|
<div className="space-y-8">
|
||||||
<Input
|
<Input
|
||||||
placeholder="Amount (sats)"
|
placeholder="Amount (sats)"
|
||||||
type="number"
|
type="number"
|
||||||
@@ -237,7 +514,7 @@ export function TransactionCard({
|
|||||||
disabled={!activeMintUrl}
|
disabled={!activeMintUrl}
|
||||||
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
|
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
|
||||||
/>
|
/>
|
||||||
<div className="flex justify-center mt-4">
|
<div className="flex justify-center mt-6">
|
||||||
<Button
|
<Button
|
||||||
onClick={onReceive}
|
onClick={onReceive}
|
||||||
disabled={!quoteAmount || !activeMintUrl || isLoading}
|
disabled={!quoteAmount || !activeMintUrl || isLoading}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { nip19 } from 'nostr-tools';
|
import { nip19 } from 'nostr-tools';
|
||||||
import { Zap, Coins, Copy, Check, QrCode } from 'lucide-react';
|
import { Zap, Coins, Copy, Check, QrCode, Link } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { exchangeRateService } from '@/lib/exchangeRateService';
|
import { exchangeRateService } from '@/lib/exchangeRateService';
|
||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { LoginIcon } from '@/components/auth/LoginIcon';
|
import { LoginIcon } from '@/components/auth/LoginIcon';
|
||||||
import { MintSelector } from './MintSelector';
|
import { MintSelector } from './MintSelector';
|
||||||
|
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
|
||||||
|
|
||||||
interface CashuMint {
|
interface CashuMint {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -17,12 +18,13 @@ interface WalletHeaderProps {
|
|||||||
balances: { [key: string]: number };
|
balances: { [key: string]: number };
|
||||||
showSats: boolean;
|
showSats: boolean;
|
||||||
setShowSats: (showSats: boolean) => void;
|
setShowSats: (showSats: boolean) => void;
|
||||||
mode: 'tokens' | 'lightning';
|
mode: 'tokens' | 'lightning' | 'bitcoin';
|
||||||
setMode: (mode: 'tokens' | 'lightning') => void;
|
setMode: (mode: 'tokens' | 'lightning' | 'bitcoin') => void;
|
||||||
userPubkey?: string;
|
userPubkey?: string;
|
||||||
npubCashUsername?: string;
|
npubCashUsername?: string;
|
||||||
onCopyToClipboard: (text: string) => Promise<void>;
|
onCopyToClipboard: (text: string) => Promise<void>;
|
||||||
onShowLightningAddressQR: (qrCode: string) => void;
|
onShowLightningAddressQR: (qrCode: string) => void;
|
||||||
|
onShowBitcoinAddressQR: (qrCode: string) => void;
|
||||||
generateQRCode: (text: string) => Promise<string>;
|
generateQRCode: (text: string) => Promise<string>;
|
||||||
// MintSelector props
|
// MintSelector props
|
||||||
activeMintUrl: string | null;
|
activeMintUrl: string | null;
|
||||||
@@ -49,6 +51,7 @@ export function WalletHeader({
|
|||||||
npubCashUsername,
|
npubCashUsername,
|
||||||
onCopyToClipboard,
|
onCopyToClipboard,
|
||||||
onShowLightningAddressQR,
|
onShowLightningAddressQR,
|
||||||
|
onShowBitcoinAddressQR,
|
||||||
generateQRCode,
|
generateQRCode,
|
||||||
// MintSelector props
|
// MintSelector props
|
||||||
activeMintUrl,
|
activeMintUrl,
|
||||||
@@ -64,6 +67,7 @@ export function WalletHeader({
|
|||||||
setDropdownOpen,
|
setDropdownOpen,
|
||||||
}: WalletHeaderProps) {
|
}: WalletHeaderProps) {
|
||||||
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
|
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
|
||||||
|
const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false);
|
||||||
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
|
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
|
||||||
@@ -74,14 +78,24 @@ export function WalletHeader({
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const toggleMode = () => {
|
const toggleMode = () => {
|
||||||
const newMode = mode === 'tokens' ? 'lightning' : 'tokens';
|
let newMode: 'tokens' | 'lightning' | 'bitcoin';
|
||||||
|
if (mode === 'lightning') {
|
||||||
|
newMode = 'tokens';
|
||||||
|
} else if (mode === 'tokens') {
|
||||||
|
newMode = 'bitcoin';
|
||||||
|
} else {
|
||||||
|
newMode = 'lightning';
|
||||||
|
}
|
||||||
|
|
||||||
setMode(newMode);
|
setMode(newMode);
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: `${newMode === 'tokens' ? 'Cashu' : 'Lightning'} Enabled!`,
|
title: `${newMode === 'tokens' ? 'Cashu' : newMode === 'lightning' ? 'Lightning' : 'Bitcoin'} Enabled!`,
|
||||||
description: newMode === 'tokens'
|
description: newMode === 'tokens'
|
||||||
? 'Send and receive with Cashu eCash'
|
? 'Send and receive with Cashu eCash'
|
||||||
: 'Send and receive with Lightning',
|
: newMode === 'lightning'
|
||||||
|
? 'Send and receive with Lightning'
|
||||||
|
: 'Send and receive with on-chain Bitcoin',
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -92,13 +106,15 @@ export function WalletHeader({
|
|||||||
<div className="absolute top-3 left-3 sm:left-4 z-10">
|
<div className="absolute top-3 left-3 sm:left-4 z-10">
|
||||||
<button
|
<button
|
||||||
onClick={toggleMode}
|
onClick={toggleMode}
|
||||||
className="px-3 py-2 rounded-lg bg-background hover:bg-background/80 transition-colors flex items-center justify-center"
|
className="p-3 rounded-full bg-background hover:bg-background/80 transition-colors flex items-center justify-center"
|
||||||
title={mode === 'tokens' ? 'Switch to Lightning' : 'Switch to Cashu Tokens'}
|
title={mode === 'tokens' ? 'Switch to Lightning' : mode === 'lightning' ? 'Switch to Bitcoin' : 'Switch to Cashu Tokens'}
|
||||||
>
|
>
|
||||||
{mode === 'tokens' ? (
|
{mode === 'tokens' ? (
|
||||||
<Coins className="h-6 w-6" />
|
<Coins className="h-6 w-6" />
|
||||||
) : (
|
) : mode === 'lightning' ? (
|
||||||
<Zap className="h-6 w-6" />
|
<Zap className="h-6 w-6" />
|
||||||
|
) : (
|
||||||
|
<Link className="h-6 w-6" />
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -128,8 +144,8 @@ export function WalletHeader({
|
|||||||
<div className="w-full max-w-[400px] mx-auto">
|
<div className="w-full max-w-[400px] mx-auto">
|
||||||
<div className="grid grid-cols-1 gap-3">
|
<div className="grid grid-cols-1 gap-3">
|
||||||
{/* Lightning Address Row */}
|
{/* Lightning Address Row */}
|
||||||
{userPubkey && (
|
{userPubkey && mode !== 'bitcoin' && (
|
||||||
<div className="flex gap-2 items-center min-w-0">
|
<div className="flex gap-2 items-center min-w-[300px]">
|
||||||
<button
|
<button
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
const lightningAddress = `${npubCashUsername}@npubx.cash`;
|
const lightningAddress = `${npubCashUsername}@npubx.cash`;
|
||||||
@@ -168,22 +184,65 @@ export function WalletHeader({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Bitcoin Address Row */}
|
||||||
|
{userPubkey && mode === 'bitcoin' && (() => {
|
||||||
|
const bitcoinAddress = nostrPubkeyToBitcoinAddress(userPubkey);
|
||||||
|
return bitcoinAddress ? (
|
||||||
|
<div className="flex gap-2 items-center min-w-[300px]">
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
await onCopyToClipboard(bitcoinAddress);
|
||||||
|
setBitcoinAddressCopied(true);
|
||||||
|
setTimeout(() => setBitcoinAddressCopied(false), 2000);
|
||||||
|
}}
|
||||||
|
className="flex items-center gap-2 px-3 py-1.5 bg-muted hover:bg-muted/80 rounded-md border text-base font-mono transition-colors flex-1 h-[40px] min-w-0"
|
||||||
|
title="Click to copy Bitcoin address"
|
||||||
|
>
|
||||||
|
<div className="min-w-0 flex-1 flex items-center">
|
||||||
|
<span className="truncate min-w-0 flex-1">
|
||||||
|
{bitcoinAddress}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{bitcoinAddressCopied ? (
|
||||||
|
<Check className="h-4 w-4 text-green-600 flex-shrink-0" />
|
||||||
|
) : (
|
||||||
|
<Copy className="h-4 w-4 text-muted-foreground flex-shrink-0" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
const qr = await generateQRCode(bitcoinAddress);
|
||||||
|
onShowBitcoinAddressQR(qr);
|
||||||
|
}}
|
||||||
|
className="flex items-center justify-center px-2 py-1.5 hover:bg-muted rounded-md transition-colors h-[40px] w-[42px] flex-shrink-0"
|
||||||
|
title="Show QR Code"
|
||||||
|
>
|
||||||
|
<QrCode className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : null;
|
||||||
|
})()}
|
||||||
|
|
||||||
{/* Mint Selector Row */}
|
{/* Mint Selector Row */}
|
||||||
<MintSelector
|
{mode !== 'bitcoin' && (
|
||||||
balances={balances}
|
<div className="min-w-[300px]">
|
||||||
showSats={showSats}
|
<MintSelector
|
||||||
activeMintUrl={activeMintUrl}
|
balances={balances}
|
||||||
setActiveMintUrl={setActiveMintUrl}
|
showSats={showSats}
|
||||||
mints={mints}
|
activeMintUrl={activeMintUrl}
|
||||||
mintUrl={mintUrl}
|
setActiveMintUrl={setActiveMintUrl}
|
||||||
setMintUrl={setMintUrl}
|
mints={mints}
|
||||||
onAddMint={onAddMint}
|
mintUrl={mintUrl}
|
||||||
onRemoveMint={onRemoveMint}
|
setMintUrl={setMintUrl}
|
||||||
onShowDenominations={onShowDenominations}
|
onAddMint={onAddMint}
|
||||||
getCleanMintLabel={getCleanMintLabel}
|
onRemoveMint={onRemoveMint}
|
||||||
dropdownOpen={dropdownOpen}
|
onShowDenominations={onShowDenominations}
|
||||||
setDropdownOpen={setDropdownOpen}
|
getCleanMintLabel={getCleanMintLabel}
|
||||||
/>
|
dropdownOpen={dropdownOpen}
|
||||||
|
setDropdownOpen={setDropdownOpen}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -61,6 +61,20 @@ export function useMintManager({
|
|||||||
normalizedUrl = `https://${normalizedUrl}`;
|
normalizedUrl = `https://${normalizedUrl}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if mint with same name already exists (case insensitive)
|
||||||
|
const existingMint = mints.find(mint =>
|
||||||
|
mint.url.toLowerCase() === normalizedUrl.toLowerCase()
|
||||||
|
);
|
||||||
|
|
||||||
|
if (existingMint) {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Mint Already Exists',
|
||||||
|
description: 'A mint with this URL already exists',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
await coco.mint.addMint(normalizedUrl);
|
await coco.mint.addMint(normalizedUrl);
|
||||||
setMintUrl('');
|
setMintUrl('');
|
||||||
|
|
||||||
@@ -75,7 +89,7 @@ export function useMintManager({
|
|||||||
description: err instanceof Error ? err.message : 'Unknown error',
|
description: err instanceof Error ? err.message : 'Unknown error',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, [mintUrl, coco, toast]);
|
}, [mintUrl, coco, mints, toast]);
|
||||||
|
|
||||||
// Show remove confirmation modal
|
// Show remove confirmation modal
|
||||||
const handleRemoveMintClick = useCallback((mint: CashuMint) => {
|
const handleRemoveMintClick = useCallback((mint: CashuMint) => {
|
||||||
@@ -190,14 +204,25 @@ export function useMintManager({
|
|||||||
[repositories, toast]
|
[repositories, toast]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Auto-select first mint when mints change
|
// Auto-select first mint when mints change, or add default mint if none exist
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (mints.length > 0 && !activeMintUrl) {
|
if (mints.length > 0 && !activeMintUrl) {
|
||||||
// Select first mint initially - user can change via dropdown
|
// Select first mint initially - user can change via dropdown
|
||||||
// Don't sync to npub.cash on auto-select, only on manual changes
|
// Don't sync to npub.cash on auto-select, only on manual changes
|
||||||
handleSetActiveMint(mints[0].url, false);
|
handleSetActiveMint(mints[0].url, false);
|
||||||
|
} else if (mints.length === 0 && !activeMintUrl && coco) {
|
||||||
|
// Add default mint if no mints exist
|
||||||
|
const addDefaultMint = async () => {
|
||||||
|
try {
|
||||||
|
await coco.mint.addMint('https://mint.chorus.community');
|
||||||
|
// The mint will be added and refreshMints will be called via event listeners
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to add default mint:', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
addDefaultMint();
|
||||||
}
|
}
|
||||||
}, [mints, activeMintUrl, handleSetActiveMint]);
|
}, [mints, activeMintUrl, handleSetActiveMint, coco]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
activeMintUrl,
|
activeMintUrl,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||||
import { isUnknownMintError, extractMintUrlFromError } from './walletUtils';
|
import { isUnknownMintError, extractMintUrlFromError } from './walletUtils';
|
||||||
|
import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder';
|
||||||
|
|
||||||
interface UseWalletTransactionsProps {
|
interface UseWalletTransactionsProps {
|
||||||
coco: any; // Coco instance
|
coco: any; // Coco instance
|
||||||
@@ -37,6 +38,8 @@ export function useWalletTransactions({
|
|||||||
const [pendingLightningAddress, setPendingLightningAddress] = useState<
|
const [pendingLightningAddress, setPendingLightningAddress] = useState<
|
||||||
string | null
|
string | null
|
||||||
>(null);
|
>(null);
|
||||||
|
const [decodedInvoiceAmount, setDecodedInvoiceAmount] = useState<number | null>(null);
|
||||||
|
const [pendingInvoice, setPendingInvoice] = useState<string | null>(null);
|
||||||
|
|
||||||
// Transaction output state
|
// Transaction output state
|
||||||
const [sentToken, setSentToken] = useState<string | null>(null);
|
const [sentToken, setSentToken] = useState<string | null>(null);
|
||||||
@@ -303,26 +306,34 @@ export function useWalletTransactions({
|
|||||||
setPendingLightningAddress(input);
|
setPendingLightningAddress(input);
|
||||||
setLightningAddressInput('');
|
setLightningAddressInput('');
|
||||||
} else {
|
} else {
|
||||||
// It's a regular Lightning invoice
|
// It's a regular Lightning invoice - decode to show amount first
|
||||||
try {
|
if (isValidBolt11Invoice(input)) {
|
||||||
const meltQuote = await coco.quotes.createMeltQuote(
|
const amount = decodeBolt11Amount(input);
|
||||||
activeMintUrl,
|
if (amount) {
|
||||||
input
|
// Show amount confirmation screen
|
||||||
);
|
setPendingInvoice(input);
|
||||||
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
setDecodedInvoiceAmount(amount);
|
||||||
|
setLightningInvoice('');
|
||||||
toast({
|
return;
|
||||||
title: 'Invoice Paid',
|
} else {
|
||||||
description:
|
// Failed to decode amount - show error and don't attempt payment
|
||||||
'Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.',
|
toast({
|
||||||
});
|
variant: 'destructive',
|
||||||
setLightningInvoice('');
|
title: 'Invalid Invoice',
|
||||||
} catch (err) {
|
description: 'Unable to decode the lightning invoice amount. Please check the invoice format.',
|
||||||
|
});
|
||||||
|
setLightningInvoice('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Not a valid BOLT11 invoice - show error and don't attempt payment
|
||||||
toast({
|
toast({
|
||||||
variant: 'destructive',
|
variant: 'destructive',
|
||||||
title: 'Invoice Payment Failed',
|
title: 'Invalid Invoice',
|
||||||
description: err instanceof Error ? err.message : 'Unknown error',
|
description: 'This does not appear to be a valid lightning invoice. Please check the format.',
|
||||||
});
|
});
|
||||||
|
setLightningInvoice('');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -334,6 +345,8 @@ export function useWalletTransactions({
|
|||||||
lightningAddressInput,
|
lightningAddressInput,
|
||||||
lightningAddressAmount,
|
lightningAddressAmount,
|
||||||
pendingLightningAddress,
|
pendingLightningAddress,
|
||||||
|
pendingInvoice,
|
||||||
|
decodedInvoiceAmount,
|
||||||
activeMintUrl,
|
activeMintUrl,
|
||||||
toast,
|
toast,
|
||||||
getEncodedToken,
|
getEncodedToken,
|
||||||
@@ -341,6 +354,34 @@ export function useWalletTransactions({
|
|||||||
getLightningInvoice,
|
getLightningInvoice,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// Handle confirmed invoice payment
|
||||||
|
const handleConfirmInvoicePayment = useCallback(async () => {
|
||||||
|
if (!coco || !pendingInvoice || !activeMintUrl) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const meltQuote = await coco.quotes.createMeltQuote(
|
||||||
|
activeMintUrl,
|
||||||
|
pendingInvoice
|
||||||
|
);
|
||||||
|
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: 'Invoice Paid',
|
||||||
|
description: `Lightning invoice paid successfully for ${decodedInvoiceAmount} sats!`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Reset state
|
||||||
|
setPendingInvoice(null);
|
||||||
|
setDecodedInvoiceAmount(null);
|
||||||
|
} catch (err) {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Invoice Payment Failed',
|
||||||
|
description: err instanceof Error ? err.message : 'Unknown error',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [coco, pendingInvoice, activeMintUrl, decodedInvoiceAmount, toast]);
|
||||||
|
|
||||||
// Cleanup mint quote listener on component unmount
|
// Cleanup mint quote listener on component unmount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
@@ -368,6 +409,10 @@ export function useWalletTransactions({
|
|||||||
setLightningAddressAmount,
|
setLightningAddressAmount,
|
||||||
pendingLightningAddress,
|
pendingLightningAddress,
|
||||||
setPendingLightningAddress,
|
setPendingLightningAddress,
|
||||||
|
decodedInvoiceAmount,
|
||||||
|
setDecodedInvoiceAmount,
|
||||||
|
pendingInvoice,
|
||||||
|
setPendingInvoice,
|
||||||
// Transaction output state
|
// Transaction output state
|
||||||
sentToken,
|
sentToken,
|
||||||
setSentToken,
|
setSentToken,
|
||||||
@@ -380,6 +425,7 @@ export function useWalletTransactions({
|
|||||||
// Handlers
|
// Handlers
|
||||||
handleReceive,
|
handleReceive,
|
||||||
handleSend,
|
handleSend,
|
||||||
|
handleConfirmInvoicePayment,
|
||||||
// Refs
|
// Refs
|
||||||
mintQuoteUnsubscribeRef,
|
mintQuoteUnsubscribeRef,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { fetchUTXOs, type UTXO } from '@/lib/bitcoin';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to fetch and manage Bitcoin balance from UTXOs
|
||||||
|
*/
|
||||||
|
export function useBitcoinBalance(address: string | null) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['bitcoin-balance', address],
|
||||||
|
queryFn: async (): Promise<{ balance: number; utxos: UTXO[] }> => {
|
||||||
|
if (!address) {
|
||||||
|
return { balance: 0, utxos: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const utxos = await fetchUTXOs(address);
|
||||||
|
const balance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
|
||||||
|
|
||||||
|
return { balance, utxos };
|
||||||
|
},
|
||||||
|
enabled: !!address,
|
||||||
|
refetchInterval: 30000, // Refetch every 30 seconds
|
||||||
|
staleTime: 10000, // Consider data stale after 10 seconds
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { useNostrLogin } from '@nostrify/react/login';
|
||||||
|
import { nip19 } from 'nostr-tools';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to check if the current user is logged in with nsec and get the private key.
|
||||||
|
* Only works when user is logged in with nsec (not extension or bunker).
|
||||||
|
*/
|
||||||
|
export function useNsecAccess() {
|
||||||
|
const { logins } = useNostrLogin();
|
||||||
|
|
||||||
|
const currentLogin = logins[0];
|
||||||
|
|
||||||
|
// Check if user is logged in with nsec
|
||||||
|
const hasNsecAccess = currentLogin?.type === 'nsec';
|
||||||
|
|
||||||
|
// Get the private key in hex format (only if nsec login)
|
||||||
|
const getPrivateKey = (): string | null => {
|
||||||
|
if (!hasNsecAccess || !currentLogin) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// The nsec is stored in the login data as 'data.nsec' property
|
||||||
|
const loginData = currentLogin as { data?: { nsec: string } };
|
||||||
|
const nsec = loginData.data?.nsec;
|
||||||
|
|
||||||
|
if (!nsec) {
|
||||||
|
console.error('No nsec found in login data');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const decoded: { type: string; data: Uint8Array | string | object } = nip19.decode(nsec) as { type: string; data: Uint8Array | string | object };
|
||||||
|
|
||||||
|
// Type guard to ensure we have an nsec
|
||||||
|
if (decoded.type !== 'nsec') {
|
||||||
|
console.error('Invalid nsec format, got type:', decoded.type);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert Uint8Array to hex string
|
||||||
|
return Buffer.from(decoded.data as Uint8Array).toString('hex');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to decode nsec:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
hasNsecAccess,
|
||||||
|
getPrivateKey,
|
||||||
|
loginType: currentLogin?.type,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
import * as bitcoin from 'bitcoinjs-lib';
|
||||||
|
import { nip19 } from 'nostr-tools';
|
||||||
|
import * as ecc from '@bitcoinerlab/secp256k1';
|
||||||
|
import { ECPairFactory, type ECPairAPI } from 'ecpair';
|
||||||
|
|
||||||
|
// Initialize ECC library immediately
|
||||||
|
bitcoin.initEccLib(ecc);
|
||||||
|
|
||||||
|
// Lazy initialization to avoid issues in test environment
|
||||||
|
let ECPair: ECPairAPI | null = null;
|
||||||
|
|
||||||
|
function getECPair(): ECPairAPI {
|
||||||
|
if (!ECPair) {
|
||||||
|
ECPair = ECPairFactory(ecc);
|
||||||
|
}
|
||||||
|
return ECPair;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert Nostr pubkey (hex) to Bitcoin Taproot address
|
||||||
|
*/
|
||||||
|
export function nostrPubkeyToBitcoinAddress(pubkeyHex: string): string {
|
||||||
|
try {
|
||||||
|
const pubkeyBuffer = Buffer.from(pubkeyHex, 'hex');
|
||||||
|
|
||||||
|
const { address } = bitcoin.payments.p2tr({
|
||||||
|
internalPubkey: pubkeyBuffer,
|
||||||
|
network: bitcoin.networks.bitcoin,
|
||||||
|
});
|
||||||
|
|
||||||
|
return address || '';
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error generating Bitcoin address:', error);
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert npub to Bitcoin Taproot address
|
||||||
|
*/
|
||||||
|
export function npubToBitcoinAddress(npub: string): string {
|
||||||
|
try {
|
||||||
|
const decoded = nip19.decode(npub);
|
||||||
|
|
||||||
|
if (decoded.type !== 'npub') {
|
||||||
|
throw new Error('Invalid npub format');
|
||||||
|
}
|
||||||
|
|
||||||
|
const pubkeyHex = decoded.data as string;
|
||||||
|
return nostrPubkeyToBitcoinAddress(pubkeyHex);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error converting npub to Bitcoin address:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface for UTXO (Unspent Transaction Output)
|
||||||
|
*/
|
||||||
|
export interface UTXO {
|
||||||
|
txid: string;
|
||||||
|
vout: number;
|
||||||
|
value: number; // in satoshis
|
||||||
|
status: {
|
||||||
|
confirmed: boolean;
|
||||||
|
block_height?: number;
|
||||||
|
block_hash?: string;
|
||||||
|
block_time?: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch UTXOs for a Bitcoin address from Blockstream API
|
||||||
|
*/
|
||||||
|
export async function fetchUTXOs(address: string): Promise<UTXO[]> {
|
||||||
|
const response = await fetch(`https://blockstream.info/api/address/${address}/utxo`);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch UTXOs');
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get recommended fee rates from Blockstream API
|
||||||
|
*/
|
||||||
|
export async function getFeeRates(): Promise<{
|
||||||
|
fastestFee: number;
|
||||||
|
halfHourFee: number;
|
||||||
|
hourFee: number;
|
||||||
|
economyFee: number;
|
||||||
|
minimumFee: number;
|
||||||
|
}> {
|
||||||
|
const response = await fetch('https://blockstream.info/api/fee-estimates');
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch fee estimates');
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
return {
|
||||||
|
fastestFee: Math.ceil(data['1'] || 1),
|
||||||
|
halfHourFee: Math.ceil(data['3'] || 1),
|
||||||
|
hourFee: Math.ceil(data['6'] || 1),
|
||||||
|
economyFee: Math.ceil(data['144'] || 1),
|
||||||
|
minimumFee: Math.ceil(data['504'] || 1),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broadcast a transaction to the Bitcoin network
|
||||||
|
*/
|
||||||
|
export async function broadcastTransaction(txHex: string): Promise<string> {
|
||||||
|
const response = await fetch('https://blockstream.info/api/tx', {
|
||||||
|
method: 'POST',
|
||||||
|
body: txHex,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.text();
|
||||||
|
throw new Error(`Failed to broadcast transaction: ${error}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.text(); // Returns the transaction ID
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create and sign a Bitcoin transaction
|
||||||
|
* @param privateKeyHex - Private key in hex format (from Nostr nsec)
|
||||||
|
* @param toAddress - Recipient Bitcoin address
|
||||||
|
* @param amountSats - Amount to send in satoshis
|
||||||
|
* @param utxos - Available UTXOs
|
||||||
|
* @param feeRate - Fee rate in sat/vB
|
||||||
|
* @returns Signed transaction hex
|
||||||
|
*/
|
||||||
|
export async function createBitcoinTransaction(
|
||||||
|
privateKeyHex: string,
|
||||||
|
toAddress: string,
|
||||||
|
amountSats: number,
|
||||||
|
utxos: UTXO[],
|
||||||
|
feeRate: number
|
||||||
|
): Promise<{ txHex: string; fee: number }> {
|
||||||
|
// Create key pair from private key
|
||||||
|
const privateKeyBuffer = Buffer.from(privateKeyHex, 'hex');
|
||||||
|
const keyPair = getECPair().fromPrivateKey(privateKeyBuffer);
|
||||||
|
|
||||||
|
// Get x-only public key (32 bytes) for Taproot
|
||||||
|
// Remove the first byte (compression flag) from the 33-byte compressed pubkey
|
||||||
|
const internalPubkey = keyPair.publicKey.slice(1, 33);
|
||||||
|
|
||||||
|
// Get sender's address for change
|
||||||
|
const { address: changeAddress } = bitcoin.payments.p2tr({
|
||||||
|
internalPubkey,
|
||||||
|
network: bitcoin.networks.bitcoin,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!changeAddress) {
|
||||||
|
throw new Error('Failed to generate change address');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create transaction builder
|
||||||
|
const psbt = new bitcoin.Psbt({ network: bitcoin.networks.bitcoin });
|
||||||
|
|
||||||
|
// Add inputs (UTXOs)
|
||||||
|
let totalInput = 0;
|
||||||
|
for (const utxo of utxos) {
|
||||||
|
psbt.addInput({
|
||||||
|
hash: utxo.txid,
|
||||||
|
index: utxo.vout,
|
||||||
|
witnessUtxo: {
|
||||||
|
script: bitcoin.payments.p2tr({
|
||||||
|
internalPubkey,
|
||||||
|
network: bitcoin.networks.bitcoin,
|
||||||
|
}).output!,
|
||||||
|
value: BigInt(utxo.value),
|
||||||
|
},
|
||||||
|
tapInternalKey: internalPubkey,
|
||||||
|
});
|
||||||
|
|
||||||
|
totalInput += utxo.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Estimate transaction size
|
||||||
|
// P2TR input: ~57.5 vBytes, P2TR output: ~43 vBytes
|
||||||
|
const estimatedSize = utxos.length * 57.5 + 2 * 43 + 10.5; // 2 outputs (recipient + change) + overhead
|
||||||
|
const estimatedFee = Math.ceil(estimatedSize * feeRate);
|
||||||
|
|
||||||
|
// Calculate change
|
||||||
|
const change = totalInput - amountSats - estimatedFee;
|
||||||
|
|
||||||
|
if (change < 0) {
|
||||||
|
throw new Error(
|
||||||
|
`Insufficient funds. Need ${amountSats + estimatedFee} sats, have ${totalInput} sats`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add output for recipient
|
||||||
|
psbt.addOutput({
|
||||||
|
address: toAddress,
|
||||||
|
value: BigInt(amountSats),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add change output if significant (> dust limit)
|
||||||
|
const dustLimit = 546; // Standard dust limit for Bitcoin
|
||||||
|
if (change > dustLimit) {
|
||||||
|
psbt.addOutput({
|
||||||
|
address: changeAddress,
|
||||||
|
value: BigInt(change),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a Taproot signer
|
||||||
|
// For Taproot key-path spending, we need to tweak the private key
|
||||||
|
const tweakedSigner = keyPair.tweak(
|
||||||
|
bitcoin.crypto.taggedHash('TapTweak', internalPubkey)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Sign all inputs
|
||||||
|
for (let i = 0; i < utxos.length; i++) {
|
||||||
|
psbt.signInput(i, tweakedSigner);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finalize and extract transaction
|
||||||
|
psbt.finalizeAllInputs();
|
||||||
|
const tx = psbt.extractTransaction();
|
||||||
|
|
||||||
|
return {
|
||||||
|
txHex: tx.toHex(),
|
||||||
|
fee: estimatedFee,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert satoshis to BTC
|
||||||
|
*/
|
||||||
|
export function satsToBTC(sats: number): string {
|
||||||
|
return (sats / 100000000).toFixed(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert BTC to satoshis
|
||||||
|
*/
|
||||||
|
export function btcToSats(btc: number): number {
|
||||||
|
return Math.round(btc * 100000000);
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
/**
|
||||||
|
* Decodes a BOLT11 lightning invoice and extracts the amount in satoshis.
|
||||||
|
* Based on the lightning-decoder project implementation.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decode a BOLT11 invoice and extract the amount in satoshis
|
||||||
|
* @param invoice - The BOLT11 invoice string
|
||||||
|
* @returns The amount in satoshis, or null if amount cannot be determined
|
||||||
|
*/
|
||||||
|
export function decodeBolt11Amount(invoice: string): number | null {
|
||||||
|
try {
|
||||||
|
// Validate and prepare invoice
|
||||||
|
if (!invoice || typeof invoice !== 'string') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedInvoice = invoice.toLowerCase().trim();
|
||||||
|
|
||||||
|
// Check if it's a valid BOLT11 invoice
|
||||||
|
if (!isValidBolt11Invoice(normalizedInvoice)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse the prefix to extract amount
|
||||||
|
// Format: lnbc[amount][suffix] where suffix can be m, u, n, p
|
||||||
|
const prefixMatch = normalizedInvoice.match(/^lnbc(\d*)([munp]?)/);
|
||||||
|
if (!prefixMatch) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [, amountStr, suffix] = prefixMatch;
|
||||||
|
|
||||||
|
// If no amount specified, return null (amountless invoice)
|
||||||
|
if (!amountStr) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const amount = parseInt(amountStr, 10);
|
||||||
|
if (isNaN(amount)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Define multipliers for different denominations
|
||||||
|
const multipliers: Record<string, number> = {
|
||||||
|
m: 0.001, // milli-bitcoin
|
||||||
|
u: 0.000001, // micro-bitcoin
|
||||||
|
n: 0.000000001, // nano-bitcoin
|
||||||
|
p: 0.000000000001 // pico-bitcoin
|
||||||
|
};
|
||||||
|
|
||||||
|
// Apply multiplier if suffix exists
|
||||||
|
const multiplier = multipliers[suffix] || 1;
|
||||||
|
const amountInBitcoin = amount * multiplier;
|
||||||
|
|
||||||
|
// Convert Bitcoin to satoshis (1 Bitcoin = 100,000,000 satoshis)
|
||||||
|
const amountInSatoshis = Math.round(amountInBitcoin * 100_000_000);
|
||||||
|
|
||||||
|
return amountInSatoshis;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error decoding BOLT11 invoice:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate if a string is a valid BOLT11 invoice
|
||||||
|
* @param invoice - The string to validate
|
||||||
|
* @returns true if the string appears to be a valid BOLT11 invoice
|
||||||
|
*/
|
||||||
|
export function isValidBolt11Invoice(invoice: string): boolean {
|
||||||
|
if (!invoice || typeof invoice !== 'string') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalized = invoice.toLowerCase().trim();
|
||||||
|
|
||||||
|
// BOLT11 invoices start with 'lnbc' and contain '1' followed by characters (the bech32 separator)
|
||||||
|
// They also need to be long enough to contain the required components
|
||||||
|
return (
|
||||||
|
normalized.startsWith('lnbc') &&
|
||||||
|
/1[a-z0-9]/.test(normalized) &&
|
||||||
|
normalized.length > 20 // Minimum reasonable length for a BOLT11 invoice
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,3 +1,12 @@
|
|||||||
|
/**
|
||||||
|
* Polyfill for Buffer in browser environment
|
||||||
|
*
|
||||||
|
* Many Node.js libraries like bitcoinjs-lib expect Buffer to be globally available.
|
||||||
|
* This polyfill makes the buffer package's Buffer available globally.
|
||||||
|
*/
|
||||||
|
import { Buffer } from 'buffer';
|
||||||
|
globalThis.Buffer = Buffer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Polyfill for AbortSignal.any()
|
* Polyfill for AbortSignal.any()
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -15,3 +15,16 @@ createRoot(document.getElementById("root")!).render(
|
|||||||
<App />
|
<App />
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Register service worker for PWA
|
||||||
|
if ('serviceWorker' in navigator) {
|
||||||
|
window.addEventListener('load', () => {
|
||||||
|
navigator.serviceWorker.register('/sw.js')
|
||||||
|
.then((registration) => {
|
||||||
|
console.log('SW registered: ', registration);
|
||||||
|
})
|
||||||
|
.catch((registrationError) => {
|
||||||
|
console.log('SW registration failed: ', registrationError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user