Skip to content

Feat: issue #437 implementation#445

Merged
grunch merged 4 commits into
developfrom
feature-missing-rating-on-new-order-event
Feb 21, 2025
Merged

Feat: issue #437 implementation#445
grunch merged 4 commits into
developfrom
feature-missing-rating-on-new-order-event

Conversation

@arkanoider

@arkanoider arkanoider commented Feb 19, 2025

Copy link
Copy Markdown
Collaborator

Hi @Catrya ,

i did the fix for rating of user not present in the nostr event when a new order is created. Please take a look and test when you're available.

Summary by CodeRabbit

  • Refactor

    • Streamlined user reputation handling by removing the ability to fetch user ratings.
    • Updated the handling of reputation data to utilize a more versatile structure.
  • Chore

    • Enhanced error handling for API requests and improved clarity in error reporting.
    • Adjusted imports to support new logic for user reputation retrieval.
    • Updated function signatures to provide more specific error types.

@arkanoider arkanoider requested review from Catrya and grunch February 19, 2025 10:48
@coderabbitai

coderabbitai Bot commented Feb 19, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This update removes the user reputation fetching functionality from the rating module by eliminating the get_user_reputation function and its associated dependencies. The code now relies on a database check via is_user_present to retrieve user ratings. Additionally, function signatures in the rating conversion module were updated to use a tuple type instead of a custom Rating type, and error handling in the utility module was improved by refining the return type of the retry function.

Changes

File Change Summary
src/app/rate_user.rs Removed the get_user_reputation function and its related imports (NOSTR_CLIENT, NOSTR_REPLACEABLE_EVENT_KIND), eliminating the capability to fetch user reputation.
src/nip33.rs Removed create_rating_string function; updated order_to_tags to accept Option<(f64, i64, i64)> instead of Option<Rating>, simplifying the rating conversion logic.
src/util.rs Enhanced error handling in retries_yadio_request (return type now includes MostroError); replaced the call to the removed reputation function with is_user_present to obtain ratings; adjusted imports.
src/app/release.rs Updated function signatures to include MostroError in return types and modified create_order_event to be asynchronous, enhancing error handling and clarity.
src/lnurl.rs Updated resolv_ln_address function to return Result<String, MostroError> and standardized error handling throughout the function.

Possibly related PRs

  • Feat: issue #437 implementation #445: The changes in the main PR and the retrieved PR are directly related as both involve the removal of the get_user_reputation function from src/app/rate_user.rs, indicating a shared focus on user reputation management.
  • Seller can rate buyer after release funds #426: The changes in the main PR, which involve the removal of the get_user_reputation function, are related to the modifications in the retrieved PR that also remove the rate_counterpart function, as both PRs impact the user rating functionality within the application.
  • Rate user feature #404: The changes in the main PR, which involve the removal of the get_user_reputation function in src/app/rate_user.rs, are related to the modifications in the retrieved PR, specifically the updates to user reputation handling in src/app/rate_user.rs, as both PRs focus on user reputation management and involve changes to the same file.

Suggested reviewers

  • grunch

Poem

Oh, I hop through the code at speed,
Leaving old functions where they no longer lead.
New paths now check the user's name,
With floating numbers, never quite the same.
In fields of logic, I cheer and play—
A rabbit’s code-happiness, hip hip hooray!
🥕🐇


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.

@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/util.rs (1)

46-47: Consider preserving original error details.

Here, errors are mapped without capturing the underlying error message. Preserving the original error details often helps with debugging and troubleshooting.

Below is a sample diff demonstrating how to retain the original error message:

-        .map_err(|_| MostroInternalErr(ServiceError::NoAPIResponse))?
+        .map_err(|err| MostroInternalErr(ServiceError::NoAPIResponse(err.to_string())))?

-        .map_err(|_| MostroInternalErr(ServiceError::MalformedAPIRes))?
+        .map_err(|err| MostroInternalErr(ServiceError::MalformedAPIRes(err.to_string())))?

