Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cancel in waiting-buyer-invoice or waiting-payment #432

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

Catrya
Copy link
Collaborator

@Catrya Catrya commented Jan 18, 2025

closes #379

Added:

When the maker cancels an order in status waiting-buyer-invoice or waiting-payment, the order goes to status canceled and the taker will be notified that it was cancelled

When the taker cancels an order in the status waiting-buyer-invoice or waiting-payment, the order goes to status pending. The maker will be notified that it was cancelled only if the maker has already been notified to submit their invoice or pay the hold invoice

Summary by CodeRabbit

  • New Features

    • Enhanced order cancellation process with broader status handling.
    • Improved user role-based cancellation logic.
    • Added comprehensive notifications for order cancellations.
  • Bug Fixes

    • Streamlined invoice cancellation handling.
    • Refined conditions for order status changes during cancellation.

Copy link
Contributor

coderabbitai bot commented Jan 18, 2025

Walkthrough

The pull request modifies the cancel_action function in src/app/cancel.rs, expanding the order cancellation logic to provide more flexibility for users. The changes allow makers to cancel orders in WaitingBuyerInvoice or WaitingPayment statuses, with different handling based on whether the canceling user is the order creator or the taker. The function now includes more comprehensive checks for order status, user roles, and invoice handling, consolidating previously separate invoice cancellation methods directly into the cancellation process.

Changes

File Change Summary
src/app/cancel.rs - Updated cancel_action function logic for order cancellation
- Expanded status checks for cancellation eligibility
- Added user role-based cancellation handling
- Removed separate cancel_add_invoice and cancel_pay_hold_invoice functions

Assessment against linked issues

Objective Addressed Explanation
Cancel order in waiting-buyer-invoice or waiting-payment [#379]
Send cancellation messages to both maker and taker
Handle invoice cancellation for different scenarios

Possibly related PRs

  • AddInvoice: send message to buyer on cancel #425: This PR modifies the cancel_add_invoice function, which has been removed in the main PR, indicating a direct relationship in the context of cancellation logic.
  • Fix cancel on waiting payment #428: This PR involves changes to the cancel_pay_hold_invoice function, which has also been removed in the main PR, suggesting a connection in the overall cancellation handling logic.

Poem

🐰 A Rabbit's Cancellation Tale 🎫
In the world of orders, swift and bright,
Cancellation now takes a nimble flight.
Maker's wish, a simple command,
Status changes at their hand.
Freedom flows, no more delay! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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)
src/app/cancel.rs (1)

104-135: Refactor to eliminate code duplication in cancellation handling

The blocks of code handling order cancellation for creators (lines 104–135) and takers (lines 136–184) contain similar logic, such as updating the order status, canceling hold invoices, and sending notifications. Refactoring these blocks to extract common functionality into helper functions can improve maintainability and reduce repetition.

Also applies to: 136-184

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 01710f4 and ec08b81.

📒 Files selected for processing (1)
  • src/app/cancel.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tests

src/app/cancel.rs Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/app/cancel.rs (1)

136-186: ⚠️ Potential issue

Fix logical error: Notifications may not be sent due to premature status update.

When the taker cancels the order, the status is updated to Pending at line 173. The subsequent status checks at lines 145-147 and 159-161 will never be true because the status has already been changed, causing the creator to miss cancellation notifications.

Store the original status before updating it:

+        let original_status = order.status.clone();
         if let Ok(order_updated) = update_order_event(my_keys, Status::Pending, &order).await {
             let _ = order_updated.update(pool).await;
         }

         if order.kind == OrderKind::Buy.to_string()
-            && order.status == Status::WaitingBuyerInvoice.to_string()
+            && original_status == Status::WaitingBuyerInvoice.to_string()
         {
             // ... notification code ...
         }

         if order.kind == OrderKind::Sell.to_string()
-            && order.status == Status::WaitingPayment.to_string()
+            && original_status == Status::WaitingPayment.to_string()
         {
             // ... notification code ...
         }
🧹 Nitpick comments (1)
src/app/cancel.rs (1)

91-102: Consider simplifying taker identification logic.

While the current implementation is correct, it can be more concise by using a ternary operation.

-        let taker_pubkey: String;
-        if seller_pubkey == &order.creator_pubkey {
-            taker_pubkey = buyer_pubkey.to_string();
-        } else {
-            taker_pubkey = seller_pubkey.to_string();
-        }
+        let taker_pubkey = if seller_pubkey == &order.creator_pubkey {
+            buyer_pubkey.to_string()
+        } else {
+            seller_pubkey.to_string()
+        };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ec08b81 and d9b63f3.

📒 Files selected for processing (1)
  • src/app/cancel.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tests
🔇 Additional comments (2)
src/app/cancel.rs (2)

88-90: LGTM! Status checks align with requirements.

The condition correctly handles both WaitingPayment and WaitingBuyerInvoice statuses as specified in the PR objectives.


104-135: LGTM! Creator cancellation flow is well-structured.

The implementation correctly:

  1. Updates order status
  2. Handles hold invoice cancellation
  3. Sends notifications to both parties

and remove unused functions cancel_add_invoice cancel_pay_hold_invoice
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/app/cancel.rs (2)

91-102: Consider simplifying taker identification logic.

While the current implementation is correct, it could be more concise.

Consider this more idiomatic approach:

-        let taker_pubkey: String;
-        if seller_pubkey == &order.creator_pubkey {
-            taker_pubkey = buyer_pubkey.to_string();
-        } else {
-            taker_pubkey = seller_pubkey.to_string();
-        }
+        let taker_pubkey = if seller_pubkey == &order.creator_pubkey {
+            buyer_pubkey.to_string()
+        } else {
+            seller_pubkey.to_string()
+        };

144-168: Consider reducing code duplication in taker cancellation logic.

The price reset and order update logic is duplicated between Buy and Sell order handling.

Consider extracting the common logic:

+            fn reset_order_state(
+                order: &mut Order,
+                pool: &Pool<Sqlite>,
+                my_keys: &Keys,
+            ) -> Result<()> {
+                if order.price_from_api {
+                    order.amount = 0;
+                    order.fee = 0;
+                }
+                update_order_to_initial_state(pool, order.id, order.amount, order.fee).await?;
+                update_order_event(my_keys, Status::Pending, order).await?;
+                Ok(())
+            }
+
             if order.kind == OrderKind::Buy.to_string() {
                 if order.status == Status::WaitingBuyerInvoice.to_string() {
                     send_new_order_msg(
                         request_id,
                         Some(order.id),
                         Action::Canceled,
                         None,
                         &creator_pubkey,
                         None,
                     )
                     .await;
                 }
-                if order.price_from_api {
-                    order.amount = 0;
-                    order.fee = 0;
-                }
                 edit_seller_pubkey_order(pool, order.id, None).await?;
                 edit_master_seller_pubkey_order(pool, order.id, None).await?;
-                update_order_to_initial_state(pool, order.id, order.amount, order.fee).await?;
-                update_order_event(my_keys, Status::Pending, &order).await?;
+                reset_order_state(&mut order, pool, my_keys)?;
                 info!(
                     "{}: Canceled order Id {} republishing order",
                     buyer_pubkey, order.id
                 );
             }

             if order.kind == OrderKind::Sell.to_string() {
                 if order.status == Status::WaitingPayment.to_string() {
                     send_new_order_msg(
                         request_id,
                         Some(order.id),
                         Action::Canceled,
                         None,
                         &creator_pubkey,
                         None,
                     )
                     .await;
                 }
-                if order.price_from_api {
-                    order.amount = 0;
-                    order.fee = 0;
-                }
                 edit_buyer_pubkey_order(pool, order.id, None).await?;
                 edit_master_buyer_pubkey_order(pool, order.id, None).await?;
-                update_order_to_initial_state(pool, order.id, order.amount, order.fee).await?;
-                update_order_event(my_keys, Status::Pending, &order).await?;
+                reset_order_state(&mut order, pool, my_keys)?;
                 info!(
                     "{}: Canceled order Id {} republishing order",
                     buyer_pubkey, order.id
                 );
             }

Also applies to: 170-194

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d9b63f3 and aacfba0.

📒 Files selected for processing (1)
  • src/app/cancel.rs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tests
🔇 Additional comments (3)
src/app/cancel.rs (3)

88-90: LGTM! Status checks align with requirements.

The condition correctly handles both WaitingPayment and WaitingBuyerInvoice statuses as specified in the PR objectives.


104-134: LGTM! Creator cancellation logic is robust.

The implementation correctly:

  • Updates order status to Canceled
  • Handles hold invoice cancellation
  • Sends notifications to both parties

144-194: Verify the impact of resetting price and fee.

The code resets amount and fee to 0 when price_from_api is true. Please ensure this doesn't cause issues with order republishing.

Run this script to check the impact:

✅ Verification successful

Price and fee reset is a verified pattern for market price orders

The code intentionally uses amount = 0 as a marker to trigger fresh market price fetching when orders are taken. This ensures market prices are current when orders are republished. The system has proper validation in place to prevent orders with invalid amounts from being processed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any assumptions about non-zero amount/fee in the codebase

# Search for amount/fee validation or checks
rg -A 5 'amount.*[=><!].*0|fee.*[=><!].*0'

# Search for order republishing logic
ast-grep --pattern 'update_order_to_initial_state($$$)'

Length of output: 8783

@Catrya
Copy link
Collaborator Author

Catrya commented Jan 20, 2025

please @grunch @arkanoider take a look
I've changed the cancel code a bit, and although I've already tested it and it works well to me, remember that I'm pretty new to coding

@Catrya Catrya requested a review from arkanoider January 20, 2025 19:42
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.

Allow a maker to cancel an order in status waiting-buyer-invoice or waiting-payment
1 participant