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

refactor!: change rounding parameters to use defaults #89

Merged
merged 3 commits into from
Nov 9, 2024
Merged

Conversation

shuhuiluo
Copy link
Collaborator

@shuhuiluo shuhuiluo commented Nov 9, 2024

This commit updates the rounding parameters in multiple modules to use Option<Rounding> with a default value if none is specified. This change simplifies method calls and improves code flexibility by allowing optional rounding strategies.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced flexibility in rounding parameters across various methods, allowing users to specify None for rounding in CurrencyAmount, FractionBase, Percent, and Price structs.
  • Bug Fixes

    • Improved handling of default rounding strategies in methods where rounding may not be specified.
  • Documentation

    • Updated test cases to reflect changes in method signatures and ensure comprehensive coverage of new optional rounding functionality.

This commit updates the rounding parameters in multiple modules to use `Option<Rounding>` with a default value if none is specified. This change simplifies method calls and improves code flexibility by allowing optional rounding strategies.
@shuhuiluo shuhuiluo requested a review from malik672 November 9, 2024 09:06
Copy link

coderabbitai bot commented Nov 9, 2024

Walkthrough

The changes in this pull request include an update to the Cargo.toml file for the uniswap-sdk-core package, changing the version from 3.1.0 to 3.2.0. Additionally, modifications were made to several structs and traits in the codebase, specifically altering the rounding parameter in multiple methods to accept an Option<Rounding> type instead of a direct Rounding type. This change enhances the flexibility of rounding options across various functionalities without altering the core logic.

Changes

File Path Change Summary
Cargo.toml Version updated from 3.1.0 to 3.2.0. No other changes made to metadata or dependencies.
src/constants.rs Updated Rounding enum to derive Default and set RoundHalfUp as the default variant.
src/entities/fractions/currency_amount.rs Changed rounding parameter in to_significant and to_fixed methods to Option<Rounding>.
src/entities/fractions/fraction.rs Modified to_significant and to_fixed methods in FractionBase trait to accept Option<Rounding>.
src/entities/fractions/percent.rs Updated to_significant and to_fixed methods in Percent struct to accept Option<Rounding>.
src/entities/fractions/price.rs Altered to_significant and to_fixed methods in Price struct to accept Option<Rounding>.

Possibly related PRs

Suggested reviewers

  • malik672

🐇 In the meadow where bunnies hop,
A version change, we can't stop!
With rounding options, oh so neat,
Flexibility makes our work complete!
From 3.1 to 3.2 we cheer,
Hopping forward, the future is clear! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ae225e4 and 1dc9ae3.

📒 Files selected for processing (1)
  • src/constants.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/constants.rs

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

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

🧹 Outside diff range and nitpick comments (4)
src/constants.rs (1)

22-22: Consider documenting the default behavior.

Since RoundHalfUp is now the default rounding strategy when None is provided, it would be helpful to document this behavior in the enum's documentation.

 /// Represents three various ways to round
 #[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
 pub enum Rounding {
     /// Rounds down to the nearest whole number.
     RoundDown,
 
-    /// Rounds to the nearest whole number, rounding halfway cases away from zero.
+    /// Rounds to the nearest whole number, rounding halfway cases away from zero.
+    /// This is the default rounding strategy when none is specified.
     #[default]
     RoundHalfUp,
 
     /// Rounds up to the nearest whole number.
     RoundUp,
 }
src/entities/fractions/percent.rs (1)

97-107: Add test coverage for explicit rounding cases.

While the tests verify the default rounding behavior (using None), they should also cover cases where specific rounding strategies are provided via Some(Rounding).

Consider adding these test cases:

#[test]
fn test_to_significant_with_explicit_rounding() {
    assert_eq!(
        Percent::new(154, 10000)
            .to_significant(3, Some(Rounding::RoundDown))
            .unwrap(),
        "1.54".to_string()
    );
}

#[test]
fn test_to_fixed_with_explicit_rounding() {
    assert_eq!(
        Percent::new(154, 10000).to_fixed(2, Some(Rounding::RoundDown)),
        "1.54".to_string()
    );
}
src/entities/fractions/price.rs (1)

Line range hint 155-220: Enhance test coverage for rounding scenarios.

While the current tests verify the basic functionality with None rounding parameter, consider adding test cases for:

  1. Explicit rounding strategies using Some(Rounding)
  2. Edge cases where different rounding strategies would produce different results
  3. Boundary conditions where rounding becomes significant

This would ensure the new optional rounding parameter behaves correctly across all scenarios.

Example test cases to add:

#[test]
fn test_different_rounding_strategies() {
    let p = Price::new(TOKEN0.clone(), TOKEN1.clone(), 123456, 789);
    
    // Test different rounding modes
    assert_ne!(
        p.to_significant(2, Some(Rounding::RoundDown)).unwrap(),
        p.to_significant(2, Some(Rounding::RoundUp)).unwrap(),
        "Rounding strategies should produce different results for this case"
    );
    
    // Test None vs Some default
    assert_eq!(
        p.to_significant(2, None).unwrap(),
        p.to_significant(2, Some(Rounding::RoundDown)).unwrap(),
        "None should match the default rounding strategy"
    );
}
src/entities/fractions/fraction.rs (1)

124-132: LGTM! Consider documenting the default rounding behavior.

The change to make the rounding parameter optional is well-implemented using idiomatic Rust. The use of unwrap_or_default() ensures safe handling of the optional parameter.

Consider adding a doc comment to specify which rounding strategy is used by default when None is provided.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8ae28ac and a3aadc2.

📒 Files selected for processing (6)
  • Cargo.toml (1 hunks)
  • src/constants.rs (1 hunks)
  • src/entities/fractions/currency_amount.rs (2 hunks)
  • src/entities/fractions/fraction.rs (2 hunks)
  • src/entities/fractions/percent.rs (3 hunks)
  • src/entities/fractions/price.rs (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • Cargo.toml
🔇 Additional comments (5)
src/constants.rs (1)

16-16: LGTM! Note: This is a breaking change.

The addition of Default trait is well-aligned with the PR objectives to support optional rounding parameters. The version bump to 3.2.0 correctly reflects this breaking change.

Let's verify the version bump:

✅ Verification successful

Version bump to 3.2.0 confirmed

The version in Cargo.toml is correctly set to 3.2.0, which aligns with the breaking change introduced by adding the Default trait to the Rounding enum.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that Cargo.toml version has been bumped
grep -A 1 '^\[package\]' Cargo.toml | grep 'version = "3.2.0"'

Length of output: 64


Script:

#!/bin/bash
# Let's check the actual version in Cargo.toml
cat Cargo.toml | grep -A 5 '^\[package\]'

# Also check git diff to see version changes
git diff origin/main Cargo.toml | grep '^[+-]version'

Length of output: 583

src/entities/fractions/percent.rs (2)

27-27: LGTM! Method signature changes align with the refactoring goals.

The change from Rounding to Option<Rounding> improves API flexibility by allowing default rounding behavior when None is provided. The implementation correctly propagates the optional rounding parameter to the underlying Fraction methods.

Also applies to: 37-37


27-27: Verify consistent usage across the codebase.

Let's ensure all callers have been updated to handle the new Option parameter.

Also applies to: 37-37

✅ Verification successful

All usages are already compatible with Option

The search results show that all calls to to_significant() and to_fixed() across the codebase are already using the optional rounding parameter correctly:

  • All implementations accept Option<Rounding>
  • All calls either pass None or Some(Rounding::...)
  • No direct usage of Rounding:: without Option wrapping was found

The change is consistent with the existing codebase usage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining direct usage of these methods with Rounding
# This should help identify any calls that haven't been updated

echo "Searching for potential calls to to_significant that might need updating..."
rg "to_significant\([^,]+,[^,]+,\s*Rounding::"

echo "Searching for potential calls to to_fixed that might need updating..."
rg "to_fixed\([^,]+,[^,]+,\s*Rounding::"

Length of output: 401


Script:

#!/bin/bash
# Let's try a different approach to find all usages of these methods
# and verify the parameter patterns

echo "Searching for all calls to to_significant..."
rg "to_significant\(" -A 2

echo -e "\nSearching for all calls to to_fixed..."
rg "to_fixed\(" -A 2

echo -e "\nLet's also check the method definitions..."
ast-grep --pattern 'fn to_significant($$$) { $$$ }'
ast-grep --pattern 'fn to_fixed($$$) { $$$ }'

Length of output: 6723

src/entities/fractions/price.rs (1)

126-126: LGTM: Clean implementation of optional rounding parameters.

The changes to make rounding parameters optional via Option<Rounding> are well-implemented and align with the PR objectives. The implementation maintains backward compatibility while adding flexibility for callers.

Also applies to: 135-135

src/entities/fractions/fraction.rs (1)

144-145: LGTM! Verify test coverage for the optional rounding parameter.

The implementation is consistent with the changes in to_significant and follows good Rust practices.

Let's verify the test coverage for these changes:

✅ Verification successful

Test coverage exists for both to_fixed and to_significant with optional rounding parameter

The codebase shows comprehensive test coverage for both methods in multiple test cases:

  • src/entities/fractions/currency_amount.rs has test cases for both methods with None rounding parameter:
    • test_to_fixed_0_decimals: amount.to_fixed(0, None)
    • test_to_fixed_18_decimals: amount.to_fixed(9, None)
    • test_to_significant_0_decimals: amount.to_significant(4, None)
    • test_to_significant_18_decimals: amount.to_significant(9, None)

The test coverage adequately verifies the default rounding behavior when None is passed as the rounding parameter.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for the new optional rounding parameter

# Look for test cases that exercise the None case for rounding
rg -U "test.*\{.*to_(significant|fixed).*None.*\}" .

# Look for test cases that exercise the Some case for rounding
rg -U "test.*\{.*to_(significant|fixed).*Some.*\}" .

Length of output: 109


Script:

#!/bin/bash
# Let's try a broader search for test cases related to to_fixed and to_significant

# Search for test functions containing to_fixed
rg -U "fn test.*\{.*to_fixed.*\}" -A 10 .

# Search for test functions containing to_significant
rg -U "fn test.*\{.*to_significant.*\}" -A 10 .

# Also search for any usage of Rounding in tests
rg "Rounding" --type rust "tests/"

Length of output: 173


Script:

#!/bin/bash
# Let's try a different approach to find test cases
# First, let's locate all test files in the repository
fd "test.*\.rs$"

# Then search for any test-related code in the src directory
rg "#\[test\]" -A 10 "src/"

# And look for any usage of to_fixed or to_significant in the entire codebase
rg "to_(fixed|significant)" --type rust

Length of output: 45746

src/entities/fractions/currency_amount.rs Show resolved Hide resolved
src/entities/fractions/currency_amount.rs Show resolved Hide resolved
@malik672
Copy link
Owner

malik672 commented Nov 9, 2024

@shuhuiluo everything is okay, but the default for rounding should be roundDown not roundHalfUp due to safety

@shuhuiluo
Copy link
Collaborator Author

@shuhuiluo everything is okay, but the default for rounding should be roundDown not roundHalfUp due to safety

Revert your change. The default is ROUND_HALF_UP.
https://github.com/Uniswap/sdks/blob/1d845e41813dabe0a15ca6375eb7893d8f6fdd42/sdks/sdk-core/src/entities/fractions/fraction.ts#L126

@malik672
Copy link
Owner

malik672 commented Nov 9, 2024

@shuhuiluo everything is okay, but the default for rounding should be roundDown not roundHalfUp due to safety

Revert your change. The default is ROUND_HALF_UP. https://github.com/Uniswap/sdks/blob/1d845e41813dabe0a15ca6375eb7893d8f6fdd42/sdks/sdk-core/src/entities/fractions/fraction.ts#L126

it's been wrong since lmaoo

Copy link
Owner

@malik672 malik672 left a comment

Choose a reason for hiding this comment

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

will merge this, then do a pr to change it to round_half_up

@malik672 malik672 merged commit 29e893d into master Nov 9, 2024
3 checks passed
@shuhuiluo
Copy link
Collaborator Author

@shuhuiluo everything is okay, but the default for rounding should be roundDown not roundHalfUp due to safety

Revert your change. The default is ROUND_HALF_UP. https://github.com/Uniswap/sdks/blob/1d845e41813dabe0a15ca6375eb7893d8f6fdd42/sdks/sdk-core/src/entities/fractions/fraction.ts#L126

it's been wrong since lmaoo

You don't understand.

@shuhuiluo shuhuiluo deleted the rounding branch November 9, 2024 10:21
@shuhuiluo
Copy link
Collaborator Author

@shuhuiluo everything is okay, but the default for rounding should be roundDown not roundHalfUp due to safety

Revert your change. The default is ROUND_HALF_UP. https://github.com/Uniswap/sdks/blob/1d845e41813dabe0a15ca6375eb7893d8f6fdd42/sdks/sdk-core/src/entities/fractions/fraction.ts#L126

it's been wrong since lmaoo

Most people round half up for display, i.e. 0.465 to 0.47. It has nothing to do with safety.

@malik672
Copy link
Owner

malik672 commented Nov 9, 2024

@shuhuiluo everything is okay, but the default for rounding should be roundDown not roundHalfUp due to safety

Revert your change. The default is ROUND_HALF_UP. https://github.com/Uniswap/sdks/blob/1d845e41813dabe0a15ca6375eb7893d8f6fdd42/sdks/sdk-core/src/entities/fractions/fraction.ts#L126

it's been wrong since lmaoo

Most people round half up for display, i.e. 0.465 to 0.47. It has nothing to do with safety.

that's not how i think about it tbh, imagine something like 3.5 a round half will take it to 4 while a round down will take it to 3

@shuhuiluo
Copy link
Collaborator Author

@shuhuiluo everything is okay, but the default for rounding should be roundDown not roundHalfUp due to safety

Revert your change. The default is ROUND_HALF_UP. https://github.com/Uniswap/sdks/blob/1d845e41813dabe0a15ca6375eb7893d8f6fdd42/sdks/sdk-core/src/entities/fractions/fraction.ts#L126

it's been wrong since lmaoo

Most people round half up for display, i.e. 0.465 to 0.47. It has nothing to do with safety.

that's not how i think about it tbh, imagine something like 3.5 a round half will take it to 4 while a round down will take it to 3

So what? What's the purpose of to_fixed? How does it mess up safety?

@malik672
Copy link
Owner

malik672 commented Nov 9, 2024

to_fixed in my opinion is different tbh, but we should just do it the way uniswap did it

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.

2 participants