mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
messy, nwc support +_wallet fixes
This commit is contained in:
1 parent
11ac73776c
commit
45ff37e752
10 files changed
+594
-284
No files matched your search
+153
-61
@@ -3,12 +3,12 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useNWC } from '@/hooks/useNWC';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import type { NWCConnection } from '@/hooks/useNWC';
|
||||
import { nip57, nip19 } from 'nostr-tools';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import type { WebLNProvider } from 'webln';
|
||||
import { LNURL } from '@nostrify/nostrify/ln';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent, NostrFilter } from '@nostrify/nostrify';
|
||||
@@ -24,30 +24,30 @@ function parseNWCUri(uri: string): NWCConnection | null {
|
||||
const walletPubkey = url.pathname.replace('//', '');
|
||||
const secret = url.searchParams.get('secret');
|
||||
const relayParam = url.searchParams.getAll('relay');
|
||||
const lud16 = url.searchParams.get('lud16') || undefined;
|
||||
const _lud16 = url.searchParams.get('lud16') || undefined;
|
||||
|
||||
if (!walletPubkey || !secret || relayParam.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
walletPubkey,
|
||||
secret,
|
||||
relayUrls: relayParam,
|
||||
lud16,
|
||||
connectionString: uri,
|
||||
alias: 'Parsed NWC',
|
||||
isConnected: false,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function useZaps(target: Event, webln: WebLNProvider | null, nwcConnection: NWCConnection | null, onZapSuccess?: () => void) {
|
||||
export function useZaps(target: Event, webln: WebLNProvider | null, _nwcConnection: NWCConnection | 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 { sendNWCRequest } = useNWC();
|
||||
const { sendPayment, getActiveConnection, connections, activeConnection } = useNWC();
|
||||
const [isZapping, setIsZapping] = useState(false);
|
||||
const [invoice, setInvoice] = useState<string | null>(null);
|
||||
|
||||
@@ -104,6 +104,7 @@ export function useZaps(target: Event, webln: WebLNProvider | null, nwcConnectio
|
||||
}
|
||||
|
||||
setIsZapping(true);
|
||||
setInvoice(null); // Clear any previous invoice at the start
|
||||
|
||||
if (!user) {
|
||||
toast({
|
||||
@@ -126,74 +127,166 @@ export function useZaps(target: Event, webln: WebLNProvider | null, nwcConnectio
|
||||
return;
|
||||
}
|
||||
|
||||
const { lud06, lud16 } = author.data.metadata;
|
||||
if (!lud16 && !lud06) {
|
||||
const { lud16 } = author.data.metadata;
|
||||
if (!lud16) {
|
||||
toast({
|
||||
title: 'Lightning address not found',
|
||||
description: 'The author does not have a lightning address (lud16 or lud06) configured.',
|
||||
description: 'The author does not have a lightning address configured.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const lnurl = lud06 ? LNURL.fromString(lud06) : LNURL.fromLightningAddress(lud16!);
|
||||
const zapAmount = amount * 1000; // convert to millisats
|
||||
const zapRequest = await user.signer.signEvent(nip57.makeZapRequest({
|
||||
profile: target.pubkey,
|
||||
event: target,
|
||||
amount: zapAmount,
|
||||
relays: [config.relayUrl],
|
||||
comment: comment,
|
||||
}));
|
||||
// Get zap endpoint using the old reliable method
|
||||
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 { pr: newInvoice } = await lnurl.getInvoice({
|
||||
const zapAmount = amount * 1000; // convert to millisats
|
||||
const relays = [config.relayUrl];
|
||||
|
||||
// Create zap request (unsigned, like the old implementation)
|
||||
const zapRequest = nip57.makeZapRequest({
|
||||
profile: target.pubkey,
|
||||
event: target.id,
|
||||
amount: zapAmount,
|
||||
nostr: zapRequest,
|
||||
relays,
|
||||
comment: comment,
|
||||
});
|
||||
|
||||
// Try NWC first if available
|
||||
if (nwcConnection) {
|
||||
try {
|
||||
const response = await sendNWCRequest(nwcConnection, {
|
||||
method: 'pay_invoice',
|
||||
params: {
|
||||
invoice: newInvoice,
|
||||
amount: zapAmount,
|
||||
},
|
||||
});
|
||||
// Handle addressable events (restored from old implementation)
|
||||
if (naddr) {
|
||||
const decoded = nip19.decode(naddr).data as nip19.AddressPointer;
|
||||
zapRequest.tags.push(["a", `${decoded.kind}:${decoded.pubkey}:${decoded.identifier}`]);
|
||||
zapRequest.tags = zapRequest.tags.filter(t => t[0] !== 'e');
|
||||
}
|
||||
|
||||
if (response.error) {
|
||||
throw new Error(`NWC Error: ${response.error.message}`);
|
||||
// Sign and publish the zap request
|
||||
publishEvent(zapRequest, {
|
||||
onSuccess: async (event) => {
|
||||
try {
|
||||
// Use the old fetch method - more reliable than LNURL validation
|
||||
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(event))}`);
|
||||
const responseData = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}: ${responseData.reason || 'Unknown error'}`);
|
||||
}
|
||||
|
||||
const newInvoice = responseData.pr;
|
||||
if (!newInvoice || typeof newInvoice !== 'string') {
|
||||
throw new Error('Lightning service did not return a valid invoice');
|
||||
}
|
||||
|
||||
// Get the current active NWC connection dynamically
|
||||
const currentNWCConnection = getActiveConnection();
|
||||
|
||||
console.debug('Zap payment - detailed state check:', {
|
||||
// Raw state
|
||||
connectionsLength: connections.length,
|
||||
activeConnectionString: activeConnection ? activeConnection.substring(0, 50) + '...' : null,
|
||||
|
||||
// Connection details
|
||||
connections: connections.map(c => ({
|
||||
alias: c.alias,
|
||||
isConnected: c.isConnected,
|
||||
connectionString: c.connectionString.substring(0, 50) + '...'
|
||||
})),
|
||||
|
||||
// getActiveConnection result
|
||||
currentNWCConnection: currentNWCConnection ? {
|
||||
alias: currentNWCConnection.alias,
|
||||
isConnected: currentNWCConnection.isConnected,
|
||||
connectionString: currentNWCConnection.connectionString.substring(0, 50) + '...'
|
||||
} : null
|
||||
});
|
||||
|
||||
// Try NWC first if available and properly connected
|
||||
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
|
||||
try {
|
||||
console.debug('Attempting NWC payment...', {
|
||||
amount,
|
||||
alias: currentNWCConnection.alias,
|
||||
invoiceLength: newInvoice.length
|
||||
});
|
||||
|
||||
const response = await sendPayment(currentNWCConnection, newInvoice);
|
||||
|
||||
console.debug('NWC payment successful:', { preimage: response.preimage });
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
setInvoice(null);
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats via NWC to the author.`,
|
||||
});
|
||||
|
||||
// Close dialog last to ensure clean state
|
||||
onZapSuccess?.();
|
||||
return;
|
||||
} catch (nwcError) {
|
||||
console.error('NWC payment failed, falling back:', nwcError);
|
||||
|
||||
// Show specific NWC error to user for debugging
|
||||
const errorMessage = nwcError instanceof Error ? nwcError.message : 'Unknown NWC error';
|
||||
toast({
|
||||
title: 'NWC payment failed',
|
||||
description: `${errorMessage}. Falling back to other payment methods...`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to WebLN or manual payment
|
||||
if (webln) {
|
||||
await webln.sendPayment(newInvoice);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
setInvoice(null);
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats to the author.`,
|
||||
});
|
||||
|
||||
// Close dialog last to ensure clean state
|
||||
onZapSuccess?.();
|
||||
} else {
|
||||
setInvoice(newInvoice);
|
||||
setIsZapping(false);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Zap error:', err);
|
||||
toast({
|
||||
title: 'Zap failed',
|
||||
description: (err as Error).message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsZapping(false);
|
||||
}
|
||||
|
||||
},
|
||||
onError: (err) => {
|
||||
console.error('Failed to publish zap request:', err);
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats via NWC to the author.`,
|
||||
});
|
||||
onZapSuccess?.();
|
||||
return;
|
||||
} catch (nwcError) {
|
||||
console.error('NWC payment failed, falling back:', nwcError);
|
||||
toast({
|
||||
title: 'NWC payment failed',
|
||||
description: 'Falling back to manual payment...',
|
||||
title: 'Zap failed',
|
||||
description: 'Failed to create zap request',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to WebLN or manual payment
|
||||
if (webln) {
|
||||
await webln.sendPayment(newInvoice);
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats to the author.`,
|
||||
});
|
||||
onZapSuccess?.();
|
||||
} else {
|
||||
setInvoice(newInvoice);
|
||||
}
|
||||
setIsZapping(false);
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Zap error:', err);
|
||||
toast({
|
||||
@@ -201,7 +294,6 @@ export function useZaps(target: Event, webln: WebLNProvider | null, nwcConnectio
|
||||
description: (err as Error).message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsZapping(false);
|
||||
}
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user