story-research-zapwall/lib/paymentPollingZapReceipt.ts

85 lines
2.3 KiB
TypeScript

import { nostrService } from './nostr'
import { getPrimaryRelaySync } from './config'
import type { Event } from 'nostr-tools'
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(pool: import('nostr-tools').SimplePool, articlePubkey: string, articleId: string) {
const filters = [
{
kinds: [9735],
'#p': [articlePubkey],
'#e': [articleId],
limit: 1,
},
]
const relayUrl = getPrimaryRelaySync()
const { createSubscription } = require('@/types/nostr-tools-extended')
return createSubscription(pool, [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').Subscription,
amount: number,
recipientPubkey: string
): Promise<string | undefined> {
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: 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<string | undefined> {
try {
const pool = nostrService.getPool()
if (!pool) {
return undefined
}
const sub = createZapReceiptSubscription(pool, 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
}
}