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

perf!: refactor types and replace num-bigint with fastnum #93

Merged
merged 2 commits into from
Jan 5, 2025

Conversation

shuhuiluo
Copy link
Collaborator

@shuhuiluo shuhuiluo commented Jan 5, 2025

Replace num-bigint and bigdecimal with fastnum for improved performance and simplified arithmetic operations. Updated Cargo.toml, core types, and utility functions to utilize fastnum's features and refined the API for consistency. This commits also includes enhancements in test cases and clean-ups for derived constants and methods.

Summary by CodeRabbit

  • New Features

    • Added support for new numeric types using fastnum library.
    • Introduced new utility functions for type conversions.
  • Breaking Changes

    • Updated package version to 4.0.0-rc.
    • Modified token fee handling from optional to fixed values.
    • Changed type representations for big numbers and decimals.
  • Improvements

    • Enhanced square root calculation algorithm.
    • Simplified type handling and conversions.
    • Optimized performance for large number operations.
  • Dependency Changes

    • Removed bigdecimal, num-bigint, and num-integer.
    • Added fastnum dependency.

Replace `num-bigint` and `bigdecimal` with `fastnum` for improved performance and simplified arithmetic operations. Updated `Cargo.toml`, core types, and utility functions to utilize `fastnum`'s features and refined the API for consistency. This commits also includes enhancements in test cases and clean-ups for derived constants and methods.
@shuhuiluo shuhuiluo requested a review from malik672 January 5, 2025 08:57
Copy link

coderabbitai bot commented Jan 5, 2025

Walkthrough

This pull request introduces a comprehensive update to the Uniswap SDK Core in Rust, focusing on dependency management, type conversions, and core functionality improvements. The changes include updating the package version to 4.0.0-rc, replacing existing numeric libraries with fastnum, modifying type representations, and refactoring several utility functions. The modifications span across multiple files, affecting constants, token representations, fraction handling, and utility methods.

Changes

File Change Summary
Cargo.toml - Updated package version to 4.0.0-rc
- Added fastnum dependency
- Removed bigdecimal, num-bigint, and num-integer dependencies
- Modified feature configurations
README.md - Updated dependency version to 4.0.0
src/constants.rs - Converted MAX_UINT256 from lazy static to const
src/entities/fractions/currency_amount.rs - Changed decimal_scale type from BigUint to BigInt
- Updated initialization logic and method implementations
src/entities/fractions/fraction.rs - Changed denominator type to i512!
- Updated accessor methods and arithmetic operations
src/entities/fractions/price.rs - Added fastnum import and updated scalar calculation
src/entities/token.rs - Modified TokenMeta struct to use u64 for fees
- Updated Token creation method
src/examples/token_example.rs - Changed fee parameters from None to 0 in Token instantiation
src/lib.rs - Replaced type aliases with fastnum implementations
src/utils/compute_zksync_create2_address.rs - Modified test function to change how salt is computed
src/utils/mod.rs - Added new types module and re-exported its items
src/utils/sqrt.rs - Updated sqrt function to accept BigInt directly and improved error handling
src/utils/types.rs - Added functions for converting between numeric types

Suggested reviewers

  • malik672

Possibly related PRs

Poem

🐰 A Rabbit's Ode to Code Transformation
Bits and bytes, a numeric dance,
Fastnum leaps with elegant stance,
From BigInt to i512 we glide,
Precision and speed now reside!
Code evolves, no need to fret! 🚀


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.

Updated the `BigDecimal` type alias to `fastnum::D512` for consistency. Modified the `to_big_decimal` function to account for the sign of the input, ensuring proper construction of `BigDecimal` instances.
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: 1

🧹 Nitpick comments (6)
src/utils/mod.rs (2)

5-5: Document the newly introduced types module.

Adding a dedicated types module is a great step toward better organization. However, consider including inline documentation or Rustdoc on the types module itself to help future maintainers understand its purpose and usage.


11-11: Avoid wildcard exports for clearer code.

Re-exporting everything with pub use types::*; can lead to name collisions and makes it less clear what is actually available from the module. Explicit imports improve maintainability and clarity.

src/utils/sqrt.rs (1)

39-40: Potential Floating Precision Pitfall in Tests
While casting to f64 and using sqrt().floor() up to 999 likely works fine, increasing the test range without special handling of large numbers may introduce floating-point inaccuracies. Consider a purely integer-based comparison for larger test ranges.

src/entities/token.rs (1)

12-14: Changed buy_fee_bps and sell_fee_bps to Non-Optional
Replacing Option<BigUint> with u64 removes nullable overhead and clarifies that fees must always have a numeric value. This simplifies logic across the board, but verify that zero truly represents “no fee” in all contexts.

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

148-149: Retrieving numerator and denominator by value.
Obtaining the values by value instead of reference may have a small copying overhead, but it simplifies usage. Ensure that this design decision is safe given your performance goals.

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

87-90: Returning BigInt by value in numerator/denominator.
While returning by value simplifies usage, it may incur an overhead for copies of large integers. Evaluate if returning references is more optimal for performance in tight loops.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1d2acdc and fd228d3.

📒 Files selected for processing (13)
  • Cargo.toml (1 hunks)
  • README.md (1 hunks)
  • src/constants.rs (1 hunks)
  • src/entities/fractions/currency_amount.rs (9 hunks)
  • src/entities/fractions/fraction.rs (14 hunks)
  • src/entities/fractions/price.rs (3 hunks)
  • src/entities/token.rs (8 hunks)
  • src/examples/token_example.rs (1 hunks)
  • src/lib.rs (1 hunks)
  • src/utils/compute_zksync_create2_address.rs (1 hunks)
  • src/utils/mod.rs (1 hunks)
  • src/utils/sqrt.rs (3 hunks)
  • src/utils/types.rs (1 hunks)
🔇 Additional comments (43)
src/utils/sqrt.rs (4)

2-2: Use of fastnum::i512 Import Looks Appropriate
No issues found with importing i512 from the fastnum crate.


12-27: Manual Newton's Method for Integer Square Root Appears Correct
The step-by-step approximation and early returns for special cases look correct. This implementation is straightforward, and negative inputs return an error. Be mindful of performance if this is repeatedly called on very large integers, but overall this is a solid approach.


49-50: 2^i Test Logic is Proper
Raising 2 to power i and verifying its square root ensures a solid large-integer test case.


56-57: Validation Against MAX_UINT256
Ensuring that sqrt of the maximum 256-bit integer yields the expected result (2^128 - 1) demonstrates robust coverage of edge cases.

src/utils/types.rs (3)

7-9: Constructing BigDecimal from BigInt
Using BigDecimal::from_parts with a default Context is concise. Confirm that the default context meets precision and rounding needs; for most use cases, it's sufficient, but specialized scenarios might require explicit precision.


13-15: Unwrapping on from_le_slice
Since U256 is always 32 bytes, this unwrap should never fail. Nevertheless, note that any unexpected usage outside U256 invariants would panic here. For library code, consider if there's ever a scenario it could be misused.


19-21: BigInt Conversion From U256
Creating a BigInt from a U256 by first converting to BigUint is logical. No issues found.

src/examples/token_example.rs (1)

15-16: Using Zero Fees Instead of Optional Fields
Switching from None to 0 aligns with the new TokenMeta signature. This is consistent with a simpler, always-present fee model.

src/lib.rs (1)

52-55: Updated Type Aliases to fastnum
Replacing the older numeric types with fastnum::I512, fastnum::U512, and fastnum::UD512 is consistent with the PR’s performance-focused objectives. Verify that any downstream code depending on bigdecimal or num-bigint functionalities has been fully migrated.

src/entities/token.rs (8)

7-7: Allowing Copy in TokenMeta
Making the struct Copy is generally safe when it holds only numeric and address fields. Confirm that there's no future plan to store heap-allocated data or references here.


65-66: Constructor Updates for Mandatory Fees
Switching parameters to u64 ensures no missing fees. Any advanced fee structure can be handled with more explicit design if needed.


138-139: Macro Defaults Buy/Sell Fee to 0
This macro usage enforces the new non-optional fee model. Straightforward and consistent.


149-150: Macro Defaults (Cont’d)
Identical pattern for defaulting fees to zero, robust for typical usage.


160-161: Macro Assignment of Fees to 0
Expected usage aligns with the struct’s updated definition, no concerns here.


171-172: Continuing the Macro Change
Consistent repetition of zero-fee default in the macro. Remains clear and uniform.


182-183: Exact Same Macro Pattern for Named Token
Again, sets buy and sell fees to zero by default, reflecting the new design choice.


193-194: Final Macro Variation
Same approach, finalizing the zero-fee macro usage across all expansions.

src/entities/fractions/currency_amount.rs (9)

3-3: Adopting fastnum::i512 import.
Great move towards using fastnum::i512 for larger integer arithmetic. This aligns well with the PR's objective of replacing num-bigint.


14-14: Switching decimal_scale to BigInt.
Using BigInt for the scale factor is consistent with the updated approach across the codebase. This change helps maintain a uniform numeric type strategy.


28-28: Floor division to avoid overflow.
Verifying numerator.div_floor(denominator) > MAX_UINT256 ensures an overflow boundary check. This logic appears correct, but confirm that fractional cases aren’t incorrectly handled downstream.


37-37: Using i512!(10).pow(...).
Replacing BigUint::from(10).pow(exponent) with i512!(10).pow(...) is consistent with the new fastnum-based approach and appears correct.


83-84: Constructing BigDecimal from quotient and decimal_scale.
These lines properly convert the raw quotient and scale into decimal form. The direct usage of to_big_decimal() is clear and avoids unnecessary clones.


119-119: Fraction-based to_significant/to_fixed calculations.
Using Fraction::new with decimal_scale to compute precision-limited outputs is a neat approach. Make sure any rounding edge cases are covered in tests (especially near boundaries).

Also applies to: 136-136


195-195: Boundary test with MAX_UINT256.
Creating a currency amount at the maximum boundary is a solid test for overflow. Good coverage.


202-202: Overflow test scenarios.
These lines test amounts just above MAX_UINT256. Ensuring an error is thrown or the operation panics as expected is crucial.

Also applies to: 209-209


216-218: Verifying numerator exceeding MAX_UINT256.
This is a valid test for partial fractions where the numerator is slightly above MAX_UINT256. Good to confirm we can handle intermediate values safely.

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

9-9: Importing fastnum::i512.
This aligns with the overall library switch, ensuring consistency in large-integer operations.


26-26: Default denominator to i512!(1).
Switching the default from BigInt::from(1) to i512!(1) neatly integrates the new crate.


103-103: Refactored remainder/invert/to_decimal.
These lines remove unnecessary clones by returning BigInt directly. This is cleaner, though confirm usage patterns to ensure minimal overhead.

Also applies to: 111-111, 117-117


132-138: Refined significant digits logic.
Introducing .with_rounding_mode(rounding_strategy) and carefully computing integer_digits is a good approach. Ensure edge rounding cases get tested (e.g., borderline half-ups).


147-148: Fixed decimal rounding.
Using explicit rounding mode for decimal places keeps the logic predictable. Good improvement for controlling precision.


155-155: as_fraction now constructs a simple Fraction.
Returning a fresh Fraction::new(...) avoids references to self. This improves code clarity.


182-183: Direct numeric field return.
Removing references in numerator/denominator aligns with standard Rust patterns in the rest of the code.

Also applies to: 188-189


197-197: Comparison using cross multiplication.
This pattern is standard for fraction equality and ordering checks. No immediate issues found.

Also applies to: 217-217


241-241: Arithmetic operations with cross multiplication.
The approach for fraction addition, subtraction, multiplication, and division is correct. The cross multiplication logic is well-known, but watch out for potential overflows if the multiplied parts can exceed current bounds.

Also applies to: 256-256, 262-263, 283-283, 298-298, 304-305, 331-332, 357-358

src/constants.rs (1)

28-29: Transitioning to a compile-time MAX_UINT256.
Replacing the lazy_static approach with pub const MAX_UINT256 is a solid change for performance and memory usage. This also avoids runtime initialization overhead.

Cargo.toml (3)

3-3: Bumping version to 4.0.0-rc.
Signifying a major release candidate aligns nicely with the breaking changes from num-bigint to fastnum.


13-13: Adding fastnum dependency.
This aligns with the PR's goal of replacing num-bigint. Confirm that disabling default features and enabling libm meets all your needs (e.g., no missing features that might cause issues).


19-19: Introducing a default feature array and extending std.
Providing an empty default feature set is a sensible approach to keep the crate lightweight, while extending the std feature with "fastnum/std" ensures correct integration.

Also applies to: 20-20

src/utils/compute_zksync_create2_address.rs (1)

35-35: LGTM! Ownership semantics improved

The change to pass bytes directly to keccak256 instead of &bytes is correct as it aligns better with Rust's ownership model, since keccak256 takes ownership of its input.

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

2-2: LGTM! Aligned with performance objectives

The addition of fastnum::i512 import aligns with the PR's objective of replacing num-bigint with more performant alternatives.


39-40: LGTM! Improved scalar calculations

The change from BigInt to i512 for power calculations is a good optimization:

  • Fixed-size integer operations can be more performant than arbitrary-precision
  • The range of i512 is more than sufficient for token decimal calculations (typically ≤ 18)

74-75: LGTM! Removed unnecessary clones

Good optimization by removing unnecessary .clone() calls since the values can be moved directly into the new Price constructor.

README.md Show resolved Hide resolved
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fd228d3 and bba761d.

📒 Files selected for processing (2)
  • src/lib.rs (1 hunks)
  • src/utils/types.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/types.rs
🔇 Additional comments (2)
src/lib.rs (2)

52-55: Verify numerical precision requirements with new fixed-size types.

The switch from arbitrary-precision types (num-bigint::BigInt, bigdecimal::BigDecimal) to fixed-size types (fastnum::I512, fastnum::D512) could impact numerical operations. While this change should improve performance, we need to ensure that 512 bits provide sufficient precision for all SDK use cases.

Run this script to analyze numeric literal usage and verify precision requirements:

✅ Verification successful

Fixed-size types provide sufficient precision for the codebase

Based on the analysis of numeric literals and operations in the codebase:

  1. The largest explicit numeric value found is 340282366920938463463374607431768211455 in src/utils/sqrt.rs, which fits within I512/U512.
  2. Most large numbers in the codebase are Ethereum addresses (40-character hex strings), which are well within the 512-bit capacity.
  3. BigInt operations found in the code:
    • Powers of 2 calculations in sqrt.rs
    • Operations with MAX_UINT256 in currency_amount.rs
      All these operations are within the 512-bit range.

The switch to fixed-size 512-bit types from fastnum appears safe as:

  • No arbitrary-precision arithmetic patterns were found
  • All numeric literals and operations are well within the 512-bit capacity
  • Ethereum-related calculations (addresses, amounts, etc.) naturally fit within these bounds
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for large numeric literals that might exceed I512/U512 capacity

# Search for numeric literals in the codebase
rg -n '(?:\b\d{20,}\b|0x[0-9a-fA-F]{40,}\b)' --type rust

# Search for BigInt/BigUint/BigDecimal operations that might rely on arbitrary precision
ast-grep --pattern 'BigInt::from($$$)' --lang rust
ast-grep --pattern 'BigUint::from($$$)' --lang rust
ast-grep --pattern 'BigDecimal::from($$$)' --lang rust

Length of output: 2966


52-55: Verify rounding mode compatibility.

Ensure that all rounding modes previously used with bigdecimal::RoundingMode have equivalent options in fastnum::decimal::RoundingMode to maintain consistent behavior.

Run this script to check rounding mode usage:

✅ Verification successful

Rounding modes are compatible and properly mapped

The verification shows that the rounding modes are compatible between the old and new implementations:

  1. The old Rounding enum has three variants:

    • RoundDown
    • RoundHalfUp (default)
    • RoundUp
  2. These are correctly mapped to fastnum::decimal::RoundingMode in the to_rounding_strategy function:

    • Rounding::RoundDownRoundingMode::Down
    • Rounding::RoundHalfUpRoundingMode::HalfUp
    • Rounding::RoundUpRoundingMode::Up

The mapping preserves the same rounding behavior across the codebase, maintaining consistent functionality in both Fraction and CurrencyAmount implementations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for rounding mode usage in the codebase

# Search for RoundingMode usage
ast-grep --pattern 'RoundingMode::$_' --lang rust

Length of output: 318


Script:

#!/bin/bash
# Let's check the enum definition of the old Rounding type
ast-grep --pattern 'enum Rounding {$$$}' --lang rust

# Also check the fastnum RoundingMode definition
rg -A10 'pub enum RoundingMode' 

Length of output: 88


Script:

#!/bin/bash
# Let's check for any imports or uses of the old rounding type
rg -B2 -A2 'use.*Rounding'

# And check the file where we found the rounding mode usage
cat src/entities/fractions/fraction.rs

Length of output: 13425


Script:

#!/bin/bash
# Let's check for the old Rounding enum definition and any imports
rg -B2 -A2 'enum Rounding'

# Also check for any other files that might use the Rounding enum
rg -l 'Rounding::'

Length of output: 396


Script:

#!/bin/bash
# Let's see the complete Rounding enum definition
cat src/constants.rs

# And check how it's used in currency_amount.rs
cat src/entities/fractions/currency_amount.rs

Length of output: 10123

src/lib.rs Show resolved Hide resolved
@shuhuiluo shuhuiluo closed this Jan 5, 2025
@shuhuiluo shuhuiluo reopened this Jan 5, 2025
@shuhuiluo
Copy link
Collaborator Author

Merge this fucking one first.

@malik672 malik672 merged commit 91ab1d4 into master Jan 5, 2025
5 checks passed
@shuhuiluo shuhuiluo deleted the fastnum branch January 5, 2025 15:18
@shuhuiluo shuhuiluo restored the fastnum branch January 5, 2025 15:27
@shuhuiluo shuhuiluo deleted the fastnum branch January 5, 2025 15:28
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