mirror of
https://github.com/hoornet/vega.git
synced 2026-05-14 23:28:36 -07:00
Add zaps: NWC wallet connect + NIP-57 zap flow
- NWC client (nwc.ts): parse URI, encrypt/send kind 23194, await kind 23195 response - Lightning store: persist NWC URI to localStorage, zap() via NDKZapper + lnPay callback - ZapModal: amount presets (21/100/500/1000/5000 sats), custom amount, optional comment, paying/success/error states, prompts to Settings if no wallet connected - ⚡ zap button on NoteCard (action row) and ProfileView (header, next to follow) - Settings > Lightning Wallet section: paste NWC URI, connect/disconnect Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ import { useUIStore } from "../../stores/ui";
|
|||||||
import { timeAgo, shortenPubkey } from "../../lib/utils";
|
import { timeAgo, shortenPubkey } from "../../lib/utils";
|
||||||
import { publishReaction, publishReply } from "../../lib/nostr";
|
import { publishReaction, publishReply } from "../../lib/nostr";
|
||||||
import { NoteContent } from "./NoteContent";
|
import { NoteContent } from "./NoteContent";
|
||||||
|
import { ZapModal } from "../zap/ZapModal";
|
||||||
|
|
||||||
interface NoteCardProps {
|
interface NoteCardProps {
|
||||||
event: NDKEvent;
|
event: NDKEvent;
|
||||||
@@ -35,6 +36,7 @@ export function NoteCard({ event }: NoteCardProps) {
|
|||||||
const [replyError, setReplyError] = useState<string | null>(null);
|
const [replyError, setReplyError] = useState<string | null>(null);
|
||||||
const [replySent, setReplySent] = useState(false);
|
const [replySent, setReplySent] = useState(false);
|
||||||
const replyRef = useRef<HTMLTextAreaElement>(null);
|
const replyRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
const [showZap, setShowZap] = useState(false);
|
||||||
|
|
||||||
const handleLike = async () => {
|
const handleLike = async () => {
|
||||||
if (!loggedIn || liked || liking) return;
|
if (!loggedIn || liked || liking) return;
|
||||||
@@ -139,9 +141,23 @@ export function NoteCard({ event }: NoteCardProps) {
|
|||||||
>
|
>
|
||||||
{liked ? "♥" : "♡"}{reactionCount !== null && reactionCount > 0 ? ` ${reactionCount}` : liked ? " liked" : " like"}
|
{liked ? "♥" : "♡"}{reactionCount !== null && reactionCount > 0 ? ` ${reactionCount}` : liked ? " liked" : " like"}
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowZap(true)}
|
||||||
|
className="text-[11px] text-text-dim hover:text-zap transition-colors"
|
||||||
|
>
|
||||||
|
⚡ zap
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{showZap && (
|
||||||
|
<ZapModal
|
||||||
|
target={{ type: "note", event, recipientPubkey: event.pubkey }}
|
||||||
|
recipientName={name}
|
||||||
|
onClose={() => setShowZap(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Inline reply box */}
|
{/* Inline reply box */}
|
||||||
{showReply && (
|
{showReply && (
|
||||||
<div className="mt-2 border-l-2 border-border pl-3">
|
<div className="mt-2 border-l-2 border-border pl-3">
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { useProfile, invalidateProfileCache } from "../../hooks/useProfile";
|
|||||||
import { fetchUserNotes, publishProfile } from "../../lib/nostr";
|
import { fetchUserNotes, publishProfile } from "../../lib/nostr";
|
||||||
import { shortenPubkey } from "../../lib/utils";
|
import { shortenPubkey } from "../../lib/utils";
|
||||||
import { NoteCard } from "../feed/NoteCard";
|
import { NoteCard } from "../feed/NoteCard";
|
||||||
|
import { ZapModal } from "../zap/ZapModal";
|
||||||
|
|
||||||
function EditProfileForm({ pubkey, onSaved }: { pubkey: string; onSaved: () => void }) {
|
function EditProfileForm({ pubkey, onSaved }: { pubkey: string; onSaved: () => void }) {
|
||||||
const { profile, fetchOwnProfile } = useUserStore();
|
const { profile, fetchOwnProfile } = useUserStore();
|
||||||
@@ -108,6 +109,7 @@ export function ProfileView() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [editing, setEditing] = useState(false);
|
const [editing, setEditing] = useState(false);
|
||||||
const [followPending, setFollowPending] = useState(false);
|
const [followPending, setFollowPending] = useState(false);
|
||||||
|
const [showZap, setShowZap] = useState(false);
|
||||||
|
|
||||||
const isFollowing = follows.includes(pubkey);
|
const isFollowing = follows.includes(pubkey);
|
||||||
|
|
||||||
@@ -161,6 +163,13 @@ export function ProfileView() {
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
{!isOwn && loggedIn && (
|
{!isOwn && loggedIn && (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => setShowZap(true)}
|
||||||
|
className="text-[11px] px-3 py-1 border border-border text-zap hover:border-zap/40 hover:bg-zap/5 transition-colors"
|
||||||
|
>
|
||||||
|
⚡ zap
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={handleFollowToggle}
|
onClick={handleFollowToggle}
|
||||||
disabled={followPending}
|
disabled={followPending}
|
||||||
@@ -172,6 +181,7 @@ export function ProfileView() {
|
|||||||
>
|
>
|
||||||
{followPending ? "…" : isFollowing ? "unfollow" : "follow"}
|
{followPending ? "…" : isFollowing ? "unfollow" : "follow"}
|
||||||
</button>
|
</button>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -219,6 +229,14 @@ export function ProfileView() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{showZap && (
|
||||||
|
<ZapModal
|
||||||
|
target={{ type: "profile", pubkey }}
|
||||||
|
recipientName={name}
|
||||||
|
onClose={() => setShowZap(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Notes */}
|
{/* Notes */}
|
||||||
{loading && <div className="px-4 py-8 text-text-dim text-[12px] text-center">Loading notes…</div>}
|
{loading && <div className="px-4 py-8 text-text-dim text-[12px] text-center">Loading notes…</div>}
|
||||||
{!loading && notes.length === 0 && <div className="px-4 py-8 text-text-dim text-[12px] text-center">No notes found.</div>}
|
{!loading && notes.length === 0 && <div className="px-4 py-8 text-text-dim text-[12px] text-center">No notes found.</div>}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useUserStore } from "../../stores/user";
|
import { useUserStore } from "../../stores/user";
|
||||||
|
import { useLightningStore } from "../../stores/lightning";
|
||||||
|
import { isValidNwcUri } from "../../lib/lightning/nwc";
|
||||||
import { getNDK, getStoredRelayUrls, addRelay, removeRelay } from "../../lib/nostr";
|
import { getNDK, getStoredRelayUrls, addRelay, removeRelay } from "../../lib/nostr";
|
||||||
|
|
||||||
function RelayRow({ url, onRemove }: { url: string; onRemove: () => void }) {
|
function RelayRow({ url, onRemove }: { url: string; onRemove: () => void }) {
|
||||||
@@ -121,6 +123,75 @@ function IdentitySection() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function WalletSection() {
|
||||||
|
const { nwcUri, setNwcUri, clearNwcUri } = useLightningStore();
|
||||||
|
const [input, setInput] = useState("");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const handleSave = () => {
|
||||||
|
const uri = input.trim();
|
||||||
|
if (!uri) return;
|
||||||
|
if (!isValidNwcUri(uri)) {
|
||||||
|
setError("Invalid NWC URI. Must start with nostr+walletconnect://");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
setSaving(true);
|
||||||
|
setNwcUri(uri);
|
||||||
|
setInput("");
|
||||||
|
setError(null);
|
||||||
|
} catch (err) {
|
||||||
|
setError(String(err));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section>
|
||||||
|
<h2 className="text-text text-[11px] font-medium uppercase tracking-widest mb-2 text-text-dim">Lightning Wallet (NWC)</h2>
|
||||||
|
{nwcUri ? (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2 px-3 py-2 border border-border mb-2">
|
||||||
|
<span className="text-zap text-[11px]">⚡</span>
|
||||||
|
<span className="text-text text-[12px] flex-1">Wallet connected</span>
|
||||||
|
<button
|
||||||
|
onClick={clearNwcUri}
|
||||||
|
className="text-[10px] text-text-dim hover:text-danger transition-colors shrink-0"
|
||||||
|
>
|
||||||
|
disconnect
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-text-dim text-[10px] px-1">Your NWC connection is active. You can zap notes and profiles.</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<textarea
|
||||||
|
value={input}
|
||||||
|
onChange={(e) => { setInput(e.target.value); setError(null); }}
|
||||||
|
placeholder="nostr+walletconnect://…"
|
||||||
|
rows={3}
|
||||||
|
className="w-full bg-bg border border-border px-3 py-2 text-text text-[11px] font-mono resize-none focus:outline-none focus:border-accent/50 placeholder:text-text-dim mb-2"
|
||||||
|
style={{ WebkitUserSelect: "text", userSelect: "text" } as React.CSSProperties}
|
||||||
|
/>
|
||||||
|
{error && <p className="text-danger text-[11px] mb-2">{error}</p>}
|
||||||
|
<button
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={!input.trim() || saving}
|
||||||
|
className="px-4 py-1.5 text-[11px] border border-border text-text-muted hover:text-accent hover:border-accent/40 transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
connect wallet
|
||||||
|
</button>
|
||||||
|
<p className="text-text-dim text-[10px] mt-2 px-1">
|
||||||
|
Get an NWC connection string from Alby, Mutiny, or any NWC-compatible wallet.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function SettingsView() {
|
export function SettingsView() {
|
||||||
return (
|
return (
|
||||||
<div className="h-full flex flex-col">
|
<div className="h-full flex flex-col">
|
||||||
@@ -129,6 +200,7 @@ export function SettingsView() {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div className="flex-1 overflow-y-auto p-4 space-y-8">
|
<div className="flex-1 overflow-y-auto p-4 space-y-8">
|
||||||
|
<WalletSection />
|
||||||
<RelaySection />
|
<RelaySection />
|
||||||
<IdentitySection />
|
<IdentitySection />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
162
src/components/zap/ZapModal.tsx
Normal file
162
src/components/zap/ZapModal.tsx
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useLightningStore, ZapTargetSpec } from "../../stores/lightning";
|
||||||
|
import { useUIStore } from "../../stores/ui";
|
||||||
|
|
||||||
|
const AMOUNT_PRESETS = [21, 100, 500, 1000, 5000];
|
||||||
|
|
||||||
|
type ZapState = "idle" | "paying" | "success" | "error";
|
||||||
|
|
||||||
|
interface ZapModalProps {
|
||||||
|
target: ZapTargetSpec;
|
||||||
|
recipientName: string;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ZapModal({ target, recipientName, onClose }: ZapModalProps) {
|
||||||
|
const { nwcUri, zap } = useLightningStore();
|
||||||
|
const { setView } = useUIStore();
|
||||||
|
const [amountSats, setAmountSats] = useState(21);
|
||||||
|
const [customAmount, setCustomAmount] = useState("");
|
||||||
|
const [useCustom, setUseCustom] = useState(false);
|
||||||
|
const [comment, setComment] = useState("");
|
||||||
|
const [state, setState] = useState<ZapState>("idle");
|
||||||
|
const [errorMsg, setErrorMsg] = useState("");
|
||||||
|
|
||||||
|
const effectiveAmount = useCustom ? (parseInt(customAmount) || 0) : amountSats;
|
||||||
|
|
||||||
|
const handleZap = async () => {
|
||||||
|
if (effectiveAmount <= 0) return;
|
||||||
|
setState("paying");
|
||||||
|
setErrorMsg("");
|
||||||
|
try {
|
||||||
|
await zap(target, effectiveAmount, comment.trim() || undefined);
|
||||||
|
setState("success");
|
||||||
|
setTimeout(onClose, 1500);
|
||||||
|
} catch (err) {
|
||||||
|
setState("error");
|
||||||
|
setErrorMsg(err instanceof Error ? err.message : String(err));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleBackdrop = (e: React.MouseEvent) => {
|
||||||
|
if (e.target === e.currentTarget) onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-black/60 flex items-center justify-center z-50"
|
||||||
|
onClick={handleBackdrop}
|
||||||
|
>
|
||||||
|
<div className="bg-bg border border-border w-80 shadow-2xl">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="border-b border-border px-4 py-3 flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<div className="text-text text-[13px] font-medium">⚡ Zap {recipientName}</div>
|
||||||
|
{!nwcUri && <div className="text-danger text-[10px] mt-0.5">No wallet connected</div>}
|
||||||
|
</div>
|
||||||
|
<button onClick={onClose} className="text-text-dim hover:text-text text-[11px] transition-colors">✕</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* No wallet state */}
|
||||||
|
{!nwcUri && (
|
||||||
|
<div className="px-4 py-5 text-center">
|
||||||
|
<p className="text-text-dim text-[12px] mb-3">
|
||||||
|
Connect a Lightning wallet using a Nostr Wallet Connect (NWC) URI to send zaps.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
onClick={() => { onClose(); setView("settings"); }}
|
||||||
|
className="px-4 py-1.5 text-[11px] border border-accent/60 text-accent hover:bg-accent hover:text-white transition-colors"
|
||||||
|
>
|
||||||
|
go to settings →
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Zap form */}
|
||||||
|
{nwcUri && state === "idle" && (
|
||||||
|
<div className="px-4 py-4 space-y-4">
|
||||||
|
{/* Amount presets */}
|
||||||
|
<div>
|
||||||
|
<div className="text-text-dim text-[10px] uppercase tracking-widest mb-2">Amount (sats)</div>
|
||||||
|
<div className="grid grid-cols-5 gap-1.5 mb-2">
|
||||||
|
{AMOUNT_PRESETS.map((amt) => (
|
||||||
|
<button
|
||||||
|
key={amt}
|
||||||
|
onClick={() => { setAmountSats(amt); setUseCustom(false); }}
|
||||||
|
className={`py-1.5 text-[11px] border transition-colors ${
|
||||||
|
!useCustom && amountSats === amt
|
||||||
|
? "border-accent bg-accent/10 text-accent"
|
||||||
|
: "border-border text-text-muted hover:border-accent/40 hover:text-text"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{amt}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
value={customAmount}
|
||||||
|
onChange={(e) => { setCustomAmount(e.target.value.replace(/\D/g, "")); setUseCustom(true); }}
|
||||||
|
onFocus={() => setUseCustom(true)}
|
||||||
|
placeholder="custom amount…"
|
||||||
|
className={`w-full bg-bg border px-3 py-1.5 text-text text-[12px] focus:outline-none transition-colors ${
|
||||||
|
useCustom ? "border-accent/60" : "border-border"
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Comment */}
|
||||||
|
<div>
|
||||||
|
<div className="text-text-dim text-[10px] uppercase tracking-widest mb-2">Comment (optional)</div>
|
||||||
|
<input
|
||||||
|
value={comment}
|
||||||
|
onChange={(e) => setComment(e.target.value)}
|
||||||
|
placeholder="Great post!"
|
||||||
|
maxLength={140}
|
||||||
|
className="w-full bg-bg border border-border px-3 py-1.5 text-text text-[12px] focus:outline-none focus:border-accent/50"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Zap button */}
|
||||||
|
<button
|
||||||
|
onClick={handleZap}
|
||||||
|
disabled={effectiveAmount <= 0}
|
||||||
|
className="w-full py-2 text-[12px] font-medium bg-zap hover:bg-zap/90 text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
⚡ Zap {effectiveAmount > 0 ? `${effectiveAmount} sats` : ""}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Paying state */}
|
||||||
|
{nwcUri && state === "paying" && (
|
||||||
|
<div className="px-4 py-8 text-center">
|
||||||
|
<div className="text-zap text-2xl mb-2">⚡</div>
|
||||||
|
<p className="text-text-dim text-[12px]">Sending {effectiveAmount} sats…</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Success state */}
|
||||||
|
{state === "success" && (
|
||||||
|
<div className="px-4 py-8 text-center">
|
||||||
|
<div className="text-zap text-2xl mb-2">⚡</div>
|
||||||
|
<p className="text-text text-[13px] font-medium">Zapped!</p>
|
||||||
|
<p className="text-text-dim text-[11px] mt-1">{effectiveAmount} sats sent to {recipientName}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Error state */}
|
||||||
|
{state === "error" && (
|
||||||
|
<div className="px-4 py-5 space-y-3">
|
||||||
|
<p className="text-danger text-[12px]">{errorMsg}</p>
|
||||||
|
<button
|
||||||
|
onClick={() => setState("idle")}
|
||||||
|
className="w-full py-1.5 text-[11px] border border-border text-text-muted hover:text-text transition-colors"
|
||||||
|
>
|
||||||
|
try again
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
97
src/lib/lightning/nwc.ts
Normal file
97
src/lib/lightning/nwc.ts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
import NDK, { NDKEvent, NDKFilter, NDKKind, NDKPrivateKeySigner } from "@nostr-dev-kit/ndk";
|
||||||
|
|
||||||
|
interface NwcConnection {
|
||||||
|
walletPubkey: string;
|
||||||
|
relayUrl: string;
|
||||||
|
secret: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseNwcUri(uri: string): NwcConnection {
|
||||||
|
const cleaned = uri.replace("nostr+walletconnect://", "https://");
|
||||||
|
const url = new URL(cleaned);
|
||||||
|
const walletPubkey = url.hostname;
|
||||||
|
const relayUrl = url.searchParams.get("relay");
|
||||||
|
const secret = url.searchParams.get("secret");
|
||||||
|
|
||||||
|
if (!walletPubkey || !relayUrl || !secret) {
|
||||||
|
throw new Error("Invalid NWC URI: missing pubkey, relay, or secret");
|
||||||
|
}
|
||||||
|
|
||||||
|
return { walletPubkey, relayUrl, secret };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isValidNwcUri(uri: string): boolean {
|
||||||
|
try {
|
||||||
|
parseNwcUri(uri);
|
||||||
|
return uri.startsWith("nostr+walletconnect://");
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function payInvoiceViaNWC(nwcUri: string, bolt11: string): Promise<string> {
|
||||||
|
const { walletPubkey, relayUrl, secret } = parseNwcUri(nwcUri);
|
||||||
|
|
||||||
|
const ndk = new NDK({ explicitRelayUrls: [relayUrl] });
|
||||||
|
const signer = new NDKPrivateKeySigner(secret);
|
||||||
|
ndk.signer = signer;
|
||||||
|
await ndk.connect();
|
||||||
|
|
||||||
|
// Wait briefly for relay connection
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
const check = () => {
|
||||||
|
const relays = Array.from(ndk.pool?.relays?.values() ?? []);
|
||||||
|
if (relays.some((r) => r.connected)) resolve();
|
||||||
|
else setTimeout(check, 200);
|
||||||
|
};
|
||||||
|
setTimeout(() => resolve(), 8000); // timeout fallback
|
||||||
|
check();
|
||||||
|
});
|
||||||
|
|
||||||
|
const walletUser = ndk.getUser({ pubkey: walletPubkey });
|
||||||
|
const requestContent = JSON.stringify({
|
||||||
|
method: "pay_invoice",
|
||||||
|
params: { invoice: bolt11 },
|
||||||
|
});
|
||||||
|
|
||||||
|
const encrypted = await signer.encrypt(walletUser, requestContent, "nip04");
|
||||||
|
|
||||||
|
const requestEvent = new NDKEvent(ndk);
|
||||||
|
requestEvent.kind = NDKKind.NostrWalletConnectReq;
|
||||||
|
requestEvent.content = encrypted;
|
||||||
|
requestEvent.tags = [["p", walletPubkey]];
|
||||||
|
await requestEvent.sign();
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
sub.stop();
|
||||||
|
reject(new Error("NWC payment timed out (30s)"));
|
||||||
|
}, 30000);
|
||||||
|
|
||||||
|
const filter: NDKFilter = {
|
||||||
|
kinds: [NDKKind.NostrWalletConnectRes],
|
||||||
|
authors: [walletPubkey],
|
||||||
|
"#e": [requestEvent.id!],
|
||||||
|
};
|
||||||
|
|
||||||
|
const sub = ndk.subscribe(filter, { closeOnEose: false });
|
||||||
|
|
||||||
|
sub.on("event", async (event: NDKEvent) => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
sub.stop();
|
||||||
|
try {
|
||||||
|
const decrypted = await signer.decrypt(walletUser, event.content, "nip04");
|
||||||
|
const response = JSON.parse(decrypted);
|
||||||
|
if (response.error) {
|
||||||
|
reject(new Error(response.error.message || "NWC payment failed"));
|
||||||
|
} else {
|
||||||
|
resolve(response.result?.preimage ?? "");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
requestEvent.publish();
|
||||||
|
});
|
||||||
|
}
|
||||||
82
src/stores/lightning.ts
Normal file
82
src/stores/lightning.ts
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import { create } from "zustand";
|
||||||
|
import { NDKEvent, NDKUser, NDKZapper, LnPayCb } from "@nostr-dev-kit/ndk";
|
||||||
|
import { getNDK } from "../lib/nostr";
|
||||||
|
import { payInvoiceViaNWC, isValidNwcUri } from "../lib/lightning/nwc";
|
||||||
|
|
||||||
|
const NWC_STORAGE_KEY = "wrystr_nwc_uri";
|
||||||
|
|
||||||
|
interface ZapTarget {
|
||||||
|
type: "note";
|
||||||
|
event: NDKEvent;
|
||||||
|
recipientPubkey: string;
|
||||||
|
recipientLud16?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ZapProfileTarget {
|
||||||
|
type: "profile";
|
||||||
|
pubkey: string;
|
||||||
|
lud16?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ZapTargetSpec = ZapTarget | ZapProfileTarget;
|
||||||
|
|
||||||
|
interface LightningState {
|
||||||
|
nwcUri: string | null;
|
||||||
|
setNwcUri: (uri: string) => void;
|
||||||
|
clearNwcUri: () => void;
|
||||||
|
zap: (target: ZapTargetSpec, amountSats: number, comment?: string) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useLightningStore = create<LightningState>(() => ({
|
||||||
|
nwcUri: localStorage.getItem(NWC_STORAGE_KEY),
|
||||||
|
|
||||||
|
setNwcUri: (uri: string) => {
|
||||||
|
if (!isValidNwcUri(uri)) throw new Error("Invalid NWC URI");
|
||||||
|
localStorage.setItem(NWC_STORAGE_KEY, uri);
|
||||||
|
useLightningStore.setState({ nwcUri: uri });
|
||||||
|
},
|
||||||
|
|
||||||
|
clearNwcUri: () => {
|
||||||
|
localStorage.removeItem(NWC_STORAGE_KEY);
|
||||||
|
useLightningStore.setState({ nwcUri: null });
|
||||||
|
},
|
||||||
|
|
||||||
|
zap: async (targetSpec: ZapTargetSpec, amountSats: number, comment?: string) => {
|
||||||
|
const { nwcUri } = useLightningStore.getState();
|
||||||
|
if (!nwcUri) throw new Error("No wallet connected. Add an NWC connection in Settings.");
|
||||||
|
|
||||||
|
const ndk = getNDK();
|
||||||
|
if (!ndk.signer) throw new Error("Not logged in");
|
||||||
|
|
||||||
|
let target: NDKEvent | NDKUser;
|
||||||
|
if (targetSpec.type === "note") {
|
||||||
|
target = targetSpec.event;
|
||||||
|
} else {
|
||||||
|
target = ndk.getUser({ pubkey: targetSpec.pubkey });
|
||||||
|
}
|
||||||
|
|
||||||
|
const lnPay: LnPayCb = async ({ pr }) => {
|
||||||
|
const preimage = await payInvoiceViaNWC(nwcUri, pr);
|
||||||
|
return { preimage };
|
||||||
|
};
|
||||||
|
|
||||||
|
const zapper = new NDKZapper(target, amountSats * 1000, "msat", {
|
||||||
|
comment,
|
||||||
|
lnPay,
|
||||||
|
ndk,
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
zapper.on("complete", (results) => {
|
||||||
|
const errors = Array.from(results.values()).filter((r) => r instanceof Error);
|
||||||
|
if (errors.length > 0) {
|
||||||
|
reject(errors[0]);
|
||||||
|
} else {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
zapper.zap().catch(reject);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}));
|
||||||
Reference in New Issue
Block a user