minimal zap support

This commit is contained in:
Chad Curtis committed 2025-07-12 19:19:41 +00:00
1 parent b11e843196
commit d68f2d8486
5 files changed
+725 -1

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
import { useState } from 'react';
import { Zap } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { requestProvider } from 'webln';
import type { WebLNProvider } from 'webln';
import { ZapModal } from './ZapModal';
import { useAuthor } from '@/hooks/useAuthor';
import { useNostrLogin } from '@nostrify/react';
export interface ZapTarget {
pubkey: string;
id: string;
relays?: string[];
dTag?: string;
naddr?: string;
}
interface ZapButtonProps {
target: ZapTarget;
children?: React.ReactNode;
className?: string;
}
export function ZapButton({ target, children, className }: ZapButtonProps) {
const [webln, setWebln] = useState<WebLNProvider | null>(null);
const [isModalOpen, setIsModalOpen] = useState(false);
const { user } = useNostrLogin();
const { data: author } = useAuthor(target.pubkey);
const handleOpenModal = async () => {
if (!webln) {
try {
const provider = await requestProvider();
setWebln(provider);
} catch (err) {
// Silently fail
console.error(err);
}
}
setIsModalOpen(true);
};
if (!user || user.pubkey === target.pubkey || !author?.metadata?.lud16) {
return null;
}
return (
<>
<Button size="sm" onClick={handleOpenModal} className={className}>
<Zap className={`h-4 w-4 ${children ? 'mr-2' : ''}`} />
{children}
</Button>
{isModalOpen && <ZapModal open={isModalOpen} onOpenChange={setIsModalOpen} target={target} webln={webln} />}
</>
);
}
+157
View File
@@ -0,0 +1,157 @@
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import type { WebLNProvider } from 'webln';
import type { ZapTarget } from '@/components/ZapButton';
import QRCode from 'qrcode';
import { Zap, Copy } from 'lucide-react';
import React, { useState, useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
interface ZapModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
target: ZapTarget;
webln: WebLNProvider | null;
}
const presetAmounts = [1, 50, 100, 250, 1000];
export function ZapModal({ open, onOpenChange, target, webln }: ZapModalProps) {
const { toast } = useToast();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, () => onOpenChange(false));
const [amount, setAmount] = useState<number | string>(100);
const [comment, setComment] = useState<string>('');
const inputRef = useRef<HTMLInputElement>(null);
const qrCodeRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
if (target) {
setComment('Zapped with MKStack!');
}
}, [target]);
useEffect(() => {
if (invoice && qrCodeRef.current) {
QRCode.toCanvas(qrCodeRef.current, invoice, { width: 256 });
}
}, [invoice]);
const handleCopy = () => {
if (invoice) {
navigator.clipboard.writeText(invoice);
toast({
title: 'Copied to clipboard!',
});
}
};
useEffect(() => {
if (open) {
setAmount(100);
setInvoice(null);
}
}, [open, setInvoice]);
const handleZap = () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
};
return (
<Dialog open={open} onOpenChange={onOpenChange} data-testid="zap-modal">
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>{invoice ? 'Manual Zap' : 'Send a Zap'}</DialogTitle>
<DialogDescription asChild>
{invoice ? (
<div>Scan the QR code with a lightning-enabled wallet or copy the invoice below.</div>
) : (
<>
<div>Zaps are small Bitcoin payments that support the creator of this item.</div>
<div className="mt-2">If you enjoyed this, consider sending a zap!</div>
</>
)}
</DialogDescription>
</DialogHeader>
{invoice ? (
<div className="flex flex-col items-center gap-4 py-4">
<canvas ref={qrCodeRef} />
<div className="flex w-full items-center gap-2">
<Input value={invoice} readOnly className="flex-1" />
<Button onClick={handleCopy} variant="outline" size="icon">
<Copy className="h-4 w-4" />
</Button>
</div>
</div>
) : (
<>
<div className="grid gap-4 py-4">
<ToggleGroup
type="single"
value={String(amount)}
onValueChange={(value) => {
if (value) {
setAmount(parseInt(value, 10));
}
}}
className="grid grid-cols-5 gap-2"
>
{presetAmounts.map((presetAmount) => (
<ToggleGroupItem
key={presetAmount}
value={String(presetAmount)}
className="flex flex-col h-auto"
>
{presetAmount}
</ToggleGroupItem>
))}
</ToggleGroup>
<div className="flex items-center gap-2">
<div className="h-px flex-1 bg-muted" />
<span className="text-xs text-muted-foreground">OR</span>
<div className="h-px flex-1 bg-muted" />
</div>
<Input
ref={inputRef}
id="custom-amount"
type="number"
placeholder="Custom amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
/>
<Textarea
id="custom-comment"
placeholder="Custom comment"
value={comment}
onChange={(e) => setComment(e.target.value)}
/>
</div>
<DialogFooter>
<Button onClick={handleZap} className="w-full" disabled={isZapping}>
{isZapping ? (
'Creating invoice...'
) : (
<>
<Zap className="h-4 w-4 mr-2" />
Zap {amount} sats
</>
)}
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
);
}
+167
View File
@@ -0,0 +1,167 @@
import { useState } from 'react';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
import { nip57, nip19, Event } from 'nostr-tools';
import type { WebLNProvider } from 'webln';
import type { ZapTarget } from '@/components/ZapButton';
import { useQuery } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent, NostrFilter } from '@nostrify/nostrify';
export function useZaps(target: ZapTarget, webln: WebLNProvider | null, onZapSuccess?: () => void) {
const { nostr } = useNostr();
const { toast } = useToast();
const { user } = useCurrentUser();
const { config } = useAppContext();
const { mutate: publishEvent } = useNostrPublish();
const author = useAuthor(target?.pubkey);
const [isZapping, setIsZapping] = useState(false);
const [invoice, setInvoice] = useState<string | null>(null);
const queryKey = target.naddr ? `naddr:${target.naddr}` : `event:${target.id}`;
const { data: zaps, ...query } = useQuery<NostrEvent[], Error>({
queryKey: ['zaps', queryKey],
queryFn: async (c) => {
if (!target.id && !target.naddr) return [];
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const filters: NostrFilter[] = [];
if (target.naddr) {
try {
const decoded = nip19.decode(target.naddr);
if (decoded.type === 'naddr') {
const { kind, pubkey, identifier } = decoded.data;
filters.push({
kinds: [9735],
'#a': [`${kind}:${pubkey}:${identifier}`],
});
}
} catch (e) {
console.error("Invalid naddr", target.naddr, e);
}
} else {
filters.push({
kinds: [9735],
'#e': [target.id],
});
}
if (filters.length === 0) return [];
const events = await nostr.query(filters, { signal });
return events;
},
enabled: !!target.id || !!target.naddr,
});
const zap = async (amount: number, comment: string) => {
if (amount <= 0) {
return;
}
setIsZapping(true);
if (!user) {
toast({
title: 'Login required',
description: 'You must be logged in to send a zap.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
try {
const lud16 = author.data?.metadata?.lud16;
if (!lud16) {
toast({
title: 'Lightning address not found',
description: 'The author does not have a lightning address configured.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
if (!author.data) {
toast({
title: 'Author not found',
description: 'Could not find the author of this item.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
const zapEndpoint = await nip57.getZapEndpoint(author.data.event as Event);
if (!zapEndpoint) {
toast({
title: 'Zap endpoint not found',
description: 'Could not find a zap endpoint for the author.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
const zapAmount = amount * 1000; // convert to millisats
const relays = [config.relayUrl];
const zapRequest = nip57.makeZapRequest({
profile: target.pubkey,
event: target.id,
amount: zapAmount,
relays,
comment: comment,
});
if (target.naddr) {
const naddr = nip19.decode(target.naddr).data as nip19.AddressPointer;
zapRequest.tags.push(["a", `${naddr.kind}:${naddr.pubkey}:${naddr.identifier}`]);
zapRequest.tags = zapRequest.tags.filter(t => t[0] !== 'e');
}
publishEvent(zapRequest, {
onSuccess: async (event) => {
try {
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(event))}`);
const { pr: newInvoice } = await res.json();
if (webln) {
await webln.sendPayment(newInvoice);
toast({
title: 'Zap successful!',
description: `You sent ${amount} sats to the author.`,
});
onZapSuccess?.();
} else {
setInvoice(newInvoice);
}
} catch (err) {
console.error('Zap error:', err);
toast({
title: 'Zap failed',
description: (err as Error).message,
variant: 'destructive',
});
} finally {
setIsZapping(false);
}
},
});
} catch (err) {
toast({
title: 'Zap failed',
description: (err as Error).message,
variant: 'destructive',
});
setIsZapping(false);
}
};
return { zaps, ...query, zap, isZapping, invoice, setInvoice };
}