Skip to content

Feature-nip69-order-status#467

Merged
grunch merged 4 commits into
developfrom
feature-nip69-order-status
Mar 27, 2025
Merged

Feature-nip69-order-status#467
grunch merged 4 commits into
developfrom
feature-nip69-order-status

Conversation

@arkanoider

@arkanoider arkanoider commented Mar 25, 2025

Copy link
Copy Markdown
Collaborator

@Catrya,

this should fix #369 .

Order status in nostr event should be one of this now:

  • pending
  • in-progress
  • success
  • canceled

Summary by CodeRabbit

  • New Features
    • Enhanced order processing to validate input before triggering events, ensuring that only orders with valid statuses generate events.
  • Bug Fixes
    • Improved error handling to prevent events from being created when order information is incomplete or invalid.
  • Documentation
    • Added documentation for new functions detailing their arguments and return values, clarifying the order status evaluation process.

@coderabbitai

coderabbitai Bot commented Mar 25, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This pull request introduces a new function, create_status_tags, which takes an Order struct and returns a Result containing a tuple of a boolean and a Status. The function checks the order's status and maps errors to MostroInternalErr. The existing order_to_tags function has been modified to utilize create_status_tags, changing its return type to handle potential errors. Additionally, the create_order_event function has been updated to ensure that events are only created when valid tags are present, enhancing error handling across the relevant functions.

Changes

File Change Summary
src/nip33.rs Added new function create_status_tags to check order status and updated order_to_tags to use this function, changing its return type to Result<Option<Tags>, MostroError>.
src/app/release.rs Modified create_order_event to check for valid tags from order_to_tags before creating an event, enhancing error handling.
src/util.rs Updated get_tags_for_new_order to return Result<Option<Tags>, MostroError>, adjusting internal logic to handle possible absence of tags. Updated calls to this function in publish_order and update_order_event accordingly.

Assessment against linked issues

