add npubxCash lightning address

This commit is contained in:
lemonknowsall committed 2025-10-07 00:48:29 -07:00
1 parent 565305a592
commit 579cd3584b
5 files changed
+1351 -9

No files matched your search

+612
View File
@@ -0,0 +1,612 @@
# 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.
+267 -9
View File
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
import { useNpubCash } from '@/hooks/useNpubCash';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useLightningAddress } from '@/hooks/useLightningAddress';
import { Button } from '@/components/ui/button';
@@ -8,7 +9,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger} from '@/components/ui/dropdown-menu';
import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp } from 'lucide-react';
import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp, CreditCard } from 'lucide-react';
import QRCode from 'qrcode';
export function CashuWallet() {
@@ -37,6 +38,18 @@ export function CashuWallet() {
getHistory,
} = useCashu();
const {
lightningAddress,
unclaimedAmount,
quotes,
isLoading: isNpubCashLoading,
error: npubCashError,
fetchQuotes,
refresh: refreshNpubCash,
retryAuth,
setMint,
} = useNpubCash();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
// ============================================================================
@@ -81,6 +94,7 @@ export function CashuWallet() {
const [copiedToken, setCopiedToken] = useState(false);
const [copiedInvoice, setCopiedInvoice] = useState<string | null>(null);
const [copiedLightningAddress, setCopiedLightningAddress] = useState(false);
// ============================================================================
@@ -130,6 +144,19 @@ export function CashuWallet() {
}
};
// Copy Lightning address to clipboard
const copyLightningAddress = async () => {
if (!lightningAddress) return;
try {
await navigator.clipboard.writeText(lightningAddress);
setCopiedLightningAddress(true);
setTimeout(() => setCopiedLightningAddress(false), 2000);
} catch (err) {
console.error('Failed to copy Lightning address:', err);
}
};
// ============================================================================
// HELPER FUNCTIONS - QR Code
@@ -151,6 +178,29 @@ export function CashuWallet() {
}
};
// ============================================================================
// HELPER FUNCTIONS - Mint Management
// ============================================================================
/**
* Set active mint and sync with npubx.cash
*/
const handleSetActiveMint = useCallback(async (mintUrl: string | null) => {
// Set the active mint locally
setActiveMintUrl(mintUrl);
// If we have a mint URL, also update npubx.cash preference
if (mintUrl) {
try {
await setMint(mintUrl);
console.log(`✅ Updated npubx.cash mint preference to: ${mintUrl}`);
} catch (error) {
console.error('❌ Failed to update npubx.cash mint preference:', error);
// Don't throw - we still want to set the local mint even if npubx.cash fails
}
}
}, [setMint]);
// ============================================================================
// HELPER FUNCTIONS - History
// ============================================================================
@@ -446,6 +496,68 @@ export function CashuWallet() {
}
};
// Claim npub.cash quotes
const handleClaimNpubCashQuote = async (quote: typeof quotes[0]) => {
try {
console.log('🎯 Claiming npubx.cash quote:', quote);
console.log('📋 Quote details:', {
quote_id: quote.quoteId,
mint_url: quote.mintUrl,
amount: quote.amount,
state: quote.state,
request: quote.request?.substring(0, 50) + '...'
});
// Add mint if not already added
const hasMint = mints.some(m => m.url === quote.mintUrl);
if (!hasMint) {
console.log('➕ Adding mint:', quote.mintUrl);
await addMint(quote.mintUrl);
}
// Call the mint's API directly since this is an external quote
console.log('🔄 Redeeming npubx.cash quote via mint API:', quote.quoteId, 'from mint:', quote.mintUrl);
console.log('🔄 Lightning invoice:', quote.request);
// Try the /mint endpoint for quote redemption
const response = await fetch(`${quote.mintUrl}/mint`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
quote: quote.quoteId, // Use the quote ID to redeem
}),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: 'Failed to redeem quote' }));
throw new Error(errorData.message || `Mint API error: ${response.status}`);
}
const data = await response.json();
console.log('✅ Mint API response:', data);
if (data.paid && data.proofs) {
// We received tokens, now we need to add them to our wallet
console.log('🔄 Adding received tokens to wallet...');
await receive(JSON.stringify(data.proofs));
console.log('✅ Successfully claimed tokens from npubx.cash quote');
} else {
throw new Error('No tokens received from mint');
}
// Refresh quotes and balances
await fetchQuotes();
await refreshBalances();
alert(`Successfully claimed ${quote.amount} sats!`);
} catch (err) {
console.error('Failed to claim npub.cash quote:', err);
alert(`Failed to claim: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
};
const handleShowDenominations = async (mintUrl: string) => {
try {
console.log('🔍 Getting token denominations for mint:', mintUrl);
@@ -496,9 +608,9 @@ export function CashuWallet() {
const highestBalance = balances[highest.url] || 0;
return currentBalance > highestBalance ? current : highest;
});
setActiveMintUrl(mintWithHighestBalance.url);
handleSetActiveMint(mintWithHighestBalance.url);
}
}, [mints, activeMintUrl, balances]);
}, [mints, activeMintUrl, balances, handleSetActiveMint]);
// Load transaction history when wallet is initialized
useEffect(() => {
@@ -594,6 +706,7 @@ export function CashuWallet() {
await checkAndRedeemPendingQuotes();
await refreshBalances();
await loadHistory();
await refreshNpubCash();
console.log('💰 Current balances after manual refresh:', balances);
}}
className="mt-2"
@@ -624,7 +737,7 @@ export function CashuWallet() {
<DropdownMenuItem
key={`dd-mint-${mint.url || `unknown-${index}`}`}
className="flex items-center justify-between"
onClick={() => setActiveMintUrl(mint.url)}
onClick={() => handleSetActiveMint(mint.url)}
>
<div className="flex items-center gap-2">
<span className="font-medium">{getCleanMintLabel(mint)}</span>
@@ -662,19 +775,80 @@ export function CashuWallet() {
</div>
)}
</div>
{/* npub.cash Lightning Address */}
{lightningAddress && (
<div className="mt-4 p-4 bg-muted/30 rounded-lg">
<div className="flex items-center justify-center gap-2 mb-2">
<CreditCard className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">Your Lightning Address</span>
</div>
<div className="flex items-center justify-center gap-2">
<code className="bg-background px-3 py-2 rounded text-sm font-mono border">
{lightningAddress}
</code>
<Button
size="sm"
variant="outline"
onClick={copyLightningAddress}
className="h-8"
>
{copiedLightningAddress ? (
<Check className="h-3 w-3" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</div>
{unclaimedAmount > 0 && (
<div className="mt-2 flex items-center justify-center gap-2">
<Badge variant="secondary" className="text-sm">
{unclaimedAmount} sats unclaimed
</Badge>
<Button
size="sm"
variant="outline"
onClick={refreshNpubCash}
disabled={isNpubCashLoading}
className="h-6 text-xs"
>
<RefreshCw className={`h-3 w-3 mr-1 ${isNpubCashLoading ? 'animate-spin' : ''}`} />
Refresh
</Button>
</div>
)}
</div>
)}
</div>
)}
{/* ========================================================================
SECTION: Error Display
======================================================================== */}
{error && (
{(error || npubCashError) && (
<Alert variant="destructive" className="mb-6">
<AlertDescription className="flex items-center justify-between">
{error}
<Button variant="outline" size="sm" onClick={clearError}>
Dismiss
</Button>
<div className="flex-1">
{error || npubCashError}
{npubCashError && npubCashError.includes('Authorization') && (
<div className="text-xs mt-1 opacity-75">
Try refreshing the page or check your Nostr extension
</div>
)}
</div>
<div className="flex gap-2">
{npubCashError && (
<Button variant="outline" size="sm" onClick={retryAuth}>
Retry Auth
</Button>
)}
<Button variant="outline" size="sm" onClick={() => {
if (error) clearError();
// npub.cash errors are handled by retryAuth
}}>
Dismiss
</Button>
</div>
</AlertDescription>
</Alert>
)}
@@ -1037,6 +1211,90 @@ export function CashuWallet() {
</Card>
)}
{/* ========================================================================
SECTION: npub.cash Received Payments
======================================================================== */}
{quotes.length > 0 && (
<Card className="mt-6">
<CardHeader>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center">
<CreditCard className="h-5 w-5 mr-2" />
Received Payments (npub.cash)
</div>
<Button
variant="ghost"
size="sm"
onClick={refreshNpubCash}
disabled={isNpubCashLoading}
className="gap-1"
>
<RefreshCw className={`h-4 w-4 ${isNpubCashLoading ? 'animate-spin' : ''}`} />
Refresh
</Button>
</CardTitle>
<CardDescription>
Lightning payments received to your npub.cash address
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
{quotes && quotes.length > 0 ? quotes.map(quote => {
const isExpired = quote.expiresAt < Date.now() / 1000;
const isPaid = quote.state === 'PAID';
return (
<div key={quote.quoteId} className="border rounded-lg p-3">
<div className="flex justify-between items-start mb-2">
<div>
<p className="font-semibold">{quote.amount} sats</p>
<p className="text-xs text-muted-foreground">
{quote.paidAt ? new Date(quote.paidAt * 1000).toLocaleString() : 'Unknown date'}
</p>
</div>
<div className="flex gap-2 items-center">
<Badge
variant={
isPaid ? 'default' :
isExpired ? 'secondary' :
'outline'
}
>
{quote.state}
</Badge>
{isPaid && !isExpired && (
<Button
size="sm"
onClick={() => handleClaimNpubCashQuote(quote)}
disabled={isLoading}
>
Claim
</Button>
)}
</div>
</div>
<div className="space-y-1 text-xs text-muted-foreground">
<p className="truncate">Mint: {quote.mintUrl}</p>
{isExpired && (
<p className="text-destructive">
Expired: {new Date(quote.expiresAt * 1000).toLocaleString()}
</p>
)}
{quote.locked && (
<Badge variant="outline" className="text-xs">
🔒 Locked to your pubkey
</Badge>
)}
</div>
</div>
);
}) : null}
</div>
</CardContent>
</Card>
)}
{/* ========================================================================
SECTION: Transaction History
======================================================================== */}
+10
View File
@@ -561,10 +561,20 @@ export function useCashu(): UseCashuReturn {
try {
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 (managerRef.current as { quotes: { redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.redeemMintQuote(mintUrl, quoteId);
console.log('✅ redeemMintQuote: Quote redeemed successfully, refreshing balances...');
await refreshBalances();
} 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';
setError(errorMessage);
throw err;
+455
View File
@@ -0,0 +1,455 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useLocalStorage } from './useLocalStorage';
import { useCurrentUser } from './useCurrentUser';
import { nip19, finalizeEvent, generateSecretKey } from 'nostr-tools';
import type { EventTemplate } from 'nostr-tools';
// API Base URL - can be configured
const NPUBCASH_API_BASE = 'https://npubx.cash/api/v2';
const NPUBCASH_DOMAIN = 'npubx.cash';
// Types for npub.cash API responses
export interface NpubCashQuote {
createdAt: number;
paidAt: number;
expiresAt: number;
mintUrl: string;
quoteId: string;
request: string; // BOLT11 invoice
amount: number; // Amount in sats
state: 'PENDING' | 'PAID' | 'EXPIRED';
locked: boolean;
}
export interface NpubCashUserInfo {
pubkey: string;
name: string | null;
mintUrl: string;
lockQuote: boolean;
}
export interface NpubCashState {
isInitialized: boolean;
isLoading: boolean;
error: string | null;
lightningAddress: string | null;
userInfo: NpubCashUserInfo | null;
quotes: NpubCashQuote[];
unclaimedAmount: number; // Total amount in unclaimed quotes
}
export interface NpubCashActions {
// Fetch user's paid quotes
fetchQuotes: (since?: number, limit?: number) => Promise<NpubCashQuote[]>;
// Get user info/settings
fetchUserInfo: () => Promise<NpubCashUserInfo>;
// Set username (costs sats via X-Cashu header)
setUsername: (username: string) => Promise<void>;
// Set preferred mint
setMint: (mintUrl: string) => Promise<void>;
// Toggle quote locking (NUT-20)
setLockQuotes: (locked: boolean) => Promise<void>;
// Refresh all data
refresh: () => Promise<void>;
// Clear JWT token (force re-auth)
clearAuth: () => void;
// Retry authentication after error
retryAuth: () => void;
}
/**
* Hook for integrating npub.cash Lightning addresses
*
* Provides a Lightning address ([email protected]) for the current user
* and methods to fetch/manage received payments stored as Cashu quotes.
*
* @example
* ```tsx
* const { lightningAddress, quotes, unclaimedAmount, fetchQuotes } = useNpubCash();
*
* // Display Lightning address
* <p>Send sats to: {lightningAddress}</p>
*
* // Show unclaimed balance
* <p>Unclaimed: {unclaimedAmount} sats</p>
*
* // Fetch new quotes
* await fetchQuotes();
* ```
*/
export function useNpubCash(): NpubCashState & NpubCashActions {
const { user } = useCurrentUser();
const pubkey = user?.pubkey;
// Store JWT token for convenience (30min expiry)
const [jwtToken, setJwtToken] = useLocalStorage<string | null>('npubcash-jwt', null);
// Store last claimed quote timestamp to track new payments
const [lastClaimedAt, setLastClaimedAt] = useLocalStorage<number>('npubcash-last-claimed', 0);
// Component state
const [isInitialized, setIsInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [userInfo, setUserInfo] = useState<NpubCashUserInfo | null>(null);
const [quotes, setQuotes] = useState<NpubCashQuote[]>([]);
const [hasTriedInitialization, setHasTriedInitialization] = useState(false);
// Generate Lightning address from pubkey
const lightningAddress = useMemo(() => {
if (!pubkey) return null;
const npub = nip19.npubEncode(pubkey);
return `${npub}@${NPUBCASH_DOMAIN}`;
}, [pubkey]);
/**
* Create NIP-98 auth token for a request
*/
const createNIP98Token = useCallback(async (url: string, method: string, body?: unknown): Promise<string> => {
if (!user) {
throw new Error('No user logged in');
}
// Parse URL and reconstruct it to match server expectations
// Remove query parameters from the URL used in NIP-98 token
// The server will reconstruct the full URL from the actual request
const urlObj = new URL(url);
const baseUrl = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;
console.log(`🔍 NIP-98 Token Creation - Original URL: ${url}, Base URL: ${baseUrl}, Method: ${method}`);
// Create NIP-98 event (kind 27235)
const eventTemplate: EventTemplate = {
kind: 27235,
created_at: Math.floor(Date.now() / 1000),
tags: [
['u', baseUrl],
['method', method],
],
content: '',
};
// Add payload hash for POST/PUT/PATCH requests
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('');
eventTemplate.tags.push(['payload', payloadHash]);
}
// Sign the event using the user's signer
const signedEvent = await user.signer.signEvent(eventTemplate);
// Encode as base64
const eventJson = JSON.stringify(signedEvent);
const base64Token = btoa(eventJson);
return base64Token;
}, [user]);
/**
* Get auth header (JWT if available, otherwise create NIP-98)
*/
const getAuthHeader = useCallback(async (url: string, method: string, body?: unknown): Promise<string> => {
// Try JWT first if available
if (jwtToken) {
return `Bearer ${jwtToken}`;
}
// Otherwise create NIP-98 token
const nip98Token = await createNIP98Token(url, method, body);
return `Nostr ${nip98Token}`;
}, [jwtToken, createNIP98Token]);
/**
* Obtain JWT token via NIP-98 auth
*/
const obtainJWT = useCallback(async (): Promise<string> => {
if (!pubkey) {
throw new Error('No user logged in');
}
const authUrl = `${NPUBCASH_API_BASE}/auth/nip98`;
const nip98Token = await createNIP98Token(authUrl, 'GET');
const response = await fetch(authUrl, {
method: 'GET',
headers: {
'Authorization': `Nostr ${nip98Token}`,
},
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: 'Authentication failed' }));
throw new Error(errorData.message || 'Failed to obtain JWT token');
}
const data = await response.json();
const token = data.data?.token;
if (!token) {
throw new Error('No JWT token in response');
}
setJwtToken(token);
return token;
}, [pubkey, createNIP98Token, setJwtToken]);
/**
* Make authenticated API request
*/
const apiRequest = useCallback(async <T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> => {
if (!pubkey) {
throw new Error('No user logged in');
}
const url = `${NPUBCASH_API_BASE}${endpoint}`;
let authHeader: string;
try {
authHeader = await getAuthHeader(url, options.method || 'GET', options.body ? JSON.parse(options.body as string) : undefined);
} catch (error) {
// If JWT fails, try to obtain a new one
if (jwtToken) {
setJwtToken(null);
await obtainJWT();
authHeader = await getAuthHeader(url, options.method || 'GET', options.body ? JSON.parse(options.body as string) : undefined);
} else {
throw error;
}
}
console.log(`🔍 API Request - URL: ${url}, Method: ${options.method || 'GET'}, Auth Header: ${authHeader.substring(0, 50)}...`);
const response = await fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': authHeader,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: 'Request failed' }));
throw new Error(errorData.message || `API request failed: ${response.status}`);
}
const data = await response.json();
if (data.error) {
throw new Error(data.message || 'API returned error');
}
return data.data;
}, [pubkey, jwtToken, getAuthHeader, obtainJWT, setJwtToken]);
/**
* Fetch paid quotes from npub.cash
*/
const fetchQuotes = useCallback(async (since?: number, limit: number = 50): Promise<NpubCashQuote[]> => {
try {
const queryParams = new URLSearchParams();
if (since) queryParams.set('since', since.toString());
queryParams.set('limit', limit.toString());
const endpoint = `/wallet/quotes?${queryParams.toString()}`;
const data = await apiRequest<{ quotes: NpubCashQuote[] }>(endpoint);
setQuotes(data.quotes);
return data.quotes;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch quotes';
setError(errorMessage);
throw err;
}
}, [apiRequest]);
/**
* Fetch user info/settings
*/
const fetchUserInfo = useCallback(async (): Promise<NpubCashUserInfo> => {
try {
const data = await apiRequest<{ user: NpubCashUserInfo }>('/user/info');
setUserInfo(data.user);
return data.user;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch user info';
setError(errorMessage);
throw err;
}
}, [apiRequest]);
/**
* Set Lightning address username (paid feature)
*/
const setUsername = useCallback(async (username: string): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await apiRequest('/user/username', {
method: 'POST',
body: JSON.stringify({ username }),
});
// Refresh user info
await fetchUserInfo();
setIsLoading(false);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to set username';
setError(errorMessage);
setIsLoading(false);
throw err;
}
}, [apiRequest, fetchUserInfo]);
/**
* Set preferred mint URL
*/
const setMint = useCallback(async (mintUrl: string): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await apiRequest('/user/mint', {
method: 'PATCH',
body: JSON.stringify({ mint_url: mintUrl }),
});
// Refresh user info
await fetchUserInfo();
setIsLoading(false);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to set mint';
setError(errorMessage);
setIsLoading(false);
throw err;
}
}, [apiRequest, fetchUserInfo]);
/**
* Toggle quote locking (NUT-20)
*/
const setLockQuotes = useCallback(async (locked: boolean): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await apiRequest('/user/lock', {
method: 'PATCH',
body: JSON.stringify({ lock_quotes: locked }),
});
// Refresh user info
await fetchUserInfo();
setIsLoading(false);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to set lock quotes';
setError(errorMessage);
setIsLoading(false);
throw err;
}
}, [apiRequest, fetchUserInfo]);
/**
* Refresh all data
*/
const refresh = useCallback(async (): Promise<void> => {
if (!pubkey) return;
setIsLoading(true);
setError(null);
try {
// Fetch in parallel
await Promise.all([
fetchQuotes(lastClaimedAt),
fetchUserInfo(),
]);
setIsInitialized(true);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to refresh data';
setError(errorMessage);
// If it's an auth error, don't retry automatically
if (errorMessage.includes('Authorization') || errorMessage.includes('Invalid')) {
console.warn('npub.cash auth error - not retrying automatically:', errorMessage);
}
} finally {
setIsLoading(false);
}
}, [pubkey, fetchQuotes, fetchUserInfo, lastClaimedAt]);
/**
* Clear JWT token (force NIP-98 re-auth)
*/
const clearAuth = useCallback(() => {
setJwtToken(null);
setHasTriedInitialization(false);
setIsInitialized(false);
setError(null);
}, [setJwtToken]);
/**
* Retry initialization after auth error
*/
const retryAuth = useCallback(() => {
setHasTriedInitialization(false);
setError(null);
}, []);
// Calculate unclaimed amount
const unclaimedAmount = useMemo(() => {
return quotes
.filter(q => q.state === 'PAID' && q.paidAt > lastClaimedAt)
.reduce((sum, q) => sum + q.amount, 0);
}, [quotes, lastClaimedAt]);
// Initialize on mount - only once
useEffect(() => {
if (pubkey && !isInitialized && !hasTriedInitialization) {
setHasTriedInitialization(true);
refresh();
}
}, [pubkey, isInitialized, hasTriedInitialization, refresh]);
return {
isInitialized,
isLoading,
error,
lightningAddress,
userInfo,
quotes,
unclaimedAmount,
fetchQuotes,
fetchUserInfo,
setUsername,
setMint,
setLockQuotes,
refresh,
clearAuth,
retryAuth,
};
}
export type { EventTemplate };
// Force TypeScript recompilation
+7
View File
@@ -1,6 +1,7 @@
import { useMemo } from 'react';
import { useNWC } from '@/hooks/useNWCContext';
import { useCashu } from '@/hooks/useCashu';
import { useNpubCash } from '@/hooks/useNpubCash';
import type { WebLNProvider } from '@webbtc/webln-types';
export interface WalletStatus {
@@ -12,11 +13,15 @@ export interface WalletStatus {
hasCashu: boolean;
cashuBalance: number;
isCashuInitialized: boolean;
// npub.cash integration
lightningAddress: string | null;
unclaimedSats: number;
}
export function useWallet() {
const { connections, getActiveConnection } = useNWC();
const { balances, mints, isInitialized: isCashuInitialized } = useCashu();
const { lightningAddress, unclaimedAmount } = useNpubCash();
// Get the active connection directly - no memoization to avoid stale state
const activeNWC = getActiveConnection();
@@ -55,6 +60,8 @@ export function useWallet() {
hasCashu,
cashuBalance,
isCashuInitialized,
lightningAddress,
unclaimedSats: unclaimedAmount,
};
return status;