Files
mkstack/docs/CASHU_ZAP_INTEGRATION.md
T

8.1 KiB

Unified ZapButton for AI Agents

This document explains how AI agents can easily integrate intelligent Lightning zaps into Nostr clients using the unified MKStack ZapButton component.

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.

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
  • 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

Simple Integration

import { ZapButton } from '@/components/ZapButton';
import type { Event } from 'nostr-tools';

function PostCard({ event }: { event: Event }) {
  return (
    <div className="post-card">
      <p>{event.content}</p>
      <ZapButton target={event} showCount={true} />
    </div>
  );
}

With Custom Styling

<ZapButton 
  target={event}
  className="text-sm hover:text-yellow-500 transition-colors"
  showCount={true}
/>

Component Props

interface ZapButtonProps {
  target: Event;                    // Required: The Nostr event to zap
  className?: string;               // Optional: CSS classes for styling
  showCount?: boolean;             // Optional: Show zap count (default: true)
  zapData?: {                      // Optional: External zap data to avoid refetching
    count: number;
    totalSats: number;
    isLoading?: boolean;
  };
}

How It Works

Automatic Wallet Detection

The ZapButton automatically detects if the user has:

  1. A Cashu wallet with available balance
  2. Traditional Lightning wallet (WebLN/NWC)

Payment Flow

The unified ZapButton uses an intelligent payment selection system:

  1. Cashu Available & Sufficient: Uses Cashu tokens → Lightning invoice conversion
  2. Cashu Insufficient/Unavailable: Falls back to WebLN payment
  3. WebLN Unavailable: Falls back to NWC payment
  4. NWC Unavailable: Shows manual Lightning invoice with QR code

Cashu Integration Details

When Cashu wallet is available and has sufficient balance:

  • Creates a NIP-57 compliant zap request
  • Gets Lightning invoice from recipient's zap endpoint
  • Uses createMeltQuote() to convert Cashu tokens to Lightning payment
  • Uses payMeltQuote() to execute the payment
  • Burns Cashu tokens and sends Lightning payment

Required Dependencies

Ensure these hooks are available in your app:

// Required for Cashu integration
import { useCashu } from '@/hooks/useCashu';

// Required for traditional Lightning zaps
import { useWallet } from '@/hooks/useWallet';
import { useZaps } from '@/hooks/useZaps';

Architecture Overview

IMPORTANT: The Cashu integration uses a two-component architecture:

  1. CashuWallet - Standalone wallet management interface (separate page/route)
  2. ZapButton - Integrated zap functionality within content feeds

Component Separation

The CashuWallet component is designed as a standalone wallet management interface and should remain separate from content feeds. This separation provides:

  • Clean UX: Users manage their wallet separately from consuming content
  • Performance: Wallet operations don't interfere with feed rendering
  • Security: Sensitive wallet operations are isolated
  • Mobile Optimization: Wallet can use full-screen layouts on mobile

Integration Pattern

// ✅ CORRECT: Separate wallet management
function App() {
  return (
    <Router>
      <Routes>
        <Route path="/wallet" element={<CashuWallet />} />
        <Route path="/" element={<FeedPage />} />
      </Routes>
    </Router>
  );
}

// ✅ CORRECT: ZapButton integrated in content
function FeedPage() {
  return (
    <div className="posts">
      {events.map(event => (
        <div key={event.id} className="post">
          <p>{event.content}</p>
          <ZapButton target={event} showCount={true} />
        </div>
      ))}
    </div>
  );
}

// ❌ INCORRECT: Don't embed CashuWallet in content feeds
function FeedPage() {
  return (
    <div className="posts">
      <CashuWallet /> {/* Don't do this */}
      {events.map(event => (
        <div key={event.id} className="post">
          <p>{event.content}</p>
          <ZapButton target={event} showCount={true} />
        </div>
      ))}
    </div>
  );
}

Complete Example

import { ZapButton } from '@/components/ZapButton';
import { CashuWallet } from '@/components/CashuWallet';
import type { Event } from 'nostr-tools';

function NostrApp() {
  return (
    <div className="app">
      {/* Cashu wallet for balance management */}
      <CashuWallet />
      
      {/* Posts with zap buttons */}
      <div className="posts">
        {events.map(event => (
          <div key={event.id} className="post">
            <p>{event.content}</p>
            <ZapButton target={event} showCount={true} />
          </div>
        ))}
      </div>
    </div>
  );
}

Advanced Usage

Custom Zap Data

If you're already fetching zap data elsewhere, pass it to avoid duplicate requests:

const zapData = useZaps(event);

<ZapButton 
  target={event}
  zapData={zapData}
  showCount={true}
/>

Conditional Rendering

The component automatically handles visibility based on:

  • User login status
  • Author Lightning address availability
  • Cashu wallet availability
// Only shows if user can zap
<ZapButton target={event} />

Error Handling

The component handles common error scenarios:

  • Insufficient Cashu balance
  • Lightning address not found
  • Zap endpoint unavailable
  • Payment failures

All errors are displayed via toast notifications.

Mobile Optimization

The component automatically uses:

  • Desktop: Modal dialog
  • Mobile: Bottom drawer

No additional configuration needed.

Testing

The component includes test IDs for easy testing:

// Unified zap modal
data-testid="zap-modal"

Best Practices for AI Agents

  1. Maintain Component Separation: Keep CashuWallet as a standalone page/route, not embedded in content feeds
  2. Always include CashuWallet: Provide a dedicated route/page for wallet management
  3. Use consistent styling: Apply your app's design system
  4. Handle loading states: The component manages its own loading states
  5. Trust the intelligence: The component handles payment method selection automatically
  6. Test all scenarios: Ensure Cashu, WebLN, NWC, and manual zaps all work
  7. Follow the architecture: Use ZapButton for content integration, CashuWallet for wallet management

Troubleshooting

ZapButton Not Showing

  • Check if user is logged in
  • Verify author has Lightning address (lud06/lud16)
  • Ensure Cashu wallet is initialized

Cashu Zaps Not Working

  • Verify Cashu wallet has sufficient balance
  • Check mint connectivity
  • Ensure Lightning invoice is valid

Payment Method Fallbacks Not Working

  • Verify WebLN/NWC connection
  • Check Lightning wallet availability
  • Ensure zap endpoint is accessible
  • Test manual QR code fallback

Integration Checklist

  • Import unified ZapButton component
  • Create dedicated route/page for CashuWallet (don't embed in content feeds)
  • Ensure useCashu hook is available
  • Test all payment methods: Cashu → WebLN → NWC → Manual QR
  • Verify mobile responsiveness
  • Test error handling scenarios
  • Verify component separation (wallet management vs content integration)

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.