Skip to content

Conversation

Teebor-Choka
Copy link
Contributor

  • Fix backwards compatibility of the withdraw endpoint in currency

Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

📝 Walkthrough

Walkthrough

The pull request introduces modifications to the hoprd/rest-api/src/account.rs file, focusing on the deserialization logic for the WithdrawBodyRequest structure. A new deserialize_balance_type function is added to handle the deserialization of the currency field, replacing the previous DisplayFromStr approach. The changes include a deprecation comment for the old deserialization method and update the error handling in the balances function to manage balance retrieval more robustly.

Changes

File Change Summary
hoprd/rest-api/src/account.rs - Added deserialize_balance_type function for BalanceType deserialization
- Updated WithdrawBodyRequest currency field deserialization
- Added deprecation comment for previous deserialization method
- Improved error handling in balances function

Possibly related PRs

Suggested reviewers

  • Teebor-Choka
  • NumberFour8

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.

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.

@Teebor-Choka Teebor-Choka added the bug Something isn't working label Dec 18, 2024
@Teebor-Choka Teebor-Choka added this to the 2.2.0-rc.1 milestone Dec 18, 2024
@Teebor-Choka Teebor-Choka marked this pull request as ready for review December 18, 2024 11:46
@Teebor-Choka Teebor-Choka self-assigned this Dec 18, 2024
@Teebor-Choka Teebor-Choka requested review from NumberFour8, Jaguaras and a team December 18, 2024 11:48
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 (2)
hoprd/rest-api/src/account.rs (2)

137-148: Add test cases for case-sensitive deserialization

The function correctly handles both "Native" and "NATIVE" cases, improving backwards compatibility. However, the test suite only verifies the "HOPR" case.

Consider adding these test cases to verify all supported formats:

#[test]
fn test_balance_type_deserialization() -> anyhow::Result<()> {
    // Test existing format
    let hopr: WithdrawBodyRequest = serde_json::from_str(r#"{"currency": "HOPR", "amount": "20000", "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe"}"#)?;
    assert_eq!(hopr.currency, BalanceType::HOPR);

    // Test both native formats
    let native: WithdrawBodyRequest = serde_json::from_str(r#"{"currency": "Native", "amount": "20000", "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe"}"#)?;
    assert_eq!(native.currency, BalanceType::Native);

    let native_upper: WithdrawBodyRequest = serde_json::from_str(r#"{"currency": "NATIVE", "amount": "20000", "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe"}"#)?;
    assert_eq!(native_upper.currency, BalanceType::Native);

    // Test error case
    let error = serde_json::from_str::<WithdrawBodyRequest>(r#"{"currency": "invalid", "amount": "20000", "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe"}"#);
    assert!(error.is_err());

    Ok(())
}

159-160: Update schema example to document all supported formats

The schema example only shows one format ("HOPR"), but the API now supports multiple formats for the currency field ("Native"/"NATIVE").

Update the schema example to document all supported formats:

 #[schema(example = json!({
         "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
         "amount": "20000",
-        "currency": "HOPR"
+        "currency": "HOPR"  // Supported values: "HOPR", "Native", "NATIVE"
     }))]
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be3ea04 and b8a054a.

📒 Files selected for processing (1)
  • hoprd/rest-api/src/account.rs (2 hunks)
🔇 Additional comments (1)
hoprd/rest-api/src/account.rs (1)

Line range hint 137-160: Verify existing API usage patterns

Let's verify how the withdraw endpoint is currently being used to ensure we maintain compatibility.

✅ Verification successful

Based on the gathered information, I can now provide the final response:

Backwards compatibility is maintained for the withdraw endpoint

The changes to the balance type deserialization maintain compatibility with existing clients:

  • The Python client implementation in tests/hopr.py uses the string format for currency ("Native" or "HOPR")
  • Integration tests in test_integration.py demonstrate working functionality with "Native" currency type
  • The deserializer explicitly handles both "Native" and "NATIVE" case variants, ensuring backward compatibility
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for withdraw endpoint usage in tests and examples
rg -A 2 -B 2 'currency.*(?:NATIVE|Native|HOPR)' --type rust

# Search for any HTTP client implementations that might be using the endpoint
rg -A 5 '/account/withdraw' --type typescript --type javascript --type python

Length of output: 1309


Script:

#!/bin/bash
# Let's search for test files and client implementations with more inclusive patterns
rg -A 5 "withdraw" --type rust

