Author SHA1 Message Date
lemonknowsall 5c4c73f8ef edit with shakespeare button 2025-10-20 16:37:26 -07:00
lemonknowsall d0c28b77b8 Docs update for Nutstack wallet integration 2025-10-20 13:41:14 -07:00
lemonknowsall 1c991e3185 Nutstack PWA Manifest 2025-10-20 13:25:54 -07:00
lemonknowsall 24920117ae add slider reset for payment confirmation 2025-10-19 22:02:06 -07:00
lemonknowsall 722b1a743f fixed send card for on-chain and added pay to pubkey 2025-10-19 21:54:27 -07:00
lemonknowsall 617edd1784 ln decoder, default mint, drawer formatting 2025-10-19 11:05:35 -07:00
lemonknowsall 7390dd6c19 fixed npubx.cash payments 2025-10-18 11:41:10 -07:00
lemonknowsall 6d35028424 header spacing and styling 2025-10-18 11:04:24 -07:00
lemonknowsall bea63c75aa transaction history drawer and separate mint display 2025-10-18 00:22:50 -07:00
lemonknowsall e4ee51335e upgraded mobile styling 2025-10-17 13:39:29 -07:00
lemonknowsall 8ef018df8a moved cards to drawers for mobile view 2025-10-16 23:32:07 -07:00
lemonknowsall 56bdebff5d updated transactions look 2025-10-16 22:20:18 -07:00
lemonknowsall 6162217ce9 silent return bug on lnaddress payments 2025-10-16 17:26:46 -07:00
lemonknowsall ea57135d1e npubxcash lnaddress subscriptions working 2025-10-16 17:05:39 -07:00
lemonknowsall b5bc571aa7 refactor the refactor 2025-10-16 13:03:59 -07:00
lemonknowsall 77803dda38 implement mint removal 2025-10-15 23:12:01 -07:00
lemonknowsall 73c68f2655 remove scroll bar from login modal 2025-10-15 22:13:37 -07:00
lemonknowsall f78013b083 npubxcash lightning address redemption working 2025-10-15 21:29:39 -07:00
lemonknowsall bd956cef3f implement npubcash-sdk to simplify code 2025-10-15 01:22:12 -07:00
lemonknowsall 2ac097d8de code cleanup round 2 2025-10-15 00:10:24 -07:00
lemonknowsall aaf12120e6 move files together 2025-10-13 19:57:15 -07:00
lemonknowsall 5ce402105c code cleanup 2025-10-13 16:52:25 -07:00
lemonknowsall dd3f4465c5 put lightning address in balance card 2025-10-13 16:27:15 -07:00
lemonknowsall c8ad3b1a36 get user info from npubxcash 2025-10-13 13:10:02 -07:00
lemonknowsall 1701cce6b0 add lightning address and qr modal 2025-10-13 12:46:17 -07:00
lemonknowsall 346ba70710 set mint with npubxcash 2025-10-13 12:33:02 -07:00
61 changed files with 4568 additions and 3622 deletions

No files matched your search

+88 -7
View File
@@ -19,6 +19,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/components/wallet/`: Wallet system components including `CashuWallet` (main wallet interface), `WalletHeader` (balance display and mode toggle), `TransactionCard` (send/receive forms), `MintSelector` (mint management), `TransactionHistory` (unified history)
- Zap components: `ZapButton` (unified component with Cashu integration), `LightningWalletModal` for Lightning fallback management
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
@@ -34,11 +35,9 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `useZaps`: Lightning zap functionality with Cashu integration and payment processing
- `useCashu`: Cashu wallet management (balances, mints, melt quotes)
- `useLightningAddress`: Lightning address validation and LNURL endpoint discovery
- `useWallet`: Unified wallet detection (Cashu + WebLN + NWC) with intelligent payment method selection
- `useNWC`: Nostr Wallet Connect connection management
- `useNWCContext`: Access NWC context provider
- **Cashu hooks**: `useCashu` (core wallet management), `useMintManager` (mint operations), `useWalletTransactions` (send/receive), `useHistoryManager` (transaction history)
- **Bitcoin hooks**: `useBitcoinBalance` (UTXO tracking), `useNsecAccess` (private key access for signing)
- **Integration hooks**: `useNpubCash` (npub.cash API), `useLightningAddress` (Lightning address validation), `useWallet` (unified wallet detection), `useNWC` (Nostr Wallet Connect), `useNWCContext` (NWC context provider)
- `useShakespeare`: AI chat completions with Shakespeare AI API
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
@@ -142,9 +141,9 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
1. Edit AGENTS.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
## "Vibed with NutStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
When building the site for the first time, include "Vibed with NutStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
@@ -770,6 +769,88 @@ function EditProfilePage() {
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Cashu Token System
NutStack includes comprehensive Cashu token support using the coco-cashu-core library:
#### Core Architecture
- **Token Management**: Uses coco-cashu-core for token operations and proof management
- **Mint Operations**: Support for multiple mints with denomination handling
- **Token Encoding**: Built-in token encoding/decoding for secure transfers
- **Proof Storage**: IndexedDB-based proof storage via coco-cashu-indexeddb
#### Key Hooks
- `useCashu`: Core wallet state, balances, and mint management
- `useMintManager`: Mint addition, removal, and denomination display
- `useWalletTransactions`: Send/receive token operations
- `useHistoryManager`: Transaction history tracking
#### Npub.cash Integration
- **Hosted Mints**: Automatic mint synchronization with npub.cash
- **Quote Management**: Real-time quote updates and synchronization
- **User Management**: Seamless integration with npub.cash user accounts
#### Usage Example
```tsx
import { useCashu } from '@/hooks/cashu/useCashu';
function WalletComponent() {
const { balances, mints, coco } = useCashu();
// Access token balances across all mints
const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
return <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
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
+58 -7
View File
@@ -1,8 +1,22 @@
# MKStack
# NutStack
[![Edit with Shakespeare](https://shakespeare.diy/badge.svg)](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**
MKStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, MKStack provides everything you need to create decentralized apps on the Nostr protocol.
NutStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, NutStack provides everything you need to create decentralized apps on the Nostr protocol.
## 🚀 Quick Start
@@ -11,7 +25,7 @@ Build your Nostr app in 3 simple steps:
### 1. Install & Create
```bash
npm install -g @getstacks/stacks
stacks mkstack
stacks nutstack
```
### 2. Build with AI
@@ -26,14 +40,14 @@ npm run deploy
# ✅ App deployed to NostrDeploy.com!
```
## ✨ What Makes MKStack Special
## ✨ What Makes NutStack Special
- **🤖 AI-First Development**: Build complete Nostr apps with just one prompt using Dork AI agent
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Wallet Connect (NIP-47)
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), on-chain Bitcoin transactions, Wallet Connect (NIP-47), Npub.cash integration
- **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included
## 🛠 Technology Stack
@@ -84,7 +98,7 @@ Real Nostr applications built using MKStack:
### Nostr Protocol Support
- **Social Features**: User profiles (NIP-01), follow lists (NIP-02), reactions (NIP-25), reposts (NIP-18)
- **Messaging**: Private DMs (NIP-17), public chat (NIP-28), group chat (NIP-29), encryption (NIP-44)
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47)
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47), on-chain Bitcoin transactions using Taproot addresses derived from Nostr keys
- **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52)
### Data Management
@@ -94,6 +108,15 @@ Real Nostr applications built using MKStack:
- Infinite scroll with TanStack Query
- Multi-relay support
### Wallet System
- `useCashu` hook for Cashu wallet management
- `useMintManager` hook for mint operations
- `useWalletTransactions` hook for send/receive operations
- `useHistoryManager` hook for transaction history
- `useBitcoinBalance` hook for Bitcoin UTXO tracking
- `useNsecAccess` hook for private key access (Bitcoin signing)
- `useNpubCash` hook for Npub.cash API integration
### UI Components
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
- `NoteContent` component for rich text rendering
@@ -182,6 +205,34 @@ MKStack includes 48+ shadcn/ui components:
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
- **Secure authentication**: Use signer interface, never request private keys directly
## 💰 Unified Wallet System
NutStack includes a comprehensive three-mode wallet system that supports multiple payment methods:
### Three Payment Modes
- **Tokens Mode**: Cashu token operations with mint management
- **Lightning Mode**: Lightning invoice payments, Lightning address support, and zaps
- **Bitcoin Mode**: On-chain Bitcoin transactions using Taproot addresses
### Key Features
- **Mode Switching**: Seamless switching between payment methods via UI toggle
- **Unified Interface**: Single `CashuWallet` component handles all payment types
- **Nostr Integration**: Bitcoin addresses derived from Nostr public keys using Taproot (P2TR)
- **Private Key Access**: Bitcoin transactions require nsec login for transaction signing
- **Transaction History**: Unified history tracking across all payment methods
- **Mobile Optimized**: Responsive design with drawer/modal patterns for mobile
### Architecture
The wallet system uses a component-based architecture:
- `CashuWallet` - Main wallet interface with mode switching
- `WalletHeader` - Balance display and mode toggle
- `TransactionCard` - Send/receive forms for each mode
- `MintSelector` - Cashu mint management
- `TransactionHistory` - Unified transaction history
## 📱 Responsive Design
- Mobile-first approach with Tailwind breakpoints
@@ -233,6 +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.*
-612
View File
@@ -1,612 +0,0 @@
# npub.cash Lightning Address Integration
This document explains how to integrate npub.cash Lightning addresses into your Nostr application, allowing users to receive Lightning payments without any setup.
## Overview
npub.cash is a Lightning address service powered by Cashu and Nostr. It provides instant Lightning addresses for any Nostr public key, with no registration required. Payments are stored as Cashu quotes that users can later claim.
### How It Works
1. **Identity**: Your Nostr pubkey becomes your Lightning address (`[email protected]`)
2. **Receiving**: When someone sends sats, npub.cash stores a paid Cashu quote linked to your pubkey
3. **Claiming**: Authenticate with NIP-98 to fetch and redeem your paid quotes from the configured mint
## Key Features
- **Zero Setup**: Any Nostr pubkey is instantly a valid Lightning address
- **Nostr Identity**: Uses NIP-98 authentication (no separate account needed)
- **Privacy**: Cashu provides better privacy than plain Lightning
- **Flexible**: Set your preferred Cashu mint
- **Optional Locking**: Enable NUT-20 quote locking for enhanced security
## Basic Usage
### Get Your Lightning Address
```tsx
import { useNpubCash } from '@/hooks/useNpubCash';
function MyLightningAddress() {
const { lightningAddress, isLoading } = useNpubCash();
if (isLoading) return <p>Loading...</p>;
return (
<div>
<h3>My Lightning Address</h3>
<p className="font-mono">{lightningAddress}</p>
<button onClick={() => navigator.clipboard.writeText(lightningAddress)}>
Copy
</button>
</div>
);
}
```
### Display Unclaimed Balance
```tsx
function UnclaimedBalance() {
const { unclaimedAmount, quotes, refresh } = useNpubCash();
return (
<div>
<h3>Unclaimed Payments</h3>
<p>{unclaimedAmount} sats from {quotes.length} payments</p>
<button onClick={refresh}>Refresh</button>
</div>
);
}
```
### Fetch and Display Quotes
```tsx
function PaymentHistory() {
const { quotes, fetchQuotes, isLoading } = useNpubCash();
useEffect(() => {
fetchQuotes();
}, [fetchQuotes]);
return (
<div>
<h3>Received Payments</h3>
{quotes.map(quote => (
<div key={quote.quote_id} className="border p-4 rounded">
<p>Amount: {quote.amount} sats</p>
<p>Mint: {quote.mint_url}</p>
<p>Status: {quote.state}</p>
<p>Paid: {new Date(quote.paid_at * 1000).toLocaleString()}</p>
</div>
))}
</div>
);
}
```
## Advanced Features
### Set Username (Paid Feature)
Users can optionally purchase a custom username for a cleaner Lightning address:
```tsx
function UsernameSelector() {
const { userInfo, setUsername, isLoading } = useNpubCash();
const handleSetUsername = async () => {
try {
await setUsername('myusername');
// Address becomes: [email protected]
alert('Username set successfully!');
} catch (error) {
// Payment required - X-Cashu header returned
console.error(error);
}
};
return (
<div>
<p>Current: {userInfo?.name || 'Using npub'}</p>
<button onClick={handleSetUsername} disabled={isLoading}>
Set Username
</button>
</div>
);
}
```
### Configure Preferred Mint
```tsx
function MintSelector() {
const { userInfo, setMint, isLoading } = useNpubCash();
const [mintUrl, setMintUrl] = useState('');
const handleSetMint = async () => {
try {
await setMint(mintUrl);
alert('Mint updated successfully!');
} catch (error) {
console.error('Failed to set mint:', error);
}
};
return (
<div>
<p>Current Mint: {userInfo?.mint_url}</p>
<input
type="text"
value={mintUrl}
onChange={(e) => setMintUrl(e.target.value)}
placeholder="https://mint.example.com"
/>
<button onClick={handleSetMint} disabled={isLoading}>
Update Mint
</button>
</div>
);
}
```
### Enable Quote Locking (NUT-20)
Lock quotes to your pubkey for enhanced security:
```tsx
function QuoteLocking() {
const { userInfo, setLockQuotes, isLoading } = useNpubCash();
const toggleLocking = async () => {
try {
await setLockQuotes(!userInfo?.lock_quote);
alert('Quote locking updated!');
} catch (error) {
console.error('Failed to update locking:', error);
}
};
return (
<div>
<label>
<input
type="checkbox"
checked={userInfo?.lock_quote || false}
onChange={toggleLocking}
disabled={isLoading}
/>
Lock quotes to my pubkey (NUT-20)
</label>
<p className="text-sm text-muted-foreground">
Requires wallet with NUT-20 support
</p>
</div>
);
}
```
## Complete Example: Receive Payment Widget
```tsx
import { useState } from 'react';
import { useNpubCash } from '@/hooks/useNpubCash';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
function ReceivePaymentWidget() {
const {
lightningAddress,
unclaimedAmount,
quotes,
isLoading,
refresh,
} = useNpubCash();
const [copied, setCopied] = useState(false);
const copyAddress = async () => {
if (!lightningAddress) return;
await navigator.clipboard.writeText(lightningAddress);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<Card>
<CardHeader>
<CardTitle>Receive Lightning Payments</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Lightning Address */}
<div>
<label className="text-sm font-medium">Your Lightning Address</label>
<div className="flex gap-2 items-center mt-1">
<code className="flex-1 bg-muted px-3 py-2 rounded text-sm">
{lightningAddress || 'Loading...'}
</code>
<Button
size="sm"
onClick={copyAddress}
disabled={!lightningAddress}
>
{copied ? 'Copied!' : 'Copy'}
</Button>
</div>
</div>
{/* Unclaimed Balance */}
<div className="flex justify-between items-center p-4 bg-muted rounded">
<span className="font-medium">Unclaimed Balance</span>
<Badge variant="secondary" className="text-lg">
{unclaimedAmount} sats
</Badge>
</div>
{/* Payment History */}
<div>
<div className="flex justify-between items-center mb-2">
<span className="text-sm font-medium">Recent Payments</span>
<Button
size="sm"
variant="outline"
onClick={refresh}
disabled={isLoading}
>
Refresh
</Button>
</div>
<div className="space-y-2 max-h-[300px] overflow-y-auto">
{quotes.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">
No payments received yet
</p>
) : (
quotes.map(quote => (
<div
key={quote.quote_id}
className="border rounded p-3 space-y-1"
>
<div className="flex justify-between items-center">
<span className="font-semibold">{quote.amount} sats</span>
<Badge
variant={quote.state === 'PAID' ? 'default' : 'secondary'}
>
{quote.state}
</Badge>
</div>
<p className="text-xs text-muted-foreground">
{new Date(quote.paid_at * 1000).toLocaleString()}
</p>
<p className="text-xs text-muted-foreground truncate">
{quote.mint_url}
</p>
</div>
))
)}
</div>
</div>
</CardContent>
</Card>
);
}
export default ReceivePaymentWidget;
```
## API Reference
### Hook: `useNpubCash()`
Returns an object with the following properties and methods:
#### State
- `isInitialized: boolean` - Whether the hook has loaded initial data
- `isLoading: boolean` - Whether an API request is in progress
- `error: string | null` - Error message if any operation failed
- `lightningAddress: string | null` - User's npub.cash Lightning address
- `userInfo: NpubCashUserInfo | null` - User settings (mint, username, locking)
- `quotes: NpubCashQuote[]` - Array of received payment quotes
- `unclaimedAmount: number` - Total sats in unclaimed paid quotes
#### Methods
##### `fetchQuotes(since?: number, limit?: number): Promise<NpubCashQuote[]>`
Fetch paid quotes from npub.cash.
- `since` - Optional Unix timestamp to only fetch quotes paid after this time
- `limit` - Maximum number of quotes to return (default: 50)
```tsx
const quotes = await fetchQuotes(Date.now() / 1000 - 86400); // Last 24 hours
```
##### `fetchUserInfo(): Promise<NpubCashUserInfo>`
Fetch current user settings.
```tsx
const info = await fetchUserInfo();
console.log('Preferred mint:', info.mint_url);
```
##### `setUsername(username: string): Promise<void>`
Set a custom username (paid feature via Cashu 402).
```tsx
await setUsername('alice'); // Address becomes [email protected]
```
##### `setMint(mintUrl: string): Promise<void>`
Set preferred Cashu mint for receiving payments.
```tsx
await setMint('https://mint.example.com');
```
##### `setLockQuotes(locked: boolean): Promise<void>`
Enable or disable quote locking to pubkey (NUT-20).
```tsx
await setLockQuotes(true); // Enable locking
```
##### `refresh(): Promise<void>`
Refresh all data (quotes and user info) from npub.cash.
```tsx
await refresh();
```
##### `clearAuth(): void`
Clear stored JWT token, forcing NIP-98 re-authentication on next request.
```tsx
clearAuth(); // Next API call will require NIP-98 signature
```
## Types
### `NpubCashQuote`
```tsx
interface NpubCashQuote {
created_at: number; // Unix timestamp when quote was created
paid_at: number; // Unix timestamp when invoice was paid
expires_at: number; // Unix timestamp when quote expires
mint_url: string; // Cashu mint URL for this quote
quote_id: string; // Unique quote identifier
request: string; // Original BOLT11 invoice
amount: number; // Amount in sats
state: 'PENDING' | 'PAID' | 'EXPIRED';
locked: boolean; // Whether quote is locked to pubkey
}
```
### `NpubCashUserInfo`
```tsx
interface NpubCashUserInfo {
pubkey: string; // User's Nostr public key (hex)
name: string | null; // Custom username (if set)
mint_url: string; // User's preferred Cashu mint
lock_quote: boolean; // Whether quote locking is enabled
}
```
## Authentication
The hook handles authentication automatically using two methods:
### NIP-98 HTTP Auth
For every API request, the hook can create a NIP-98 event (kind 27235) signed by the user's Nostr key. This is the primary authentication method.
### JWT Tokens
To avoid repeated signing requests (especially for browser extensions), the hook can obtain a JWT token using a single NIP-98 request. The token is cached in localStorage and automatically refreshed when expired.
```tsx
// JWT is obtained automatically on first API call
// Cached in localStorage as 'npubcash-jwt'
// Valid for 30 minutes
```
## Integration with Cashu Wallet
To claim the received funds, integrate with the existing `useCashu` hook:
```tsx
import { useNpubCash } from '@/hooks/useNpubCash';
import { useCashu } from '@/hooks/useCashu';
function ClaimFunds() {
const { quotes } = useNpubCash();
const { redeemMintQuote, addMint } = useCashu();
const claimQuote = async (quote: NpubCashQuote) => {
try {
// Add mint if not already added
await addMint(quote.mint_url);
// Redeem the quote to receive Cashu tokens
await redeemMintQuote(quote.mint_url, quote.quote_id);
alert(`Claimed ${quote.amount} sats!`);
} catch (error) {
console.error('Failed to claim:', error);
}
};
return (
<div>
{quotes.map(quote => (
<div key={quote.quote_id}>
<p>{quote.amount} sats</p>
<button onClick={() => claimQuote(quote)}>Claim</button>
</div>
))}
</div>
);
}
```
## Best Practices
### 1. Track Claimed Quotes
The hook stores `lastClaimedAt` timestamp in localStorage to track which quotes are new. Update this after claiming:
```tsx
const [lastClaimed, setLastClaimed] = useLocalStorage('npubcash-last-claimed', 0);
const claimAll = async () => {
for (const quote of quotes) {
await redeemMintQuote(quote.mint_url, quote.quote_id);
}
setLastClaimed(Date.now() / 1000);
};
```
### 2. Handle Expired Quotes
Quotes expire after a certain time. Filter expired quotes in your UI:
```tsx
const activeQuotes = quotes.filter(q =>
q.state === 'PAID' && q.expires_at > Date.now() / 1000
);
```
### 3. Poll for New Payments
Set up periodic polling to check for new payments:
```tsx
useEffect(() => {
const interval = setInterval(() => {
refresh();
}, 30000); // Every 30 seconds
return () => clearInterval(interval);
}, [refresh]);
```
### 4. Display QR Code for Address
Make it easy for users to receive payments by displaying a QR code:
```tsx
import QRCode from 'qrcode.react';
function AddressQR() {
const { lightningAddress } = useNpubCash();
return (
<div>
<QRCode value={`lightning:${lightningAddress}`} size={256} />
<p className="text-xs">{lightningAddress}</p>
</div>
);
}
```
## Error Handling
The hook provides error state for failed operations:
```tsx
function ErrorDisplay() {
const { error, clearAuth, refresh } = useNpubCash();
if (!error) return null;
const handleRetry = () => {
if (error.includes('Authentication')) {
clearAuth(); // Clear stale JWT
}
refresh(); // Try again
};
return (
<div className="bg-destructive/10 p-4 rounded">
<p className="text-sm text-destructive">{error}</p>
<button onClick={handleRetry}>Retry</button>
</div>
);
}
```
## Configuration
### Custom npub.cash Domain
If using a self-hosted npub.cash instance:
```tsx
// In useNpubCash.ts, modify:
const NPUBCASH_API_BASE = 'https://your-instance.com/api/v2';
const NPUBCASH_DOMAIN = 'your-instance.com';
```
## Troubleshooting
### "No user logged in" Error
Ensure the user is logged in via `useCurrentUser`:
```tsx
const { user } = useCurrentUser();
const npubCash = useNpubCash();
if (!user) {
return <p>Please log in first</p>;
}
```
### "NIP-98 validation failed"
Check that:
1. System clock is accurate (NIP-98 events must be recent)
2. URL matches exactly (no query params in NIP-98 event URL)
3. User's signer is working properly
### JWT Token Issues
If JWT tokens aren't working, clear and re-authenticate:
```tsx
const { clearAuth, refresh } = useNpubCash();
clearAuth();
await refresh(); // Will create new NIP-98 auth
```
## Related Documentation
- [Cashu Zap Integration](./CASHU_ZAP_INTEGRATION.md)
- [Nostr Comments System](./NOSTR_COMMENTS.md)
- [AI Chat Integration](./AI_CHAT.md)
## Additional Resources
- [npub.cash Documentation](https://npubx.cash/docs)
- [NIP-98: HTTP Auth](https://github.com/nostr-protocol/nips/blob/master/98.md)
- [Cashu Protocol](https://docs.cashu.space/)
- [NUT-20: Locked Tokens](https://github.com/cashubtc/nuts/blob/main/20.md)
---
**Built with MKStack** - The complete framework for building Nostr applications with AI.
@@ -1,20 +1,48 @@
# Unified ZapButton for AI Agents
# Unified Wallet System for AI Agents (NutStack)
This document explains how AI agents can easily integrate intelligent Lightning zaps into Nostr clients using the unified MKStack `ZapButton` component.
This document explains how AI agents can easily integrate intelligent Lightning zaps and comprehensive wallet functionality into Nostr clients using the unified NutStack wallet system.
## Overview
The `ZapButton` component automatically prioritizes Cashu wallet balances for NIP-57 Lightning zaps when available, with intelligent fallback to traditional Lightning payments (WebLN → NWC → Manual QR). This provides a seamless user experience where users can zap directly from their Cashu token balance or use traditional Lightning methods.
NutStack includes a comprehensive three-mode wallet system that supports multiple payment methods:
- **Tokens Mode**: Cashu token operations with mint management
- **Lightning Mode**: Lightning invoice payments, Lightning address support, and zaps
- **Bitcoin Mode**: On-chain Bitcoin transactions using Taproot addresses
The `CashuWallet` component provides a complete standalone wallet interface with seamless mode switching, while the `ZapButton` component offers intelligent Lightning zaps with Cashu integration for content feeds.
### Three-Mode Architecture
**Tokens Mode**:
- Cashu token send/receive operations
- Multiple mint management
- Token encoding/decoding
- Transaction history tracking
**Lightning Mode**:
- Lightning invoice payment processing
- Lightning address support
- NIP-57 compliant zaps
- WebLN/NWC integration
**Bitcoin Mode**:
- On-chain Bitcoin transactions using Taproot addresses
- UTXO management via Blockstream API
- Fee estimation and transaction building
- Requires nsec login for transaction signing
## Key Features
- **Unified Component**: Single `ZapButton` handles all zap scenarios
- **Intelligent Payment Selection**: Automatically chooses the best available payment method
- **Cashu Integration**: Uses Cashu wallet balance when available and sufficient
- **Smart Fallbacks**: Falls back to WebLN → NWC → Manual QR code
- **Three-Mode Wallet**: Complete wallet system supporting Cashu tokens, Lightning, and Bitcoin
- **Mode Switching**: Seamless switching between payment methods via UI toggle
- **Unified Interface**: Single `CashuWallet` component handles all payment types
- **Intelligent Zap Integration**: `ZapButton` automatically prioritizes Cashu balances for zaps
- **Nostr Integration**: Bitcoin addresses derived from Nostr public keys using Taproot (P2TR)
- **Mobile Optimized**: Responsive design with drawer/modal patterns
- **Transaction History**: Unified history tracking across all payment methods
- **NIP-57 Compliant**: Full compliance with Lightning zap standards
- **Zero Configuration**: Works out of the box with existing Nostr infrastructure
- **Mobile Optimized**: Responsive design with drawer/modal patterns
## Basic Usage
@@ -89,6 +117,30 @@ When Cashu wallet is available and has sufficient balance:
**CRITICAL**: The `useCashu` hook MUST be wrapped in a Context Provider to avoid infinite loops!
### Bitcoin Dependencies
Add these packages for Bitcoin functionality:
```bash
npm install bitcoinjs-lib @bitcoinerlab/secp256k1 ecpair
```
### Cashu Dependencies
Add these packages for Cashu token functionality:
```bash
npm install coco-cashu-core coco-cashu-indexeddb @scure/bip39
```
### Npub.cash Dependencies
Add these packages for npub.cash integration:
```bash
npm install npubcash-sdk npubcash-types
```
### Setup CashuContext (Required!)
Create `src/contexts/CashuContext.tsx`:
@@ -271,6 +323,70 @@ The component automatically handles visibility based on:
<ZapButton target={event} />
```
## CashuWallet Component
The `CashuWallet` component provides a complete standalone wallet interface supporting all three payment modes:
### Basic Implementation
```tsx
import { CashuWallet } from '@/components/wallet/CashuWallet';
function App() {
return (
<Router>
<Routes>
<Route path="/wallet" element={<CashuWallet />} />
<Route path="/" element={<FeedPage />} />
</Routes>
</Router>
);
}
```
### Three-Mode System
The wallet automatically handles mode switching between:
```tsx
// Mode state management
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
// Mode-specific operations
if (mode === 'bitcoin') {
// Bitcoin transaction handling
} else if (mode === 'tokens') {
// Cashu token operations
} else {
// Lightning operations
}
```
### Component Architecture
- **WalletHeader**: Balance display, mode toggle, mint selector
- **TransactionCard**: Send/receive forms for each mode
- **TransactionHistory**: Unified transaction history
- **MintSelector**: Cashu mint management
### Props and State
The component manages comprehensive state for all three modes:
```tsx
// Bitcoin state
const [bitcoinAmount, setBitcoinAmount] = useState('');
const [bitcoinRecipient, setBitcoinRecipient] = useState('');
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
// Cashu state
const { balances, mints, coco } = useCashu();
const { activeMintUrl, setActiveMintUrl } = useMintManager();
// Lightning state
const { getInvoice: getLightningInvoice } = useLightningAddress();
```
## Error Handling
The component handles common error scenarios:
@@ -279,7 +395,99 @@ The component handles common error scenarios:
- Zap endpoint unavailable
- Payment failures
All errors are displayed via toast notifications.
## Bitcoin Mode
NutStack supports on-chain Bitcoin transactions using Taproot addresses derived from Nostr keys:
### Nsec Requirement
Bitcoin transactions require nsec login to access the private key for transaction signing:
```tsx
import { useNsecAccess } from '@/hooks/useNsecAccess';
function BitcoinTransaction() {
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
if (!hasNsecAccess) {
return <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
@@ -382,6 +590,18 @@ useEffect(() => {
- [ ] **CRITICAL**: Create `CashuContext.tsx` with `CashuProvider` (see Required Dependencies)
- [ ] **CRITICAL**: Wrap app with `<CashuProvider>` in App.tsx
- [ ] **CRITICAL**: Import `useCashu` from `@/contexts/CashuContext` in ALL components
- [ ] **Bitcoin Setup**:
- [ ] Install Bitcoin dependencies: `bitcoinjs-lib`, `@bitcoinerlab/secp256k1`, `ecpair`
- [ ] Import Bitcoin utility functions from `@/lib/bitcoin`
- [ ] Ensure user login with nsec for Bitcoin features
- [ ] Test Bitcoin send/receive with Taproot addresses
- [ ] Verify UTXO fetching and balance display
- [ ] **Cashu Setup**:
- [ ] Install Cashu dependencies: `coco-cashu-core`, `coco-cashu-indexeddb`, `@scure/bip39`
- [ ] Initialize coco-cashu-core with mnemonic
- [ ] Add mint management UI
- [ ] Test token send/receive flows
- [ ] Verify npub.cash integration (optional)
- [ ] Import unified `ZapButton` component
- [ ] Create dedicated route/page for `CashuWallet` (don't embed in content feeds)
- [ ] Test all payment methods: Cashu → WebLN → NWC → Manual QR
@@ -390,4 +610,4 @@ useEffect(() => {
- [ ] Verify component separation (wallet management vs content integration)
- [ ] Check console for infinite `refreshBalances` loops (should see throttling logs if working correctly)
This unified integration provides a seamless, intelligent zap experience that automatically selects the best available payment method while leveraging the benefits of both Cashu tokens and Lightning payments.
This unified integration provides a seamless, intelligent wallet experience that automatically selects the best available payment method while leveraging the benefits of Cashu tokens, Lightning payments, and on-chain Bitcoin transactions.
+126 -110
View File
@@ -47,13 +47,14 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"coco-cashu-core": "1.0.0-rc5",
"coco-cashu-core": "1.0.0-rc10",
"coco-cashu-indexeddb": "0.8.0",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
"npubcash-sdk": "^0.2.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
@@ -106,6 +107,7 @@
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",
"integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
@@ -128,22 +130,6 @@
"lru-cache": "^10.4.3"
}
},
"node_modules/@babel/code-frame": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz",
"integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/helper-validator-identifier": "^7.27.1",
"js-tokens": "^4.0.0",
"picocolors": "^1.1.1"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/generator": {
"version": "7.28.3",
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.28.3.tgz",
@@ -1267,6 +1253,7 @@
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
"integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
"dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^5.1.2",
@@ -1406,6 +1393,7 @@
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
"integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.stat": "2.0.5",
@@ -1419,6 +1407,7 @@
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
"integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 8"
@@ -1428,6 +1417,7 @@
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
"integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.scandir": "2.1.5",
@@ -1467,6 +1457,7 @@
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
"integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",
"dev": true,
"license": "MIT",
"optional": true,
"engines": {
@@ -3501,27 +3492,6 @@
"react": "^18 || ^19"
}
},
"node_modules/@testing-library/dom": {
"version": "10.4.1",
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz",
"integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.10.4",
"@babel/runtime": "^7.12.5",
"@types/aria-query": "^5.0.1",
"aria-query": "5.3.0",
"dom-accessibility-api": "^0.5.9",
"lz-string": "^1.5.0",
"picocolors": "1.1.1",
"pretty-format": "^27.0.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@testing-library/jest-dom": {
"version": "6.9.1",
"resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz",
@@ -3577,14 +3547,6 @@
}
}
},
"node_modules/@types/aria-query": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true,
"license": "MIT",
"peer": true
},
"node_modules/@types/chai": {
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.2.tgz",
@@ -3692,7 +3654,7 @@
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"devOptional": true,
"dev": true,
"license": "MIT"
},
"node_modules/@types/qrcode": {
@@ -3709,7 +3671,7 @@
"version": "18.3.25",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.25.tgz",
"integrity": "sha512-oSVZmGtDPmRZtVDqvdKUi/qgCsWp5IDY29wp8na8Bj4B3cc99hfNzvNhlMkVVxctkAOGUA3Km7MMpBHAnWfcIA==",
"devOptional": true,
"dev": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
@@ -3720,7 +3682,7 @@
"version": "18.3.7",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"devOptional": true,
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0"
@@ -4234,12 +4196,14 @@
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
"integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==",
"dev": true,
"license": "MIT"
},
"node_modules/anymatch": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
"integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
"dev": true,
"license": "ISC",
"dependencies": {
"normalize-path": "^3.0.0",
@@ -4253,6 +4217,7 @@
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8.6"
@@ -4265,6 +4230,7 @@
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz",
"integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==",
"dev": true,
"license": "MIT"
},
"node_modules/argparse": {
@@ -4364,6 +4330,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true,
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
@@ -4380,6 +4347,7 @@
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
"integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -4403,6 +4371,7 @@
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
"dev": true,
"license": "MIT",
"dependencies": {
"fill-range": "^7.1.1"
@@ -4478,6 +4447,7 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",
"integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 6"
@@ -4552,6 +4522,7 @@
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"dev": true,
"license": "MIT",
"dependencies": {
"anymatch": "~3.1.2",
@@ -4576,6 +4547,7 @@
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"license": "ISC",
"dependencies": {
"is-glob": "^4.0.1"
@@ -4679,9 +4651,9 @@
}
},
"node_modules/coco-cashu-core": {
"version": "1.0.0-rc5",
"resolved": "https://registry.npmjs.org/coco-cashu-core/-/coco-cashu-core-1.0.0-rc5.tgz",
"integrity": "sha512-xAefjI4vseF/KyAafi54NNkDy0S+vZIAyjfKAp7KkVqkAgIzdQ9meMiDKJDTBR3yI47lqvFZ7Pf0IlOSRlnsnQ==",
"version": "1.0.0-rc10",
"resolved": "https://registry.npmjs.org/coco-cashu-core/-/coco-cashu-core-1.0.0-rc10.tgz",
"integrity": "sha512-EQVVFgkakGqWMloDJR2bJ4d4Skpahz8/UgKwCzjxuyIxhVeSswKBcUQNHCGMZiZR1BxpLjTH8l9wwuPb4xoS8A==",
"dependencies": {
"@cashu/cashu-ts": "^2.7.2"
},
@@ -4723,6 +4695,7 @@
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
"integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 6"
@@ -4745,6 +4718,7 @@
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
@@ -4766,6 +4740,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
"integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",
"dev": true,
"license": "MIT",
"bin": {
"cssesc": "bin/cssesc"
@@ -5022,6 +4997,7 @@
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",
"integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/dijkstrajs": {
@@ -5034,15 +5010,8 @@
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",
"integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==",
"license": "MIT"
},
"node_modules/dom-accessibility-api": {
"version": "0.5.16",
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/dom-helpers": {
"version": "5.2.1",
@@ -5058,6 +5027,7 @@
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
"dev": true,
"license": "MIT"
},
"node_modules/electron-to-chromium": {
@@ -5099,6 +5069,7 @@
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
"dev": true,
"license": "MIT"
},
"node_modules/entities": {
@@ -5443,6 +5414,7 @@
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.stat": "^2.0.2",
@@ -5459,6 +5431,7 @@
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"license": "ISC",
"dependencies": {
"is-glob": "^4.0.1"
@@ -5485,6 +5458,7 @@
"version": "1.19.1",
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz",
"integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==",
"dev": true,
"license": "ISC",
"dependencies": {
"reusify": "^1.0.4"
@@ -5525,6 +5499,7 @@
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
"dev": true,
"license": "MIT",
"dependencies": {
"to-regex-range": "^5.0.1"
@@ -5575,6 +5550,7 @@
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
"integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
"dev": true,
"license": "ISC",
"dependencies": {
"cross-spawn": "^7.0.6",
@@ -5605,6 +5581,7 @@
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
@@ -5619,6 +5596,7 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
@@ -5646,6 +5624,7 @@
"version": "10.4.5",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
"integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==",
"dev": true,
"license": "ISC",
"dependencies": {
"foreground-child": "^3.1.0",
@@ -5666,6 +5645,7 @@
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
"integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",
"dev": true,
"license": "ISC",
"dependencies": {
"is-glob": "^4.0.3"
@@ -5678,6 +5658,7 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
@@ -5687,6 +5668,7 @@
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
"integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^2.0.1"
@@ -5732,6 +5714,7 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
@@ -5870,6 +5853,7 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
"integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
"dev": true,
"license": "MIT",
"dependencies": {
"binary-extensions": "^2.0.0"
@@ -5882,6 +5866,7 @@
"version": "2.16.1",
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",
"integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",
"dev": true,
"license": "MIT",
"dependencies": {
"hasown": "^2.0.2"
@@ -5897,6 +5882,7 @@
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -5915,6 +5901,7 @@
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-extglob": "^2.1.1"
@@ -5927,6 +5914,7 @@
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.12.0"
@@ -5943,12 +5931,14 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"dev": true,
"license": "ISC"
},
"node_modules/jackspeak": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
"integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/cliui": "^8.0.2"
@@ -5964,6 +5954,7 @@
"version": "1.21.7",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz",
"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==",
"dev": true,
"license": "MIT",
"bin": {
"jiti": "bin/jiti.js"
@@ -6089,6 +6080,7 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
"integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14"
@@ -6101,6 +6093,7 @@
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
"dev": true,
"license": "MIT"
},
"node_modules/locate-path": {
@@ -6166,17 +6159,6 @@
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc"
}
},
"node_modules/lz-string": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
},
"node_modules/magic-string": {
"version": "0.30.19",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.19.tgz",
@@ -6205,6 +6187,7 @@
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 8"
@@ -6214,6 +6197,7 @@
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"dev": true,
"license": "MIT",
"dependencies": {
"braces": "^3.0.3",
@@ -6227,6 +6211,7 @@
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8.6"
@@ -6262,6 +6247,7 @@
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
"integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=16 || 14 >=14.17"
@@ -6290,6 +6276,7 @@
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
"integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"any-promise": "^1.0.0",
@@ -6301,6 +6288,7 @@
"version": "3.3.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
"integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
"dev": true,
"funding": [
{
"type": "github",
@@ -6333,6 +6321,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
"integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -6464,6 +6453,21 @@
"integrity": "sha512-78BTryCLcLYv96ONU8Ws3Q1JzjlAt+43pWQhIl86xZmWeegYCNLPml7yQ+gG3vR6V5h4XGj+TxO+SS5dsThQIA==",
"license": "MIT"
},
"node_modules/npubcash-sdk": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/npubcash-sdk/-/npubcash-sdk-0.2.0.tgz",
"integrity": "sha512-Y8UcXYsEbW0mm5VrZDHG1i4YrwYAwFbJPFqQ6GOyVxFDt6/JZ42yLPMu+wWKvEEOCJO5IHwwYkiXQXzFyAK3pA==",
"dependencies": {
"nostr-tools": "^2.15.0",
"npubcash-types": "^0.1.1"
}
},
"node_modules/npubcash-types": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/npubcash-types/-/npubcash-types-0.1.1.tgz",
"integrity": "sha512-/HGfes2cvQpkrWOuUrdemJJhJUQu+xiXl4x+AxQtKUMGCB8uEhfrXJfAQ0n+DgtkIX1YVLOh0a/e6E5LX+fUew==",
"license": "MIT"
},
"node_modules/nwsapi": {
"version": "2.2.22",
"resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.22.tgz",
@@ -6484,6 +6488,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz",
"integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 6"
@@ -6552,6 +6557,7 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
"dev": true,
"license": "BlueOak-1.0.0"
},
"node_modules/parent-module": {
@@ -6593,6 +6599,7 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -6602,12 +6609,14 @@
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
"dev": true,
"license": "MIT"
},
"node_modules/path-scurry": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
"integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"lru-cache": "^10.2.0",
@@ -6640,6 +6649,7 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"dev": true,
"license": "ISC"
},
"node_modules/picomatch": {
@@ -6658,6 +6668,7 @@
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
"integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -6667,6 +6678,7 @@
"version": "4.0.7",
"resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz",
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 6"
@@ -6696,6 +6708,7 @@
"version": "8.5.6",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
"integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
"dev": true,
"funding": [
{
"type": "opencollective",
@@ -6724,6 +6737,7 @@
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz",
"integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==",
"dev": true,
"license": "MIT",
"dependencies": {
"postcss-value-parser": "^4.0.0",
@@ -6741,6 +6755,7 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz",
"integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==",
"dev": true,
"funding": [
{
"type": "opencollective",
@@ -6766,6 +6781,7 @@
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz",
"integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==",
"dev": true,
"funding": [
{
"type": "opencollective",
@@ -6808,6 +6824,7 @@
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz",
"integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==",
"dev": true,
"funding": [
{
"type": "opencollective",
@@ -6833,6 +6850,7 @@
"version": "6.1.2",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",
"integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==",
"dev": true,
"license": "MIT",
"dependencies": {
"cssesc": "^3.0.0",
@@ -6860,6 +6878,7 @@
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
"dev": true,
"license": "MIT"
},
"node_modules/prelude-ls": {
@@ -6872,36 +6891,6 @@
"node": ">= 0.8.0"
}
},
"node_modules/pretty-format": {
"version": "27.5.1",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0",
"react-is": "^17.0.1"
},
"engines": {
"node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"
}
},
"node_modules/pretty-format/node_modules/ansi-styles": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
@@ -6950,6 +6939,7 @@
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
"integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",
"dev": true,
"funding": [
{
"type": "github",
@@ -7036,14 +7026,6 @@
}
}
},
"node_modules/react-is": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true,
"license": "MIT",
"peer": true
},
"node_modules/react-remove-scroll": {
"version": "2.7.1",
"resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.1.tgz",
@@ -7190,6 +7172,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
"integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==",
"dev": true,
"license": "MIT",
"dependencies": {
"pify": "^2.3.0"
@@ -7199,6 +7182,7 @@
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
"integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
"dev": true,
"license": "MIT",
"dependencies": {
"picomatch": "^2.2.1"
@@ -7211,6 +7195,7 @@
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8.6"
@@ -7290,6 +7275,7 @@
"version": "1.22.10",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz",
"integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-core-module": "^2.16.0",
@@ -7320,6 +7306,7 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
"integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
"dev": true,
"license": "MIT",
"engines": {
"iojs": ">=1.0.0",
@@ -7330,7 +7317,7 @@
"version": "4.52.4",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.52.4.tgz",
"integrity": "sha512-CLEVl+MnPAiKh5pl4dEWSyMTpuflgNQiLGhMv8ezD5W/qP8AKvmYpCOKRRNOh7oRKnauBZ4SyeYkMS+1VSyKwQ==",
"devOptional": true,
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "1.0.8"
@@ -7379,6 +7366,7 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
"integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",
"dev": true,
"funding": [
{
"type": "github",
@@ -7450,6 +7438,7 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
@@ -7462,6 +7451,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -7478,6 +7468,7 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
"integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=14"
@@ -7490,6 +7481,7 @@
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
@@ -7513,6 +7505,7 @@
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
"integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"eastasianwidth": "^0.2.0",
@@ -7531,6 +7524,7 @@
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
@@ -7545,12 +7539,14 @@
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/string-width-cjs/node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
@@ -7563,6 +7559,7 @@
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz",
"integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^6.0.1"
@@ -7579,6 +7576,7 @@
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
@@ -7591,6 +7589,7 @@
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
"integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
@@ -7649,6 +7648,7 @@
"version": "3.35.0",
"resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.0.tgz",
"integrity": "sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.2",
@@ -7684,6 +7684,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
"integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -7713,6 +7714,7 @@
"version": "3.4.18",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.18.tgz",
"integrity": "sha512-6A2rnmW5xZMdw11LYjhcI5846rt9pbLSabY5XPxo+XWdxwZaFEn47Go4NzFiHu9sNNmr/kXivP1vStfvMaK1GQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
@@ -7759,6 +7761,7 @@
"version": "6.1.2",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",
"integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==",
"dev": true,
"license": "MIT",
"dependencies": {
"cssesc": "^3.0.0",
@@ -7772,6 +7775,7 @@
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",
"integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==",
"dev": true,
"license": "MIT",
"dependencies": {
"any-promise": "^1.0.0"
@@ -7781,6 +7785,7 @@
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz",
"integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==",
"dev": true,
"license": "MIT",
"dependencies": {
"thenify": ">= 3.1.0 < 4"
@@ -7880,6 +7885,7 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-number": "^7.0.0"
@@ -7931,6 +7937,7 @@
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz",
"integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/tslib": {
@@ -7956,6 +7963,7 @@
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
@@ -8144,6 +8152,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"dev": true,
"license": "MIT"
},
"node_modules/vaul": {
@@ -8428,6 +8437,7 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
@@ -8476,6 +8486,7 @@
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
"integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.1.0",
@@ -8494,6 +8505,7 @@
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
@@ -8511,12 +8523,14 @@
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/wrap-ansi-cjs/node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
@@ -8531,6 +8545,7 @@
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
@@ -8543,6 +8558,7 @@
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
+5 -4
View File
@@ -4,7 +4,7 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "npm i --silent && vite",
"dev": "npm i --legacy-peer-deps --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
@@ -15,9 +15,6 @@
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@scure/bip39": "^2.0.0",
"coco-cashu-core": "1.0.0-rc5",
"coco-cashu-indexeddb": "0.8.0",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -45,17 +42,21 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@scure/bip39": "^2.0.0",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"coco-cashu-core": "1.0.0-rc10",
"coco-cashu-indexeddb": "0.8.0",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
"npubcash-sdk": "^0.2.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 282 KiB

+21
View File
@@ -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"
}
]
}
+33
View File
@@ -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));
}
});
+1 -1
View File
@@ -31,7 +31,7 @@ const queryClient = new QueryClient({
});
const defaultConfig: AppConfig = {
theme: "light",
theme: "system",
relayUrl: "wss://relay.primal.net",
};
+1 -1
View File
@@ -4,7 +4,7 @@ import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { CashuWallet } from "./components/CashuWallet";
import { CashuWallet } from "./components/wallet/CashuWallet";
export function AppRouter() {
return (
-771
View File
@@ -1,771 +0,0 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
import { useCashuMints } from '@/hooks/cashu/useCashuMints';
import { useLightningAddress } from '@/hooks/useLightningAddress';
import { useToast } from '@/hooks/useToast';
import { useQRCode } from '@/hooks/useQRCode';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { QRModal } from '@/components/ui/qr-modal';
import { LoadingModal } from '@/components/wallet/LoadingModal';
import { BalanceDisplay } from '@/components/wallet/BalanceDisplay';
import { ReceiveCard } from '@/components/wallet/ReceiveCard';
import { SendCard } from '@/components/wallet/SendCard';
import { TransactionHistory } from '@/components/wallet/TransactionHistory';
import { ProofBreakdownModal } from '@/components/wallet/ProofBreakdownModal';
import { RemoveMintModal } from '@/components/wallet/RemoveMintModal';
export function CashuWallet() {
// ============================================================================
// HOOKS
// ============================================================================
const {
isInitialized,
isLoading,
error,
balances,
mints,
receive,
send,
getProofs,
addMint,
removeMint,
createMintQuote,
createMeltQuote,
payMeltQuote,
redeemMintQuote,
addMintQuote,
on,
refreshBalances,
refreshMints,
clearError,
getHistory,
} = useCashu();
const { getCleanMintLabel } = useCashuMints(null);
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
// ============================================================================
// STATE - Input Values
// ============================================================================
const [tokenInput, setTokenInput] = useState('');
const [mintUrl, setMintUrl] = useState('');
const [sendAmount, setSendAmount] = useState('');
const [quoteAmount, setQuoteAmount] = useState('');
const [lightningInvoice, setLightningInvoice] = useState('');
const [lightningAddressInput, setLightningAddressInput] = useState('');
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
// ============================================================================
// STATE - UI State
// ============================================================================
const [showSats, setShowSats] = useState(true);
const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens');
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
// ============================================================================
// STATE - Transaction State
// ============================================================================
const [sentToken, setSentToken] = useState<string | null>(null);
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
const [pendingLightningAddress, setPendingLightningAddress] = useState<string | null>(null);
// ============================================================================
// STATE - History
// ============================================================================
const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([]);
const [isLoadingHistory, setIsLoadingHistory] = useState(false);
const [isHistoryExpanded, setIsHistoryExpanded] = useState(false);
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
const [proofBreakdown, setProofBreakdown] = useState<{
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
} | null>(null);
const [showLightningQR, setShowLightningQR] = useState(false);
const [lightningQRCode, setLightningQRCode] = useState<string>('');
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
const [currentInvoice, setCurrentInvoice] = useState<{
quoteId: string;
mintUrl: string;
amount: number;
invoice: string;
qrCodeUrl: string;
expiry: number;
} | null>(null);
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
const [mintToRemove, setMintToRemove] = useState<{
url: string;
name?: string;
} | null>(null);
// Ref to store the mint quote redeemed event unsubscribe function
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
// ============================================================================
// COMPUTED VALUES
// ============================================================================
const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// ============================================================================
// HELPER FUNCTIONS - QR Code Generation
// ============================================================================
// Generate QR code for sent token
const generateSentTokenQRCode = async (token: string) => {
try {
const qrCodeUrl = await generateQRCode(token);
setSentTokenQRCode(qrCodeUrl);
} catch (err) {
console.error('Failed to generate sent token QR code:', err);
}
};
// ============================================================================
// HELPER FUNCTIONS - Mint Management
// ============================================================================
/**
* Set active mint
*/
const handleSetActiveMint = useCallback(async (mintUrl: string | null) => {
// Set the active mint locally
setActiveMintUrl(mintUrl);
}, []);
// ============================================================================
// HELPER FUNCTIONS - History
// ============================================================================
const loadHistory = useCallback(async () => {
try {
setIsLoadingHistory(true);
const entries = await getHistory(50, 0); //TODO: show entire history
setHistoryEntries(entries);
} catch (err) {
console.error('Failed to load history:', err);
} finally {
setIsLoadingHistory(false);
}
}, [getHistory]);
// ============================================================================
// EVENT HANDLERS - Receive
// ============================================================================
const handleReceive = async () => {
if (mode === 'tokens') {
if (!tokenInput.trim()) return;
try {
await receive(tokenInput);
setTokenInput('');
console.log('✅ Token received successfully!');
toast({
title: "Token Received",
description: "Cashu token redeemed successfully!",
});
} catch (err) {
const errorMessage = `Failed to receive token: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Receive Failed",
description: errorMessage,
});
}
} else {
// Lightning mode - create mint quote
if (!quoteAmount || !activeMintUrl) return;
try {
const amount = parseInt(quoteAmount);
if (isNaN(amount) || amount <= 0) {
console.warn('⚠️ Invalid amount');
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
const quote = await createMintQuote(activeMintUrl, amount);
// Generate QR code for the Lightning invoice
const qrCodeUrl = await generateQRCode(quote.request);
// Set the invoice data and show modal
setCurrentInvoice({
quoteId: quote.quote,
mintUrl: activeMintUrl,
amount,
invoice: quote.request,
qrCodeUrl,
expiry: quote.expiry
});
setShowInvoiceModal(true);
console.log('✅ Mint quote created:', quote);
console.log('🔗 Lightning Invoice:', quote.request);
console.log('💡 Wallet will automatically redeem when payment is detected');
toast({
title: "Lightning Invoice Created",
description: "Wallet will automatically claim tokens when payment is detected.",
});
setQuoteAmount('');
// Clean up any previous listener
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
// Listen for payment notification via mint-quote:redeemed event (note: hyphenated!)
console.log('🔔 Setting up payment listener for quote:', quote.quote);
const quoteId = quote.quote;
const invoiceAmount = amount;
const unsubscribe = on('mint-quote:redeemed', (payload: unknown) => {
const redeemedQuote = payload as { quoteId?: string };
console.log('🔔 Mint quote redeemed event received:', redeemedQuote);
// Check if this is the quote we're waiting for
if (redeemedQuote.quoteId === quoteId) {
console.log('✅ Our quote was redeemed! Payment detected:', redeemedQuote);
toast({
title: "Payment Received",
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
});
setShowInvoiceModal(false);
setCurrentInvoice(null);
// Clean up the event listener
mintQuoteUnsubscribeRef.current = null;
unsubscribe();
}
});
// Store unsubscribe function for cleanup
mintQuoteUnsubscribeRef.current = unsubscribe;
} catch (err) {
const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Quote Creation Failed",
description: errorMessage,
});
}
}
};
// ============================================================================
// EVENT HANDLERS - Send
// ============================================================================
const handleSend = async () => {
if (mode === 'tokens') {
if (!sendAmount || !activeMintUrl) return;
try {
const amount = parseInt(sendAmount);
if (isNaN(amount) || amount <= 0) {
console.warn('⚠️ Invalid amount');
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
const encodedToken = await send(activeMintUrl, amount);
setSentToken(encodedToken);
await generateSentTokenQRCode(encodedToken);
console.log('✅ Token created successfully!');
console.log('📤 Encoded token:', encodedToken);
setSendAmount('');
} catch (err) {
const errorMessage = `Failed to send tokens: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Send Failed",
description: errorMessage,
});
}
} else {
// Lightning mode
if (!activeMintUrl) return;
// Step 1: Check if we have a pending Lightning address awaiting amount
if (pendingLightningAddress) {
// Step 2: User entered amount, now resolve address and pay
if (!lightningAddressAmount) return;
try {
const amount = parseInt(lightningAddressAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
console.log('🔄 Resolving Lightning address:', pendingLightningAddress, 'for amount:', amount);
const invoice = await getLightningInvoice({
lightningAddress: pendingLightningAddress,
amountSats: amount,
});
console.log('🔄 Creating melt quote for invoice:', invoice);
const meltQuote = await createMeltQuote(activeMintUrl, invoice);
console.log('🔄 Paying melt quote:', meltQuote.quote);
await payMeltQuote(activeMintUrl, meltQuote.quote);
console.log('✅ Lightning payment sent successfully!');
toast({
title: "Payment Sent",
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
});
// Reset state
setPendingLightningAddress(null);
setLightningAddressInput('');
setLightningAddressAmount('');
// No need to manually refresh balances - events will handle it automatically
} catch (err) {
const errorMessage = `Failed to pay Lightning address: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Payment Failed",
description: errorMessage,
});
}
} else {
// Step 1: Check if input is a Lightning address or invoice
const input = lightningInvoice.trim() || lightningAddressInput.trim();
if (!input) return;
// Check if it's a Lightning address (contains @)
if (input.includes('@')) {
console.log('📧 Detected Lightning address:', input);
setPendingLightningAddress(input);
setLightningAddressInput('');
} else {
// It's a regular Lightning invoice
try {
console.log('🔄 Creating melt quote for invoice:', input);
const meltQuote = await createMeltQuote(activeMintUrl, input);
console.log('🔄 Paying melt quote:', meltQuote.quote);
await payMeltQuote(activeMintUrl, meltQuote.quote);
console.log('✅ Lightning invoice paid successfully!');
toast({
title: "Invoice Paid",
description: "Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.",
});
setLightningInvoice('');
// No need to manually refresh balances - events will handle it automatically
} catch (err) {
const errorMessage = `Failed to pay Lightning invoice: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Invoice Payment Failed",
description: errorMessage,
});
}
}
}
}
};
// ============================================================================
// EVENT HANDLERS - Utility
// ============================================================================
const handleRemoveMintClick = useCallback((mint: { url: string; name?: string }) => {
setMintToRemove(mint);
setShowRemoveMintModal(true);
}, []);
const handleConfirmRemoveMint = useCallback(async () => {
if (!mintToRemove) return;
try {
await removeMint(mintToRemove.url);
// Manually refresh mints since there's no mint:removed event
await refreshMints();
// If the removed mint was the active mint, select the first available mint
if (activeMintUrl === mintToRemove.url) {
const remainingMints = mints.filter(m => m.url !== mintToRemove.url);
if (remainingMints.length > 0) {
setActiveMintUrl(remainingMints[0].url);
} else {
setActiveMintUrl(null);
}
}
toast({
title: "Mint Removed",
description: `${mintToRemove.name || new URL(mintToRemove.url).hostname} has been removed from your wallet`,
});
setShowRemoveMintModal(false);
setMintToRemove(null);
} catch (err) {
console.error('Failed to remove mint:', err);
toast({
variant: "destructive",
title: "Remove Failed",
description: `Failed to remove mint: ${err instanceof Error ? err.message : 'Unknown error'}`,
});
}
}, [mintToRemove, removeMint, refreshMints, activeMintUrl, mints, toast]);
// ============================================================================
// EVENT HANDLERS - Mint Management
// ============================================================================
const handleAddMint = async () => {
if (!mintUrl.trim()) return;
try {
// Normalize URL - add https:// if not present
let normalizedUrl = mintUrl.trim();
if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
normalizedUrl = `https://${normalizedUrl}`;
}
await addMint(normalizedUrl);
setMintUrl('');
// No need to manually refresh - events will handle it automatically
console.log('✅ Mint added successfully:', normalizedUrl);
toast({
title: "Mint Added",
description: "Mint added successfully!",
});
} catch (err) {
const errorMessage = `Failed to add mint: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
toast({
variant: "destructive",
title: "Add Mint Failed",
description: errorMessage,
});
}
};
// ============================================================================
// EVENT HANDLERS - Quote Management
// ============================================================================
const handleShowDenominations = async (mintUrl: string) => {
try {
console.log('🔍 Getting token denominations for mint:', mintUrl);
// Get proofs from the wallet for this specific mint
const proofs = await getProofs(mintUrl);
console.log('💰 Raw proofs for mint:', proofs);
if (!proofs || proofs.length === 0) {
toast({
variant: "destructive",
title: "No Tokens",
description: "No tokens found for this mint",
});
return;
}
// Group proofs by denomination
const denominations: { [key: number]: number } = {};
proofs.forEach((proof: { amount?: number }) => {
const amount = proof.amount || 0;
denominations[amount] = (denominations[amount] || 0) + 1;
});
const totalBalance = Object.entries(denominations)
.reduce((sum, [amount, count]) => sum + (parseInt(amount) * count), 0);
// Set the breakdown data and show the modal
setProofBreakdown({
mintUrl,
denominations,
totalBalance
});
setShowProofBreakdown(true);
} catch (err) {
console.error('Failed to get denominations:', err);
toast({
variant: "destructive",
title: "Failed to Get Denominations",
description: "Failed to get token denominations. Check console for details.",
});
}
};
// ============================================================================
// EFFECTS
// ============================================================================
// Show error toasts when errors occur
useEffect(() => {
if (error) {
toast({
variant: "destructive",
title: "Wallet Error",
description: error.message,
});
}
}, [error, toast]);
// Auto-select active mint when mints change (balances will update automatically via events)
useEffect(() => {
if (mints.length > 0 && !activeMintUrl) {
// Select first mint initially - user can change via dropdown
handleSetActiveMint(mints[0].url);
}
}, [mints, activeMintUrl, handleSetActiveMint]);
// Load transaction history when wallet is initialized
useEffect(() => {
if (isInitialized && historyEntries.length === 0) {
loadHistory();
}
}, [isInitialized, historyEntries.length, loadHistory]);
// Auto-refresh transaction history on new transactions
useEffect(() => {
if (!isInitialized) return;
console.log('📜 Setting up history auto-refresh listeners...');
// Listen for history updates (fires on send, receive transactions)
const unsubscribeHistoryUpdated = on('history:updated', () => {
console.log('📜 History updated event, refreshing...');
loadHistory();
});
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
const unsubscribeMeltCreated = on('melt-quote:created', () => {
console.log('📜 Melt quote created, refreshing history...');
loadHistory();
});
// Listen for melt quote paid (backup, in case creation event missed)
const unsubscribeMeltPaid = on('melt-quote:paid', () => {
console.log('📜 Melt quote paid, refreshing history...');
loadHistory();
});
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
const unsubscribeMintRedeemed = on('mint-quote:redeemed', () => {
console.log('📜 Mint quote redeemed (invoice paid), refreshing history...');
loadHistory();
});
return () => {
unsubscribeHistoryUpdated();
unsubscribeMeltCreated();
unsubscribeMeltPaid();
unsubscribeMintRedeemed();
};
}, [isInitialized, on, loadHistory]);
// Cleanup mint quote listener on component unmount
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
console.log('🧹 Cleaning up mint quote listener (component unmount)');
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, []);
// ============================================================================
// RENDER - Main UI
// ============================================================================
return (
<>
<LoadingModal isLoading={isLoading || !isInitialized} />
<div className="max-w-4xl mx-auto py-1 px-3 sm:px-4 relative">
{/* ========================================================================
SECTION: Balance Display
======================================================================== */}
<BalanceDisplay
totalBalance={totalBalance}
balances={balances}
showSats={showSats}
setShowSats={setShowSats}
mode={mode}
setMode={setMode}
activeMintUrl={activeMintUrl}
setActiveMintUrl={handleSetActiveMint}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={handleAddMint}
onRemoveMint={handleRemoveMintClick}
onShowDenominations={handleShowDenominations}
getCleanMintLabel={getCleanMintLabel}
/>
{/* ========================================================================
SECTION: Receive & Send Cards
======================================================================== */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<ReceiveCard
mode={mode}
tokenInput={tokenInput}
setTokenInput={setTokenInput}
quoteAmount={quoteAmount}
setQuoteAmount={setQuoteAmount}
activeMintUrl={activeMintUrl}
onReceive={handleReceive}
isLoading={isLoading}
/>
<SendCard
mode={mode}
sendAmount={sendAmount}
setSendAmount={setSendAmount}
lightningInvoice={lightningInvoice}
setLightningInvoice={setLightningInvoice}
lightningAddressInput={lightningAddressInput}
setLightningAddressInput={setLightningAddressInput}
lightningAddressAmount={lightningAddressAmount}
setLightningAddressAmount={setLightningAddressAmount}
pendingLightningAddress={pendingLightningAddress}
setPendingLightningAddress={setPendingLightningAddress}
activeMintUrl={activeMintUrl}
onSend={handleSend}
isResolvingAddress={isResolvingAddress}
isLoading={isLoading}
/>
</div>
{/* ========================================================================
SECTION: Sent Token Display
======================================================================== */}
{sentToken && (
<QRModal
isOpen={!!sentToken}
onClose={() => setSentToken(null)}
title="Cashu Token"
description="Share this token with the recipient to send them your sats"
qrCodeUrl={sentTokenQRCode}
content={sentToken}
icon="qr"
/>
)}
{/* ========================================================================
SECTION: Transaction History
======================================================================== */}
<TransactionHistory
entries={historyEntries}
isLoading={isLoadingHistory}
isExpanded={isHistoryExpanded}
setIsExpanded={setIsHistoryExpanded}
/>
{/* ========================================================================
SECTION: Modals
======================================================================== */}
<>
<ProofBreakdownModal
isOpen={showProofBreakdown}
onClose={() => setShowProofBreakdown(false)}
breakdown={proofBreakdown}
/>
<QRModal
isOpen={showLightningQR}
onClose={() => setShowLightningQR(false)}
title="Lightning Address QR Code"
description="Scan to send Lightning payments"
qrCodeUrl={lightningQRCode}
content={''}
icon="qr"
/>
{currentInvoice && (
<QRModal
isOpen={showInvoiceModal}
onClose={() => {
// Clean up event listener when modal is closed manually
if (mintQuoteUnsubscribeRef.current) {
console.log('🧹 Cleaning up mint quote listener (modal closed)');
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
setShowInvoiceModal(false);
}}
onExpiry={() => {
// Clean up event listener when invoice expires
if (mintQuoteUnsubscribeRef.current) {
console.log('🧹 Cleaning up mint quote listener (invoice expired)');
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
// Show destructive toast
toast({
variant: "destructive",
title: "Invoice Expired",
description: "The Lightning invoice has expired. Please create a new one.",
});
}}
title="Lightning Invoice"
description={`Pay this invoice to receive ${currentInvoice.amount} sats`}
qrCodeUrl={currentInvoice.qrCodeUrl}
content={currentInvoice.invoice}
icon="zap"
expiryTimestamp={currentInvoice.expiry}
/>
)}
<RemoveMintModal
isOpen={showRemoveMintModal}
onClose={() => setShowRemoveMintModal(false)}
mint={mintToRemove}
onConfirm={handleConfirmRemoveMint}
isLoading={isLoading}
/>
</>
</div>
</>
);
}
+6 -12
View File
@@ -26,7 +26,7 @@ import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useNWC } from '@/hooks/useNWCContext';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/useCashu';
import { useCashu } from '@/hooks/cashu/useCashu';
import { useToast } from '@/hooks/useToast';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
@@ -95,7 +95,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Primary Payment Method - Cashu */}
<div className="space-y-3">
<h3 className="font-medium">Primary Payment Method</h3>
<h3 className="font-medium">Primary Wallet</h3>
<div className="flex items-center justify-between p-3 border rounded-lg bg-muted/30">
<div className="flex items-center gap-3">
<Coins className="h-4 w-4 text-muted-foreground" />
@@ -116,19 +116,13 @@ const WalletContent = forwardRef<HTMLDivElement, {
</Badge>
</div>
</div>
<div className="text-xs text-muted-foreground text-center">
Cashu tokens are used first for Lightning zaps. Set up your Cashu wallet for instant payments.
</div>
</div>
<Separator />
{/* Lightning Fallback Methods */}
<div className="space-y-3">
<h3 className="font-medium">Lightning Fallback Methods</h3>
<div className="text-xs text-muted-foreground mb-3">
Used when Cashu balance is insufficient or unavailable
</div>
<h3 className="font-medium">Other Options</h3>
<div className="grid gap-3">
{/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg">
@@ -233,7 +227,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
<Separator />
<div className="text-center py-4 space-y-2">
<p className="text-sm text-muted-foreground">
Set up your Cashu wallet for instant payments, or install a WebLN extension/connect NWC wallet for Lightning fallback.
Set up your Cashu wallet for instant payments, or install a WebLN extension/connect NWC wallet for Lightning
</p>
</div>
</>
@@ -367,7 +361,7 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
Payment Settings
</DrawerTitle>
<DrawerDescription>
Manage Cashu wallet and Lightning fallback methods for zaps.
Manage wallet methods for zaps
</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto">
@@ -423,7 +417,7 @@ export function LightningWalletModal({ children, className }: LightningWalletMod
Payment Settings
</DialogTitle>
<DialogDescription>
Manage Cashu wallet and Lightning fallback methods for zaps.
Manage wallet methods for zaps
</DialogDescription>
</DialogHeader>
<WalletContent {...walletContentProps} />
+1 -1
View File
@@ -30,7 +30,7 @@ import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/useCashu';
import { useCashu } from '@/hooks/cashu/useCashu';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
+1 -1
View File
@@ -30,7 +30,7 @@ import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCashu } from '@/hooks/useCashu';
import { useCashu } from '@/hooks/cashu/useCashu';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
+2 -2
View File
@@ -182,7 +182,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl overflow-y-scroll")}
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
@@ -190,7 +190,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
Sign up or log in to continue
</DialogDescription>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1 min-h-0'>
{/* Prominent Sign Up Section */}
<div className='relative p-4 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 border border-blue-200 dark:border-blue-800 overflow-hidden'>
<div className='relative z-10 text-center space-y-3'>
+50
View File
@@ -0,0 +1,50 @@
import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
export function LoginIcon() {
const { currentUser } = useLoggedInAccounts();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
const handleLogin = () => {
setLoginDialogOpen(false);
setSignupDialogOpen(false);
};
if (currentUser) {
return (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
);
}
return (
<>
<Button
onClick={() => setLoginDialogOpen(true)}
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
title="Log in"
>
<User className="!h-6 !w-6" />
</Button>
<LoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SignupDialog
isOpen={signupDialogOpen}
onClose={() => setSignupDialogOpen(false)}
/>
</>
);
}
+1 -1
View File
@@ -301,7 +301,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
{getTitle()}
</DialogTitle>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
<div className='px-6 pt-2 pb-4 space-y-4 flex-1'>
{/* Welcome Step - New engaging introduction */}
{step === 'welcome' && (
<div className='text-center space-y-4'>
@@ -1,11 +1,11 @@
import { Card, CardContent } from '@/components/ui/card';
import { Loader2 } from 'lucide-react';
interface LoadingModalProps {
interface LoadingScreenProps {
isLoading: boolean;
}
export function LoadingModal({ isLoading }: LoadingModalProps) {
export function LoadingScreen({ isLoading }: LoadingScreenProps) {
if (!isLoading) return null;
return (
@@ -13,7 +13,6 @@ export function LoadingModal({ isLoading }: LoadingModalProps) {
<Card className="border-0 shadow-lg bg-background">
<CardContent className="flex items-center justify-center p-8">
<Loader2 className="h-8 w-8 animate-spin mr-3" />
<span className="text-lg font-medium">Loading</span>
</CardContent>
</Card>
</div>
+3 -1
View File
@@ -125,7 +125,9 @@ export function QRModal({
onClick={handleCopy}
title="Click to copy full content"
>
{content.length > 20 ? `${content.substring(0, 20)}...` : content}
{content.length > 33
? `${content.substring(0, 15)}...${content.substring(content.length - 15)}`
: content}
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
{copied ? (
<Check className="h-4 w-4 text-green-600" />
+2 -2
View File
@@ -15,10 +15,10 @@ const Slider = React.forwardRef<
)}
{...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.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>
))
Slider.displayName = SliderPrimitive.Root.displayName
-192
View File
@@ -1,192 +0,0 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Wallet, ChevronDown, Plus, X, Zap, Coins, HelpCircle } from 'lucide-react';
import { useCashuBalances } from '@/hooks/cashu/useCashuBalances';
interface CashuMint {
url: string;
name?: string;
}
interface BalanceDisplayProps {
totalBalance: number;
balances: { [key: string]: number };
showSats: boolean;
setShowSats: (showSats: boolean) => void;
mode: 'tokens' | 'lightning';
setMode: (mode: 'tokens' | 'lightning') => void;
activeMintUrl: string | null;
setActiveMintUrl: (url: string | null) => void;
mints: CashuMint[];
mintUrl: string;
setMintUrl: (url: string) => void;
onAddMint: () => void;
onRemoveMint: (mint: CashuMint) => void;
onShowDenominations: (mintUrl: string) => void;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
}
export function BalanceDisplay({
totalBalance,
balances,
showSats,
setShowSats,
mode,
setMode,
activeMintUrl,
setActiveMintUrl,
mints,
mintUrl,
setMintUrl,
onAddMint,
onRemoveMint,
onShowDenominations,
getCleanMintLabel,
}: BalanceDisplayProps) {
const { convertCurrency } = useCashuBalances(null);
return (
<div className="text-center py-2">
<div className="flex items-center justify-center gap-3">
<button
onClick={() => setShowSats(!showSats)}
className="text-5xl font-bold tabular-nums hover:opacity-80 transition-opacity cursor-pointer"
title={`Click to show in ${showSats ? 'USD' : 'sats'}`}
>
{convertCurrency(totalBalance, showSats)}
</button>
</div>
{/* Main Mode Toggle */}
<div className="mt-4 flex items-center justify-center">
<div className="flex gap-1 bg-muted rounded-lg p-1">
<button
onClick={() => setMode('tokens')}
className={`px-4 py-2 rounded text-sm transition-colors flex items-center gap-2 ${
mode === 'tokens' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Coins className="h-4 w-4" />
Cashu
</button>
<button
onClick={() => setMode('lightning')}
className={`px-4 py-2 rounded text-sm transition-colors flex items-center gap-2 ${
mode === 'lightning' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Zap className="h-4 w-4" />
Lightning
</button>
</div>
</div>
{/* Active Mint Dropdown and Balance */}
<div className="mt-3 flex items-center justify-center gap-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2 text-muted-foreground hover:text-foreground">
<Wallet className="h-4 w-4" />
{activeMintUrl ? getCleanMintLabel({ url: activeMintUrl }) : 'Select Mint'}
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" className="w-72">
{mints.length === 0 && (
<DropdownMenuItem disabled>No mints connected</DropdownMenuItem>
)}
{mints
.filter((mint) => mint.url)
.map((mint, index) => (
<DropdownMenuItem
key={`dd-mint-${mint.url || `unknown-${index}`}`}
className="flex items-center justify-between"
onClick={() => setActiveMintUrl(mint.url)}
>
<div className="flex items-center gap-2">
<span className="font-medium">{getCleanMintLabel(mint)}</span>
</div>
<Button
size="sm"
variant="ghost"
className="h-6 w-6 p-0 hover:bg-destructive hover:text-destructive-foreground"
onClick={(e) => {
e.stopPropagation();
onRemoveMint(mint);
}}
>
<X className="h-3 w-3" />
</Button>
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<div className="px-2 py-1.5">
<div className="flex gap-2">
<Input
placeholder="mint.example.com"
value={mintUrl}
onChange={(e) => setMintUrl(e.target.value)}
className="h-8"
/>
<Button size="sm" onClick={onAddMint} disabled={!mintUrl.trim()}>
<Plus className="h-3.5 w-3.5 mr-1" />
Add
</Button>
</div>
</div>
</DropdownMenuContent>
</DropdownMenu>
{/* Active Mint Balance */}
{activeMintUrl && (
<div className="flex items-center gap-2">
<button
onClick={() => activeMintUrl && onShowDenominations(activeMintUrl)}
className="text-sm font-semibold tabular-nums hover:opacity-80 transition-opacity cursor-pointer text-muted-foreground hover:text-foreground"
title="Click to see proof breakdown"
>
{convertCurrency(balances[activeMintUrl] || 0, showSats)}
</button>
{/* Help button */}
<Dialog>
<DialogTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground">
<HelpCircle className="h-4 w-4" />
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
What is a Mint?
</DialogTitle>
<DialogDescription className="space-y-3 text-left">
<p>
A <strong>mint</strong> is a server that issues and manages Cashu tokens. Think of it like a bank for digital cash.
</p>
<p>
<strong>Key features:</strong>
</p>
<ul className="list-disc list-inside space-y-1 ml-4">
<li>Issues tokens when you deposit Lightning payments</li>
<li>Redeems tokens when you receive them</li>
<li>Manages your token balance</li>
<li>Enables Lightning ↔ Cashu conversions</li>
</ul>
<p>
<strong>Note:</strong> Each mint maintains its own separate balance. You can add multiple mints to diversify your holdings and swap balances between them.
</p>
</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
</div>
)}
</div>
</div>
);
}
+669
View File
@@ -0,0 +1,669 @@
import { useState, useEffect, useRef } from 'react';
import { nip19 } from 'nostr-tools';
import { useCashu } from '@/hooks/cashu/useCashu';
import { useLightningAddress } from '@/hooks/useLightningAddress';
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { useQRCode } from '@/hooks/useQRCode';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { useMintManager } from '@/hooks/cashu/useMintManager';
import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
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 { WalletHeader } from './WalletHeader';
import { TransactionCard } from './PaymentCard';
import { WalletModals } from './MintModals';
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import { TransactionHistory } from './TransactionHistory';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChevronUp, Send, Download } from 'lucide-react';
import { Button } from '@/components/ui/button';
export function CashuWallet() {
// ============================================================================
// CORE HOOKS
// ============================================================================
const {
coco,
repositories,
isInitialized,
isLoading,
error,
balances,
mints,
getEncodedToken,
clearError,
refreshMints,
} = useCashu();
const { user } = useCurrentUser();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const { toast } = useToast();
const { generateQRCode } = useQRCode();
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 {
setMint: setNpubCashMint,
getUserInfo: getNpubCashUserInfo,
getAllQuotes,
refreshQuotes,
syncQuotesWithWallet,
isLoggedIn: isNpubCashLoggedIn,
isLoading: isNpubCashLoading,
error: npubCashError,
clearError: clearNpubCashError
} = useNpubCash();
// Wrapper to handle return type mismatch
const handleSetNpubCashMint = (mintUrl: string): Promise<boolean> => {
return setNpubCashMint(mintUrl);
};
// ============================================================================
// DOMAIN HOOKS
// ============================================================================
const {
activeMintUrl,
setActiveMintUrl,
mintUrl,
setMintUrl,
mintDropdownOpen,
setMintDropdownOpen,
handleAddMint,
handleRemoveMintClick,
handleConfirmRemoveMint,
mintToRemove,
setMintToRemove,
showRemoveMintModal,
setShowRemoveMintModal,
getCleanMintLabel,
handleShowDenominations,
} = useMintManager({
coco,
mints,
repositories,
isNpubCashLoggedIn,
setNpubCashMint: handleSetNpubCashMint,
refreshMints,
toast,
});
// Wrapper for setActiveMintUrl to handle the async nature
const handleSetActiveMintSync = (url: string | null) => {
setActiveMintUrl(url);
};
const {
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
decodedInvoiceAmount,
setDecodedInvoiceAmount,
pendingInvoice,
setPendingInvoice,
sentToken,
setSentToken,
sentTokenQRCode,
showInvoiceModal,
setShowInvoiceModal,
currentInvoice,
setCurrentInvoice,
handleReceive,
handleSend,
handleConfirmInvoicePayment,
mintQuoteUnsubscribeRef,
} = useWalletTransactions({
coco,
activeMintUrl,
isNpubCashLoggedIn,
repositories,
generateQRCode,
toast,
getEncodedToken,
getLightningInvoice,
});
const {
historyEntries,
isLoadingHistory,
isHistoryExpanded,
setIsHistoryExpanded,
} = useHistoryManager({
coco,
isInitialized,
});
// ============================================================================
// UI STATE
// ============================================================================
const [showSats, setShowSats] = useState(true);
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
const [proofBreakdown, setProofBreakdown] = useState<{
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
} | null>(null);
const [showLightningQR, setShowLightningQR] = useState(false);
const [lightningQRCode, setLightningQRCode] = useState<string>('');
const [showLightningAddressQR, setShowLightningAddressQR] = useState(false);
const [lightningAddressQRCode, setLightningAddressQRCode] = useState<string>('');
const [npubCashUserInfo, setNpubCashUserInfo] = useState<NpubCashUserInfo | null>(null);
const [showSendModal, setShowSendModal] = useState(false);
const [showReceiveModal, setShowReceiveModal] = 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
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
// ============================================================================
const totalBalance: number = mode === 'bitcoin'
? (bitcoinBalanceData?.balance || 0)
: (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// ============================================================================
// EFFECTS - Error Handling
// ============================================================================
useEffect(() => {
if (error) {
toast({
variant: "destructive",
title: "Wallet Error",
description: error.message,
});
}
}, [error, toast]);
useEffect(() => {
if (npubCashError) {
toast({
variant: "destructive",
title: "Npub.cash Error",
description: npubCashError,
});
clearNpubCashError();
}
}, [npubCashError, clearNpubCashError, toast]);
// ============================================================================
// EFFECTS - NPub.cash Integration
// ============================================================================
useEffect(() => {
if (!isNpubCashLoggedIn) {
hasCheckedNpubCashRef.current = false;
setNpubCashUserInfo(null);
return;
}
if (!isInitialized || hasCheckedNpubCashRef.current || isNpubCashLoading) return;
const fetchUserInfo = async () => {
hasCheckedNpubCashRef.current = true;
const userInfo = await getNpubCashUserInfo();
if (!userInfo) return;
setNpubCashUserInfo(userInfo);
// Sync mint from npub.cash if different from active mint
if (userInfo.mint_url && userInfo.mint_url !== activeMintUrl) {
const mintExists = mints.some(m => m.url === userInfo.mint_url);
if (!mintExists && coco) {
try {
await coco.mint.addMint(userInfo.mint_url);
setTimeout(() => setActiveMintUrl(userInfo.mint_url, false), 500);
} catch {
// Silent failure - user can manually add mint if needed
}
} else if (mintExists) {
setActiveMintUrl(userInfo.mint_url, false);
}
}
};
fetchUserInfo();
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, activeMintUrl, mints, coco, setActiveMintUrl]);
// Set up automatic quote sync subscription when logged into npub.cash
useEffect(() => {
if (!isNpubCashLoggedIn || !coco || !isInitialized) return;
let unsubscribe: (() => void) | null = null;
const setupSync = async () => {
unsubscribe = await syncQuotesWithWallet(coco, toast);
};
setupSync();
return () => {
if (unsubscribe) {
unsubscribe();
}
};
}, [isNpubCashLoggedIn, coco, isInitialized, syncQuotesWithWallet, toast]);
// ============================================================================
// EFFECTS - Cleanup
// ============================================================================
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, []);
// ============================================================================
// RENDER
// ============================================================================
return (
<>
<div className="max-w-4xl mx-auto pt-16 pb-32 px-3 sm:px-4 relative">
{/* Wallet Header (includes mode toggle, login icon, balance, lightning address, and mint selector) */}
<WalletHeader
totalBalance={totalBalance}
balances={balances}
showSats={showSats}
setShowSats={setShowSats}
mode={mode}
setMode={setMode}
userPubkey={user?.pubkey}
npubCashUsername={user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) : undefined}
onCopyToClipboard={copyToClipboard}
onShowLightningAddressQR={(qr) => {
setLightningAddressQRCode(qr);
setShowLightningAddressQR(true);
}}
onShowBitcoinAddressQR={(qr) => {
setBitcoinAddressQRCode(qr);
setShowBitcoinAddressQR(true);
}}
generateQRCode={generateQRCode}
// MintSelector props
activeMintUrl={activeMintUrl}
setActiveMintUrl={handleSetActiveMintSync}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={handleAddMint}
onRemoveMint={handleRemoveMintClick}
onShowDenominations={(mintUrl) => handleShowDenominations(mintUrl, setShowProofBreakdown, setProofBreakdown)}
getCleanMintLabel={getCleanMintLabel}
dropdownOpen={mintDropdownOpen}
setDropdownOpen={setMintDropdownOpen}
/>
{/* Action Buttons and Transaction History Container */}
<div className="fixed bottom-0 left-0 right-0 pb-8 pb-safe">
{/* Action Buttons */}
<div className="flex gap-20 justify-center py-8">
<Button
variant="outline"
size="icon"
onClick={() => setShowReceiveModal(true)}
disabled={isLoading || isNpubCashLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Download className="h-12 w-12" />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => setShowSendModal(true)}
disabled={isLoading || isNpubCashLoading}
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
>
<Send className="h-12 w-12" />
</Button>
</div>
{/* Transaction History Button */}
<div className="max-w-4xl mx-auto">
<button
onClick={() => setShowHistoryModal(true)}
className="w-full py-2 px-4 flex justify-center border-t border-muted hover:bg-muted/30 transition-colors"
>
<ChevronUp className="h-5 w-5 text-muted-foreground" />
</button>
</div>
</div>
{/* Modals */}
<>
<WalletModals
showProofBreakdown={showProofBreakdown}
setShowProofBreakdown={setShowProofBreakdown}
proofBreakdown={proofBreakdown}
showRemoveMintModal={showRemoveMintModal}
setShowRemoveMintModal={setShowRemoveMintModal}
mintToRemove={mintToRemove}
onConfirmRemoveMint={handleConfirmRemoveMint}
isLoading={isLoading || isNpubCashLoading}
showLightningQR={showLightningQR}
setShowLightningQR={setShowLightningQR}
lightningQRCode={lightningQRCode}
showLightningAddressQR={showLightningAddressQR}
setShowLightningAddressQR={setShowLightningAddressQR}
lightningAddressQRCode={lightningAddressQRCode}
userPubkey={user?.pubkey}
npubCashUserInfo={npubCashUserInfo}
currentInvoice={currentInvoice}
showInvoiceModal={showInvoiceModal}
setShowInvoiceModal={setShowInvoiceModal}
mintQuoteUnsubscribeRef={mintQuoteUnsubscribeRef}
sentToken={sentToken}
setSentToken={setSentToken}
sentTokenQRCode={sentTokenQRCode}
/>
{/* Bottom Drawer Modals */}
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
<DrawerContent className="h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
</DrawerHeader>
<div className="px-4 pb-4">
<TransactionCard
mode={mode}
operation="send"
sendAmount={sendAmount}
setSendAmount={setSendAmount}
lightningInvoice={lightningInvoice}
setLightningInvoice={setLightningInvoice}
lightningAddressInput={lightningAddressInput}
setLightningAddressInput={setLightningAddressInput}
lightningAddressAmount={lightningAddressAmount}
setLightningAddressAmount={setLightningAddressAmount}
pendingLightningAddress={pendingLightningAddress}
setPendingLightningAddress={setPendingLightningAddress}
decodedInvoiceAmount={decodedInvoiceAmount}
setDecodedInvoiceAmount={setDecodedInvoiceAmount}
pendingInvoice={pendingInvoice}
setPendingInvoice={setPendingInvoice}
tokenInput=""
setTokenInput={() => {}}
quoteAmount=""
setQuoteAmount={() => {}}
activeMintUrl={activeMintUrl}
onSend={() => {
if (mode === 'bitcoin') {
handleBitcoinSend();
} else {
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
handleSend();
if (mode === 'tokens' || wasPendingBefore) {
setShowSendModal(false);
}
}
}}
onReceive={() => {}}
onConfirmInvoice={() => {
handleConfirmInvoicePayment();
setShowSendModal(false);
}}
isResolvingAddress={isResolvingAddress}
isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading}
// Bitcoin props
bitcoinAddress={bitcoinAddress || ''}
bitcoinAmount={bitcoinAmount}
setBitcoinAmount={setBitcoinAmount}
bitcoinRecipient={bitcoinRecipient}
setBitcoinRecipient={setBitcoinRecipient}
pendingBitcoinRecipient={pendingBitcoinRecipient}
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
hasNsecAccess={hasNsecAccess}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showReceiveModal} onOpenChange={handleReceiveDrawerClose}>
<DrawerContent className="h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
</DrawerHeader>
<div className="px-4 pb-4">
<TransactionCard
mode={mode}
operation="receive"
sendAmount=""
setSendAmount={() => {}}
lightningInvoice=""
setLightningInvoice={() => {}}
lightningAddressInput=""
setLightningAddressInput={() => {}}
lightningAddressAmount=""
setLightningAddressAmount={() => {}}
pendingLightningAddress={null}
setPendingLightningAddress={() => {}}
decodedInvoiceAmount={null}
setDecodedInvoiceAmount={() => {}}
pendingInvoice={null}
setPendingInvoice={() => {}}
tokenInput={tokenInput}
setTokenInput={setTokenInput}
quoteAmount={quoteAmount}
setQuoteAmount={setQuoteAmount}
activeMintUrl={activeMintUrl}
onSend={() => {}}
onReceive={() => {
if (mode === 'bitcoin') {
handleBitcoinReceive();
setShowReceiveModal(false);
} else {
handleReceive();
setShowReceiveModal(false);
}
}}
isResolvingAddress={false}
isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading}
// Bitcoin props
bitcoinAddress={bitcoinAddress || ''}
bitcoinAmount=""
setBitcoinAmount={() => {}}
bitcoinRecipient=""
setBitcoinRecipient={() => {}}
pendingBitcoinRecipient={null}
setPendingBitcoinRecipient={() => {}}
hasNsecAccess={hasNsecAccess}
/>
</div>
</DrawerContent>
</Drawer>
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
<DrawerContent className="max-h-[80vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
</DrawerHeader>
<ScrollArea className="h-[80vh] px-4 pb-4">
<TransactionHistory
entries={historyEntries}
isLoading={isLoadingHistory}
/>
</ScrollArea>
</DrawerContent>
</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>
</>
);
}
+274
View File
@@ -0,0 +1,274 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { X, Coins, AlertTriangle, RefreshCw } from 'lucide-react';
import { QRModal } from '@/components/ui/qr-modal';
import { nip19 } from 'nostr-tools';
import { useToast } from '@/hooks/useToast';
interface ProofBreakdown {
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
}
interface MintToRemove {
url: string;
name?: string;
}
interface WalletModalProps {
// Proof Breakdown Modal
showProofBreakdown: boolean;
setShowProofBreakdown: (show: boolean) => void;
proofBreakdown: ProofBreakdown | null;
// Remove Mint Modal
showRemoveMintModal: boolean;
setShowRemoveMintModal: (show: boolean) => void;
mintToRemove: MintToRemove | null;
onConfirmRemoveMint: () => void;
isLoading: boolean;
// QR Modals
showLightningQR: boolean;
setShowLightningQR: (show: boolean) => void;
lightningQRCode: string;
showLightningAddressQR: boolean;
setShowLightningAddressQR: (show: boolean) => void;
lightningAddressQRCode: string;
userPubkey?: string;
npubCashUserInfo?: { name?: string } | null;
// Invoice Modal
currentInvoice?: {
amount: number;
qrCodeUrl: string;
invoice: string;
expiry: number;
} | null;
showInvoiceModal: boolean;
setShowInvoiceModal: (show: boolean) => void;
mintQuoteUnsubscribeRef: React.MutableRefObject<(() => void) | null>;
// Sent Token Modal
sentToken: string | null;
setSentToken: (token: string | null) => void;
sentTokenQRCode: string;
}
export function WalletModals({
showProofBreakdown,
setShowProofBreakdown,
proofBreakdown,
showRemoveMintModal,
setShowRemoveMintModal,
mintToRemove,
onConfirmRemoveMint,
isLoading,
showLightningQR,
setShowLightningQR,
lightningQRCode,
showLightningAddressQR,
setShowLightningAddressQR,
lightningAddressQRCode,
userPubkey,
npubCashUserInfo,
currentInvoice,
showInvoiceModal,
setShowInvoiceModal,
mintQuoteUnsubscribeRef,
sentToken,
setSentToken,
sentTokenQRCode,
}: WalletModalProps) {
const { toast } = useToast();
return (
<>
{/* Proof Breakdown Modal */}
{showProofBreakdown && proofBreakdown && (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
onClick={() => setShowProofBreakdown(false)}
>
<Card
className="w-full max-w-md border-0 shadow-lg bg-background"
onClick={(e) => e.stopPropagation()}
>
<CardHeader className="relative">
<Button
onClick={() => setShowProofBreakdown(false)}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<Coins className="h-5 w-5 mr-2" />
Token Breakdown
</CardTitle>
<CardDescription>
{new URL(proofBreakdown.mintUrl).hostname}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-center py-2">
<div className="text-2xl font-bold text-primary">
{proofBreakdown.totalBalance.toLocaleString()} sats
</div>
<div className="text-sm text-muted-foreground">Total Balance</div>
</div>
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">Denominations:</div>
{Object.entries(proofBreakdown.denominations)
.sort(([a], [b]) => parseInt(a) - parseInt(b))
.map(([amount, count]) => (
<div key={amount} className="flex items-center justify-between p-2 bg-muted/30 rounded">
<div className="flex items-center gap-2">
<Coins className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{parseInt(amount).toLocaleString()} sats</span>
</div>
<Badge variant="secondary" className="bg-primary/10 text-primary">
× {count}
</Badge>
</div>
))}
</div>
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded">
💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations.
</div>
</CardContent>
</Card>
</div>
)}
{/* Remove Mint Modal */}
{showRemoveMintModal && mintToRemove && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader className="relative">
<Button
onClick={() => setShowRemoveMintModal(false)}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<AlertTriangle className="h-5 w-5 mr-2 text-destructive" />
Remove Mint
</CardTitle>
<CardDescription>
Are you sure you want to remove this mint from your wallet?
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="bg-muted p-4 rounded-lg border">
<div className="font-medium">{mintToRemove.name || new URL(mintToRemove.url).hostname}</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
<div>⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.</div>
<div>💡 You can always add this mint back later if needed.</div>
</div>
<div className="flex gap-2 justify-end">
<Button
variant="outline"
onClick={() => setShowRemoveMintModal(false)}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={onConfirmRemoveMint}
disabled={isLoading}
>
{isLoading ? (
<>
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
Removing...
</>
) : (
<>
<X className="h-4 w-4 mr-2" />
Remove Mint
</>
)}
</Button>
</div>
</CardContent>
</Card>
</div>
)}
{/* QR Modals */}
<QRModal
isOpen={showLightningQR}
onClose={() => setShowLightningQR(false)}
title="Lightning Address QR Code"
description="Scan to send Lightning payments"
qrCodeUrl={lightningQRCode}
content={''}
icon="qr"
/>
<QRModal
isOpen={showLightningAddressQR}
onClose={() => setShowLightningAddressQR(false)}
title="Lightning Address"
description="Scan this QR code to send payments to your Lightning address"
qrCodeUrl={lightningAddressQRCode}
content={userPubkey ? `${npubCashUserInfo?.name || nip19.npubEncode(userPubkey)}@npubx.cash` : ''}
icon="zap"
/>
{currentInvoice && (
<QRModal
isOpen={showInvoiceModal}
onClose={() => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
setShowInvoiceModal(false);
}}
onExpiry={() => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
toast({
variant: "destructive",
title: "Invoice Expired",
description: "The Lightning invoice has expired. Please create a new one.",
});
}}
title="Lightning Invoice"
description={`Pay this invoice to receive ${currentInvoice.amount} sats`}
qrCodeUrl={currentInvoice.qrCodeUrl}
content={currentInvoice.invoice}
icon="zap"
expiryTimestamp={currentInvoice.expiry}
/>
)}
{/* Sent Token Modal */}
{sentToken && (
<QRModal
isOpen={!!sentToken}
onClose={() => setSentToken(null)}
title="Cashu Token"
description="Share this token with the recipient to send them your sats"
qrCodeUrl={sentTokenQRCode}
content={sentToken}
icon="qr"
/>
)}
</>
);
}
+192
View File
@@ -0,0 +1,192 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Plus, X, Check, ChevronDown, Wallet } from 'lucide-react';
import { useState, useEffect } from 'react';
import { exchangeRateService } from '@/lib/exchangeRateService';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
interface CashuMint {
url: string;
name?: string;
}
interface MintSelectorProps {
balances: { [key: string]: number };
showSats: boolean;
activeMintUrl: string | null;
setActiveMintUrl: (url: string | null) => void;
mints: CashuMint[];
mintUrl: string;
setMintUrl: (url: string) => void;
onAddMint: () => void;
onRemoveMint: (mint: CashuMint) => void;
onShowDenominations: (mintUrl: string) => void;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
}
export function MintSelector({
balances,
showSats,
activeMintUrl,
setActiveMintUrl,
mints,
mintUrl,
setMintUrl,
onAddMint,
onRemoveMint,
onShowDenominations,
getCleanMintLabel,
dropdownOpen,
setDropdownOpen,
}: MintSelectorProps) {
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setBtcUsdRate(rate))
.catch(() => setBtcUsdRate(null));
}, []);
const formatBalance = (sats: number): string => {
if (showSats) {
return `₿${sats.toLocaleString()}`;
} else if (btcUsdRate) {
const btcAmount = sats / 100000000;
const usd = btcAmount * btcUsdRate;
return `$${usd.toFixed(2)}`;
} else {
return `₿${sats.toLocaleString()}`;
}
};
const activeMint = mints.find(mint => mint.url === activeMintUrl);
const activeBalance = activeMint ? balances[activeMint.url] || 0 : 0;
return (
<div className="flex gap-2 items-center min-w-0">
<DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="justify-between rounded-full bg-muted hover:bg-muted/80 border text-base flex-1 h-[40px] px-3 min-w-0">
<div className="flex items-center justify-between w-full min-w-0">
{activeMint ? (
<>
<div className="flex items-center gap-2 min-w-0 flex-1">
<Check className="h-5 w-5 text-primary flex-shrink-0" />
<span className="truncate font-medium min-w-0 flex-1">{getCleanMintLabel(activeMint)}</span>
</div>
<span className="text-muted-foreground font-medium flex-shrink-0 ml-2">
{formatBalance(activeBalance)}
</span>
</>
) : (
<span className="text-muted-foreground truncate min-w-0 flex-1">Select a mint</span>
)}
</div>
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none max-h-[200px] overflow-hidden">
<div className="max-h-[120px] overflow-y-auto">
{mints
.filter((mint) => mint.url)
.map((mint, index) => {
const isActive = activeMintUrl === mint.url;
const balance = balances[mint.url] || 0;
return (
<DropdownMenuItem
key={`mint-${mint.url || `unknown-${index}`}`}
onClick={() => setActiveMintUrl(mint.url)}
className="flex items-center justify-between p-3 text-base"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
{isActive && (
<div className="flex-shrink-0">
<Check className="h-5 w-5 text-primary" />
</div>
)}
<div className="flex-1 min-w-0">
<div className="font-medium truncate">
{getCleanMintLabel(mint)}
</div>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(balance)}
</span>
<button
onClick={(e) => {
e.stopPropagation();
onRemoveMint(mint);
}}
className="p-1 rounded hover:bg-destructive hover:text-destructive-foreground transition-colors"
title="Remove mint"
>
<X className="h-4 w-4" />
</button>
</div>
</DropdownMenuItem>
);
})}
</div>
{mints.length > 0 && <DropdownMenuSeparator />}
<DropdownMenuItem asChild>
<div className="flex gap-2 p-2">
<Input
placeholder="mint.example.com"
value={mintUrl}
onChange={(e) => setMintUrl(e.target.value)}
className="flex-1"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === 'Escape') {
setDropdownOpen(false);
} else if (e.key === 'Enter') {
e.preventDefault();
if (mintUrl.trim()) {
onAddMint();
}
}
}}
onKeyUp={(e) => e.stopPropagation()}
/>
<Button
onClick={(e) => {
e.stopPropagation();
onAddMint();
}}
disabled={!mintUrl.trim()}
size="sm"
>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{activeMint && (
<div className="flex flex-col gap-1">
<button
onClick={() => onShowDenominations(activeMint.url)}
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="View token breakdown"
>
<Wallet className="h-4 w-4" />
</button>
</div>
)}
</div>
);
}
+533
View File
@@ -0,0 +1,533 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Slider } from '@/components/ui/slider';
import { Send, Download, ArrowRight, Zap, Loader2, X } from 'lucide-react';
import { useState, useEffect } from 'react';
interface TransactionCardProps {
mode: 'tokens' | 'lightning' | 'bitcoin';
operation: 'send' | 'receive';
// Send props
sendAmount: string;
setSendAmount: (value: string) => void;
lightningInvoice: string;
setLightningInvoice: (value: string) => void;
lightningAddressInput: string;
setLightningAddressInput: (value: string) => void;
lightningAddressAmount: string;
setLightningAddressAmount: (value: string) => void;
pendingLightningAddress: string | null;
setPendingLightningAddress: (value: string | null) => void;
decodedInvoiceAmount: number | null;
setDecodedInvoiceAmount: (value: number | null) => void;
pendingInvoice: string | null;
setPendingInvoice: (value: string | null) => void;
// Receive props
tokenInput: string;
setTokenInput: (value: string) => void;
quoteAmount: string;
setQuoteAmount: (value: string) => void;
// Common props
activeMintUrl: string | null;
onSend: () => void;
onReceive: () => void;
onConfirmInvoice?: () => void;
isResolvingAddress: 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({
mode,
operation,
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
decodedInvoiceAmount,
setDecodedInvoiceAmount,
pendingInvoice,
setPendingInvoice,
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
activeMintUrl,
onSend,
onReceive,
onConfirmInvoice,
isResolvingAddress,
isLoading,
bitcoinAddress,
bitcoinAmount,
setBitcoinAmount,
bitcoinRecipient,
setBitcoinRecipient,
pendingBitcoinRecipient,
setPendingBitcoinRecipient,
hasNsecAccess,
}: 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 (
<div className="space-y-8">
{/* Title */}
<div className="text-center">
<p className="text-base text-muted-foreground mt-2">
{operation === 'send' ? (
mode === 'tokens'
? 'Generate Cashu token to send'
: mode === 'bitcoin' && !pendingBitcoinRecipient
? 'Send Bitcoin on-chain'
: mode === 'bitcoin' && pendingBitcoinRecipient
? ''
: 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'
) : (
mode === 'tokens'
? 'Enter Cashu token to redeem'
: mode === 'bitcoin'
? 'Receive Bitcoin on-chain'
: 'Deposit funds with Lightning'
)}
</p>
</div>
{/* Content */}
<div className="space-y-8">
{!activeMintUrl && mode !== 'bitcoin' && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
{operation === 'send'
? (mode === 'tokens' ? 'Select a mint to send tokens' : 'Select a mint to pay Lightning invoices')
: (mode === 'tokens' ? 'Select a mint to receive tokens' : 'Select a mint to create Lightning invoice')
}
</div>
)}
{operation === 'send' ? (
// Send Mode
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
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
value={sendAmount}
onChange={(e) => setSendAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && sendAmount && activeMintUrl && !isLoading) {
onSend();
}
}}
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]"
/>
<div className="flex justify-center mt-6">
<Button
onClick={onSend}
disabled={!sendAmount || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Send className="h-5 w-5" />
</Button>
</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 ? (
// Lightning Address Amount Input with Slider
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
value={lightningAddressAmount}
onChange={(e) => setLightningAddressAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && lightningAddressAmount && activeMintUrl && !isResolvingAddress && !isLoading) {
onSend();
}
}}
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]"
/>
<div className="mt-6">
<div className="relative w-full">
<div
onMouseDown={() => handleSliderMouseDown('address')}
onMouseUp={() => handleSliderMouseUp('address')}
onMouseLeave={() => handleSliderMouseUp('address')}
onTouchEnd={() => handleSliderMouseUp('address')}
>
<Slider
value={addressSliderValue}
onValueChange={handleAddressSliderChange}
max={100}
step={1}
className="w-full h-12"
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
/>
</div>
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<span className="text-sm font-medium text-muted-foreground">
{addressSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
</span>
</div>
</div>
</div>
</div>
) : (
// Lightning Invoice/Address Input
<div className="space-y-8">
<Input
placeholder="lnbc... or [email protected]"
value={lightningInvoice || lightningAddressInput}
onChange={(e) => {
const value = e.target.value;
if (value.includes('@')) {
setLightningAddressInput(value);
setLightningInvoice('');
} else {
setLightningInvoice(value);
setLightningAddressInput('');
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && (lightningInvoice.trim() || lightningAddressInput.trim()) && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
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={onSend}
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<ArrowRight className="h-5 w-5" />
</Button>
</div>
</div>
)
) : (
// Receive Mode
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
<div className="space-y-8">
<Input
placeholder="cashuBo2Ft..."
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && tokenInput.trim() && activeMintUrl && !isLoading) {
onReceive();
}
}}
disabled={!activeMintUrl}
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={onReceive}
disabled={!tokenInput.trim() || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Download className="h-5 w-5" />
</Button>
</div>
</div>
) : (
// Lightning Invoice Receive
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
value={quoteAmount}
onChange={(e) => setQuoteAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && quoteAmount && activeMintUrl && !isLoading) {
onReceive();
}
}}
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]"
/>
<div className="flex justify-center mt-6">
<Button
onClick={onReceive}
disabled={!quoteAmount || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Zap className="h-5 w-5" />
</Button>
</div>
</div>
)
)}
</div>
</div>
);
}
@@ -1,82 +0,0 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { X, Coins } from 'lucide-react';
import { useCashuBalances } from '@/hooks/cashu/useCashuBalances';
interface ProofBreakdown {
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
}
interface ProofBreakdownModalProps {
isOpen: boolean;
onClose: () => void;
breakdown: ProofBreakdown | null;
}
export function ProofBreakdownModal({ isOpen, onClose, breakdown }: ProofBreakdownModalProps) {
const { convertCurrency } = useCashuBalances(null);
if (!isOpen || !breakdown) return null;
return (
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
onClick={onClose}
>
<Card
className="w-full max-w-md border-0 shadow-lg bg-background"
onClick={(e) => e.stopPropagation()}
>
<CardHeader className="relative">
<Button
onClick={onClose}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<Coins className="h-5 w-5 mr-2" />
Token Breakdown
</CardTitle>
<CardDescription>
{new URL(breakdown.mintUrl).hostname}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-center py-2">
<div className="text-2xl font-bold text-primary">
{convertCurrency(breakdown.totalBalance)}
</div>
<div className="text-sm text-muted-foreground">Total Balance</div>
</div>
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">Denominations:</div>
{Object.entries(breakdown.denominations)
.sort(([a], [b]) => parseInt(a) - parseInt(b))
.map(([amount, count]) => (
<div key={amount} className="flex items-center justify-between p-2 bg-muted/30 rounded">
<div className="flex items-center gap-2">
<Coins className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{parseInt(amount).toLocaleString()} sats</span>
</div>
<Badge variant="secondary" className="bg-primary/10 text-primary">
× {count}
</Badge>
</div>
))}
</div>
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded">
💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations.
</div>
</CardContent>
</Card>
</div>
);
}
-98
View File
@@ -1,98 +0,0 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Download, Zap } from 'lucide-react';
interface ReceiveCardProps {
mode: 'tokens' | 'lightning';
tokenInput: string;
setTokenInput: (value: string) => void;
quoteAmount: string;
setQuoteAmount: (value: string) => void;
activeMintUrl: string | null;
onReceive: () => void;
isLoading: boolean;
}
export function ReceiveCard({
mode,
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
activeMintUrl,
onReceive,
isLoading,
}: ReceiveCardProps) {
return (
<Card className="border-0 shadow-none bg-muted/30">
<CardHeader>
<CardTitle className="flex items-center">
<Download className="h-5 w-5 mr-2" />
Receive
</CardTitle>
<CardDescription className="min-h-[2.5rem] flex items-center">
{mode === 'tokens'
? 'Enter Cashu token to redeem'
: 'Deposit funds with Lightning'
}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{mode === 'tokens' ? (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to receive tokens
</div>
)}
<div className="flex gap-2">
<Input
placeholder="cashuBo2Ft..."
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && tokenInput.trim() && activeMintUrl && !isLoading) {
onReceive();
}
}}
className="flex-1"
disabled={!activeMintUrl}
/>
<Button onClick={onReceive} disabled={!tokenInput.trim() || !activeMintUrl || isLoading}>
<Download className="h-4 w-4 mr-2" />
Receive
</Button>
</div>
</>
) : (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to create Lightning invoice
</div>
)}
<div className="flex gap-2">
<Input
placeholder="Amount (sats)"
type="number"
value={quoteAmount}
onChange={(e) => setQuoteAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && quoteAmount && activeMintUrl && !isLoading) {
onReceive();
}
}}
disabled={!activeMintUrl}
/>
<Button onClick={onReceive} disabled={!quoteAmount || !activeMintUrl || isLoading}>
<Zap className="h-4 w-4 mr-2" />
Quote
</Button>
</div>
</>
)}
</CardContent>
</Card>
);
}
-83
View File
@@ -1,83 +0,0 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { AlertTriangle, X, RefreshCw } from 'lucide-react';
interface MintToRemove {
url: string;
name?: string;
}
interface RemoveMintModalProps {
isOpen: boolean;
onClose: () => void;
mint: MintToRemove | null;
onConfirm: () => void;
isLoading: boolean;
}
export function RemoveMintModal({ isOpen, onClose, mint, onConfirm, isLoading }: RemoveMintModalProps) {
if (!isOpen || !mint) return null;
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader className="relative">
<Button
onClick={onClose}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<AlertTriangle className="h-5 w-5 mr-2 text-destructive" />
Remove Mint
</CardTitle>
<CardDescription>
Are you sure you want to remove this mint from your wallet?
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="bg-muted p-4 rounded-lg border">
<div className="font-medium">{mint.name || new URL(mint.url).hostname}</div>
<div className="text-sm text-muted-foreground font-mono break-all">
{mint.url}
</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
<div>⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.</div>
<div>💡 You can always add this mint back later if needed.</div>
</div>
<div className="flex gap-2 justify-end">
<Button
variant="outline"
onClick={onClose}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={onConfirm}
disabled={isLoading}
>
{isLoading ? (
<>
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
Removing...
</>
) : (
<>
<X className="h-4 w-4 mr-2" />
Remove Mint
</>
)}
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
-183
View File
@@ -1,183 +0,0 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Send, Zap, Loader2, X } from 'lucide-react';
interface SendCardProps {
mode: 'tokens' | 'lightning';
sendAmount: string;
setSendAmount: (value: string) => void;
lightningInvoice: string;
setLightningInvoice: (value: string) => void;
lightningAddressInput: string;
setLightningAddressInput: (value: string) => void;
lightningAddressAmount: string;
setLightningAddressAmount: (value: string) => void;
pendingLightningAddress: string | null;
setPendingLightningAddress: (value: string | null) => void;
activeMintUrl: string | null;
onSend: () => void;
isResolvingAddress: boolean;
isLoading: boolean;
}
export function SendCard({
mode,
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
activeMintUrl,
onSend,
isResolvingAddress,
isLoading,
}: SendCardProps) {
return (
<Card className="border-0 shadow-none bg-muted/30">
<CardHeader>
<CardTitle className="flex items-center">
<Send className="h-5 w-5 mr-2" />
Send
</CardTitle>
<CardDescription className="min-h-[2.5rem] flex items-center">
{mode === 'tokens'
? 'Generate Cashu token to send'
: pendingLightningAddress
? (
<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">{pendingLightningAddress}</span>
</span>
)
: 'Pay Lightning invoices or addresses from balance'
}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{mode === 'tokens' ? (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to send tokens
</div>
)}
<div className="flex gap-2">
<Input
placeholder="Amount (sats)"
type="number"
value={sendAmount}
onChange={(e) => setSendAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && sendAmount && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl}
/>
<Button onClick={onSend} disabled={!sendAmount || !activeMintUrl || isLoading}>
<Send className="h-4 w-4 mr-2" />
Send
</Button>
</div>
</>
) : (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to pay Lightning invoices
</div>
)}
{pendingLightningAddress ? (
// Step 2: Show amount input for Lightning address
<div className="space-y-3">
<div className="flex gap-2">
<Input
placeholder="Amount (sats)"
type="number"
value={lightningAddressAmount}
onChange={(e) => setLightningAddressAmount(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && lightningAddressAmount && activeMintUrl && !isResolvingAddress && !isLoading) {
onSend();
}
}}
autoFocus
disabled={!activeMintUrl}
/>
<Button
onClick={onSend}
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
>
{isResolvingAddress ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Sending...
</>
) : (
<>
<Zap className="h-4 w-4 mr-2" />
Pay
</>
)}
</Button>
<Button
variant="outline"
size="icon"
onClick={() => {
setPendingLightningAddress(null);
setLightningAddressAmount('');
}}
className="h-10 w-10"
title="Cancel"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
) : (
// Step 1: Show invoice/address input
<div className="flex gap-2">
<Input
placeholder="lnbc... or [email protected]"
value={lightningInvoice || lightningAddressInput}
onChange={(e) => {
const value = e.target.value;
if (value.includes('@')) {
setLightningAddressInput(value);
setLightningInvoice('');
} else {
setLightningInvoice(value);
setLightningAddressInput('');
}
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && (lightningInvoice.trim() || lightningAddressInput.trim()) && activeMintUrl && !isLoading) {
onSend();
}
}}
className="flex-1"
disabled={!activeMintUrl}
/>
<Button
onClick={onSend}
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
>
<>
<Zap className="h-4 w-4 mr-2" />
Pay
</>
</Button>
</div>
)}
</>
)}
</CardContent>
</Card>
);
}
+58 -120
View File
@@ -1,17 +1,12 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, ChevronDown, ChevronUp, Coins } from 'lucide-react';
import type { HistoryEntry } from '@/hooks/useCashu';
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, Coins } from 'lucide-react';
import type { HistoryEntry } from 'coco-cashu-core';
interface TransactionHistoryProps {
entries: HistoryEntry[];
isLoading: boolean;
isExpanded: boolean;
setIsExpanded: (expanded: boolean) => void;
}
export function TransactionHistory({ entries, isLoading, isExpanded, setIsExpanded }: TransactionHistoryProps) {
export function TransactionHistory({ entries, isLoading }: TransactionHistoryProps) {
// Icon indicating transaction type (Lightning vs Cashu)
const getTransactionTypeIcon = (type: string) => {
switch (type) {
@@ -43,131 +38,74 @@ export function TransactionHistory({ entries, isLoading, isExpanded, setIsExpand
const getHistoryLabel = (type: string) => {
switch (type) {
case 'mint':
return 'Mint Tokens';
case 'melt':
return 'Melt Tokens';
case 'send':
return 'Send Tokens';
case 'receive':
return 'Receive Tokens';
return 'Received';
case 'melt':
case 'send':
return 'Sent';
default:
return type;
}
};
const getHistoryStateColor = (state?: string) => {
if (!state) return 'bg-gray-500';
switch (state) {
case 'PAID':
return 'bg-green-500';
case 'UNPAID':
return 'bg-yellow-500';
case 'PENDING':
return 'bg-blue-500';
default:
return 'bg-gray-500';
}
};
return (
<Card className="mt-6 border-0 shadow-none">
<CardHeader>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center">
<History className="h-5 w-5 mr-2" />
Transaction History
</div>
{entries.length > 3 && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsExpanded(!isExpanded)}
className="gap-1"
<div className="space-y-2">
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
<span>Loading history...</span>
</div>
) : entries.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
No transactions yet
</div>
) : (
<>
{entries.map((entry) => (
<div
key={entry.id}
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
>
{isExpanded ? (
<>
<ChevronUp className="h-4 w-4" />
Hide
</>
) : (
<>
<ChevronDown className="h-4 w-4" />
Show
</>
)}
</Button>
)}
</CardTitle>
<CardDescription>
View your recent transactions
</CardDescription>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
<span>Loading history...</span>
</div>
) : entries.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
No transaction history yet
</div>
) : (
<div className="space-y-2">
{(isExpanded ? entries : entries.slice(0, 3)).map((entry) => (
<div
key={entry.id}
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex items-start gap-3 flex-1">
<div className="mt-1">
{getTransactionTypeIcon(entry.type)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">
{getHistoryLabel(entry.type)}
</span>
{entry.state && entry.type !== 'mint' && entry.type !== 'melt' && (
<Badge
variant="secondary"
className={`${getHistoryStateColor(entry.state)} text-white text-xs`}
>
{entry.state}
</Badge>
)}
</div>
<div className="text-sm text-muted-foreground mt-1">
{new URL(entry.mintUrl).hostname}
</div>
<div className="text-xs text-muted-foreground mt-1">
{new Date(entry.createdAt).toLocaleString()}
</div>
</div>
<div className="flex items-start justify-between">
<div className="flex items-start gap-3 flex-1">
<div className="mt-1">
{getTransactionTypeIcon(entry.type)}
</div>
<div className="text-right ml-4 flex items-start gap-2">
<div>
<div className="font-semibold">
{entry.type === 'send' || entry.type === 'melt' ? '-' : '+'}
{entry.amount.toLocaleString()} {entry.unit}
</div>
{entry.type === 'melt' && (
<div className="text-xs text-muted-foreground mt-1">
+ fees
</div>
)}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">
{getHistoryLabel(entry.type)}
</span>
</div>
<div className="mt-1">
{getDirectionIcon(entry.type)}
<div className="text-sm text-muted-foreground mt-1">
{new URL(entry.mintUrl).hostname}
</div>
<div className="text-xs text-muted-foreground mt-1">
{new Date(entry.createdAt).toLocaleString()}
</div>
</div>
</div>
<div className="text-right ml-4 flex items-start gap-2">
<div>
<div className="font-semibold">
{entry.type === 'send' || entry.type === 'melt' ? '-' : '+'}
{entry.amount.toLocaleString()} {entry.unit}
</div>
{entry.type === 'melt' && (
<div className="text-xs text-muted-foreground mt-1">
+ fees
</div>
)}
</div>
<div className="mt-1">
{getDirectionIcon(entry.type)}
</div>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
))}
</>
)}
</div>
);
}
+252
View File
@@ -0,0 +1,252 @@
import { useState, useEffect } from 'react';
import { nip19 } from 'nostr-tools';
import { Zap, Coins, Copy, Check, QrCode, Link } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { exchangeRateService } from '@/lib/exchangeRateService';
import { useToast } from '@/hooks/useToast';
import { LoginIcon } from '@/components/auth/LoginIcon';
import { MintSelector } from './MintSelector';
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
interface CashuMint {
url: string;
name?: string;
}
interface WalletHeaderProps {
totalBalance: number;
balances: { [key: string]: number };
showSats: boolean;
setShowSats: (showSats: boolean) => void;
mode: 'tokens' | 'lightning' | 'bitcoin';
setMode: (mode: 'tokens' | 'lightning' | 'bitcoin') => void;
userPubkey?: string;
npubCashUsername?: string;
onCopyToClipboard: (text: string) => Promise<void>;
onShowLightningAddressQR: (qrCode: string) => void;
onShowBitcoinAddressQR: (qrCode: string) => void;
generateQRCode: (text: string) => Promise<string>;
// MintSelector props
activeMintUrl: string | null;
setActiveMintUrl: (url: string | null) => void;
mints: CashuMint[];
mintUrl: string;
setMintUrl: (url: string) => void;
onAddMint: () => void;
onRemoveMint: (mint: CashuMint) => void;
onShowDenominations: (mintUrl: string) => void;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
dropdownOpen: boolean;
setDropdownOpen: (open: boolean) => void;
}
export function WalletHeader({
totalBalance,
balances,
showSats,
setShowSats,
mode,
setMode,
userPubkey,
npubCashUsername,
onCopyToClipboard,
onShowLightningAddressQR,
onShowBitcoinAddressQR,
generateQRCode,
// MintSelector props
activeMintUrl,
setActiveMintUrl,
mints,
mintUrl,
setMintUrl,
onAddMint,
onRemoveMint,
onShowDenominations,
getCleanMintLabel,
dropdownOpen,
setDropdownOpen,
}: WalletHeaderProps) {
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false);
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
const { toast } = useToast();
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setBtcUsdRate(rate))
.catch(() => setBtcUsdRate(null));
}, []);
const toggleMode = () => {
let newMode: 'tokens' | 'lightning' | 'bitcoin';
if (mode === 'lightning') {
newMode = 'tokens';
} else if (mode === 'tokens') {
newMode = 'bitcoin';
} else {
newMode = 'lightning';
}
setMode(newMode);
toast({
title: `${newMode === 'tokens' ? 'Cashu' : newMode === 'lightning' ? 'Lightning' : 'Bitcoin'} Enabled!`,
description: newMode === 'tokens'
? 'Send and receive with Cashu eCash'
: newMode === 'lightning'
? 'Send and receive with Lightning'
: 'Send and receive with on-chain Bitcoin',
});
};
return (
<div className="flex flex-col items-center pt-10 space-y-2">
{/* Mode Toggle */}
<div className="absolute top-3 left-3 sm:left-4 z-10">
<button
onClick={toggleMode}
className="p-3 rounded-full bg-background hover:bg-background/80 transition-colors flex items-center justify-center"
title={mode === 'tokens' ? 'Switch to Lightning' : mode === 'lightning' ? 'Switch to Bitcoin' : 'Switch to Cashu Tokens'}
>
{mode === 'tokens' ? (
<Coins className="h-6 w-6" />
) : mode === 'lightning' ? (
<Zap className="h-6 w-6" />
) : (
<Link className="h-6 w-6" />
)}
</button>
</div>
{/* Login Icon */}
<div className="absolute top-3 right-3 sm:right-4 z-10">
<LoginIcon />
</div>
{/* Balance Display */}
<div className="text-center py-2">
<div className="flex items-center justify-center gap-3">
<button
onClick={() => setShowSats(!showSats)}
className="text-6xl font-bold tabular-nums hover:opacity-80 transition-opacity cursor-pointer"
title={`Click to show in ${showSats ? 'USD' : 'sats'}`}
>
<span className="text-muted-foreground italic">
{showSats ? '₿' : '$'}
</span>
{showSats ? totalBalance.toLocaleString() : (btcUsdRate ? `${(totalBalance / 100000000 * btcUsdRate).toFixed(2)}` : totalBalance.toLocaleString())}
</button>
</div>
{/* Lightning Address and Mint Selector Grid */}
<div className="mt-3 px-4">
<div className="w-full max-w-[400px] mx-auto">
<div className="grid grid-cols-1 gap-3">
{/* Lightning Address Row */}
{userPubkey && mode !== 'bitcoin' && (
<div className="flex gap-2 items-center min-w-[300px]">
<button
onClick={async () => {
const lightningAddress = `${npubCashUsername}@npubx.cash`;
await onCopyToClipboard(lightningAddress);
setLightningAddressCopied(true);
setTimeout(() => setLightningAddressCopied(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 Lightning address"
>
<div className="min-w-0 flex-1 flex items-center">
<span className="truncate min-w-0 flex-1">
{npubCashUsername || ''}
</span>
<span className="flex-shrink-0 text-muted-foreground">
@npubx.cash
</span>
</div>
{lightningAddressCopied ? (
<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 lightningAddress = `${npubCashUsername}@npubx.cash`;
const qr = await generateQRCode(lightningAddress);
onShowLightningAddressQR(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>
)}
{/* 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 */}
{mode !== 'bitcoin' && (
<div className="min-w-[300px]">
<MintSelector
balances={balances}
showSats={showSats}
activeMintUrl={activeMintUrl}
setActiveMintUrl={setActiveMintUrl}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={onAddMint}
onRemoveMint={onRemoveMint}
onShowDenominations={onShowDenominations}
getCleanMintLabel={getCleanMintLabel}
dropdownOpen={dropdownOpen}
setDropdownOpen={setDropdownOpen}
/>
</div>
)}
</div>
</div>
</div>
</div>
</div>
);
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { createContext, useContext, ReactNode } from 'react';
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/useCashu';
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/cashu/useCashu';
const CashuContext = createContext<UseCashuReturn | null>(null);
-102
View File
@@ -1,102 +0,0 @@
import { useMemo } from 'react';
import { useCashuManager } from './useCashuManager';
import { useCashuBalances } from './useCashuBalances';
import { useCashuMints } from './useCashuMints';
import { useCashuQuotes } from './useCashuQuotes';
import { useCashuWallet } from './useCashuWallet';
import { useCashuHistory } from './useCashuHistory';
import { useCashuSubscriptions } from './useCashuSubscriptions';
import { useCashuManagerOperations } from './useCashuManagerOperations';
import { UseCashuReturn, CashuWalletError } from './types';
export function useCashu(): UseCashuReturn {
const manager = useCashuManager();
const balances = useCashuBalances(manager.manager);
const mints = useCashuMints(manager.manager);
const quotes = useCashuQuotes(manager.manager, manager.repositories);
const wallet = useCashuWallet(manager.manager, manager.repositories);
const history = useCashuHistory(manager.manager);
const subscriptions = useCashuSubscriptions(manager.manager);
const managerOperations = useCashuManagerOperations(manager.manager);
// Combine all errors into a single error state
const combinedError = useMemo(() => {
const errors = [
manager.error,
balances.error,
mints.error,
quotes.error,
wallet.error,
history.error,
subscriptions.error,
managerOperations.error,
].filter(Boolean) as CashuWalletError[];
return errors.length > 0 ? errors[0] : null;
}, [manager.error, balances.error, mints.error, quotes.error, wallet.error, history.error, subscriptions.error, managerOperations.error]);
// Combine all loading states
const combinedIsLoading = useMemo(() => {
return manager.isLoading || balances.isLoading || mints.isLoading || quotes.isLoading || wallet.isLoading || history.isLoading || subscriptions.isLoading || managerOperations.isLoading;
}, [manager.isLoading, balances.isLoading, mints.isLoading, quotes.isLoading, wallet.isLoading, history.isLoading, subscriptions.isLoading, managerOperations.isLoading]);
return {
// State
isInitialized: manager.isInitialized,
isLoading: combinedIsLoading,
error: combinedError,
balances: balances.balances,
mints: mints.mints,
mnemonic: manager.mnemonic,
// Actions
// Wallet operations
receive: wallet.receive,
send: wallet.send,
getBalances: balances.getBalances,
getProofs: wallet.getProofs,
// Mint operations
addMint: mints.addMint,
removeMint: mints.removeMint,
getMints: mints.getMints,
// Quote operations
createMintQuote: quotes.createMintQuote,
redeemMintQuote: quotes.redeemMintQuote,
createMeltQuote: quotes.createMeltQuote,
payMeltQuote: quotes.payMeltQuote,
addMintQuote: quotes.addMintQuote,
// Subscription operations
awaitMintQuotePaid: subscriptions.awaitMintQuotePaid,
awaitMeltQuotePaid: subscriptions.awaitMeltQuotePaid,
// Manager operations
enableMintQuoteWatcher: managerOperations.enableMintQuoteWatcher,
disableMintQuoteWatcher: managerOperations.disableMintQuoteWatcher,
enableMintQuoteProcessor: managerOperations.enableMintQuoteProcessor,
disableMintQuoteProcessor: managerOperations.disableMintQuoteProcessor,
waitForMintQuoteProcessor: managerOperations.waitForMintQuoteProcessor,
enableProofStateWatcher: managerOperations.enableProofStateWatcher,
disableProofStateWatcher: managerOperations.disableProofStateWatcher,
// Event operations
on: managerOperations.on,
once: managerOperations.once,
off: managerOperations.off,
// Mnemonic operations
setMnemonic: manager.setMnemonic,
generateMnemonic: manager.generateMnemonic,
getMnemonic: manager.getMnemonic,
// History operations
getHistory: history.getHistory,
// Utility operations
refreshBalances: balances.refreshBalances,
refreshMints: mints.refreshMints,
clearError: manager.clearError,
};
}
-142
View File
@@ -1,142 +0,0 @@
// Error types that align with coco-cashu patterns
export class CashuWalletError extends Error {
constructor(message: string, public code: string, public details?: unknown) {
super(message);
this.name = 'CashuWalletError';
}
}
export class CashuInitializationError extends CashuWalletError {
constructor(message: string, details?: unknown) {
super(message, 'INITIALIZATION_ERROR', details);
}
}
export class CashuMintError extends CashuWalletError {
constructor(message: string, mintUrl: string, details?: unknown) {
super(message, 'MINT_ERROR', details);
this.mintUrl = mintUrl;
}
public mintUrl: string;
}
export class CashuQuoteError extends CashuWalletError {
constructor(message: string, quoteId: string, details?: unknown) {
super(message, 'QUOTE_ERROR', details);
this.quoteId = quoteId;
}
public quoteId: string;
}
export class CashuTokenError extends CashuWalletError {
constructor(message: string, token?: string, details?: unknown) {
super(message, 'TOKEN_ERROR', details);
this.token = token;
}
public token?: string;
}
// Core types
export interface CashuBalance {
[mintUrl: string]: number;
}
export interface CashuMint {
url: string;
name?: string;
info?: Record<string, unknown>;
}
export interface CashuMintQuote {
quote: string;
request: string;
expiry: number;
}
export interface CashuMeltQuote {
quote: string;
request: string;
expiry: number;
}
export interface CashuToken {
mint: string;
proofs: Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
}
export interface HistoryEntry {
id: string;
type: 'mint' | 'melt' | 'send' | 'receive';
mintUrl: string;
amount: number;
unit: string;
createdAt: number;
metadata?: Record<string, unknown>;
quoteId?: string;
state?: string;
paymentRequest?: string;
token?: CashuToken;
}
// Hook state types
export interface CashuState {
isInitialized: boolean;
isLoading: boolean;
error: CashuWalletError | null;
balances: CashuBalance;
mints: CashuMint[];
mnemonic: string | null;
}
export interface CashuActions {
// Wallet operations
receive: (token: string | CashuToken) => Promise<void>;
send: (mintUrl: string, amount: number) => Promise<string>;
getBalances: () => Promise<CashuBalance>;
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
// Mint operations
addMint: (mintUrl: string) => Promise<void>;
removeMint: (mintUrl: string) => Promise<void>;
getMints: () => Promise<CashuMint[]>;
// Quote operations
createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote>;
redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote>;
payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void>;
addMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
// Subscription operations (NEW)
awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
// Manager operations (NEW)
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
disableMintQuoteWatcher: () => Promise<void>;
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
disableMintQuoteProcessor: () => Promise<void>;
waitForMintQuoteProcessor: () => Promise<void>;
enableProofStateWatcher: () => Promise<void>;
disableProofStateWatcher: () => Promise<void>;
// Event operations (NEW)
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
off: (event: string, handler: (payload: unknown) => void | Promise<void>) => void;
// Mnemonic operations
setMnemonic: (mnemonic: string) => void;
generateMnemonic: () => string;
getMnemonic: () => string | null;
// History operations
getHistory: (limit?: number, offset?: number) => Promise<HistoryEntry[]>;
// Utility operations
refreshBalances: () => Promise<void>;
refreshMints: () => Promise<void>;
clearError: () => void;
}
export type UseCashuReturn = CashuState & CashuActions;
+251
View File
@@ -0,0 +1,251 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useLocalStorage } from '../useLocalStorage';
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
import { initializeCoco, ConsoleLogger, getEncodedToken, type Repositories } from 'coco-cashu-core';
import { IndexedDbRepositories } from 'coco-cashu-indexeddb';
// Types from coco-cashu-core
type CocoManager = Awaited<ReturnType<typeof initializeCoco>>;
// Singleton pattern to prevent multiple initializations
let globalCocoInstance: CocoManager | null = null;
let globalRepositories: Repositories | null = null;
let globalInitializationPromise: Promise<{ coco: CocoManager; repositories: Repositories }> | null = null;
export interface UseCashuReturn {
// The typed coco manager (direct library access)
coco: CocoManager | null;
// Repositories for direct access to proof data
repositories: Repositories | null;
// React state (for reactivity)
balances: { [mintUrl: string]: number };
mints: Array<{ url: string; name?: string; info?: unknown }>;
totalBalance: number;
// Status
isInitialized: boolean;
isLoading: boolean;
error: Error | null;
// Mnemonic management
mnemonic: string | null;
setMnemonic: (mnemonic: string) => void;
generateMnemonic: () => string;
// Utility functions
clearError: () => void;
getEncodedToken: typeof getEncodedToken;
refreshMints: () => Promise<void>;
}
export function useCashu(): UseCashuReturn {
const [isInitialized, setIsInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
// Mnemonic management with localStorage
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
// Manager instance ref
const cocoRef = useRef<CocoManager | null>(null);
const repositoriesRef = useRef<Repositories | null>(null);
// React state for UI reactivity
const [balances, setBalances] = useState<{ [mintUrl: string]: number }>({});
const [mints, setMints] = useState<Array<{ url: string; name?: string; info?: unknown }>>([]);
const clearError = useCallback(() => {
setError(null);
}, []);
const generateMnemonic = useCallback(() => {
return bip39.generateMnemonic(wordlist);
}, []);
const refreshMints = useCallback(async () => {
const coco = cocoRef.current;
if (!coco) return;
try {
const mintList = await coco.mint.getAllMints();
setMints(mintList.map((m: any) => ({
url: m.mintUrl,
name: m.name,
info: m.mintInfo
})));
} catch (err) {
console.error('Failed to refresh mints:', err);
}
}, []);
const setMnemonic = useCallback((newMnemonic: string) => {
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
throw new Error('Invalid mnemonic');
}
setMnemonicState(newMnemonic);
// Reinitialize manager with new mnemonic
setIsInitialized(false);
}, [setMnemonicState]);
// Initialize the coco manager
const initializeCocoManager = useCallback(async () => {
if (isInitialized || isLoading) return;
setIsLoading(true);
setError(null);
try {
// Use singleton pattern to prevent multiple initializations
if (globalCocoInstance && globalRepositories) {
console.log('Using existing coco instance (singleton)');
cocoRef.current = globalCocoInstance;
repositoriesRef.current = globalRepositories;
setIsInitialized(true);
setIsLoading(false);
return;
}
// If there's already an initialization in progress, wait for it
if (globalInitializationPromise) {
console.log('Waiting for existing initialization...');
const { coco, repositories } = await globalInitializationPromise;
cocoRef.current = coco;
repositoriesRef.current = repositories;
setIsInitialized(true);
setIsLoading(false);
return;
}
// Generate or retrieve mnemonic
let currentMnemonic = mnemonic;
if (!currentMnemonic) {
currentMnemonic = bip39.generateMnemonic(wordlist);
setMnemonicState(currentMnemonic);
}
// Create seed from mnemonic
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
// Initialize repositories with proper initialization
const repo = new IndexedDbRepositories({ name: "cashu-wallet" });
await repo.init(); // Ensure repository is properly initialized
// Create initialization promise
globalInitializationPromise = (async () => {
const coco = await initializeCoco({
repo,
seedGetter: async () => seed,
logger: new ConsoleLogger("coco", { level: "debug" }) // Use debug level for better logging
});
return { coco, repositories: repo };
})();
// Initialize coco manager using the new API
const { coco, repositories } = await globalInitializationPromise;
// Store as singleton
console.log('Storing new coco instance as singleton');
globalCocoInstance = coco;
globalRepositories = repositories;
globalInitializationPromise = null;
cocoRef.current = coco;
repositoriesRef.current = repositories;
// Enable built-in services for automatic quote processing and state watching
try {
console.log('Enabling coco services...');
await coco.enableMintQuoteWatcher({ watchExistingPendingOnStart: false });
console.log('Mint quote watcher enabled');
await coco.enableMintQuoteProcessor();
console.log('Mint quote processor enabled');
await coco.enableProofStateWatcher();
console.log('Proof state watcher enabled');
console.log('All coco services enabled successfully');
} catch (err) {
// Don't fail initialization if watchers can't be enabled
console.warn('Failed to enable some coco services:', err);
}
setIsInitialized(true);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
setError(new Error(errorMessage));
globalInitializationPromise = null; // Reset on error
} finally {
setIsLoading(false);
}
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
// Initialize on mount and when mnemonic changes
useEffect(() => {
initializeCocoManager();
}, [initializeCocoManager]);
// Auto-refresh balances and mints on manager events
useEffect(() => {
const coco = cocoRef.current;
if (!coco) return;
const refreshBalances = async () => {
try {
const newBalances = await coco.wallet.getBalances();
setBalances(newBalances);
} catch (err) {
// Silent failure - errors are handled by the manager
}
};
// Initial load
refreshBalances();
refreshMints();
// Listen to events
const unsubs = [
coco.on('proofs:saved', refreshBalances),
coco.on('proofs:state-changed', refreshBalances),
coco.on('send:created', refreshBalances),
coco.on('receive:created', refreshBalances),
coco.on('mint:added', refreshMints),
coco.on('mint:updated', refreshMints),
];
return () => unsubs.forEach(unsub => unsub());
}, [isInitialized, refreshMints]);
// Calculate total balance
const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
return {
// The typed coco manager (direct library access)
coco: cocoRef.current,
// Repositories for direct access to proof data
repositories: repositoriesRef.current,
// React state (for reactivity)
balances,
mints,
totalBalance,
// Status
isInitialized,
isLoading,
error,
// Mnemonic management
mnemonic,
setMnemonic,
generateMnemonic,
// Utility functions
clearError,
getEncodedToken,
refreshMints,
};
}
-204
View File
@@ -1,204 +0,0 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { CashuBalance, CashuWalletError } from './types';
import { exchangeRateService } from '@/lib/exchangeRateService';
import { toast } from '../useToast';
export interface UseCashuBalancesReturn {
balances: CashuBalance;
isLoading: boolean;
error: CashuWalletError | null;
refreshBalances: () => Promise<void>;
getBalances: () => Promise<CashuBalance>;
convertCurrency: (sats: number, showSats?: boolean) => string;
convertCurrencyAsync: (sats: number, showSats?: boolean) => Promise<string>;
}
export function useCashuBalances(manager: unknown | null): UseCashuBalancesReturn {
const [balances, setBalances] = useState<CashuBalance>({});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const [fallbackRate, setFallbackRate] = useState<number | null>(null);
// Throttling refs
const lastRefreshTimeRef = useRef<number>(0);
const isRefreshingRef = useRef<boolean>(false);
const REFRESH_THROTTLE_MS = 200;
const refreshBalances = useCallback(async () => {
if (!manager) return;
// Prevent concurrent calls
if (isRefreshingRef.current) {
console.log('⏭️ refreshBalances: Skipping (already in progress)');
return;
}
// Throttle rapid successive calls
const now = Date.now();
if (now - lastRefreshTimeRef.current < REFRESH_THROTTLE_MS) {
console.log('⏭️ refreshBalances: Skipping (throttled)');
return;
}
isRefreshingRef.current = true;
lastRefreshTimeRef.current = now;
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
console.log('💰 refreshBalances: Raw balances from wallet:', newBalances);
// Only update state if balances actually changed (deep comparison)
setBalances(prevBalances => {
const hasChanged =
Object.keys(newBalances).length !== Object.keys(prevBalances).length ||
Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]);
if (hasChanged) {
console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints');
return newBalances;
} else {
console.log('⏭️ refreshBalances: Balances unchanged, skipping state update');
return prevBalances;
}
});
} catch (err) {
console.error('❌ refreshBalances: Failed to refresh balances:', err);
const errorMessage = err instanceof Error ? err.message : 'Failed to refresh balances';
setError(new CashuWalletError(errorMessage, 'BALANCE_REFRESH_ERROR', { originalError: err }));
} finally {
isRefreshingRef.current = false;
}
}, [manager]);
const getBalances = useCallback(async (): Promise<CashuBalance> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
return await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get balances';
const cashuError = new CashuWalletError(errorMessage, 'GET_BALANCES_ERROR', { originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
// Set up event listeners for automatic balance updates using coco events
useEffect(() => {
if (!manager) return;
const unsubscribeProofsSaved = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('proofs:saved', () => {
console.log('📨 Proofs saved, refreshing balances...');
refreshBalances();
});
const unsubscribeProofsStateChanged = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('proofs:state-changed', () => {
console.log('🔄 Proofs state changed, refreshing balances...');
refreshBalances();
});
const unsubscribeSendCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('send:created', () => {
console.log('📤 Send created, refreshing balances...');
// Bypass throttling for send operations to ensure immediate balance update
setTimeout(async () => {
if (!manager) return;
try {
console.log('🔄 send:created: Getting balances from wallet...');
const newBalances = await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
console.log('💰 send:created: Raw balances from wallet:', newBalances);
setBalances(prevBalances => {
const hasChanged =
Object.keys(newBalances).length !== Object.keys(prevBalances).length ||
Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]);
if (hasChanged) {
console.log('✅ send:created: Balances changed, updating state:', Object.keys(newBalances).length, 'mints');
return newBalances;
} else {
console.log('⏭️ send:created: Balances unchanged, skipping state update');
return prevBalances;
}
});
} catch (err) {
console.error('❌ send:created: Failed to refresh balances:', err);
}
}, 100);
});
const unsubscribeReceiveCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('receive:created', () => {
console.log('📥 Receive created, refreshing balances...');
refreshBalances();
});
return () => {
unsubscribeProofsSaved();
unsubscribeProofsStateChanged();
unsubscribeSendCreated();
unsubscribeReceiveCreated();
};
}, [manager, refreshBalances]);
// Initial balance load
useEffect(() => {
if (manager && Object.keys(balances).length === 0) {
refreshBalances();
}
}, [manager, balances, refreshBalances]);
// Fetch exchange rate on mount for fallback
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setFallbackRate(rate))
.catch(error => {
console.warn('Failed to fetch initial exchange rate:', error);
// Keep fallbackRate as null to show sats instead of USD
});
}, []);
const convertCurrency = useCallback((sats: number, showSats: boolean = true): string => {
if (showSats) {
return `${sats.toLocaleString()} sats`;
} else {
// Only show USD if we have a valid exchange rate
if (fallbackRate) {
const btcAmount = sats / 100000000;
const usd = btcAmount * fallbackRate;
return `$${usd.toFixed(2)}`;
} else {
// If no exchange rate available, show sats instead of incorrect USD
return `${sats.toLocaleString()} sats`;
}
}
}, [fallbackRate]);
const convertCurrencyAsync = useCallback(async (sats: number, showSats: boolean = true): Promise<string> => {
if (showSats) {
return `${sats.toLocaleString()} sats`;
} else {
try {
const usd = await exchangeRateService.satsToUsd(sats);
return `$${usd.toFixed(2)}`;
} catch (error) {
console.warn('Failed to fetch exchange rate:', error);
// If exchange rate fails, show sats instead of incorrect USD
return `${sats.toLocaleString()} sats`;
}
}
}, []);
return {
balances,
isLoading,
error,
refreshBalances,
getBalances,
convertCurrency,
convertCurrencyAsync,
};
}
-42
View File
@@ -1,42 +0,0 @@
import { useState, useCallback } from 'react';
import { HistoryEntry, CashuWalletError } from './types';
export interface UseCashuHistoryReturn {
isLoading: boolean;
error: CashuWalletError | null;
getHistory: (limit?: number, offset?: number) => Promise<HistoryEntry[]>;
}
export function useCashuHistory(manager: unknown | null): UseCashuHistoryReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const getHistory = useCallback(async (limit: number = 50, offset: number = 0): Promise<HistoryEntry[]> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
console.log('📜 Getting transaction history...');
const entries = await (manager as { history: { getPaginatedHistory: (offset: number, limit: number) => Promise<unknown[]> } }).history.getPaginatedHistory(offset, limit);
console.log(`✅ Found ${entries.length} history entries`);
return entries as unknown as HistoryEntry[];
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get history';
console.error('❌ Error getting history:', err);
const cashuError = new CashuWalletError(errorMessage, 'GET_HISTORY_ERROR', { limit, offset, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
return {
isLoading,
error,
getHistory,
};
}
-167
View File
@@ -1,167 +0,0 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useLocalStorage } from '../useLocalStorage';
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
import { CashuInitializationError, CashuWalletError } from './types';
// Dynamic imports for coco-cashu packages
let Manager: unknown = null;
let IndexedDbRepositories: unknown = null;
let ConsoleLogger: unknown = null;
let getEncodedToken: unknown = null;
let _getDecodedToken: unknown = null;
// Lazy load coco-cashu packages
const loadCocoCashu = async () => {
if (Manager) return; // Already loaded
try {
const coreModule = await import('coco-cashu-core');
const indexedDbModule = await import('coco-cashu-indexeddb');
Manager = coreModule.Manager;
ConsoleLogger = coreModule.ConsoleLogger;
getEncodedToken = coreModule.getEncodedToken;
_getDecodedToken = coreModule.getDecodedToken;
IndexedDbRepositories = indexedDbModule.IndexedDbRepositories;
} catch (error) {
console.error('Failed to load coco-cashu packages:', error);
throw new CashuInitializationError(
'Cashu packages not available. Please install coco-cashu-core and coco-cashu-indexeddb',
{ error }
);
}
};
export interface UseCashuManagerReturn {
manager: unknown | null;
repositories: unknown | null;
isInitialized: boolean;
isLoading: boolean;
error: CashuWalletError | null;
mnemonic: string | null;
setMnemonic: (mnemonic: string) => void;
generateMnemonic: () => string;
getMnemonic: () => string | null;
clearError: () => void;
}
export function useCashuManager(): UseCashuManagerReturn {
const [isInitialized, setIsInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
// Mnemonic management with localStorage
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
// Manager instance refs
const managerRef = useRef<unknown>(null);
const repositoriesRef = useRef<unknown>(null);
const clearError = useCallback(() => {
setError(null);
}, []);
const generateMnemonic = useCallback(() => {
return bip39.generateMnemonic(wordlist);
}, []);
const getMnemonic = useCallback(() => {
return mnemonic;
}, [mnemonic]);
const setMnemonic = useCallback((newMnemonic: string) => {
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
throw new CashuWalletError('Invalid mnemonic', 'INVALID_MNEMONIC');
}
setMnemonicState(newMnemonic);
// Reinitialize manager with new mnemonic
setIsInitialized(false);
}, [setMnemonicState]);
// Initialize the manager
const initializeManager = useCallback(async () => {
if (isInitialized || isLoading) return;
setIsLoading(true);
setError(null);
try {
await loadCocoCashu();
// Generate or retrieve mnemonic
let currentMnemonic = mnemonic;
if (!currentMnemonic) {
currentMnemonic = bip39.generateMnemonic(wordlist);
setMnemonicState(currentMnemonic);
}
// Create seed from mnemonic
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
// Initialize repositories
const repositories = new (IndexedDbRepositories as new (options: Record<string, unknown>) => { init: () => Promise<void> })({});
await repositories.init();
repositoriesRef.current = repositories;
// Initialize manager
const manager = new (Manager as new (
repositories: unknown,
seedGetter: () => Promise<Uint8Array>,
logger?: unknown
) => {
wallet: { getBalances: () => Promise<Record<string, number>>; receive: (token: string | unknown) => Promise<void>; send: (mintUrl: string, amount: number) => Promise<unknown> };
mint: { addMint: (mintUrl: string) => Promise<unknown>; getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> };
quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise<unknown>; redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>; createMeltQuote: (mintUrl: string, invoice: string) => Promise<unknown>; payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void> };
history: { getPaginatedHistory: (offset: number, limit: number) => Promise<unknown[]> };
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
enableProofStateWatcher: () => Promise<void>;
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
})(
repositories,
async () => seed,
new (ConsoleLogger as new (name: unknown, options: { level: string }) => unknown)(undefined, { level: 'info' })
);
managerRef.current = manager;
// Enable built-in services for automatic quote processing and state watching
try {
await manager.enableMintQuoteWatcher({ watchExistingPendingOnStart: true });
await manager.enableMintQuoteProcessor();
await manager.enableProofStateWatcher();
console.log('✅ Enabled coco-cashu watcher services');
} catch (err) {
console.warn('⚠️ Failed to enable some watcher services:', err);
// Don't fail initialization if watchers can't be enabled
}
setIsInitialized(true);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
const cashuError = err instanceof CashuWalletError ? err : new CashuInitializationError(errorMessage, { originalError: err });
setError(cashuError);
console.error('Cashu initialization error:', err);
} finally {
setIsLoading(false);
}
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
// Initialize on mount and when mnemonic changes
useEffect(() => {
initializeManager();
}, [initializeManager]);
return {
manager: managerRef.current,
repositories: repositoriesRef.current,
isInitialized,
isLoading,
error,
mnemonic,
setMnemonic,
generateMnemonic,
getMnemonic,
clearError,
};
}
@@ -1,147 +0,0 @@
import { useCallback } from 'react';
import { CashuWalletError } from './types';
export interface UseCashuManagerOperationsReturn {
isLoading: boolean;
error: CashuWalletError | null;
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
disableMintQuoteWatcher: () => Promise<void>;
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
disableMintQuoteProcessor: () => Promise<void>;
waitForMintQuoteProcessor: () => Promise<void>;
enableProofStateWatcher: () => Promise<void>;
disableProofStateWatcher: () => Promise<void>;
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
off: (event: string, handler: (payload: unknown) => void | Promise<void>) => void;
}
export function useCashuManagerOperations(manager: unknown | null): UseCashuManagerOperationsReturn {
const isLoading = false; // Manager operations are typically async but don't have loading states
const error = null; // Errors are handled per-operation
const enableMintQuoteWatcher = useCallback(async (options?: { watchExistingPendingOnStart?: boolean }) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void> }).enableMintQuoteWatcher(options);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to enable mint quote watcher';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableMintQuoteWatcher', originalError: err });
}
}, [manager]);
const disableMintQuoteWatcher = useCallback(async () => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { disableMintQuoteWatcher: () => Promise<void> }).disableMintQuoteWatcher();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to disable mint quote watcher';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableMintQuoteWatcher', originalError: err });
}
}, [manager]);
const enableMintQuoteProcessor = useCallback(async (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void> }).enableMintQuoteProcessor(options);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to enable mint quote processor';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableMintQuoteProcessor', originalError: err });
}
}, [manager]);
const disableMintQuoteProcessor = useCallback(async () => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { disableMintQuoteProcessor: () => Promise<void> }).disableMintQuoteProcessor();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to disable mint quote processor';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableMintQuoteProcessor', originalError: err });
}
}, [manager]);
const waitForMintQuoteProcessor = useCallback(async () => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { waitForMintQuoteProcessor: () => Promise<void> }).waitForMintQuoteProcessor();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to wait for mint quote processor';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'waitForMintQuoteProcessor', originalError: err });
}
}, [manager]);
const enableProofStateWatcher = useCallback(async () => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { enableProofStateWatcher: () => Promise<void> }).enableProofStateWatcher();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to enable proof state watcher';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableProofStateWatcher', originalError: err });
}
}, [manager]);
const disableProofStateWatcher = useCallback(async () => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
await (manager as { disableProofStateWatcher: () => Promise<void> }).disableProofStateWatcher();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to disable proof state watcher';
throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableProofStateWatcher', originalError: err });
}
}, [manager]);
const on = useCallback((event: string, handler: (payload: unknown) => void | Promise<void>) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on(event, handler);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add event listener';
throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'on', event, originalError: err });
}
}, [manager]);
const once = useCallback((event: string, handler: (payload: unknown) => void | Promise<void>) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return (manager as { once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).once(event, handler);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add one-time event listener';
throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'once', event, originalError: err });
}
}, [manager]);
const off = useCallback((event: string, handler: (payload: unknown) => void | Promise<void>) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
(manager as { off: (event: string, handler: (payload: unknown) => void | Promise<void>) => void }).off(event, handler);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to remove event listener';
throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'off', event, originalError: err });
}
}, [manager]);
return {
isLoading,
error,
enableMintQuoteWatcher,
disableMintQuoteWatcher,
enableMintQuoteProcessor,
disableMintQuoteProcessor,
waitForMintQuoteProcessor,
enableProofStateWatcher,
disableProofStateWatcher,
on,
once,
off,
};
}
-174
View File
@@ -1,174 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { CashuMint, CashuWalletError } from './types';
export interface UseCashuMintsReturn {
mints: CashuMint[];
isLoading: boolean;
error: CashuWalletError | null;
refreshMints: () => Promise<void>;
getMints: () => Promise<CashuMint[]>;
addMint: (mintUrl: string) => Promise<void>;
removeMint: (mintUrl: string) => Promise<void>;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
}
export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
const [mints, setMints] = useState<CashuMint[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const refreshMints = useCallback(async () => {
if (!manager) return;
try {
const mintList = await (manager as { mint: { getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> } }).mint.getAllMints();
const formattedMints = mintList
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
url: mint.mintUrl, // Map mintUrl to url for consistency
name: mint.name,
info: mint.mintInfo
}));
// If no mints exist, add the default mint
if (formattedMints.length === 0) {
console.log('🔧 No mints found, adding default mint: mint.chorus.community');
try {
await (manager as { mint: { addMint: (mintUrl: string) => Promise<unknown> } }).mint.addMint('https://mint.chorus.community');
// The mint:added event will trigger refreshMints again, so we don't need to set mints here
return;
} catch (err) {
console.warn('⚠️ Failed to add default mint:', err);
// Continue with empty mints if default mint fails
}
}
setMints(formattedMints);
} catch (err) {
console.error('Failed to refresh mints:', err);
const errorMessage = err instanceof Error ? err.message : 'Failed to refresh mints';
setError(new CashuWalletError(errorMessage, 'MINT_REFRESH_ERROR', { originalError: err }));
}
}, [manager]);
const getMints = useCallback(async (): Promise<CashuMint[]> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
const mintList = await (manager as { mint: { getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> } }).mint.getAllMints();
return mintList
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
url: mint.mintUrl, // Map mintUrl to url for consistency
name: mint.name,
info: mint.mintInfo
}));
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get mints';
const cashuError = new CashuWalletError(errorMessage, 'GET_MINTS_ERROR', { originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const addMint = useCallback(async (mintUrl: string) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
await (manager as { mint: { addMint: (mintUrl: string) => Promise<unknown> } }).mint.addMint(mintUrl);
// No need to manually refresh - events will handle it automatically
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint';
const cashuError = new CashuWalletError(errorMessage, 'ADD_MINT_ERROR', { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const removeMint = useCallback(async (mintUrl: string) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
// Access the mintService directly through the manager to use deleteMint
// The manager has a private mintService property that we can access
const mintService = (manager as any).mintService;
if (!mintService || typeof mintService.deleteMint !== 'function') {
throw new CashuWalletError('Mint service not available', 'MINT_SERVICE_ERROR');
}
await mintService.deleteMint(mintUrl);
// No need to manually refresh - events will handle it automatically
console.log('✅ Mint removed successfully:', mintUrl);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to remove mint';
const cashuError = new CashuWalletError(errorMessage, 'REMOVE_MINT_ERROR', { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
// Set up event listeners for automatic mint updates using coco events
useEffect(() => {
if (!manager) return;
const unsubscribeMintAdded = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('mint:added', () => {
console.log('➕ Mint added, refreshing mints...');
refreshMints();
});
const unsubscribeMintUpdated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('mint:updated', () => {
console.log('🔄 Mint updated, refreshing mints...');
refreshMints();
});
return () => {
unsubscribeMintAdded();
unsubscribeMintUpdated();
};
}, [manager, refreshMints]);
// Initial mints load
useEffect(() => {
if (manager && mints.length === 0) {
refreshMints();
}
}, [manager, mints.length, refreshMints]);
const getCleanMintLabel = useCallback((mint: { name?: string; url: string }): string => {
if (mint.name && mint.name.trim().length > 0) {
// If name looks like a URL, strip protocol as well
return mint.name.replace(/^https?:\/\//, '');
}
try {
return new URL(mint.url).host; // host excludes protocol and preserves port if any
} catch {
// Fallback: manual strip
return mint.url.replace(/^https?:\/\//, '');
}
}, []);
return {
mints,
isLoading,
error,
refreshMints,
getMints,
addMint,
removeMint,
getCleanMintLabel,
};
}
-156
View File
@@ -1,156 +0,0 @@
import { useState, useCallback } from 'react';
import { CashuMintQuote, CashuMeltQuote, CashuWalletError, CashuQuoteError } from './types';
export interface UseCashuQuotesReturn {
isLoading: boolean;
error: CashuWalletError | null;
createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote>;
redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote>;
payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void>;
addMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
}
export function useCashuQuotes(manager: unknown | null, repositories: unknown | null): UseCashuQuotesReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const createMintQuote = useCallback(async (mintUrl: string, amount: number): Promise<CashuMintQuote> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
const quote = await (manager as { quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote> } }).quotes.createMintQuote(mintUrl, amount);
return {
quote: quote.quote,
request: quote.request,
expiry: quote.expiry
};
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to create mint quote';
const cashuError = new CashuQuoteError(errorMessage, '', { mintUrl, amount, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const redeemMintQuote = useCallback(async (mintUrl: string, quoteId: string) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
console.log('🔄 redeemMintQuote: Redeeming quote for mint:', mintUrl, 'quote:', quoteId);
console.log('🔄 redeemMintQuote: Quote ID type:', typeof quoteId, 'length:', quoteId.length);
console.log('🔄 redeemMintQuote: Mint URL type:', typeof mintUrl);
await (manager as { quotes: { redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.redeemMintQuote(mintUrl, quoteId);
console.log('✅ redeemMintQuote: Quote redeemed successfully');
} catch (err) {
console.error('❌ redeemMintQuote: Error details:', {
message: err instanceof Error ? err.message : 'Unknown error',
mintUrl,
quoteId,
quoteIdType: typeof quoteId,
quoteIdLength: quoteId.length
});
const errorMessage = err instanceof Error ? err.message : 'Failed to redeem mint quote';
const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const addMintQuote = useCallback(async (mintUrl: string, quoteId: string) => {
if (!manager || !repositories) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
console.log('📝 Adding mint quote to repository:', { mintUrl, quoteId });
// Access the mint quote repository
const mintQuoteRepo = (repositories as {
mintQuoteRepository?: {
addMintQuote: (quote: { quote: string; mintUrl: string; state: string }) => Promise<void>
}
})?.mintQuoteRepository;
if (!mintQuoteRepo) {
throw new CashuWalletError('Mint quote repository not available', 'REPOSITORY_NOT_AVAILABLE');
}
// Add the quote to the repository with UNPAID state
// The mint processor will check and redeem it
await mintQuoteRepo.addMintQuote({
quote: quoteId,
mintUrl: mintUrl,
state: 'UNPAID', // Mark as UNPAID so coco will check it
});
console.log('✅ Mint quote added to repository successfully');
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint quote';
console.error('❌ Error adding mint quote:', err);
const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager, repositories]);
const createMeltQuote = useCallback(async (mintUrl: string, invoice: string): Promise<CashuMeltQuote> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
const quote = await (manager as { quotes: { createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote> } }).quotes.createMeltQuote(mintUrl, invoice);
return {
quote: quote.quote,
request: quote.request,
expiry: quote.expiry
};
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to create melt quote';
const cashuError = new CashuQuoteError(errorMessage, '', { mintUrl, invoice, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const payMeltQuote = useCallback(async (mintUrl: string, quoteId: string) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
await (manager as { quotes: { payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.payMeltQuote(mintUrl, quoteId);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to pay melt quote';
const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
return {
isLoading,
error,
createMintQuote,
redeemMintQuote,
createMeltQuote,
payMeltQuote,
addMintQuote,
};
}
-43
View File
@@ -1,43 +0,0 @@
import { useCallback } from 'react';
import { CashuWalletError } from './types';
export interface UseCashuSubscriptionsReturn {
isLoading: boolean;
error: CashuWalletError | null;
awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
}
export function useCashuSubscriptions(manager: unknown | null): UseCashuSubscriptionsReturn {
const isLoading = false; // Subscription operations are typically async but don't have loading states
const error = null; // Errors are handled per-operation
const awaitMintQuotePaid = useCallback(async (mintUrl: string, quoteId: string): Promise<unknown> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return await (manager as { subscription: { awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown> } }).subscription.awaitMintQuotePaid(mintUrl, quoteId);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to await mint quote payment';
throw new CashuWalletError(errorMessage, 'SUBSCRIPTION_ERROR', { mintUrl, quoteId, originalError: err });
}
}, [manager]);
const awaitMeltQuotePaid = useCallback(async (mintUrl: string, quoteId: string): Promise<unknown> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return await (manager as { subscription: { awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown> } }).subscription.awaitMeltQuotePaid(mintUrl, quoteId);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to await melt quote payment';
throw new CashuWalletError(errorMessage, 'SUBSCRIPTION_ERROR', { mintUrl, quoteId, originalError: err });
}
}, [manager]);
return {
isLoading,
error,
awaitMintQuotePaid,
awaitMeltQuotePaid,
};
}
-108
View File
@@ -1,108 +0,0 @@
import { useState, useCallback } from 'react';
import { CashuToken, CashuWalletError, CashuTokenError } from './types';
// Dynamic import for getEncodedToken
let getEncodedToken: unknown = null;
const loadGetEncodedToken = async () => {
if (getEncodedToken) return;
try {
const coreModule = await import('coco-cashu-core');
getEncodedToken = coreModule.getEncodedToken;
} catch (error) {
console.error('Failed to load getEncodedToken:', error);
}
};
export interface UseCashuWalletReturn {
isLoading: boolean;
error: CashuWalletError | null;
receive: (token: string | CashuToken) => Promise<void>;
send: (mintUrl: string, amount: number) => Promise<string>;
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
}
export function useCashuWallet(manager: unknown | null, repositories: unknown | null): UseCashuWalletReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const receive = useCallback(async (token: string | CashuToken) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
await (manager as { wallet: { receive: (token: string | CashuToken) => Promise<void> } }).wallet.receive(token);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to receive token';
const cashuError = new CashuTokenError(errorMessage, typeof token === 'string' ? token : undefined, { originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const send = useCallback(async (mintUrl: string, amount: number): Promise<string> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
// Load getEncodedToken if not already loaded
await loadGetEncodedToken();
const token = await (manager as { wallet: { send: (mintUrl: string, amount: number) => Promise<CashuToken> } }).wallet.send(mintUrl, amount);
// Encode the token into a Cashu token string
const encodedToken = (getEncodedToken as (token: CashuToken) => string)(token);
return encodedToken;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to send tokens';
const cashuError = new CashuWalletError(errorMessage, 'SEND_ERROR', { mintUrl, amount, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
const getProofs = useCallback(async (mintUrl: string): Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>> => {
if (!manager || !repositories) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
console.log('🔍 Getting proofs from wallet for mint:', mintUrl);
// Access the proof repository
const proofRepo = (repositories as { proofRepository?: { getReadyProofs: (mintUrl: string) => Promise<Array<Record<string, unknown>>> } })?.proofRepository;
if (!proofRepo) {
throw new CashuWalletError('Proof repository not available', 'REPOSITORY_NOT_AVAILABLE');
}
// Get ready proofs for this mint (proofs available to spend)
const readyProofs = await proofRepo.getReadyProofs(mintUrl);
console.log(`✅ Found ${readyProofs.length} ready proofs for mint ${mintUrl}`);
return readyProofs as Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get proofs';
console.error('❌ Error getting proofs:', err);
const cashuError = new CashuWalletError(errorMessage, 'GET_PROOFS_ERROR', { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager, repositories]);
return {
isLoading,
error,
receive,
send,
getProofs,
};
}
+79
View File
@@ -0,0 +1,79 @@
import { useState, useCallback, useEffect } from 'react';
import type { HistoryEntry } from 'coco-cashu-core';
interface UseHistoryManagerProps {
coco: any; // Coco instance
isInitialized: boolean;
}
export function useHistoryManager({
coco,
isInitialized,
}: UseHistoryManagerProps) {
const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([]);
const [isLoadingHistory, setIsLoadingHistory] = useState(false);
const [isHistoryExpanded, setIsHistoryExpanded] = useState(false);
// Load history from wallet
const loadHistory = useCallback(async () => {
if (!coco) return;
try {
setIsLoadingHistory(true);
const entries = await coco.history.getPaginatedHistory(0, 50); // TODO: show entire history
setHistoryEntries(entries);
} catch (err) {
console.error('Failed to load history:', err);
} finally {
setIsLoadingHistory(false);
}
}, [coco]);
// Load history on wallet initialization
useEffect(() => {
if (isInitialized && historyEntries.length === 0) {
loadHistory();
}
}, [isInitialized, historyEntries.length, loadHistory]);
// Auto-refresh on wallet events
useEffect(() => {
if (!isInitialized || !coco) return;
// Listen for history updates (fires on send, receive transactions)
const unsubscribeHistoryUpdated = coco.on('history:updated', () => {
loadHistory();
});
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
const unsubscribeMeltCreated = coco.on('melt-quote:created', () => {
loadHistory();
});
// Listen for melt quote paid (backup, in case creation event missed)
const unsubscribeMeltPaid = coco.on('melt-quote:paid', () => {
loadHistory();
});
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
const unsubscribeMintRedeemed = coco.on('mint-quote:redeemed', () => {
loadHistory();
});
return () => {
unsubscribeHistoryUpdated();
unsubscribeMeltCreated();
unsubscribeMeltPaid();
unsubscribeMintRedeemed();
};
}, [isInitialized, coco, loadHistory]);
return {
historyEntries,
setHistoryEntries,
isLoadingHistory,
isHistoryExpanded,
setIsHistoryExpanded,
loadHistory,
};
}
+244
View File
@@ -0,0 +1,244 @@
import { useState, useCallback, useEffect } from 'react';
import { getCleanMintLabel } from './walletUtils';
export interface CashuMint {
url: string;
name?: string;
}
interface UseMintManagerProps {
coco: any; // Coco instance
mints: CashuMint[];
repositories: any; // Repositories instance
isNpubCashLoggedIn: boolean;
setNpubCashMint: (mintUrl: string) => Promise<boolean>;
refreshMints: () => Promise<void>;
toast: any; // Toast function
}
export function useMintManager({
coco,
mints,
repositories,
isNpubCashLoggedIn,
setNpubCashMint,
refreshMints,
toast,
}: UseMintManagerProps) {
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
const [mintDropdownOpen, setMintDropdownOpen] = useState(false);
const [mintUrl, setMintUrl] = useState('');
const [mintToRemove, setMintToRemove] = useState<CashuMint | null>(null);
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
// Set active mint and optionally sync to npub.cash
const handleSetActiveMint = useCallback(
async (url: string | null, syncToNpubCash = true) => {
setActiveMintUrl(url);
// Sync to npub.cash if user is logged in and we should sync
if (isNpubCashLoggedIn && url && syncToNpubCash) {
try {
await setNpubCashMint(url);
} catch (err) {
console.error('Failed to sync mint to npub.cash:', err);
}
}
},
[isNpubCashLoggedIn, setNpubCashMint]
);
// Add a new mint
const handleAddMint = useCallback(async () => {
if (!mintUrl.trim() || !coco) return;
try {
// Normalize URL - add https:// if not present
let normalizedUrl = mintUrl.trim();
if (
!normalizedUrl.startsWith('http://') &&
!normalizedUrl.startsWith('https://')
) {
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);
setMintUrl('');
toast({
title: 'Mint Added',
description: 'Mint added successfully!',
});
} catch (err) {
toast({
variant: 'destructive',
title: 'Add Mint Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [mintUrl, coco, mints, toast]);
// Show remove confirmation modal
const handleRemoveMintClick = useCallback((mint: CashuMint) => {
setMintDropdownOpen(false); // Close dropdown before showing modal
setMintToRemove(mint);
setShowRemoveMintModal(true);
}, []);
// Confirm and remove mint
const handleConfirmRemoveMint = useCallback(async () => {
if (!mintToRemove || !repositories) return;
try {
// Delete the mint from the backend using the mint repository directly
await repositories.mintRepository.deleteMint(mintToRemove.url);
// If the removed mint was active, switch to the first available mint
if (activeMintUrl === mintToRemove.url) {
const remainingMints = mints.filter(
(mint) => mint.url !== mintToRemove.url
);
if (remainingMints.length > 0) {
handleSetActiveMint(remainingMints[0].url, false);
} else {
setActiveMintUrl(null);
}
}
toast({
title: 'Mint Removed',
description: `${mintToRemove.name || mintToRemove.url} has been permanently removed`,
});
// Refresh the mints list to update the dropdown immediately
await refreshMints();
setShowRemoveMintModal(false);
setMintToRemove(null);
} catch (err) {
console.error('Failed to remove mint:', err);
toast({
variant: 'destructive',
title: 'Remove Mint Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [
mintToRemove,
mints,
activeMintUrl,
handleSetActiveMint,
repositories,
toast,
refreshMints,
]);
// Show denomination breakdown for a mint
const handleShowDenominations = useCallback(
async (
mintUrl: string,
setShowProofBreakdown: (show: boolean) => void,
setProofBreakdown: (breakdown: {
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
}) => void
) => {
if (!repositories) return;
try {
// Access proofs directly through the proof repository
const proofs = await repositories.proofRepository.getReadyProofs(
mintUrl
);
if (!proofs || proofs.length === 0) {
toast({
variant: 'destructive',
title: 'No Tokens',
description: 'No tokens found for this mint',
});
return;
}
// Group proofs by denomination
const denominations: { [key: number]: number } = {};
proofs.forEach((proof: { amount?: number }) => {
const amount = proof.amount || 0;
denominations[amount] = (denominations[amount] || 0) + 1;
});
const totalBalance = Object.entries(denominations).reduce(
(sum, [amount, count]) => sum + parseInt(amount) * count,
0
);
// Set the breakdown data and show the modal
setProofBreakdown({
mintUrl,
denominations,
totalBalance,
});
setShowProofBreakdown(true);
} catch (err) {
toast({
variant: 'destructive',
title: 'Failed to Get Denominations',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
},
[repositories, toast]
);
// Auto-select first mint when mints change, or add default mint if none exist
useEffect(() => {
if (mints.length > 0 && !activeMintUrl) {
// Select first mint initially - user can change via dropdown
// Don't sync to npub.cash on auto-select, only on manual changes
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, coco]);
return {
activeMintUrl,
setActiveMintUrl: handleSetActiveMint,
mintUrl,
setMintUrl,
mintDropdownOpen,
setMintDropdownOpen,
handleAddMint,
handleRemoveMintClick,
handleConfirmRemoveMint,
mintToRemove,
setMintToRemove,
showRemoveMintModal,
setShowRemoveMintModal,
getCleanMintLabel,
handleShowDenominations,
};
}
+432
View File
@@ -0,0 +1,432 @@
import { useState, useCallback, useRef, useEffect } from 'react';
import { isUnknownMintError, extractMintUrlFromError } from './walletUtils';
import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder';
interface UseWalletTransactionsProps {
coco: any; // Coco instance
activeMintUrl: string | null;
isNpubCashLoggedIn: boolean;
repositories: any; // Repositories instance
generateQRCode: (text: string) => Promise<string>;
toast: any; // Toast function
getEncodedToken: (token: any) => string;
getLightningInvoice: (params: {
lightningAddress: string;
amountSats: number;
}) => Promise<string>;
}
export function useWalletTransactions({
coco,
activeMintUrl,
isNpubCashLoggedIn,
repositories,
generateQRCode,
toast,
getEncodedToken,
getLightningInvoice,
}: UseWalletTransactionsProps) {
// Receive state
const [tokenInput, setTokenInput] = useState('');
const [quoteAmount, setQuoteAmount] = useState('');
// Send state
const [sendAmount, setSendAmount] = useState('');
const [lightningInvoice, setLightningInvoice] = useState('');
const [lightningAddressInput, setLightningAddressInput] = useState('');
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
const [pendingLightningAddress, setPendingLightningAddress] = useState<
string | null
>(null);
const [decodedInvoiceAmount, setDecodedInvoiceAmount] = useState<number | null>(null);
const [pendingInvoice, setPendingInvoice] = useState<string | null>(null);
// Transaction output state
const [sentToken, setSentToken] = useState<string | null>(null);
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
// Invoice modal state
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
const [currentInvoice, setCurrentInvoice] = useState<{
quoteId: string;
mintUrl: string;
amount: number;
invoice: string;
qrCodeUrl: string;
expiry: number;
} | null>(null);
// Ref to store the mint quote redeemed event unsubscribe function
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
// Generate QR code for sent token
const generateSentTokenQRCode = useCallback(async (token: string) => {
try {
const qrCodeUrl = await generateQRCode(token);
setSentTokenQRCode(qrCodeUrl);
} catch (err) {
console.error('Failed to generate sent token QR code:', err);
}
}, [generateQRCode]);
// Handle unknown mint error by adding the mint and retrying
const handleUnknownMintError = useCallback(
async (mintUrl: string) => {
if (!coco) return;
try {
console.log('Adding unknown mint:', mintUrl);
// Add the mint
await coco.mint.addMint(mintUrl);
// Retry receiving the token
await coco.wallet.receive(tokenInput);
setTokenInput('');
toast({
title: 'Token Received',
description: `Cashu token redeemed successfully! Added new mint: ${mintUrl}`,
});
} catch (retryErr) {
console.error('Failed to add mint and retry receive:', retryErr);
toast({
variant: 'destructive',
title: 'Receive Failed',
description: `Failed to add mint and receive token: ${retryErr instanceof Error ? retryErr.message : 'Unknown error'}`,
});
}
},
[coco, tokenInput, toast]
);
// Handle receive (token or Lightning)
const handleReceive = useCallback(async () => {
if (!coco) return;
// Receive Cashu token mode
if (!tokenInput && !quoteAmount) {
return;
}
if (tokenInput) {
// Receive token mode
try {
console.log(
'Attempting to receive token:',
tokenInput.substring(0, 20) + '...'
);
await coco.wallet.receive(tokenInput);
setTokenInput('');
toast({
title: 'Token Received',
description: 'Cashu token redeemed successfully!',
});
} catch (err) {
console.error('Token receive error:', err);
// Handle UnknownMintError by automatically adding the mint
if (isUnknownMintError(err)) {
const mintUrl = extractMintUrlFromError(err);
if (mintUrl) {
await handleUnknownMintError(mintUrl);
return;
}
}
toast({
variant: 'destructive',
title: 'Receive Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else if (quoteAmount && activeMintUrl) {
// Lightning quote mode
try {
const amount = parseInt(quoteAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
// Generate QR code for the Lightning invoice
const qrCodeUrl = await generateQRCode(quote.request);
// Set the invoice data and show modal
setCurrentInvoice({
quoteId: quote.quote,
mintUrl: activeMintUrl,
amount,
invoice: quote.request,
qrCodeUrl,
expiry: quote.expiry,
});
setShowInvoiceModal(true);
setQuoteAmount('');
// Clean up any previous listener
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
// Listen for payment notification via mint-quote:redeemed event
const quoteId = quote.quote;
const invoiceAmount = amount;
const unsubscribe = coco.on('mint-quote:redeemed', (payload: unknown) => {
const redeemedQuote = payload as { quoteId?: string };
// Check if this is the quote we're waiting for
if (redeemedQuote.quoteId === quoteId) {
toast({
title: 'Payment Received',
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
});
setShowInvoiceModal(false);
setCurrentInvoice(null);
// Clean up the event listener
mintQuoteUnsubscribeRef.current = null;
unsubscribe();
}
});
// Store unsubscribe function for cleanup
mintQuoteUnsubscribeRef.current = unsubscribe;
} catch (err) {
toast({
variant: 'destructive',
title: 'Quote Creation Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}
}, [
coco,
tokenInput,
quoteAmount,
activeMintUrl,
toast,
generateQRCode,
handleUnknownMintError,
]);
// Handle send (token or Lightning)
const handleSend = useCallback(async () => {
if (!coco) return;
if (!sendAmount && !lightningInvoice && !lightningAddressInput && !pendingLightningAddress) {
return;
}
// Send Cashu token mode
if (sendAmount && activeMintUrl) {
try {
const amount = parseInt(sendAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const token = await coco.wallet.send(activeMintUrl, amount);
const encodedToken = getEncodedToken(token);
setSentToken(encodedToken);
await generateSentTokenQRCode(encodedToken);
setSendAmount('');
} catch (err) {
toast({
variant: 'destructive',
title: 'Send Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else if (activeMintUrl) {
// Lightning mode
// Step 1: Check if we have a pending Lightning address awaiting amount
if (pendingLightningAddress) {
// Step 2: User entered amount, now resolve address and pay
if (!lightningAddressAmount) return;
try {
const amount = parseInt(lightningAddressAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const invoice = await getLightningInvoice({
lightningAddress: pendingLightningAddress,
amountSats: amount,
});
const meltQuote = await coco.quotes.createMeltQuote(
activeMintUrl,
invoice
);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: 'Payment Sent',
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
});
// Reset state
setPendingLightningAddress(null);
setLightningAddressInput('');
setLightningAddressAmount('');
} catch (err) {
console.error('Payment error:', err);
toast({
variant: 'destructive',
title: 'Payment Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else {
// Step 1: Check if input is a Lightning address or invoice
const input = lightningInvoice.trim() || lightningAddressInput.trim();
if (!input) return;
// Check if it's a Lightning address (contains @)
if (input.includes('@')) {
setPendingLightningAddress(input);
setLightningAddressInput('');
} else {
// It's a regular Lightning invoice - decode to show amount first
if (isValidBolt11Invoice(input)) {
const amount = decodeBolt11Amount(input);
if (amount) {
// Show amount confirmation screen
setPendingInvoice(input);
setDecodedInvoiceAmount(amount);
setLightningInvoice('');
return;
} else {
// Failed to decode amount - show error and don't attempt payment
toast({
variant: 'destructive',
title: 'Invalid Invoice',
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({
variant: 'destructive',
title: 'Invalid Invoice',
description: 'This does not appear to be a valid lightning invoice. Please check the format.',
});
setLightningInvoice('');
return;
}
}
}
}
}, [
coco,
sendAmount,
lightningInvoice,
lightningAddressInput,
lightningAddressAmount,
pendingLightningAddress,
pendingInvoice,
decodedInvoiceAmount,
activeMintUrl,
toast,
getEncodedToken,
generateSentTokenQRCode,
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
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, []);
return {
// Receive state
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
// Send state
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
decodedInvoiceAmount,
setDecodedInvoiceAmount,
pendingInvoice,
setPendingInvoice,
// Transaction output state
sentToken,
setSentToken,
sentTokenQRCode,
// Invoice modal state
showInvoiceModal,
setShowInvoiceModal,
currentInvoice,
setCurrentInvoice,
// Handlers
handleReceive,
handleSend,
handleConfirmInvoicePayment,
// Refs
mintQuoteUnsubscribeRef,
};
}
+23
View File
@@ -0,0 +1,23 @@
export const getCleanMintLabel = (mint: { name?: string; url: string }): string => {
if (mint.name && mint.name.trim().length > 0) {
return mint.name.replace(/^https?:\/\//, '');
}
try {
return new URL(mint.url).host;
} catch {
return mint.url.replace(/^https?:\/\//, '');
}
};
export const isUnknownMintError = (err: unknown): boolean => {
const errorMessage = (err as any)?.message || err?.toString() || '';
return (err as any)?.constructor?.name === 'UnknownMintError' ||
errorMessage.includes('UnknownMintError') ||
(errorMessage.includes('Mint') && errorMessage.includes('is not known'));
};
export const extractMintUrlFromError = (err: unknown): string | null => {
const errorMessage = (err as any)?.message || err?.toString() || '';
const mintUrlMatch = errorMessage.match(/Mint (https?:\/\/[^\s]+)/);
return mintUrlMatch?.[1] || null;
};
+24
View File
@@ -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
});
}
-17
View File
@@ -1,17 +0,0 @@
// Re-export the new modular useCashu hook and types
export { useCashu } from './cashu/index';
export type {
UseCashuReturn,
CashuBalance,
CashuMint,
CashuMintQuote,
CashuMeltQuote,
CashuToken,
HistoryEntry,
CashuWalletError,
CashuInitializationError,
CashuMintError,
CashuQuoteError,
CashuTokenError
} from './cashu/types';
+100 -9
View File
@@ -79,21 +79,49 @@ export function useLightningAddress(): UseLightningAddressReturn {
// Step 1: Fetch LNURL-pay info
const lnurlEndpoint = `https://${domain}/.well-known/lnurlp/${username}`;
console.log('Resolving Lightning address:', {
lightningAddress,
lnurlEndpoint,
amountSats
});
const lnurlResponse = await fetch(lnurlEndpoint, {
headers: { 'Accept': 'application/json' },
});
if (!lnurlResponse.ok) {
throw new Error(`Failed to resolve Lightning address: ${lnurlResponse.status}`);
console.error('LNURL Endpoint Error:', {
lightningAddress,
lnurlEndpoint,
status: lnurlResponse.status,
statusText: lnurlResponse.statusText
});
throw new Error(`Failed to resolve Lightning address: ${lnurlResponse.status} ${lnurlResponse.statusText}`);
}
const lnurlData: LNURLPayResponse = await lnurlResponse.json();
if (lnurlData.status !== 'OK') {
console.log('LNURL Response:', {
lightningAddress,
lnurlData
});
if (lnurlData.status && lnurlData.status !== 'OK') {
console.error('LNURL Status Error:', {
lightningAddress,
status: lnurlData.status,
response: lnurlData
});
throw new Error('LNURL endpoint returned error status');
}
if (lnurlData.tag !== 'payRequest') {
console.error('LNURL Tag Error:', {
lightningAddress,
expectedTag: 'payRequest',
actualTag: lnurlData.tag,
response: lnurlData
});
throw new Error(`Unexpected LNURL tag: ${lnurlData.tag}`);
}
@@ -101,11 +129,32 @@ export function useLightningAddress(): UseLightningAddressReturn {
const minSats = lnurlData.minSendable / 1000;
const maxSats = lnurlData.maxSendable / 1000;
console.log('Amount validation:', {
lightningAddress,
amountSats,
minSats,
maxSats,
minSendable: lnurlData.minSendable,
maxSendable: lnurlData.maxSendable
});
if (amountSats < minSats) {
console.error('Amount below minimum:', {
lightningAddress,
amountSats,
minSats,
maxSats
});
throw new Error(`Amount ${amountSats} sats is below minimum ${minSats} sats`);
}
if (amountSats > maxSats) {
console.error('Amount exceeds maximum:', {
lightningAddress,
amountSats,
minSats,
maxSats
});
throw new Error(`Amount ${amountSats} sats exceeds maximum ${maxSats} sats`);
}
@@ -119,26 +168,68 @@ export function useLightningAddress(): UseLightningAddressReturn {
callbackUrl.searchParams.set('comment', comment);
}
console.log('Requesting invoice:', {
lightningAddress,
amountSats,
amountMsats,
callbackUrl: callbackUrl.toString(),
comment
});
const invoiceResponse = await fetch(callbackUrl.toString(), {
headers: { 'Accept': 'application/json' },
});
if (!invoiceResponse.ok) {
throw new Error(`Failed to get invoice: ${invoiceResponse.status}`);
console.error('Invoice Request Error:', {
lightningAddress,
amountSats,
callbackUrl: callbackUrl.toString(),
status: invoiceResponse.status,
statusText: invoiceResponse.statusText
});
throw new Error(`Failed to get invoice: ${invoiceResponse.status} ${invoiceResponse.statusText}`);
}
const invoiceData: LNURLInvoiceResponse = await invoiceResponse.json();
if (invoiceData.status !== 'OK') {
throw new Error(invoiceData.reason || 'Invoice generation failed');
console.log('Invoice Response:', {
lightningAddress,
amountSats,
invoiceData
});
// Check if we have a valid invoice (some providers return invoice directly without status field)
if (invoiceData.pr) {
console.log('Invoice generated successfully:', {
lightningAddress,
amountSats,
invoiceLength: invoiceData.pr.length
});
setIsLoading(false);
return invoiceData.pr;
}
if (!invoiceData.pr) {
throw new Error('No invoice returned from provider');
// If no invoice but has status field, check for errors
if (invoiceData.status && invoiceData.status !== 'OK') {
const errorReason = invoiceData.reason || 'Invoice generation failed';
console.error('LNURL Invoice Error:', {
lightningAddress,
amountSats,
status: invoiceData.status,
reason: errorReason,
response: invoiceData
});
throw new Error(`Invoice generation failed: ${errorReason}`);
}
setIsLoading(false);
return invoiceData.pr;
// If we get here, no invoice was provided
console.error('LNURL Invoice Missing PR:', {
lightningAddress,
amountSats,
response: invoiceData
});
throw new Error('No invoice returned from provider');
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
+74
View File
@@ -0,0 +1,74 @@
import { useCallback } from 'react';
import { useCurrentUser } from './useCurrentUser';
import type { NostrEvent } from '@nostrify/nostrify';
export interface NIP98Options {
url: string;
method: string;
body?: unknown;
}
/**
* Hook for creating NIP-98 HTTP Authentication headers
* Based on https://github.com/nostr-protocol/nips/blob/master/98.md
*/
export function useNIP98() {
const { user } = useCurrentUser();
/**
* Create a NIP-98 authorization header for HTTP requests
* @param options - The request details (url, method, optional body)
* @returns Promise<string> - The "Nostr base64..." authorization header value
*/
const createAuthHeader = useCallback(async (options: NIP98Options): Promise<string> => {
if (!user) {
throw new Error('User must be logged in to create NIP-98 auth header');
}
const { url, method, body } = options;
// Parse URL to remove query parameters (per NIP-98 spec)
const urlObj = new URL(url);
const urlWithoutQuery = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;
const tags: string[][] = [
['u', urlWithoutQuery],
['method', method.toUpperCase()],
];
// If there's a request body (POST, PUT, PATCH), add payload hash
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
const bodyString = JSON.stringify(body);
const encoder = new TextEncoder();
const data = encoder.encode(bodyString);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const payloadHash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
tags.push(['payload', payloadHash]);
}
// Create and sign the NIP-98 event (kind 27235)
const event = await user.signer.signEvent({
kind: 27235,
content: '',
tags,
created_at: Math.floor(Date.now() / 1000),
}) as NostrEvent;
// Encode the event as base64
const eventJson = JSON.stringify(event);
const base64Event = btoa(eventJson);
return `Nostr ${base64Event}`;
}, [user]);
return {
createAuthHeader,
isLoggedIn: !!user,
pubkey: user?.pubkey,
signer: user?.signer,
};
}
+320
View File
@@ -0,0 +1,320 @@
import { useCallback, useState, useMemo, useEffect, useRef } from 'react';
import { useNIP98 } from './useNIP98';
import { NPCClient, JWTAuthProvider } from 'npubcash-sdk';
import type { User, Quote } from 'npubcash-types';
const NPUBCASH_BASE_URL = 'https://npubx.cash';
export interface NpubCashUserInfo {
pubkey: string;
name?: string;
mint_url: string;
lock_quote: boolean;
}
/**
* Hook for interacting with npub.cash API using the official SDK
*/
export function useNpubCash() {
const { createAuthHeader, signer, isLoggedIn, pubkey } = useNIP98();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Ref to track last sync timestamp for incremental updates
const lastSyncRef = useRef<number>(0);
// Create NPCClient instance using the SDK with JWTAuthProvider for proper WebSocket auth
const npcClient = useMemo(() => {
if (!isLoggedIn || !signer) return null;
// Adapt NostrSigner to JWTAuthProvider's expected SigningFunc signature
const signingFunc = async (eventTemplate: any) => {
return await signer.signEvent(eventTemplate);
};
const auth = new JWTAuthProvider(NPUBCASH_BASE_URL, signingFunc);
return new NPCClient(NPUBCASH_BASE_URL, auth);
}, [isLoggedIn, signer]);
// Generic wrapper for SDK calls with loading state
const withLoading = useCallback(async <T>(operation: () => Promise<T>): Promise<T | null> => {
try {
setIsLoading(true);
setError(null);
return await operation();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
setError(errorMessage);
return null;
} finally {
setIsLoading(false);
}
}, []);
const setMint = useCallback(async (mintUrl: string): Promise<boolean> => {
if (!npcClient) return false;
const result = await withLoading(() => npcClient.settings.setMintUrl(mintUrl));
return result !== null;
}, [npcClient, withLoading]);
const getUserInfo = useCallback(async (): Promise<NpubCashUserInfo | null> => {
if (!npcClient) return null;
// Since SDK doesn't have getUserInfo, we'll use manual implementation
// This could be enhanced if SDK adds this method
return withLoading(async () => {
const url = `${NPUBCASH_BASE_URL}/api/v2/user/info`;
const authHeader = await createAuthHeader({ url, method: 'GET' });
const response = await fetch(url, {
method: 'GET',
headers: { 'Authorization': authHeader, 'Content-Type': 'application/json' },
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || `Failed to get user info (${response.status})`);
}
const data = await response.json();
return data.data.user;
});
}, [npcClient, createAuthHeader, withLoading]);
const getAllQuotes = useCallback(async (): Promise<Quote[]> => {
if (!npcClient) return [];
const result = await withLoading(() => npcClient.getAllQuotes());
return result || [];
}, [npcClient, withLoading]);
const getQuotesSince = useCallback(async (since: number): Promise<Quote[]> => {
if (!npcClient) return [];
const result = await withLoading(() => npcClient.getQuotesSince(since));
return result || [];
}, [npcClient, withLoading]);
const setLockQuotes = useCallback(async (lockQuotes: boolean): Promise<boolean> => {
if (!npcClient) return false;
const result = await withLoading(() => npcClient.settings.setLock(lockQuotes));
return result !== null;
}, [npcClient, withLoading]);
const subscribeToQuotes = useCallback((
onUpdate: (quoteId: string) => void,
onError?: (msg: string) => void
) => {
if (!npcClient) return () => {};
return npcClient.subscribe(onUpdate, onError);
}, [npcClient]);
const refreshQuotes = useCallback(async (coco: any, toast: any): Promise<void> => {
if (!npcClient || !coco) return;
try {
// Fetch all quotes from npub.cash
const quotes = await getAllQuotes();
if (quotes.length === 0) {
toast({
title: "No Quotes Found",
description: "No pending quotes found on npub.cash",
});
return;
}
// Group quotes by mint URL
const quotesByMint = quotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof quotes>);
let addedQuotes = 0;
// Process each mint's quotes
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
// Check if mint exists, add if not
const isKnown = await coco.mint.isKnownMint(mintUrl);
if (!isKnown) {
await coco.mint.addMint(mintUrl);
}
// Add quotes to the wallet (matching main.ts format)
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
addedQuotes += mintQuotes.length;
} catch (err) {
console.warn(`Failed to process quotes for mint ${mintUrl}:`, err);
}
}
if (addedQuotes > 0) {
toast({
title: "Quotes Refreshed",
description: `Successfully added ${addedQuotes} quotes from npub.cash`,
});
} else {
toast({
title: "No New Quotes",
description: "All quotes from npub.cash are already processed",
});
}
} catch (err) {
toast({
variant: "destructive",
title: "Refresh Failed",
description: err instanceof Error ? err.message : 'Failed to refresh quotes',
});
}
}, [npcClient, getAllQuotes]);
const clearError = useCallback(() => setError(null), []);
// Subscribe to quote updates and sync to wallet automatically
const syncQuotesWithWallet = useCallback(async (coco: any, toast: any): Promise<() => void> => {
if (!npcClient || !coco) return () => {};
try {
// Fetch and sync all quotes initially
const quotes = await getAllQuotes();
if (quotes.length > 0) {
const quotesByMint = quotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof quotes>);
let addedQuotes = 0;
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
const isKnown = await coco.mint.isKnownMint(mintUrl);
if (!isKnown) {
await coco.mint.addMint(mintUrl);
}
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
addedQuotes += mintQuotes.length;
} catch (err) {
console.warn(`Failed to sync quotes for mint ${mintUrl}:`, err);
}
}
if (addedQuotes > 0) {
toast({
title: "Quotes Synced",
description: `Synced ${addedQuotes} quotes from npub.cash`,
});
lastSyncRef.current = Math.floor(Date.now() / 1000);
}
}
// Subscribe to real-time updates
const unsubscribe = subscribeToQuotes(
async (quoteId: string) => {
try {
// When a quote is updated, fetch newer quotes and sync
const recentQuotes = await getQuotesSince(lastSyncRef.current);
if (recentQuotes.length > 0) {
const quotesByMint = recentQuotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof recentQuotes>);
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
const isKnown = await coco.mint.isKnownMint(mintUrl);
if (!isKnown) {
await coco.mint.addMint(mintUrl);
}
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
} catch (err) {
console.warn(`Failed to sync quote ${quoteId} for mint ${mintUrl}:`, err);
}
}
lastSyncRef.current = Math.floor(Date.now() / 1000);
}
} catch (err) {
console.error('Failed to sync quote update:', err);
}
},
(err: string) => {
console.error('Quote subscription error:', err);
toast({
variant: "destructive",
title: "Sync Error",
description: "Failed to sync quotes from npub.cash",
});
}
);
return unsubscribe;
} catch (err) {
console.error('Failed to set up quote sync:', err);
toast({
variant: "destructive",
title: "Sync Failed",
description: err instanceof Error ? err.message : 'Failed to set up quote sync',
});
return () => {};
}
}, [npcClient, getAllQuotes, getQuotesSince, subscribeToQuotes]);
return {
// Core methods
setMint,
getUserInfo,
// Quote management methods
getAllQuotes,
getQuotesSince,
setLockQuotes,
subscribeToQuotes,
refreshQuotes,
syncQuotesWithWallet,
// Status
isLoading,
error,
isLoggedIn,
pubkey,
clearError,
// SDK instance for advanced usage
npcClient,
};
}
+51
View File
@@ -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,
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { useMemo } from 'react';
import { useNWC } from '@/hooks/useNWCContext';
import { useCashu } from '@/hooks/useCashu';
import { useCashu } from '@/hooks/cashu/useCashu';
import type { WebLNProvider } from '@webbtc/webln-types';
export interface WalletStatus {
+5 -5
View File
@@ -4,7 +4,7 @@ import { useAuthor } from '@/hooks/useAuthor';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
import { useNWC } from '@/hooks/useNWCContext';
import { useCashu } from '@/hooks/useCashu';
import { useCashu } from '@/hooks/cashu/useCashu';
import type { NWCConnection } from '@/hooks/useNWC';
import { nip57 } from 'nostr-tools';
import type { Event } from 'nostr-tools';
@@ -30,7 +30,7 @@ export function useZaps(
const author = useAuthor(actualTarget?.pubkey);
const { sendPayment, getActiveConnection } = useNWC();
const { createMeltQuote, payMeltQuote, balances, mints, isInitialized: isCashuInitialized } = useCashu();
const { coco, balances, mints, isInitialized: isCashuInitialized } = useCashu();
const [isZapping, setIsZapping] = useState(false);
const [invoice, setInvoice] = useState<string | null>(null);
@@ -258,12 +258,12 @@ export function useZaps(
return balance >= amount;
});
if (mintWithBalance) {
if (mintWithBalance && coco) {
// Create melt quote to convert Cashu tokens to Lightning payment
const meltQuote = await createMeltQuote(mintWithBalance.url, newInvoice);
const meltQuote = await coco.quotes.createMeltQuote(mintWithBalance.url, newInvoice);
// Pay the melt quote (this burns the Cashu tokens and pays the Lightning invoice)
await payMeltQuote(mintWithBalance.url, meltQuote.quote);
await coco.quotes.payMeltQuote(mintWithBalance.url, meltQuote.quote);
// Clear states immediately on success
setIsZapping(false);
+247
View File
@@ -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);
}
+85
View File
@@ -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
);
}
+9
View File
@@ -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()
*
+13
View File
@@ -15,3 +15,16 @@ createRoot(document.getElementById("root")!).render(
<App />
</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);
});
});
}