Objective Addressed Explanation
Change order status to follow NIP-69 (#369)

Possibly related PRs

  • Pay new added invoice #462: The changes in the main PR, specifically the modifications to the order_to_tags function, are directly related to the changes in the retrieved PR, as both involve handling the return type of functions that deal with order statuses and tags.
  • Dispute readability #390: The changes in the main PR, specifically the modifications to the order_to_tags function, are directly related to the updates in the retrieved PR, which also involves handling the output of order_to_tags in the create_order_event function.
  • Correct full privacy mode check when orders arrives #454: The changes in the main PR, particularly the modifications to the order_to_tags function, are directly related to the updates in the retrieved PR, which also involves the order_to_tags function in the context of tag handling for orders.

Suggested reviewers

  • grunch
  • Catrya

Poem

I’m a rabbit in a coding burrow, light on my feet,
Hopping through functions with a rhythmic beat,
A new status tag now makes the order flow right,
Pending, success, or canceled in plain sight,
My code garden blooms, a delight to write! 🐇


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0a57212 and e0f4941.

📒 Files selected for processing (1)
  • src/nip33.rs (2 hunks)
🔇 Additional comments (6)
src/nip33.rs (6)

5-5: Added appropriate error import for new functionality

The import of MostroError and MostroInternalErr is necessary for the error handling introduced in the new function and modified return type.


75-96: Well-structured implementation of order status mapping for NIP-69

The create_status_tags function effectively maps internal order states to the standardized states required by NIP-69 (pending, in-progress, success, canceled). The function correctly determines whether an event should be created based on the order status and returns the appropriate standardized status.

The implementation aligns with the requirements specified in the PR, where:

  • Pending orders map to "pending" state
  • Orders in WaitingBuyerInvoice/WaitingPayment map to "in-progress"
  • Canceled orders (any cancellation type) map to "canceled"
  • Completed orders map to "success"
  • Other states don't trigger nostr events (handled in line 94)

104-111: Good signature change and error handling in order_to_tags

The function signature change to return Result<Option<Tags>, MostroError> properly supports error propagation and the conditional event creation logic. The early check and unwrapping of the status information is clean and well-commented.


127-129: Correctly implemented status tag with standardized value

The status tag now correctly uses the standardized status value from create_status_tags rather than directly using the order's internal status.


175-178: Proper implementation of conditional event creation

The function now correctly returns Some(Tags) when an event should be created and None when it shouldn't, wrapped in Ok to handle potential errors. This aligns with the requirements that only specific states should trigger nostr events.


87-88:

Details

❓ Verification inconclusive

Verify the conditional event creation logic for buy/sell orders

The code creates in-progress events conditionally based on order type checks. For WaitingBuyerInvoice, events are created only for sell orders, and for WaitingPayment, only for buy orders. Please verify this is the intended behavior.


🏁 Script executed:

#!/bin/bash
# Check for occurrences of is_sell_order and is_buy_order to understand the context
rg "is_sell_order|is_buy_order" -A 3 -B 3

Length of output: 2984


Action: Confirm Event Creation Conditions for Order Types

The logic in src/nip33.rs currently creates in-progress events as follows:

  • For Status::WaitingBuyerInvoice, it returns true only if order.is_sell_order() succeeds.
  • For Status::WaitingPayment, it returns true only if order.is_buy_order() succeeds.

However, other parts of the code (for example, in src/app/cancel.rs) show the opposite mapping:

  • Buy orders trigger status checks for WaitingBuyerInvoice
  • Sell orders trigger status checks for WaitingPayment

Please verify whether the conditional logic in nip33.rs is intentional or if the conditions should be swapped to match the expected behavior throughout the codebase.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@arkanoider arkanoider assigned arkanoider and unassigned arkanoider Mar 25, 2025

@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: 0

🧹 Nitpick comments (2)
src/nip33.rs (2)

74-91: Documentation mismatch and function naming suggestion

The documentation on line 80 states that this function returns a "json string with order status according to nip69" but the function actually returns a plain string (not JSON-formatted). Also, the function name create_status_tag suggests it creates a tag object, but it only returns the status string.

Consider:

  1. Updating the documentation to accurately reflect the return value
  2. Renaming the function to something like determine_order_status or get_normalized_status to better reflect its purpose
-/// # Returns a json string with order status according to nip69
+/// # Returns a string with the normalized order status according to nip69
 /// Possible states for nostr event are pending, in-progress, success, canceled
-fn create_status_tag(order: &Order) -> String {
+fn determine_order_status(order: &Order) -> String {

83-90: Consider simplifying the status check logic

The current implementation uses a somewhat counterintuitive approach by checking if various status checks return errors. This makes the code a bit harder to follow. Consider refactoring to make the intent clearer.

-    if order.check_status(Status::Pending).is_err()
-        && order.check_status(Status::Success).is_err()
-        && order.check_status(Status::Canceled).is_err()
-    {
-        "in-progress".to_string()
-    } else {
-        order.status.to_string()
-    }
+    match order.status.as_str() {
+        "Pending" | "Success" | "Canceled" => order.status.to_string(),
+        _ => "in-progress".to_string()
+    }

Alternatively, if check_status is the preferred approach:

-    if order.check_status(Status::Pending).is_err()
-        && order.check_status(Status::Success).is_err()
-        && order.check_status(Status::Canceled).is_err()
-    {
-        "in-progress".to_string()
-    } else {
-        order.status.to_string()
-    }
+    // If it's not one of the standard statuses, return "in-progress"
+    if order.check_status(Status::Pending).is_ok() 
+        || order.check_status(Status::Success).is_ok()
+        || order.check_status(Status::Canceled).is_ok()
+    {
+        order.status.to_string()
+    } else {
+        "in-progress".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 9c06e48 and 5342be5.

📒 Files selected for processing (1)
  • src/nip33.rs (2 hunks)
🔇 Additional comments (2)
src/nip33.rs (2)

116-116: Good modularization of status handling

Moving the status determination logic to a dedicated function is a good improvement that enhances code modularity and maintainability.


74-91:

Details

❓ Verification inconclusive

Verify behavior change for non-standard statuses

This change introduces a potential behavior difference: previously any status would be returned as-is, but now statuses other than Pending, Success, and Canceled will be mapped to "in-progress". Please verify this is the intended behavior according to the nip69 specification.

Also applies to: 116-116


🏁 Script executed:

#!/bin/bash
# Check if there are any order statuses in the codebase other than the three explicitly handled ones
echo "Searching for Status enum definition..."
rg -A 10 "enum Status" --type rust

echo "Searching for potential status values used in the codebase..."
rg "Status::[A-Za-z]+" --type rust | sort | uniq

Length of output: 6336


Attention: Verify Mapping for Non-Standard Statuses

The updated create_status_tag() function in src/nip33.rs (lines 74–91 and line 116) now converts any order status that isn’t Pending, Success, or Canceled to "in-progress". Our code search uncovered numerous other status values (e.g., SettledHoldInvoice, WaitingBuyerInvoice, CooperativelyCanceled, etc.) used across the codebase. This behavior represents a departure from the previous implementation where statuses were returned as-is. Please verify that this change aligns with the nip69 specification and is intended; if non-standard statuses should be preserved instead of defaulting to "in-progress", further adjustments might be necessary.

@Catrya Catrya left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @arkanoider
Statuses should only be published once. What's happening is that every time the database status changes, a 38383 event with the status in-progress is published again. This event should only be published once when the order is taken and moves to the waiting-buyer-invoice or awaiting-payment in the db. But not again when it moves to active or fiatsent in db.

It's also happening that when a dispute is opened, when the admin resolves it, another event with the status in-progress is published. It should be canceled if the admin canceled it, or success if the admin completed it.

I still need to do more testing, but this is what I've found so far.

@arkanoider

Copy link
Copy Markdown
Collaborator Author

@Catrya

do a round of tests with this improvements.

Use this pull request of mostro-core with the new In Progress status.

@arkanoider arkanoider requested a review from Catrya March 25, 2025 22:31
@arkanoider

Copy link
Copy Markdown
Collaborator Author

@Catrya now we should have this mapping between order status and nostr events:

  • New order --> Event created with pending state
  • Order taken --> Event created with in-progress state
  • Order canceled, canceled by admin or coop canceled --> Events created with Canceled state
  • Order success or completed by admin --> Events created with Success state

Other states should not create events on nostr.

@Catrya Catrya left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

tACK great job @arkanoider

@grunch grunch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

utACK

@grunch grunch merged commit 8022076 into develop Mar 27, 2025
@grunch grunch deleted the feature-nip69-order-status branch March 27, 2025 17:42
arkanoider added a commit that referenced this pull request Apr 30, 2025
* 📝 Add docstrings to `feature-full-privacy-mode-checks` (#455)

* add feature to check correctly if order is full privacy or normal

* 📝 Add docstrings to `feature-full-privacy-mode-checks`

Docstrings generation was requested by @arkanoider.

* #454 (comment)

The following files were modified:

* `src/app/order.rs`
* `src/util.rs`

---------

Co-authored-by: arkanoider <github.913zc@simplelogin.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: arkanoider <113362043+arkanoider@users.noreply.github.com>

* Fix network in order event (#452)

Now in orers event 38383 the network that comes out is the correct one

* Feature anyhow removal (#459)

* remove of anyhow dependency start

* removed anyhow dependecy

* remove patch from cargo.toml

* Update mostro-core version

---------

Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>

* Feature disputes (#463)

* Feature: dispute fix for new logic

* fix for coop cancel case

* Add logic for info message about dispute for solver

* first working dispute info message for admin after taking disputes

* added fields to dispute info message for solver

* removed some probably useless and refactored a bit admin-take-dispute function

* clippy suggestion

* other cosmetics to admin take file

* some other cosmetics on admin-take-dispute file

* fix on admin-take

* Update admin_take_dispute.rs

* fixed a wrong search of order id in admin take file@

* Fix: added correct check to add solver from admin cli

* fix: wrong check on admin cancel

* Fix initiator pubkey: now is the trade key of initiator not identity

* quick fix for full privacy orders

* new logic with mixed full privacy - regular reputation mode

* Update cargo toml to compile with version 0.6.32 of mostro-core - this is in preparation for migrating to nostr-sdk 0.40

* rollback sdk to 0.38 version to merge disputes - we will come back to 0.40 when we will fix signature issue

* Update mostro-core dependency

---------

Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>

* added correction for the case of buyer adding back a new invoice after payment failure (#462)

* Fix for nostr sdk 40 issue on incoming message (#465)

* testing sdk 40

* fix for sdk 40

* cleaned cargo.toml

* Bump mostro core version

---------

Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>

* fix: sends order with an updated 'status' field as the reply to add-invoice when there is a preimage (#464)

* Feature-nip69-order-status (#467)

* feature: align to nip69 order status in nostr event

* Improved in progress nip69 logic

* refined event states of the order with nip69 request

* add another check to avoid multiple events with in-progress state

* Privacy range order fix (#468)

* add optional field for users in full privacy inside solver message

* To be tested - privacy range child order fix

* fix cargo.toml

* bumped mostro-core version to 6.35

* New user or privacy order send same user info with zeros (#471)

* new user or privacy order send same user info with zeros

* fix days field and removed some println! macro with nicer tracing messages

* bumped mostro-core version to 6.36 and added requested fix to compile

* Add previous order state in database for solver message (#472)

* add previous state in database for solver message

* bumped mostro-core version to 6.36

* Taker info message to maker.

I think that could be modifies in a more generic UserInfo.
 (#473)

* added logic to send infos to maker when an order is taken

* Add takers info message for maker

* fix cargo.toml

* set peer pubkey to empty string when notifying taker reputation to maker

* moved user info message to the right point of the order flow

* fix cargo.toml

* changed message struct from UserDisputeInfo to UserInfo

* fix: get master keys for user infos

* Bumped mostro-core to version 6.38

* fix for buy order flow with message to maker (#479)

* Rabbit fixes

---------

Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Catrya <140891948+Catrya@users.noreply.github.com>
Co-authored-by: Bilthon <bilthon@gmail.com>
arkanoider added a commit that referenced this pull request May 18, 2025
* feature: align to nip69 order status in nostr event

* Improved in progress nip69 logic

* refined event states of the order with nip69 request

* add another check to avoid multiple events with in-progress state
grunch added a commit that referenced this pull request May 29, 2025
* 📝 Add docstrings to `feature-full-privacy-mode-checks` (#455)

* add feature to check correctly if order is full privacy or normal

* 📝 Add docstrings to `feature-full-privacy-mode-checks`

Docstrings generation was requested by @arkanoider.

* #454 (comment)

The following files were modified:

* `src/app/order.rs`
* `src/util.rs`

---------

Co-authored-by: arkanoider <github.913zc@simplelogin.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: arkanoider <113362043+arkanoider@users.noreply.github.com>

* Feature disputes (#463)

* Feature: dispute fix for new logic

* fix for coop cancel case

* Add logic for info message about dispute for solver

* first working dispute info message for admin after taking disputes

* added fields to dispute info message for solver

* removed some probably useless and refactored a bit admin-take-dispute function

* clippy suggestion

* other cosmetics to admin take file

* some other cosmetics on admin-take-dispute file

* fix on admin-take

* Update admin_take_dispute.rs

* fixed a wrong search of order id in admin take file@

* Fix: added correct check to add solver from admin cli

* fix: wrong check on admin cancel

* Fix initiator pubkey: now is the trade key of initiator not identity

* quick fix for full privacy orders

* new logic with mixed full privacy - regular reputation mode

* Update cargo toml to compile with version 0.6.32 of mostro-core - this is in preparation for migrating to nostr-sdk 0.40

* rollback sdk to 0.38 version to merge disputes - we will come back to 0.40 when we will fix signature issue

* Update mostro-core dependency

---------

Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>

* Fix for nostr sdk 40 issue on incoming message (#465)

* testing sdk 40

* fix for sdk 40

* cleaned cargo.toml

* Bump mostro core version

---------

Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>

* Feature-nip69-order-status (#467)

* feature: align to nip69 order status in nostr event

* Improved in progress nip69 logic

* refined event states of the order with nip69 request

* add another check to avoid multiple events with in-progress state

* Taker info message to maker.

I think that could be modifies in a more generic UserInfo.
 (#473)

* added logic to send infos to maker when an order is taken

* Add takers info message for maker

* fix cargo.toml

* set peer pubkey to empty string when notifying taker reputation to maker

* moved user info message to the right point of the order flow

* fix cargo.toml

* changed message struct from UserDisputeInfo to UserInfo

* fix: get master keys for user infos

* Bumped mostro-core to version 6.38

* first commit for database encryption

* Moving on with encryption work

* Implemented base64 on cipher

* Takebuy and takesell pending orders check now working with encryption

* Removed unwraps

* Finishing code: changed password management and completing checks

* Finishing code: used hashset for search

* added unit test for evaluate timings

* first order cycle completed - to be fixed empty password case

* Added logic for testing a caching idea using hashmap to speed up search of identity keys when encrypted

* ready to start review process

* Cleaned test

* removed patch from cargo.toml

* Rabbit fixes

* some improvements to have also rating working with encryption

* Removed useless call in db.rs

* fix for tests

* Cosmetics on release.rs - improved a bit a function in more ribust way

* fix: wrong check on full privacy orders in disputes

* fix: more meaningful variable name in dispute setup

* fix: wrong commented lines reactivated

* fix: some fixes in privacy orders with encryption

* fix: some fixes following coderabbit advices

Introduced a random delay on password entering to avoid timing attacks.

Removed awaiting from store_encrypted function that does not require async.

* refactor: removed many useless connection opening to database with direct use of borrowed pool variable

* chore: more meaningful text for user in db.rs

* chore: improved encryption unit test

now fix salt for testing works - fix salt and password are used to test timings with decryption using key caching, to test it do:

cargo test test_fetch_string_column_scalar -- --nocapture

* refactor: some improvements in db.rs

improved password error management

reduce code duplication for pending orders checks

* chore(rebase-on-main): commit cargo.lock for rebasing on top of main encrytpion

* feat: completing refactor and rebase of encryption pr

* refactor: introduced new refactoring of encryption-decryption function

- cargo compiles now, we will have to create the new mostro-core after some testings.

- bumped nostr-sdk to 0.41 release, no breaking changes

* chore: temporary added git branch of mostro-core to compile

* chore(test): fix tests

* chore: bumped mostro-core version in cargo.toml

* fix: wrong database path string creation

* chore: fix tests in db.rs

* fix: child order after a trade with a full privacy user have wrong master keys

* fix: typo on check password hash function

* fix: child order event after a complete order does not send user information also if order is normal (not full privacy)

* fix: if a child order come from a privacy order user rating are sent in the event wit all zeroes

* fix: fixed bug found by Catrya

- when I recreate the child order master keys were saved without encryption
  so when a takesell or takebuy comes in the search for pending user orders generate a decrytpion error.

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Francisco Calderón <fjcalderon@gmail.com>
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.

3 participants