Skip to content

nwc payment result fallback#44

Closed
ntheile wants to merge 4 commits into
masterfrom
nwc-payment-result-fallback
Closed

nwc payment result fallback#44
ntheile wants to merge 4 commits into
masterfrom
nwc-payment-result-fallback

Conversation

@ntheile

@ntheile ntheile commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Added support for canceling payment requests in the TypeScript API.
    • Payment requests can now fall back to a lookup flow and continue until the payment is confirmed or canceled.
  • Bug Fixes

    • Improved payment handling so settled payments are recognized even when the initial response is delayed or missing.
    • Added better validation and error reporting for invalid payment amounts and address lookups.
  • Tests

    • Expanded integration and unit coverage for cancellation, timeouts, and payment confirmation behavior.

@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ntheile, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 41 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f4a1badf-4d05-412a-9050-e8f2376fbe38

📥 Commits

Reviewing files that changed from the base of the PR and between 3ce6510 and 4d1d517.

📒 Files selected for processing (3)
  • bindings/typescript/src/__tests__/nwc.test.ts
  • bindings/typescript/src/nodes/nwc.ts
  • crates/lni/nwc/api.rs
📝 Walkthrough

Walkthrough

This PR adds cancellation support to NwcNode.payInvoice across TypeScript bindings (new RequestCancellationOptions type, Canceled error code, abortable request execution, and a lookup-based fallback path) and reworks the Rust NWC pay_invoice implementation to race direct payment against polling-based transaction/invoice lookup, alongside related test additions.

Changes

TypeScript NWC cancellation support

Layer / File(s) Summary
Cancellation types and error code
bindings/typescript/src/types.ts, bindings/typescript/src/errors.ts
Adds RequestCancellationOptions interface, updates LightningNode.payInvoice signature, and adds 'Canceled' to LniErrorCode.
NwcNode cancellation infrastructure and fallback
bindings/typescript/src/nodes/nwc.ts
Adds active-request tracking, cancellation-aware close(), payInvoiceWithLookupFallback, lookupInvoiceWithOptions, rewritten withTimeout, and executeCancelableNip47Request using Nostr pool subscribe/publish.
Tests for cancellation
bindings/typescript/src/__tests__/nwc.test.ts, bindings/typescript/src/__tests__/integration/nwc.real.test.ts
Extends mocks and test suite for cancelable request behavior; adds a real integration test verifying AbortController cancellation.

Rust NWC pay_invoice polling and lookup fixes

Layer / File(s) Summary
pay_invoice polling implementation
crates/lni/nwc/api.rs
Adds validation, polling constants, and races direct nwc.pay_invoice against lookup-based polling via tokio::select!.
Lookup and address parsing adjustments
crates/lni/nwc/api.rs
Updates lightning-address parsing via reqwest::Url, adjusts lookup_invoice request/response handling, and reformats list_transactions/poll_invoice_events call sites.
Unit test additions
crates/lni/nwc/api.rs
Adds tests mapping pay responses/settled transactions into PayInvoiceResponse and extends mismatch assertions.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant NwcNode
  participant NwcPool
  participant LookupInvoice

  Caller->>NwcNode: payInvoice(params, options)
  NwcNode->>NwcNode: payInvoiceWithLookupFallback
  par direct request
    NwcNode->>NwcPool: publish pay_invoice command
    NwcPool-->>NwcNode: subscribe reply event
  and lookup fallback
    NwcNode->>LookupInvoice: poll lookup_invoice after delay
    LookupInvoice-->>NwcNode: settled transaction preimage
  end
  Caller->>NwcNode: abort signal
  NwcNode->>NwcPool: cancel active requests
  NwcNode-->>Caller: reject with Canceled or resolve response