-        .map_err(|_| MostroInternalErr(ServiceError::NoAPIResponse))?;
+        .map_err(|err| MostroInternalErr(ServiceError::NoAPIResponse(err.to_string())))?;

Also applies to: 49-50, 60-60

src/nip33.rs (1)

39-41: Floating-point rating format could be refined.

Switching from Option<Rating> to Option<f64> simplifies the flow but consider limiting precision (e.g., rounding) to avoid overly long decimal representations in the tag.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 825ba61 and 83e689f.

📒 Files selected for processing (3)
  • src/app/rate_user.rs (0 hunks)
  • src/nip33.rs (2 hunks)
  • src/util.rs (6 hunks)
💤 Files with no reviewable changes (1)
  • src/app/rate_user.rs
🔇 Additional comments (5)
src/util.rs (4)

4-4: Praise for newly introduced imports.

These additional imports for database checks, invoice states, and HashMap usage look appropriate and align well with the rest of the code changes.

Also applies to: 16-16, 28-28


42-42: Enhanced error-handling signature.

Changing the function to return Result<_, MostroError> is a solid improvement, ensuring consistent and descriptive error handling throughout the codebase.


203-205: User presence check aligned with new approach.

Loading user data from the database harmonizes with the removal of the outdated reputation-fetching method and ensures accurate rating retrieval.


208-208: Passing user rating for event tags looks correct.

Supplying user.total_rating to order_to_tags naturally integrates the user's database-sourced reputation into the event.

src/nip33.rs (1)

68-68: Function signature update streamlines rating usage.

Using Option<f64> instead of a custom Rating struct is consistent with the updated user reputation approach across the codebase.

Comment thread src/util.rs
.await
.map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
// We transform the order fields to tags to use in the event
let tags = order_to_tags(&new_order_db, reputation);

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.

We need to show to the counterpart 3 fields, total_rating, total_reviews and days_operating, we need to refactor to that

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[
    "rating",
    "4.5"
],
[
    "reviews",
    "54"
],
[
    "days_operating",
    "456"
],

Is it good like this @grunch ?
Days operating filed I suppose it's calculated from user creation time in mostrod users table in database right?

@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 when i try to create a new order this appears in mostrod logs

2025-02-19T15:53:44.827163Z  WARN mostrod::app: Error in NewOrder with context Order id not present in database

@arkanoider arkanoider closed this Feb 19, 2025
@arkanoider arkanoider deleted the feature-missing-rating-on-new-order-event branch February 19, 2025 16:38
@arkanoider arkanoider reopened this Feb 19, 2025
@arkanoider arkanoider force-pushed the feature-missing-rating-on-new-order-event branch from 83e689f to 849e233 Compare February 19, 2025 16:49
@arkanoider

Copy link
Copy Markdown
Collaborator Author

Hi @arkanoider when i try to create a new order this appears in mostrod logs

2025-02-19T15:53:44.827163Z  WARN mostrod::app: Error in NewOrder with context Order id not present in database

I did a big shit! :) Will check asap...in office I was not able to test.

@arkanoider

Copy link
Copy Markdown
Collaborator Author

@Catrya give another try to this please.

@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)

39-50: Add validation and improve robustness of operating days calculation.

The current implementation has potential edge cases:

  1. No validation for future timestamps
  2. Possible i32 overflow for very old accounts
  3. Potential loss of precision due to integer division

Consider this more robust implementation:

