Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 23 additions & 22 deletions packages/core/src/handlers/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,32 @@ const webhookSchema = z.object({
async function handleIncomingPayment() {
const node = createMoneyDevKitNode();
const client = createMoneyDevKitClient();
const payments = node.receivePayments();

if (payments.length === 0) {
return;
}

payments.forEach((payment) => {
// Use callback-based receive to process payments IMMEDIATELY as they arrive
// This allows instant customer confirmation while node continues running
node.receivePaymentsWithCallback((payment) => {
// Mark payment received in local state IMMEDIATELY
markPaymentReceived(payment.paymentHash);
});

try {
await client.checkouts.paymentReceived({
payments: payments.map((payment) => ({
paymentHash: payment.paymentHash,
// amount comes in msat from the node, convert to sats
amountSats: payment.amount / 1000,
sandbox: false,
})),
});
} catch (error) {
warn(
"Failed to notify MoneyDevKit checkout about received payments. Will rely on local state and retry on next webhook.",
error,
);
}
// Notify backend asynchronously (fire and forget for speed)
// Note: payment.amount is in msat, convert to sats
client.checkouts
.paymentReceived({
payments: [
{
paymentHash: payment.paymentHash,
amountSats: payment.amount / 1000,
sandbox: false,
},
],
})
.catch((error) => {
warn(
"Failed to notify MoneyDevKit checkout about received payment. Will rely on local state and retry on next webhook.",
error,
);
});
});
}

export async function handleMdkWebhook(request: Request): Promise<Response> {
Expand Down
23 changes: 23 additions & 0 deletions packages/core/src/lightning-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,29 @@ export class MoneyDevKitNode {
)
}

/**
* Receive payments with an immediate callback for each payment received.
*
* This method behaves like `receivePayments` but fires a callback immediately
* when each payment is received, allowing for instant customer confirmation
* while the node continues to run for the full timeout period.
*/
receivePaymentsWithCallback(
onPaymentReceived: (payment: { paymentHash: string; amount: number }) => void
) {
return this.node.receivePaymentWithCallback(
RECEIVE_PAYMENTS_MIN_THRESHOLD_MS,
RECEIVE_PAYMENTS_QUIET_THRESHOLD_MS,
(err: unknown, payment: { paymentHash: string; amount: number }) => {
if (err) {
console.error('[MoneyDevKitNode] Payment callback error:', err)
return
}
onPaymentReceived(payment)
}
)
}

payBolt12Offer(bolt12: string, amountMsat: number): string {
return this.node.payBolt12Offer(bolt12, amountMsat, 30)
}
Expand Down
Loading