Skip to content

fix(orders): handle inbound add-invoice in the kind-14 ingest - #288

Merged
Catrya merged 3 commits into
mainfrom
fix/maker-buyer-add-invoice
Aug 7, 2026
Merged

fix(orders): handle inbound add-invoice in the kind-14 ingest#288
Catrya merged 3 commits into
mainfrom
fix/maker-buyer-add-invoice

Conversation

@Catrya

@Catrya Catrya commented Aug 7, 2026

Copy link
Copy Markdown
Member

Closes #287

Problem

The kind-14 ingest (dispatch_mostro_message) had no arm for an inbound
add-invoice, so it fell into the catch-all and was dropped. That message is
how the daemon asks a maker buyer for their invoice after the seller taker
paid the hold invoice. The trade never reached WaitingBuyerInvoice, the user
was never prompted to act, and the daemon canceled the order by timeout
(reproduced against a real daemon — see the timeline in #287).

Fix

  • New Action::AddInvoice arm, next to the existing PayInvoice one. It is
    keyed by the message's order id (the message arrives on the global feed with
    trade_index=None), and persists the status and the calculated sats to both
    the order book and the trade DB.
  • The order book gets the amount too because the add-invoice screen polls it
    (tradeAmountProvider) and refuses an LN address — and NWC auto-generation —
    without a known amount.
  • The daemon's follow-up add-invoice carrying a Payload::Peer (counterparty
    reputation) is ignored for now.
  • status_for_action now maps AddInvoice → WaitingBuyerInvoice, covering
    payload-less messages.
  • A taker is unaffected: their nonce-correlated copy is still consumed by the
    take interception before the per-action arms run.

No Dart changes: with the status persisted, the existing MyOrderScreen
branch (waitingBuyerInvoice && !isSelling) already navigates the maker buyer
to the add-invoice screen. Global auto-navigation from anywhere in the app is
tracked separately in #283.

Changes

  • rust/src/api/orders.rs: new ingest arm, add_invoice_sync helper,
    status_for_action mapping, unit tests.
  • specs/004-mostro-p2p-client/contracts/orders.md: AddInvoice row in the
    inbound actions table; stale section heading fixed (dispatch_mostro_message
    over Kind 14, not the long-gone process_gift_wrap_rumor).

Testing

  • cargo test (249 passed) and cargo clippy (no new warnings).
  • ./scripts/frb-generate.sh --check — no bridge surface changes.
  • Manual reproduction of the maker-buyer flow pending review feedback.

Summary by CodeRabbit

  • New Features

    • Added support for processing inbound invoice messages and updating order amounts and statuses.
    • Improved handling of invoice responses, including replies without payloads and zero-amount orders.
    • Non-order follow-up messages are now safely ignored.
  • Documentation

    • Documented invoice message handling, trade updates, amount synchronization, and late-message processing.

Catrya added 2 commits August 6, 2026 18:01
- New AddInvoice arm: the daemon's invoice request to a maker buyer was
  falling into the catch-all, the trade never left WaitingPayment and
  died by timeout.
- Persists status and calculated sats to the order book and trade DB,
  keyed by the message's order id (it arrives with trade_index=None).
- The book gets the amount too: the add-invoice screen polls it and
  refuses an LN address without a known amount.
- The follow-up AddInvoice with a Peer payload (reputation) is ignored.
- status_for_action maps AddInvoice → WaitingBuyerInvoice for
  payload-less messages; add_invoice_sync helper with unit tests.
- New AddInvoice row in the inbound actions table: Order payload syncs
  status and sats to book and DB, keyed by order id; the Peer follow-up
  (reputation) is ignored.
- Column header generalized to local trade row, the table already
  covered actions affecting both roles.
- Stale section heading fixed: the consumer is dispatch_mostro_message
  over Kind 14 not the long-gone process_gift_wrap_rumor.
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

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

Next review available in: 28 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7e848a25-01ef-4eff-a82e-064c755c0443

📥 Commits

Reviewing files that changed from the base of the PR and between c21c141 and e5cda9c.

📒 Files selected for processing (2)
  • rust/src/api/orders.rs
  • specs/004-mostro-p2p-client/contracts/orders.md

Walkthrough

The inbound AddInvoice action now updates maker-buyer order and trade records with status and amount data. Payload-less replies infer WaitingBuyerInvoice, while unsupported payloads are ignored. Tests and the order contract cover the new behavior.

Changes

Inbound AddInvoice handling

Layer / File(s) Summary
Dispatch and state synchronization
rust/src/api/orders.rs
The dispatcher handles AddInvoice, extracts status and positive satoshi amounts from Order payloads, updates the order book and trade database, and ignores non-Order payloads.
Validation and contract coverage
rust/src/api/orders.rs, specs/004-mostro-p2p-client/contracts/orders.md
Tests cover populated, zero, and missing payloads. The contract documents order-ID correlation, late messages, synchronization, and ignored Peer payloads.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related issues

Possibly related PRs

  • MostroP2P/app#271 — Related rust/src/api/orders.rs trade-status synchronization and daemon-derived state handling.

Suggested reviewers: grunch, andreadiazcorreia, codamw

Poem

A rabbit saw an invoice arrive,
And helped the waiting trade survive.
Order and ledger hopped in line,
While peer replies stayed benign.
Tests chased each payload through—
“AddInvoice” now knows what to do! 🐇

🚥 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 clearly identifies the fix for inbound AddInvoice handling in kind-14 ingest.
Linked Issues check ✅ Passed The changes implement issue #287 by handling AddInvoice, persisting status and amount, ignoring Peer payloads, and supporting payload-less messages.
Out of Scope Changes check ✅ Passed The code, tests, and contract updates directly support issue #287 and the stated PR objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/maker-buyer-add-invoice

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
rust/src/api/orders.rs (1)

4259-4297: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Exercise the new AddInvoice branches at their call sites.

These tests cover Payload::Order, zero amounts, and no payload. They do not assert that a Payload::Peer follow-up returns None. The mapping test also does not prove that classify_take_reply(&Action::AddInvoice, &None) returns WaitingBuyerInvoice. Add both assertions.

As per coding guidelines, add targeted tests when expanding complex logic, asynchronous workflows, or protocol handling.

Proposed regression assertions
-        use mostro_core::message::Payload;
+        use mostro_core::message::{Payload, Peer};
...
+        assert!(
+            add_invoice_sync(&Some(Payload::Peer(Peer {
+                pubkey: "peer".to_string(),
+                reputation: None,
+            })))
+            .is_none()
+        );
...
     fn status_for_action_maps_add_invoice() {
+        use mostro_core::message::Action;
...
+        match classify_take_reply(&Action::AddInvoice, &None) {
+            DaemonReply::TakeAccepted { status, .. } => assert_eq!(
+                status,
+                Some(crate::api::types::OrderStatus::WaitingBuyerInvoice)
+            ),
+            _ => panic!("expected TakeAccepted"),
+        }
     }
🤖 Prompt for 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.

In `@rust/src/api/orders.rs` around lines 4259 - 4297, Add assertions to the
existing add-invoice tests: verify add_invoice_sync returns None for a
Payload::Peer follow-up, and verify classify_take_reply(&Action::AddInvoice,
&None) returns WaitingBuyerInvoice. Keep the assertions focused on these two
newly exercised branches.

Source: Coding guidelines

🤖 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 `@rust/src/api/orders.rs`:
- Around line 2046-2056: Update the AddInvoice synchronization flow around
order_book().get_order(), order_book().upsert_order(), and
db.update_trade_fields() so the maker-buyer path persists or reconciles the
order-book record even when the cached order is absent, ensuring both target
rows exist before synchronization. Make update_trade_fields() detect and surface
zero-row matches instead of treating them as success, and handle that outcome in
the caller.

---

Nitpick comments:
In `@rust/src/api/orders.rs`:
- Around line 4259-4297: Add assertions to the existing add-invoice tests:
verify add_invoice_sync returns None for a Payload::Peer follow-up, and verify
classify_take_reply(&Action::AddInvoice, &None) returns WaitingBuyerInvoice.
Keep the assertions focused on these two newly exercised branches.
🪄 Autofix

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: affbc8c4-88ef-4d8a-9d14-ff0a328d7747

📥 Commits

Reviewing files that changed from the base of the PR and between 8cca0a1 and c21c141.

📒 Files selected for processing (2)
  • rust/src/api/orders.rs
  • specs/004-mostro-p2p-client/contracts/orders.md

Comment thread rust/src/api/orders.rs
- add_invoice_sync returns None for the daemon's Peer follow-up, so the
  reputation message cannot clobber the just-written status.
- classify_take_reply on a payload-less add-invoice now carries
  WaitingBuyerInvoice via the new status_for_action mapping; pinned.

@ermeme ermeme 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.

Reviewed the current head.

The AddInvoice ingest path matches the reproduced maker-buyer failure: the inbound Action::AddInvoice with an Order payload now persists WaitingBuyerInvoice plus the calculated sats to both the order book and trade DB, while the follow-up Peer payload is left as a no-op. The take/add-invoice nonce handling and the status_for_action coverage also look consistent with the existing action-only reply flow.

I also rechecked the prior CodeRabbit thread: the zero-row DB no-op is intentional for uncorrelated kind-14 messages, and the remaining cold-cache book gap is shared by other ingest arms rather than an AddInvoice-specific blocker.

Validation:

  • GitHub checks are green: Rust, Flutter, and Web all succeeded on this head.
  • Local cargo test --no-default-features passed (249 passed, 8 ignored).
  • Local cargo clippy --no-default-features -- -D warnings passed.
  • ./scripts/frb-generate.sh --check passed.

Non-blocking note: the touched docs still have one older reference to process_gift_wrap_rumor in the same section, but the behavior and new table entry are correct.

@Catrya
Catrya merged commit 526f277 into main Aug 7, 2026
4 checks passed
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.

Inbound add-invoice from the daemon is not handled — maker-buyer trades die by timeout

1 participant