# 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 (`npub1xxx...@npubx.cash`) 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

Loading...

; return (

My Lightning Address

{lightningAddress}

); } ``` ### Display Unclaimed Balance ```tsx function UnclaimedBalance() { const { unclaimedAmount, quotes, refresh } = useNpubCash(); return (

Unclaimed Payments

{unclaimedAmount} sats from {quotes.length} payments

); } ``` ### Fetch and Display Quotes ```tsx function PaymentHistory() { const { quotes, fetchQuotes, isLoading } = useNpubCash(); useEffect(() => { fetchQuotes(); }, [fetchQuotes]); return (

Received Payments

{quotes.map(quote => (

Amount: {quote.amount} sats

Mint: {quote.mint_url}

Status: {quote.state}

Paid: {new Date(quote.paid_at * 1000).toLocaleString()}

))}
); } ``` ## 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: myusername@npubx.cash alert('Username set successfully!'); } catch (error) { // Payment required - X-Cashu header returned console.error(error); } }; return (

Current: {userInfo?.name || 'Using npub'}

); } ``` ### 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 (

Current Mint: {userInfo?.mint_url}

setMintUrl(e.target.value)} placeholder="https://mint.example.com" />
); } ``` ### 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 (

Requires wallet with NUT-20 support

); } ``` ## 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 ( Receive Lightning Payments {/* Lightning Address */}
{lightningAddress || 'Loading...'}
{/* Unclaimed Balance */}
Unclaimed Balance {unclaimedAmount} sats
{/* Payment History */}
Recent Payments
{quotes.length === 0 ? (

No payments received yet

) : ( quotes.map(quote => (
{quote.amount} sats {quote.state}

{new Date(quote.paid_at * 1000).toLocaleString()}

{quote.mint_url}

)) )}
); } 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` 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` Fetch current user settings. ```tsx const info = await fetchUserInfo(); console.log('Preferred mint:', info.mint_url); ``` ##### `setUsername(username: string): Promise` Set a custom username (paid feature via Cashu 402). ```tsx await setUsername('alice'); // Address becomes alice@npubx.cash ``` ##### `setMint(mintUrl: string): Promise` Set preferred Cashu mint for receiving payments. ```tsx await setMint('https://mint.example.com'); ``` ##### `setLockQuotes(locked: boolean): Promise` Enable or disable quote locking to pubkey (NUT-20). ```tsx await setLockQuotes(true); // Enable locking ``` ##### `refresh(): Promise` 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 (
{quotes.map(quote => (

{quote.amount} sats

))}
); } ``` ## 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 (

{lightningAddress}

); } ``` ## 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 (

{error}

); } ``` ## 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

Please log in first

; } ``` ### "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.