# Search for any HTTP client implementations with proper file extensions
rg -A 5 '/account/withdraw' -g '*.ts' -g '*.js' -g '*.py'

# Look for API tests specifically
fd -e test.ts -e test.js -e test.py -e test.rs | xargs rg -l "withdraw"

# Check for any OpenAPI/Swagger definitions that might document the endpoint
fd -e yaml -e json | xargs rg -l "withdraw"

Length of output: 42318


Script:

#!/bin/bash
# Let's check for test files that specifically test the withdraw endpoint
rg -A 5 -B 5 "test.*withdraw" tests/

# Look for any Python client usage of the withdraw endpoint
rg -A 5 "withdraw" tests/hopr.py

# Check for any API documentation or OpenAPI specs
fd -e yaml -e json | xargs rg -A 5 "/account/withdraw"

Length of output: 1287

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

🔭 Outside diff range comments (1)
hoprd/rest-api/src/account.rs (1)

Line range hint 223-242: Add test cases for backwards compatibility

The current test only covers the "HOPR" case. To ensure backwards compatibility, we should add test cases for both "Native" and "NATIVE" variants.

Add these test cases:

#[test]
fn withdraw_input_should_support_native_variants() -> anyhow::Result<()> {
    // Test lowercase "Native"
    let native: WithdrawBodyRequest = serde_json::from_str(
        r#"{
        "currency": "Native",
        "amount": "20000",
        "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe"}"#,
    )?;
    assert_eq!(native.currency, BalanceType::Native);

    // Test uppercase "NATIVE"
    let NATIVE: WithdrawBodyRequest = serde_json::from_str(
        r#"{
        "currency": "NATIVE",
        "amount": "20000",
        "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe"}"#,
    )?;
    assert_eq!(NATIVE.currency, BalanceType::Native);

    Ok(())
}
🧹 Nitpick comments (2)
hoprd/rest-api/src/account.rs (2)

143-147: Improve error message for invalid balance types

The error message for invalid balance types could be more helpful by listing the supported values.

-        _ => Err(serde::de::Error::custom("Unsupported balance type")),
+        _ => Err(serde::de::Error::custom("Unsupported balance type. Expected 'Native', 'NATIVE', or 'HOPR'")),

159-160: Remove commented-out code

The old implementation using DisplayFromStr should be removed rather than commented out, as it's being replaced by the new deserialization approach.

-    // #[serde_as(as = "DisplayFromStr")]
     #[serde(deserialize_with = "deserialize_balance_type")]
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be3ea04 and b8a054a.

📒 Files selected for processing (1)
  • hoprd/rest-api/src/account.rs (2 hunks)
🔇 Additional comments (1)
hoprd/rest-api/src/account.rs (1)

137-148: Verify all currency field usages in the codebase

Let's ensure there are no other places in the codebase that might be affected by this change in currency field deserialization.

✅ Verification successful

Let me gather more context about the BalanceType usage to ensure we have a complete picture.


Based on the comprehensive search results, I can now provide a final response regarding the currency field deserialization changes:

Currency field deserialization changes are properly contained

The implementation of deserialize_balance_type in hoprd/rest-api/src/account.rs is the only place where currency/balance type deserialization is handled in the REST API. All other usages of BalanceType in the codebase are internal enum usages that are not affected by the deserialization changes.

  • The change only affects how external JSON requests are parsed in the REST API
  • All internal usages of BalanceType use the enum variants directly
  • No other parts of the codebase rely on string-based deserialization of balance types
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential currency field usages that might need similar handling
rg -l 'currency.*BalanceType' --type rust

# Search for similar struct definitions that might need the same treatment
ast-grep --pattern 'struct $_ {
  $$$
  currency: BalanceType,
  $$$
}'

Length of output: 286


Script:

#!/bin/bash
# Search for all BalanceType usages and their context
rg -A 5 -B 5 'BalanceType' --type rust

# Search for any serialization/deserialization of BalanceType
ast-grep --pattern 'impl $_ for BalanceType'

Length of output: 108220

@Teebor-Choka Teebor-Choka merged commit 10ecce3 into master Dec 18, 2024
41 of 46 checks passed
@Teebor-Choka Teebor-Choka deleted the kauki/merge-back/2.1.5 branch December 18, 2024 16:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working crate:hoprd-api
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants