15 KiB
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
- Identity: Your Nostr pubkey becomes your Lightning address (
[email protected]) - Receiving: When someone sends sats, npub.cash stores a paid Cashu quote linked to your pubkey
- 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
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
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
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:
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
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:
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
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 dataisLoading: boolean- Whether an API request is in progresserror: string | null- Error message if any operation failedlightningAddress: string | null- User's npub.cash Lightning addressuserInfo: NpubCashUserInfo | null- User settings (mint, username, locking)quotes: NpubCashQuote[]- Array of received payment quotesunclaimedAmount: 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 timelimit- Maximum number of quotes to return (default: 50)
const quotes = await fetchQuotes(Date.now() / 1000 - 86400); // Last 24 hours
fetchUserInfo(): Promise<NpubCashUserInfo>
Fetch current user settings.
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).
await setUsername('alice'); // Address becomes [email protected]
setMint(mintUrl: string): Promise<void>
Set preferred Cashu mint for receiving payments.
await setMint('https://mint.example.com');
setLockQuotes(locked: boolean): Promise<void>
Enable or disable quote locking to pubkey (NUT-20).
await setLockQuotes(true); // Enable locking
refresh(): Promise<void>
Refresh all data (quotes and user info) from npub.cash.
await refresh();
clearAuth(): void
Clear stored JWT token, forcing NIP-98 re-authentication on next request.
clearAuth(); // Next API call will require NIP-98 signature
Types
NpubCashQuote
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
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.
// 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:
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:
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:
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:
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:
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:
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:
// 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:
const { user } = useCurrentUser();
const npubCash = useNpubCash();
if (!user) {
return <p>Please log in first</p>;
}
"NIP-98 validation failed"
Check that:
- System clock is accurate (NIP-98 events must be recent)
- URL matches exactly (no query params in NIP-98 event URL)
- User's signer is working properly
JWT Token Issues
If JWT tokens aren't working, clear and re-authenticate:
const { clearAuth, refresh } = useNpubCash();
clearAuth();
await refresh(); // Will create new NIP-98 auth
Related Documentation
Additional Resources
Built with MKStack - The complete framework for building Nostr applications with AI.