const LNBITS_URL = process.env.LNBITS_URL; const LNBITS_API_KEY = process.env.LNBITS_API_KEY; function getBaseUrl(): string { if (!LNBITS_URL) { throw new Error("LNBITS_URL environment variable is not set"); } return LNBITS_URL.replace(/\/$/, ""); } function getHeaders(): Record { if (!LNBITS_API_KEY) { throw new Error("LNBITS_API_KEY environment variable is not set"); } return { "Content-Type": "application/json", "X-Api-Key": LNBITS_API_KEY, }; } export interface LNbitsInvoice { paymentHash: string; paymentRequest: string; } export interface LNbitsInvoiceStatus { paid: boolean; paidAt?: Date; } export async function createInvoice( amountSats: number, memo: string, ): Promise { const baseUrl = getBaseUrl(); const response = await fetch(`${baseUrl}/api/v1/payments`, { method: "POST", headers: getHeaders(), body: JSON.stringify({ out: false, amount: amountSats, memo, }), }); if (!response.ok) { const body = await response.text(); throw new Error(`LNbits createInvoice failed (${response.status}): ${body}`); } const data = (await response.json()) as { payment_hash: string; payment_request: string; }; return { paymentHash: data.payment_hash, paymentRequest: data.payment_request, }; } export async function checkInvoicePaid( paymentHash: string, ): Promise { const baseUrl = getBaseUrl(); const response = await fetch(`${baseUrl}/api/v1/payments/${paymentHash}`, { method: "GET", headers: getHeaders(), }); if (!response.ok) { const body = await response.text(); throw new Error(`LNbits checkInvoice failed (${response.status}): ${body}`); } const data = (await response.json()) as { paid: boolean; details?: { time?: number }; }; return { paid: data.paid, paidAt: data.paid && data.details?.time ? new Date(data.details.time * 1000) : undefined, }; }