Loading
sequenceDiagram
  participant Client
  participant NwcApi
  participant NwcRelay
  participant PollTask

  Client->>NwcApi: pay_invoice(params)
  NwcApi->>NwcApi: validate amount_msats
  par direct call
    NwcApi->>NwcRelay: nwc.pay_invoice(request)
  and polling
    NwcApi->>PollTask: poll_paid_invoice_result
    PollTask->>NwcRelay: lookup_invoice / list_transactions
  end
  NwcRelay-->>NwcApi: preimage or settled transaction
  NwcApi-->>Client: PayInvoiceResponse
Loading

Possibly related PRs

  • lightning-node-interface/lni#36: Both PRs modify lookupInvoice to buffer/intercept lookup errors and fall back to scanning transactions for a matching payment hash.
  • lightning-node-interface/lni#42: Both PRs modify NwcNode.payInvoice in bindings/typescript/src/nodes/nwc.ts, sharing the same timeout/close request-execution surface.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding fallback logic for NWC payment results.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch nwc-payment-result-fallback

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3ce6510e07

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread bindings/typescript/src/nodes/nwc.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@bindings/typescript/src/nodes/nwc.ts`:
- Around line 433-467: The fallback polling in pollPaidInvoiceResult can run
forever when neither httpTimeout nor an AbortSignal is provided, because the
loop only exits on external cancellation. Update the lookup fallback in NwcNode
to enforce a bounded retry window by adding a default maximum timeout or max
poll attempts even when this.timeoutMs is unset, and thread that limit through
the poll loop and delay/lookup calls. Keep the existing cancellation handling
for AbortSignal and Canceled errors, but ensure payInvoice eventually fails
deterministically instead of polling indefinitely.
- Around line 60-70: The cancelable NIP-47 flow is depending on private
`@getalby/sdk` internals via `getCancelableClient()` and
`executeCancelableNip47Request()`, which makes `pay_invoice`/`lookup_invoice`
cancellation fragile. Refactor `nwc.ts` to stop reaching into `client.pool`,
`client.relayUrls`, `client.walletPubkey`, `client.encryptionType`, and the
underscored methods; instead, use only public SDK APIs or add an explicit
supported interface/adapter for the needed behavior so the implementation does
not break on SDK updates.
- Around line 725-733: The timeout handler in the NWC request flow is closing
the shared NWCClient, which can break other in-flight NIP-47 operations. Update
the timeout cleanup in the request path around activeRequest.cancel so it only
cancels/times out the current request and does not call this.client.close();
keep the websocket client alive for concurrent calls such as lookup_invoice
fallback and other operations.

In `@crates/lni/nwc/api.rs`:
- Around line 281-285: The `pay_invoice` flow in `api.rs` is returning
immediately from `tokio::select!`, so an early error from `direct_payment`
cancels `poll_paid_invoice_result` before it can confirm a late payment. Update
the `pay_invoice` logic around the `tokio::select!` block to keep polling alive
when `direct_payment` fails, and only surface the direct payment error if
`poll_paid_invoice_result` also fails or times out. Use the existing
`direct_payment` and `poll_paid_invoice_result` branches to preserve the poll
result as the deciding outcome.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: eed33b93-18cd-4628-9b3c-7d0d9053e4d3

📥 Commits

Reviewing files that changed from the base of the PR and between 1afd87c and 3ce6510.

📒 Files selected for processing (6)
  • bindings/typescript/src/__tests__/integration/nwc.real.test.ts
  • bindings/typescript/src/__tests__/nwc.test.ts
  • bindings/typescript/src/errors.ts
  • bindings/typescript/src/nodes/nwc.ts
  • bindings/typescript/src/types.ts
  • crates/lni/nwc/api.rs

Comment thread bindings/typescript/src/nodes/nwc.ts Outdated
Comment thread bindings/typescript/src/nodes/nwc.ts
Comment thread bindings/typescript/src/nodes/nwc.ts Outdated
Comment thread crates/lni/nwc/api.rs
@ntheile ntheile closed this Jul 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant