import { nostrService } from './nostr' import { getPrimaryRelaySync } from './config' export function parseZapAmount(event: import('nostr-tools').Event): number { const amountTag = event.tags.find((tag) => tag[0] === 'amount')?.[1] return amountTag ? Math.floor(parseInt(amountTag, 10) / 1000) : 0 } export function createZapReceiptSubscription(poolWithSub: import('@/types/nostr-tools-extended').SimplePoolWithSub, articlePubkey: string, articleId: string) { const filters = [ { kinds: [9735], '#p': [articlePubkey], '#e': [articleId], limit: 1, }, ] const relayUrl = getPrimaryRelaySync() return poolWithSub.sub([relayUrl], filters) } export function handleZapReceiptEvent( event: import('nostr-tools').Event, amount: number, recipientPubkey: string, finalize: (value: string | undefined) => void ): void { const amountInSats = parseZapAmount(event) if (amountInSats === amount && event.pubkey === recipientPubkey) { finalize(event.id) } } export function createZapReceiptPromise( sub: import('@/types/nostr-tools-extended').SimplePoolWithSub['sub'] extends (...args: any[]) => infer R ? R : never, amount: number, recipientPubkey: string ): Promise { return new Promise((resolve) => { let resolved = false const finalize = (value: string | undefined) => { if (resolved) { return } resolved = true sub.unsub() resolve(value) } sub.on('event', (event) => { handleZapReceiptEvent(event, amount, recipientPubkey, finalize) }) sub.on('eose', () => finalize(undefined)) setTimeout(() => finalize(undefined), 3000) }) } export async function getZapReceiptId( articlePubkey: string, articleId: string, amount: number, recipientPubkey: string ): Promise { try { const pool = nostrService.getPool() if (!pool) { return undefined } const poolWithSub = pool as import('@/types/nostr-tools-extended').SimplePoolWithSub const sub = createZapReceiptSubscription(poolWithSub, articlePubkey, articleId) return createZapReceiptPromise(sub, amount, recipientPubkey) } catch (error) { console.error('Error getting zap receipt ID', { articleId, recipientPubkey, error: error instanceof Error ? error.message : 'Unknown error', }) return undefined } }