-fn calculate_operating_days(created_at: i64) -> i32 {
+fn calculate_operating_days(created_at: i64) -> i64 {
     let now = Timestamp::now();
-    let days = (now.as_u64() - created_at as u64) / 86400;
-    days as i32
+    if created_at > now.as_i64() {
+        return 0;
+    }
+    (now.as_i64() - created_at) / 86400
}

73-73: Improve maintainability of reputation data handling.

The implementation correctly handles the reputation data tuple, but could benefit from named constants and type definitions for better maintainability.

Consider adding these improvements:

type ReputationData = (f64, i64, i64); // (rating, review_count, created_at)

const DEFAULT_RATING: &str = "0";
const DEFAULT_REVIEWS: &str = "0";

pub fn order_to_tags(order: &Order, reputation_data: Option<ReputationData>) -> Tags {
    // ... existing code ...
}

This makes the code more self-documenting and easier to maintain.

Also applies to: 105-114

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 849e233 and a6ebf16.

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

39-63: LGTM! Error handling improvements.

The changes enhance error handling by making errors explicit in the return type and using map_err for cleaner error conversion.


203-210: LGTM! User reputation handling improvements.

The changes correctly implement the new user rating system by:

  1. Using is_user_present to fetch user data
  2. Passing complete user data (rating, reviews, creation date) to order_to_tags

4-4: LGTM! Import adjustments.

The import changes correctly support the new functionality:

  • is_user_present for the new user rating system
  • InvoiceState for invoice state handling
  • HashMap for collections

Also applies to: 16-16, 28-28

@arkanoider

Copy link
Copy Markdown
Collaborator Author

Modified rating tag as JSON object:

[
  "rating",
  "{\"total_reviews\":1,\"total_rating\":3.0,\"days\":33}"
],

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

when a order is in pending status is ok

        "[\"rating\",{\"total_reviews\":1,\"total_rating\":5.0,\"days\":0}]"

But when changes the status the Days are wrong:

        "rating",
        "[\"rating\",{\"total_reviews\":0,\"total_rating\":0.0,\"days\":20138}]"

@Catrya

Catrya commented Feb 19, 2025

Copy link
Copy Markdown
Member

I was thinking that it would be good to add to the message that the Maker receives to pay the hold invoice if he is the seller, or to put the invoice if he is the buyer, the reputation of the Taker, the number of ratings and the days he has been using a Mostro.

Do you think it would be better if I open an issue for that or that it is addressed within this same PR?
@arkanoider @grunch

@arkanoider

Copy link
Copy Markdown
Collaborator Author

when a order is in pending status is ok

        "[\"rating\",{\"total_reviews\":1,\"total_rating\":5.0,\"days\":0}]"

But when changes the status the Days are wrong:

        "rating",
        "[\"rating\",{\"total_reviews\":0,\"total_rating\":0.0,\"days\":20138}]"

Ok got it, just need to manage the None case better. Now we just use the data of reputation when order is created, when there is an update of order state or when we create a child order we set the data to None option.

Maybe we can always add rating data to all messages related to orders? What do you think?

@Catrya @grunch

@arkanoider

arkanoider commented Feb 20, 2025

Copy link
Copy Markdown
Collaborator Author

when a order is in pending status is ok

        "[\"rating\",{\"total_reviews\":1,\"total_rating\":5.0,\"days\":0}]"

But when changes the status the Days are wrong:

        "rating",
        "[\"rating\",{\"total_reviews\":0,\"total_rating\":0.0,\"days\":20138}]"

Ok got it, just need to manage the None case better. Now we just use the data of reputation when order is created, when there is an update of order state or when we create a child order we set the data to None option.

Maybe we can always add rating data to all messages related to orders? What do you think?

@Catrya @grunch

Mmmmhhh...i will try to answer to myself, maybe it was correct to have rating tagvonly in a new order event the reputation of the maker, which makes sense because the taker can see it and use it to take a decision.

After taking an order all the event update of the could be without rating tag ( or set to null or zero ), maybe just when we have a child new order from a range order we can publish it back for the new child order. The "bad" thing in this case is that rating is the same as before because users won't have sent the ratings to each other.

Let me know what you think guys...
@Catrya @grunch

…te it. During trade is not showed ( i think it's no more meaningful during status update ) - bonus removed another ref to anyhow, target is to remove dep completely

@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 (1)

131-140: Consider moving the rating tag insertion position.

The rating tag is currently inserted at a hardcoded position (index 7). This could break if the tags vector structure changes.

Consider using a more flexible approach:

-    tags.insert(7, Tag::custom(
+    tags.push(Tag::custom(
         TagKind::Custom(Cow::Borrowed("rating")),
         vec![create_rating_tag(reputation_data)],
     ));
src/app/release.rs (1)

382-413: Consider extracting user rating logic to a separate function.

The user rating extraction logic in create_order_event is complex and could benefit from being moved to a dedicated function.

Consider refactoring like this:

+async fn get_user_rating_data(order: &Order, pool: &Pool<Sqlite>) -> Result<(f64, i64, i64), MostroError> {
+    let identity_pubkey = match order.is_sell_order() {
+        Ok(_) => order.get_master_seller_pubkey()?,
+        Err(_) => order.get_master_buyer_pubkey()?,
+    };
+
+    let user = crate::db::is_user_present(pool, identity_pubkey.to_string()).await?;
+    Ok((user.total_rating, user.total_reviews, user.created_at))
+}
+
 async fn create_order_event(new_order: &mut Order, my_keys: &Keys) -> Result<Event, MostroError> {
     let pool = match crate::db::connect().await {
         Ok(p) => p,
         Err(e) => return Err(MostroInternalErr(ServiceError::DbAccessError(e.to_string()))),
     };
 
-    let identity_pubkey = match new_order.is_sell_order() {
-        Ok(_) => new_order.get_master_seller_pubkey().map_err(MostroInternalErr)?,
-        Err(_) => new_order.get_master_buyer_pubkey().map_err(MostroInternalErr)?,
-    };
-
-    let user = crate::db::is_user_present(&pool, identity_pubkey.to_string())
-        .await
-        .map_err(|e| MostroInternalErr(ServiceError::DbAccessError(e.to_string())))?;
+    let rating_data = get_user_rating_data(new_order, &pool)
+        .await
+        .map(Some)
+        .unwrap_or(None);
 
-    let tags = crate::nip33::order_to_tags(
-        new_order,
-        Some((user.total_rating, user.total_reviews, user.created_at)),
-    );
+    let tags = crate::nip33::order_to_tags(new_order, rating_data);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 64f9cf9 and 0c41a03.

📒 Files selected for processing (3)
  • src/app/release.rs (5 hunks)
  • src/lnurl.rs (3 hunks)
  • src/nip33.rs (4 hunks)
🔇 Additional comments (3)
src/lnurl.rs (1)

35-35: LGTM! Error handling improvements look good.

The changes standardize error handling by:

  • Using explicit MostroError return type
  • Consistently mapping errors to specific ServiceError variants
  • Using map_err for error transformation

Also applies to: 45-45, 51-51, 67-67, 70-75

src/nip33.rs (1)

47-56: LGTM! Well-structured rating tag implementation.

The new create_rating_tag function:

  • Uses JSON for structured data representation
  • Includes comprehensive rating metrics (total_reviews, total_rating, days)
  • Handles optional reputation data gracefully
src/app/release.rs (1)

204-208: LGTM! Improved error handling for payment request validation.

The change properly handles missing payment requests by returning a specific InvoiceInvalidError.

@arkanoider

Copy link
Copy Markdown
Collaborator Author

@Catrya if you can do a round of test with latest here let me know.

  • Rating appears only in event of new order ( maker creation or child orders ).
  • Rating is cancelled during messages of a trade, no more meaningful imo. It is useful when a taker decide if he wants to take an order.
  • Downside in child orders is that user have not rated each other at that moment so rating is not updated.

Let me know your thoughts and results.

@grunch

Removed other use of anyhow my objective it to completely remove dependence from cargo.toml, we are near.

@Catrya

Catrya commented Feb 20, 2025

Copy link
Copy Markdown
Member

@Catrya if you can do a round of test with latest here let me know.

  • Rating appears only in event of new order ( maker creation or child orders ).
  • Rating is cancelled during messages of a trade, no more meaningful imo. It is useful when a taker decide if he wants to take an order.
  • Downside in child orders is that user have not rated each other at that moment so rating is not updated.

Let me know your thoughts and results.

@grunch

Removed other use of anyhow my objective it to completely remove dependence from cargo.toml, we are near.

Hi @arkanoider I like rating appears only in new order event.

But, I have not been able to test it when a child order is published because there is a bug that does not allow a child order to be published when it is by range.
(The bug is not from this PR, it comes from develop branch. I will look for the commit in which it was introduced)

@Catrya

Catrya commented Feb 20, 2025

Copy link
Copy Markdown
Member

Well, I tested it again, for me it's ok

The bug that I thought wouldn't let me try it out isn't actually that bad, the publication of child orders does work, but if the amount left is less than the initial range limit, it sends a command that it shouldn't send, but that has nothing to do with this PR

@grunch

grunch commented Feb 20, 2025

Copy link
Copy Markdown
Member

I was thinking that it would be good to add to the message that the Maker receives to pay the hold invoice if he is the seller, or to put the invoice if he is the buyer, the reputation of the Taker, the number of ratings and the days he has been using a Mostro.

Do you think it would be better if I open an issue for that or that it is addressed within this same PR? @arkanoider @grunch

yes please create a new issue for that, let's not include it here and keep this one small

@grunch

grunch commented Feb 20, 2025

Copy link
Copy Markdown
Member

when a order is in pending status is ok

        "[\"rating\",{\"total_reviews\":1,\"total_rating\":5.0,\"days\":0}]"

But when changes the status the Days are wrong:

        "rating",
        "[\"rating\",{\"total_reviews\":0,\"total_rating\":0.0,\"days\":20138}]"

Ok got it, just need to manage the None case better. Now we just use the data of reputation when order is created, when there is an update of order state or when we create a child order we set the data to None option.

Maybe we can always add rating data to all messages related to orders? What do you think?

@Catrya @grunch

I think the rating data is only needed on pending orders

@arkanoider

Copy link
Copy Markdown
Collaborator Author

when a order is in pending status is ok

        "[\"rating\",{\"total_reviews\":1,\"total_rating\":5.0,\"days\":0}]"

But when changes the status the Days are wrong:

        "rating",
        "[\"rating\",{\"total_reviews\":0,\"total_rating\":0.0,\"days\":20138}]"

Ok got it, just need to manage the None case better. Now we just use the data of reputation when order is created, when there is an update of order state or when we create a child order we set the data to None option.

Maybe we can always add rating data to all messages related to orders? What do you think?

@Catrya @grunch

I think the rating data is only needed on pending orders

yep! it should be like that now!

@grunch

grunch commented Feb 20, 2025

Copy link
Copy Markdown
Member

when a order is in pending status is ok

        "[\"rating\",{\"total_reviews\":1,\"total_rating\":5.0,\"days\":0}]"

But when changes the status the Days are wrong:

        "rating",
        "[\"rating\",{\"total_reviews\":0,\"total_rating\":0.0,\"days\":20138}]"

Ok got it, just need to manage the None case better. Now we just use the data of reputation when order is created, when there is an update of order state or when we create a child order we set the data to None option.
Maybe we can always add rating data to all messages related to orders? What do you think?
@Catrya @grunch

Mmmmhhh...i will try to answer to myself, maybe it was correct to have rating tagvonly in a new order event the reputation of the maker, which makes sense because the taker can see it and use it to take a decision.

After taking an order all the event update of the could be without rating tag ( or set to null or zero ), maybe just when we have a child new order from a range order we can publish it back for the new child order. The "bad" thing in this case is that rating is the same as before because users won't have sent the ratings to each other.

Let me know what you think guys... @Catrya @grunch

I agree, in the future mostro can update that order event with the new rating data, but let's not get complicated right now with that

@arkanoider

Copy link
Copy Markdown
Collaborator Author

I tested a bit on my side too, seems doing what we need now. If also @Catrya @grunch agree after testing we could merge on develop.

@Catrya

Catrya commented Feb 21, 2025

Copy link
Copy Markdown
Member

tACK @arkanoider @grunch

@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

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