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

feat(math): Upstream GDA based decimal type - errors #20827

Merged
merged 1 commit into from
Jul 3, 2024

Conversation

samricotta
Copy link
Contributor

@samricotta samricotta commented Jul 1, 2024

Description

Closes: #XXXX


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Introduced new Dec decimal type, providing enhanced precision and performance over LegacyDec.
    • Added conversion functions between LegacyDec and Dec.
    • Implemented comprehensive arithmetic operations, comparison methods, and precision handling for Dec.
  • Documentation

    • Added documentation detailing the transition from LegacyDec to Dec with emphasis on precision, format, and performance improvements.
  • Tests

    • Added benchmark tests to compare LegacyDec and Dec performance.
    • Introduced property-based tests for validating Dec operations.
  • Chores

    • Updated dependencies across multiple modules to ensure compatibility with the new Dec type.

@samricotta samricotta requested a review from a team as a code owner July 1, 2024 08:10
Copy link
Contributor

coderabbitai bot commented Jul 1, 2024

Warning

Review failed

Failed to post review comments.

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between db09ef5 and c3fe8ba.

Files ignored due to path filters (3)
  • go.sum is excluded by !**/*.sum
  • math/go.sum is excluded by !**/*.sum
  • x/group/go.sum is excluded by !**/*.sum
Files selected for processing (12)
  • docs/build/building-modules/18-decimal-handling.md (1 hunks)
  • go.mod (2 hunks)
  • math/dec.go (1 hunks)
  • math/dec_bench_test.go (1 hunks)
  • math/dec_legacy.go (1 hunks)
  • math/dec_legacy_test.go (1 hunks)
  • math/dec_rapid_test.go (1 hunks)
  • math/dec_test.go (1 hunks)
  • math/go.mod (1 hunks)
  • math/math.go (1 hunks)
  • x/group/go.mod (8 hunks)
  • x/group/internal/math/dec.go (1 hunks)
Files not summarized due to errors (2)
  • math/dec_legacy_test.go: Error: Message exceeds token limit
  • math/dec_test.go: Error: Message exceeds token limit
Files not reviewed due to errors (1)
  • math/dec_rapid_test.go (no review received)
Files skipped from review due to trivial changes (1)
  • math/go.mod
Additional context used
Path-based instructions (9)
math/math.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/group/internal/math/dec.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

docs/build/building-modules/18-decimal-handling.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

math/dec.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

math/dec_bench_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

math/dec_rapid_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

math/dec_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

math/dec_legacy.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

math/dec_legacy_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

LanguageTool
docs/build/building-modules/18-decimal-handling.md

[uncategorized] ~18-~18: Possible missing comma found.
Context: ...ec` operations are safer for concurrent use as they do not mutate the original valu...

(AI_HYDRA_LEO_MISSING_COMMA)


[typographical] ~25-~25: Consider adding a comma after this introductory phrase.
Context: ...y use Dec without any changes. As an example we will use DecCoin which is a common...

(AS_A_NN_COMMA)


[uncategorized] ~116-~116: Possible missing comma found.
Context: ... LegacyDec to a Dec without a state migration changing how the data is handled intern...

(AI_HYDRA_LEO_MISSING_COMMA)

Markdownlint
docs/build/building-modules/18-decimal-handling.md

45-45: Column: 1
Hard tabs

(MD010, no-hard-tabs)


27-27: Expected: 1; Actual: 2
Multiple consecutive blank lines

(MD012, no-multiple-blanks)


130-130: Expected: 1; Actual: 2
Multiple consecutive blank lines

(MD012, no-multiple-blanks)

Additional comments not posted (106)
math/math.go (4)

20-23: LGTM!

The Add function correctly adds two Dec values and returns the result. The error handling is appropriate.


25-38: LGTM!

The SubNonNegative function correctly subtracts y from x and returns an error if the result is negative. The error handling and logic are appropriate.


40-54: LGTM!

The SafeSubBalance function correctly subtracts y from x with arbitrary precision and returns an error if the result is negative. The error handling and logic are appropriate.


56-73: LGTM!

The SafeAddBalance function correctly adds x and y with arbitrary precision and returns an error if either value is negative. The error handling and logic are appropriate.

x/group/internal/math/dec.go (7)

Line range hint 17-23: LGTM!

The NewPositiveDecFromString function correctly creates a new Dec from a string and ensures it is positive. The error handling and logic are appropriate.


Line range hint 25-31: LGTM!

The NewNonNegativeDecFromString function correctly creates a new Dec from a string and ensures it is non-negative. The error handling and logic are appropriate.


Line range hint 37-46: LGTM!

The NewDecFromString function correctly creates a new Dec from a string and ensures it is a finite number. The error handling and logic are appropriate.


Line range hint 60-64: LGTM!

The Add function correctly adds two Dec values and returns the result with error handling for overflow. The logic and error handling are appropriate.


Line range hint 66-70: LGTM!

The Sub function correctly subtracts y from x and returns the result with error handling for overflow. The logic and error handling are appropriate.


Line range hint 87-92: LGTM!

The Quo function correctly divides x by y and returns the result with error handling for overflow. The logic and error handling are appropriate.


Line range hint 94-106: LGTM!

The SubNonNegative function correctly subtracts y from x and returns an error if the result is negative. The error handling and logic are appropriate.

docs/build/building-modules/18-decimal-handling.md (7)

1-14: LGTM!

The introduction section clearly explains the transition from LegacyDec to Dec and the reasons for the change. The content is clear and informative.


15-19: LGTM! Consider adding a comma.

The section explains the benefits of using Dec over LegacyDec. The content is clear and informative. Consider adding a comma after "concurrent use".

- `Dec` operations are safer for concurrent use as they do not mutate the original values.
+ `Dec` operations are safer for concurrent use, as they do not mutate the original values.
Tools
LanguageTool

[uncategorized] ~18-~18: Possible missing comma found.
Context: ...ec` operations are safer for concurrent use as they do not mutate the original valu...

(AI_HYDRA_LEO_MISSING_COMMA)


21-25: LGTM! Consider adding a comma.

The section explains how to use Dec in new modules and provides an example. Consider adding a comma after "As an example".

- As an example we will use `DecCoin` which is a common type used in the Cosmos SDK.
+ As an example, we will use `DecCoin` which is a common type used in the Cosmos SDK.
Tools
LanguageTool

[typographical] ~25-~25: Consider adding a comma after this introductory phrase.
Context: ...y use Dec without any changes. As an example we will use DecCoin which is a common...

(AS_A_NN_COMMA)


51-53: LGTM!

The section explains the steps required to migrate from LegacyDec to Dec. The content is clear and informative.


55-61: LGTM!

The section explains the differences in precision handling between LegacyDec and Dec. The content is clear and informative.


62-74: LGTM!

The section provides examples of byte representation changes due to different precision handling. The content is clear and informative.


114-128: LGTM! Consider adding a comma.

The section explains how to convert LegacyDec to Dec without state migration and provides example code. Consider adding a comma after "without a state migration".

- If you would like to convert a `LegacyDec` to a `Dec` without a state migration changing how the data is handled internally within the application logic and not how it's stored or represented.
+ If you would like to convert a `LegacyDec` to a `Dec` without a state migration, changing how the data is handled internally within the application logic and not how it's stored or represented.
Tools
LanguageTool

[uncategorized] ~116-~116: Possible missing comma found.
Context: ... LegacyDec to a Dec without a state migration changing how the data is handled intern...

(AI_HYDRA_LEO_MISSING_COMMA)

x/group/go.mod (2)

Line range hint 3-36: LGTM!

The dependency updates in the require section appear correct and consistent with the rest of the changes in the PR.


Line range hint 167-176: LGTM!

The module replacements in the replace section appear correct and consistent with the rest of the changes in the PR.

math/dec.go (17)

78-97: Ensure edge cases are handled and constraints are applied correctly.

The NewDecFromString method correctly handles edge cases such as NaN, signaling NaN, and infinite values. It also applies constraints provided as variadic arguments. Ensure that all constraints are properly tested.


101-104: LGTM!

The NewDecFromInt64 method correctly initializes a Dec from an int64 value.


107-111: LGTM!

The NewDecWithPrec method correctly initializes a Dec with a specified coefficient and exponent.


114-124: LGTM!

The Add method correctly performs an addition operation between two Dec values and handles errors appropriately.


151-163: LGTM!

The MulExact method correctly performs a multiplication operation without rounding and handles errors appropriately.


179-187: LGTM!

The QuoInteger method correctly performs an integer division operation between two Dec values and handles errors appropriately.


206-209: LGTM!

The Int64 method correctly converts a Dec to an int64 value.


212-222: LGTM!

The BigInt method correctly converts a Dec to a *big.Int value and handles errors appropriately.


224-242: LGTM!

The SdkIntTrim method correctly rounds a Dec towards zero and converts it to sdkmath.Int. It handles negative values appropriately.


245-246: LGTM!

The String method correctly converts a Dec to its string representation.


249-255: LGTM!

The Cmp method correctly compares two Dec values and returns the result.


258-259: LGTM!

The Equal method correctly checks if two Dec values are equal.


262-264: LGTM!

The IsZero method correctly checks if a Dec value is zero.


267-269: LGTM!

The IsNegative method correctly checks if a Dec value is negative.


272-274: LGTM!

The IsPositive method correctly checks if a Dec value is positive.


198-203: Fix error wrapping in Mul method.

The Mul method incorrectly wraps the error. Remove the wrapping.

-	return z, errors.Wrap(err, "decimal multiplication error")
+	return z, nil

Likely invalid or redundant comment.


190-195: Fix error wrapping in Rem method.

The Rem method incorrectly wraps the error. Remove the wrapping.

-	return z, errors.Wrap(err, "decimal remainder error")
+	return z, nil

Likely invalid or redundant comment.

go.mod (2)

81-81: Dependency update: github.com/cockroachdb/apd/v3

The dependency for github.com/cockroachdb/apd/v3 has been updated to version v3.2.1. Ensure compatibility with the rest of the codebase.


191-191: Module replacement: cosmossdk.io/math

The module cosmossdk.io/math is replaced with a local path ./math. Ensure this replacement is temporary and will be updated with the final version.

math/dec_bench_test.go (4)

1-7: Ensure sufficient benchmark coverage.

The benchmark tests cover various arithmetic operations and serialization for both LegacyDec and Dec. Ensure that all critical operations are benchmarked.


9-63: LGTM!

The benchmark BenchmarkCompareLegacyDecAndNewDecQuotient correctly compares the performance of division operations between LegacyDec and Dec.


65-120: LGTM!

The benchmark BenchmarkCompareLegacyDecAndNewDecSum correctly compares the performance of addition operations between LegacyDec and Dec.


122-179: LGTM!

The benchmark BenchmarkCompareLegacyDecAndNewDecSub correctly compares the performance of subtraction operations between LegacyDec and Dec.

math/dec_test.go (13)

14-124: LGTM! Comprehensive test coverage for NewDecFromString.

The test cases cover various scenarios for the NewDecFromString function, ensuring robust validation of expected outcomes.


128-160: LGTM! Comprehensive test coverage for NewDecFromInt64.

The test cases cover various scenarios for the NewDecFromInt64 function, ensuring robust validation of expected outcomes.


164-271: LGTM! Comprehensive test coverage for Add.

The test cases cover various scenarios for the Add function, ensuring robust validation of expected outcomes.


275-408: LGTM! Comprehensive test coverage for Sub.

The test cases cover various scenarios for the Sub function, ensuring robust validation of expected outcomes.


412-506: LGTM! Comprehensive test coverage for Quo.

The test cases cover various scenarios for the Quo function, ensuring robust validation of expected outcomes.


510-604: LGTM! Comprehensive test coverage for QuoExact.

The test cases cover various scenarios for the QuoExact function, ensuring robust validation of expected outcomes.


608-702: LGTM! Comprehensive test coverage for QuoInteger.

The test cases cover various scenarios for the QuoInteger function, ensuring robust validation of expected outcomes.


718-764: LGTM! Comprehensive test coverage for Reduce.

The test cases cover various scenarios for the Reduce function, ensuring robust validation of expected outcomes.


768-842: LGTM! Comprehensive test coverage for MulExact.

The test cases cover various scenarios for the MulExact function, ensuring robust validation of expected outcomes.


846-867: LGTM! Comprehensive test coverage for BigInt.

The test cases cover various scenarios for the BigInt function, ensuring robust validation of expected outcomes.


871-891: LGTM! Comprehensive test coverage for SdkIntTrim.

The test cases cover various scenarios for the SdkIntTrim function, ensuring robust validation of expected outcomes.


896-899: LGTM! Test coverage for invalid decimal string "inf".

The test case ensures that invalid decimal strings like "inf" are correctly handled.


902-906: LGTM! Simple and effective error handling helper.

The must function is correctly implemented to panic if an error occurs.

math/dec_legacy.go (20)

1-11: LGTM!

The package and import statements are correct and include all necessary packages.


13-36: LGTM!

The LegacyDec struct and constants are well-defined and provide necessary precision and configuration.


38-61: LGTM!

The variable declarations and init function are correct and initialize necessary precision multipliers and other constants.


63-95: LGTM!

The utility functions for precision multipliers are well-defined and provide necessary precision handling.


97-137: LGTM!

The LegacyNewDec and related functions are well-defined and provide necessary constructors for LegacyDec.


139-211: LGTM!

The LegacyNewDecFromStr and related functions are well-defined and handle string conversion to LegacyDec correctly.


213-227: LGTM!

The LegacyDec methods for checking value properties are well-defined and provide necessary value property checks and operations.


229-246: LGTM!

The BigInt and BigIntMut methods are well-defined and provide necessary conversions to big.Int.


248-261: LGTM!

The ImmutOp, ImmutOpInt, and ImmutOpInt64 methods are well-defined and provide necessary immutable operations for LegacyDec.


263-267: LGTM!

The SetInt64 method is well-defined and provides necessary conversion from int64 to LegacyDec.


269-373: LGTM!

The arithmetic operation methods are well-defined and provide necessary arithmetic operations for LegacyDec.


375-449: LGTM!

The quotient operation methods are well-defined and provide necessary quotient operations for LegacyDec.


451-529: LGTM!

The ApproxRoot, Power, PowerMut, and ApproxSqrt methods are well-defined and provide necessary root and power operations for LegacyDec.


531-593: LGTM!

The IsInteger, Format, and String methods are well-defined and provide necessary string and format operations for LegacyDec.


596-610: LGTM!

The Float64 and MustFloat64 methods are well-defined and provide necessary float conversion operations for LegacyDec.


612-707: LGTM!

The precision chopping methods are well-defined and provide necessary precision chopping operations for LegacyDec.


684-727: LGTM!

The rounding and truncation methods are well-defined and provide necessary rounding and truncation operations for LegacyDec.


729-748: LGTM!

The Ceil method is well-defined and provides necessary ceiling operation for LegacyDec.


751-787: LGTM!

The LegacyMaxSortableDec, LegacyValidSortableDec, and LegacySortableDecBytes methods are well-defined and provide necessary sortable operations for LegacyDec.


789-893: LGTM!

The JSON and YAML marshal/unmarshal methods are well-defined and provide necessary serialization and deserialization operations for LegacyDec.

math/dec_legacy_test.go (30)

23-25: LGTM!

The test suite initialization is correctly implemented.


27-48: LGTM!

The test cases for approximate equality are well-defined and cover various scenarios.


50-56: LGTM!

The helper function for creating LegacyDec values from strings is correctly implemented.


58-119: LGTM!

The test cases for creating LegacyDec values from strings are comprehensive and well-defined.


122-139: LGTM!

The test cases for the string representation of LegacyDec values are well-defined and cover various scenarios.


141-161: LGTM!

The test cases for the float64 conversion of LegacyDec values are well-defined and cover various scenarios.


163-196: LGTM!

The test cases for comparisons of LegacyDec values are well-defined and cover various scenarios.


199-219: LGTM!

The test cases for the equality of slices of LegacyDec values are well-defined and cover various scenarios.


221-290: LGTM!

The test cases for arithmetic operations on LegacyDec values are comprehensive and well-defined.


293-306: LGTM!

The test cases for MulRoundUp and MulTruncate methods are well-defined and cover edge cases.


308-331: LGTM!

The test cases for the banker’s rounding method are well-defined and cover various scenarios.


334-357: LGTM!

The test cases for truncation behavior are well-defined and cover various scenarios.


360-371: LGTM!

The test case for string conversion involving large numbers is well-defined and correctly implemented.


373-387: LGTM!

The test cases for multiplication with integers are well-defined and cover various scenarios.


390-409: LGTM!

The test cases for the ceiling method are well-defined and cover various scenarios.


411-417: LGTM!

The test case for overflow scenarios in the ceiling method is well-defined and correctly implemented.


419-443: LGTM!

The test cases for the power method are well-defined and cover various scenarios.


446-473: LGTM!

The test cases for the approximate root method are well-defined and cover various scenarios.


476-498: LGTM!

The test cases for the approximate square root method are well-defined and cover various scenarios.


501-524: LGTM!

The test cases for the sortable byte representation are well-defined and cover various scenarios.


526-610: LGTM!

The test cases for encoding and decoding LegacyDec values are well-defined and cover various scenarios.


613-619: LGTM!

The test cases for different orders of operations are well-defined and correctly implemented.


621-650: LGTM!

The benchmark cases for the MarshalTo method are well-defined and correctly implemented.


654-667: LGTM!

The benchmark case for the QuoMut method is well-defined and correctly implemented.


669-682: LGTM!

The benchmark case for the QuoTruncateMut method is well-defined and correctly implemented.


684-695: LGTM!

The benchmark case for the ApproxSqrt method on a Mersenne prime is well-defined and correctly implemented.


698-711: LGTM!

The benchmark case for the QuoRoundupMut method is well-defined and correctly implemented.


713-729: LGTM!

The test cases for the FormatDec method are well-defined and cover various scenarios.


731-757: LGTM!

The test cases for handling invalid decimal strings are well-defined and correctly implemented.


760-763: LGTM!

The test case for negative precision values is well-defined and correctly implemented.

Comments failed to post (6)
math/dec_test.go

706-706: Reminder: Add tests for Rem.

The TODO comment indicates that tests are missing.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?


710-710: Reminder: Add tests for NumDecimalPlaces.

The TODO comment indicates that tests are missing.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?


714-716: Reminder: Add tests for Cmp.

The TODO comment indicates that tests are missing.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?

math/dec.go

126-136: Fix error wrapping in Sub method.

The Sub method incorrectly wraps the error twice. Remove the second wrapping.

-	return z, errors.Wrap(err, "decimal subtraction error")
+	return z, nil
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

// Sub returns a new Dec with value `x-y` without mutating any argument and error if
// there is an overflow.
func (x Dec) Sub(y Dec) (Dec, error) {
	var z Dec
	_, err := apd.BaseContext.Sub(&z.dec, &x.dec, &y.dec)

	if err != nil {
		return Dec{}, ErrInvalidDec.Wrap(err.Error())
	}

	return z, nil

139-148: Fix error wrapping in Quo method.

The Quo method incorrectly wraps the error twice. Remove the second wrapping.

-	return z, errors.Wrap(err, "decimal quotient error")
+	return z, nil
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

// Quo returns a new Dec with value `x/y` (formatted as decimal128, 34 digit precision) without mutating any
// argument and error if there is an overflow.
func (x Dec) Quo(y Dec) (Dec, error) {
	var z Dec
	_, err := dec128Context.Quo(&z.dec, &x.dec, &y.dec)
	if err != nil {
		return Dec{}, ErrInvalidDec.Wrap(err.Error())
	}

	return z, nil

166-176: Fix error wrapping in QuoExact method.

The QuoExact method incorrectly wraps the error twice. Remove the second wrapping.

-	return z, errors.Wrap(err, "decimal quotient error")
+	return z, nil
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

// QuoExact is a version of Quo that returns ErrUnexpectedRounding if any rounding occurred.
func (x Dec) QuoExact(y Dec) (Dec, error) {
	var z Dec
	condition, err := dec128Context.Quo(&z.dec, &x.dec, &y.dec)
	if err != nil {
		return z, ErrInvalidDec.Wrap(err.Error())
	}
	if condition.Rounded() {
		return z, ErrUnexpectedRounding
	}
	return z, nil
Walkthrough

Walkthrough

The changes focus on replacing the older LegacyDec decimal type with a more efficient and precise Dec type in the Cosmos SDK. This transformation spans various files and involves updating protobuf messaging, introducing new conversion functions, altering mathematical operations, refining error handling, and updating benchmarks and tests to align with the new Dec structure. These enhancements aim to improve precision, performance, and maintainability.

Changes

Files/Paths Change Summary
docs/build/building-modules/... Added documentation explaining the transition from LegacyDec to Dec and necessary state migration.
protobuf Updated DecCoin message type to use Dec instead of LegacyDec.
go.mod Added and updated various dependencies including github.com/cockroachdb/apd/v3.
math/dec.go Introduced Dec struct, new arithmetic operations, error handling, and precision control functions.
math/dec_bench_test.go, dec_rapid_test.go Added benchmark and property-based tests for new decimal operations compared to legacy decimals.
math/dec_legacy.go Re-introduced LegacyDec type for backward compatibility, with numerous utility functions.
math/math.go Introduced helper functions for mathematical calculations and parsing in the ecocredit module.
x/group/go.mod Updated dependencies to align with the changes and the Go version to 1.22.

Sequence Diagram(s)

No sequence diagrams are needed as the changes are mostly internal enhancements and refactoring without significant changes to the control flow.

Possibly related issues


Tip

Early access features: enabled

We are currently testing the following features in early access:

  • OpenAI gpt-4o model for code reviews and chat: OpenAI claims that this model is better at understanding and generating code than the previous models. We seek your feedback over the next few weeks before making it generally available.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues.
  • OSS projects are currently opted into early access features by default.

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@samricotta samricotta changed the base branch from main to sam/dec-type July 1, 2024 08:10
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: 6

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between db09ef5 and c3fe8ba.

Files ignored due to path filters (3)
  • go.sum is excluded by !**/*.sum
  • math/go.sum is excluded by !**/*.sum
  • x/group/go.sum is excluded by !**/*.sum
Files selected for processing (12)
  • docs/build/building-modules/18-decimal-handling.md (1 hunks)
  • go.mod (2 hunks)
  • math/dec.go (1 hunks)
  • math/dec_bench_test.go (1 hunks)
  • math/dec_legacy.go (1 hunks)
  • math/dec_legacy_test.go (1 hunks)
  • math/dec_rapid_test.go (1 hunks)
  • math/dec_test.go (1 hunks)
  • math/go.mod (1 hunks)
  • math/math.go (1 hunks)
  • x/group/go.mod (8 hunks)
  • x/group/internal/math/dec.go (1 hunks)
Files not summarized due to errors (2)
  • math/dec_legacy_test.go: Error: Message exceeds token limit
  • math/dec_test.go: Error: Message exceeds token limit
Files not reviewed due to errors (1)
  • math/dec_rapid_test.go (no review received)
Files skipped from review due to trivial changes (1)
  • math/go.mod
Additional context used
Path-based instructions (9)
math/math.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/group/internal/math/dec.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

docs/build/building-modules/18-decimal-handling.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

math/dec.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

math/dec_bench_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

math/dec_rapid_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

math/dec_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

math/dec_legacy.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

math/dec_legacy_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

LanguageTool
docs/build/building-modules/18-decimal-handling.md

[uncategorized] ~18-~18: Possible missing comma found.
Context: ...ec` operations are safer for concurrent use as they do not mutate the original valu...

(AI_HYDRA_LEO_MISSING_COMMA)


[typographical] ~25-~25: Consider adding a comma after this introductory phrase.
Context: ...y use Dec without any changes. As an example we will use DecCoin which is a common...

(AS_A_NN_COMMA)


[uncategorized] ~116-~116: Possible missing comma found.
Context: ... LegacyDec to a Dec without a state migration changing how the data is handled intern...

(AI_HYDRA_LEO_MISSING_COMMA)

Markdownlint
docs/build/building-modules/18-decimal-handling.md

45-45: Column: 1
Hard tabs

(MD010, no-hard-tabs)


27-27: Expected: 1; Actual: 2
Multiple consecutive blank lines

(MD012, no-multiple-blanks)


130-130: Expected: 1; Actual: 2
Multiple consecutive blank lines

(MD012, no-multiple-blanks)

Additional comments not posted (106)
math/math.go (4)

20-23: LGTM!

The Add function correctly adds two Dec values and returns the result. The error handling is appropriate.


25-38: LGTM!

The SubNonNegative function correctly subtracts y from x and returns an error if the result is negative. The error handling and logic are appropriate.


40-54: LGTM!

The SafeSubBalance function correctly subtracts y from x with arbitrary precision and returns an error if the result is negative. The error handling and logic are appropriate.


56-73: LGTM!

The SafeAddBalance function correctly adds x and y with arbitrary precision and returns an error if either value is negative. The error handling and logic are appropriate.

x/group/internal/math/dec.go (7)

Line range hint 17-23: LGTM!

The NewPositiveDecFromString function correctly creates a new Dec from a string and ensures it is positive. The error handling and logic are appropriate.


Line range hint 25-31: LGTM!

The NewNonNegativeDecFromString function correctly creates a new Dec from a string and ensures it is non-negative. The error handling and logic are appropriate.


Line range hint 37-46: LGTM!

The NewDecFromString function correctly creates a new Dec from a string and ensures it is a finite number. The error handling and logic are appropriate.


Line range hint 60-64: LGTM!

The Add function correctly adds two Dec values and returns the result with error handling for overflow. The logic and error handling are appropriate.


Line range hint 66-70: LGTM!

The Sub function correctly subtracts y from x and returns the result with error handling for overflow. The logic and error handling are appropriate.


Line range hint 87-92: LGTM!

The Quo function correctly divides x by y and returns the result with error handling for overflow. The logic and error handling are appropriate.


Line range hint 94-106: LGTM!

The SubNonNegative function correctly subtracts y from x and returns an error if the result is negative. The error handling and logic are appropriate.

docs/build/building-modules/18-decimal-handling.md (7)

1-14: LGTM!

The introduction section clearly explains the transition from LegacyDec to Dec and the reasons for the change. The content is clear and informative.


15-19: LGTM! Consider adding a comma.

The section explains the benefits of using Dec over LegacyDec. The content is clear and informative. Consider adding a comma after "concurrent use".

- `Dec` operations are safer for concurrent use as they do not mutate the original values.
+ `Dec` operations are safer for concurrent use, as they do not mutate the original values.
Tools
LanguageTool

[uncategorized] ~18-~18: Possible missing comma found.
Context: ...ec` operations are safer for concurrent use as they do not mutate the original valu...

(AI_HYDRA_LEO_MISSING_COMMA)


21-25: LGTM! Consider adding a comma.

The section explains how to use Dec in new modules and provides an example. Consider adding a comma after "As an example".

- As an example we will use `DecCoin` which is a common type used in the Cosmos SDK.
+ As an example, we will use `DecCoin` which is a common type used in the Cosmos SDK.
Tools
LanguageTool

[typographical] ~25-~25: Consider adding a comma after this introductory phrase.
Context: ...y use Dec without any changes. As an example we will use DecCoin which is a common...

(AS_A_NN_COMMA)


51-53: LGTM!

The section explains the steps required to migrate from LegacyDec to Dec. The content is clear and informative.


55-61: LGTM!

The section explains the differences in precision handling between LegacyDec and Dec. The content is clear and informative.


62-74: LGTM!

The section provides examples of byte representation changes due to different precision handling. The content is clear and informative.


114-128: LGTM! Consider adding a comma.

The section explains how to convert LegacyDec to Dec without state migration and provides example code. Consider adding a comma after "without a state migration".

- If you would like to convert a `LegacyDec` to a `Dec` without a state migration changing how the data is handled internally within the application logic and not how it's stored or represented.
+ If you would like to convert a `LegacyDec` to a `Dec` without a state migration, changing how the data is handled internally within the application logic and not how it's stored or represented.
Tools
LanguageTool

[uncategorized] ~116-~116: Possible missing comma found.
Context: ... LegacyDec to a Dec without a state migration changing how the data is handled intern...

(AI_HYDRA_LEO_MISSING_COMMA)

x/group/go.mod (2)

Line range hint 3-36: LGTM!

The dependency updates in the require section appear correct and consistent with the rest of the changes in the PR.


Line range hint 167-176: LGTM!

The module replacements in the replace section appear correct and consistent with the rest of the changes in the PR.

math/dec.go (17)

78-97: Ensure edge cases are handled and constraints are applied correctly.

The NewDecFromString method correctly handles edge cases such as NaN, signaling NaN, and infinite values. It also applies constraints provided as variadic arguments. Ensure that all constraints are properly tested.


101-104: LGTM!

The NewDecFromInt64 method correctly initializes a Dec from an int64 value.


107-111: LGTM!

The NewDecWithPrec method correctly initializes a Dec with a specified coefficient and exponent.


114-124: LGTM!

The Add method correctly performs an addition operation between two Dec values and handles errors appropriately.


151-163: LGTM!

The MulExact method correctly performs a multiplication operation without rounding and handles errors appropriately.


179-187: LGTM!

The QuoInteger method correctly performs an integer division operation between two Dec values and handles errors appropriately.


206-209: LGTM!

The Int64 method correctly converts a Dec to an int64 value.


212-222: LGTM!

The BigInt method correctly converts a Dec to a *big.Int value and handles errors appropriately.


224-242: LGTM!

The SdkIntTrim method correctly rounds a Dec towards zero and converts it to sdkmath.Int. It handles negative values appropriately.


245-246: LGTM!

The String method correctly converts a Dec to its string representation.


249-255: LGTM!

The Cmp method correctly compares two Dec values and returns the result.


258-259: LGTM!

The Equal method correctly checks if two Dec values are equal.


262-264: LGTM!

The IsZero method correctly checks if a Dec value is zero.


267-269: LGTM!

The IsNegative method correctly checks if a Dec value is negative.


272-274: LGTM!

The IsPositive method correctly checks if a Dec value is positive.


198-203: Fix error wrapping in Mul method.

The Mul method incorrectly wraps the error. Remove the wrapping.

-	return z, errors.Wrap(err, "decimal multiplication error")
+	return z, nil

Likely invalid or redundant comment.


190-195: Fix error wrapping in Rem method.

The Rem method incorrectly wraps the error. Remove the wrapping.

-	return z, errors.Wrap(err, "decimal remainder error")
+	return z, nil

Likely invalid or redundant comment.

go.mod (2)

81-81: Dependency update: github.com/cockroachdb/apd/v3

The dependency for github.com/cockroachdb/apd/v3 has been updated to version v3.2.1. Ensure compatibility with the rest of the codebase.


191-191: Module replacement: cosmossdk.io/math

The module cosmossdk.io/math is replaced with a local path ./math. Ensure this replacement is temporary and will be updated with the final version.

math/dec_bench_test.go (4)

1-7: Ensure sufficient benchmark coverage.

The benchmark tests cover various arithmetic operations and serialization for both LegacyDec and Dec. Ensure that all critical operations are benchmarked.


9-63: LGTM!

The benchmark BenchmarkCompareLegacyDecAndNewDecQuotient correctly compares the performance of division operations between LegacyDec and Dec.


65-120: LGTM!

The benchmark BenchmarkCompareLegacyDecAndNewDecSum correctly compares the performance of addition operations between LegacyDec and Dec.


122-179: LGTM!

The benchmark BenchmarkCompareLegacyDecAndNewDecSub correctly compares the performance of subtraction operations between LegacyDec and Dec.

math/dec_test.go (13)

14-124: LGTM! Comprehensive test coverage for NewDecFromString.

The test cases cover various scenarios for the NewDecFromString function, ensuring robust validation of expected outcomes.


128-160: LGTM! Comprehensive test coverage for NewDecFromInt64.

The test cases cover various scenarios for the NewDecFromInt64 function, ensuring robust validation of expected outcomes.


164-271: LGTM! Comprehensive test coverage for Add.

The test cases cover various scenarios for the Add function, ensuring robust validation of expected outcomes.


275-408: LGTM! Comprehensive test coverage for Sub.

The test cases cover various scenarios for the Sub function, ensuring robust validation of expected outcomes.


412-506: LGTM! Comprehensive test coverage for Quo.

The test cases cover various scenarios for the Quo function, ensuring robust validation of expected outcomes.


510-604: LGTM! Comprehensive test coverage for QuoExact.

The test cases cover various scenarios for the QuoExact function, ensuring robust validation of expected outcomes.


608-702: LGTM! Comprehensive test coverage for QuoInteger.

The test cases cover various scenarios for the QuoInteger function, ensuring robust validation of expected outcomes.


718-764: LGTM! Comprehensive test coverage for Reduce.

The test cases cover various scenarios for the Reduce function, ensuring robust validation of expected outcomes.


768-842: LGTM! Comprehensive test coverage for MulExact.

The test cases cover various scenarios for the MulExact function, ensuring robust validation of expected outcomes.


846-867: LGTM! Comprehensive test coverage for BigInt.

The test cases cover various scenarios for the BigInt function, ensuring robust validation of expected outcomes.


871-891: LGTM! Comprehensive test coverage for SdkIntTrim.

The test cases cover various scenarios for the SdkIntTrim function, ensuring robust validation of expected outcomes.


896-899: LGTM! Test coverage for invalid decimal string "inf".

The test case ensures that invalid decimal strings like "inf" are correctly handled.


902-906: LGTM! Simple and effective error handling helper.

The must function is correctly implemented to panic if an error occurs.

math/dec_legacy.go (20)

1-11: LGTM!

The package and import statements are correct and include all necessary packages.


13-36: LGTM!

The LegacyDec struct and constants are well-defined and provide necessary precision and configuration.


38-61: LGTM!

The variable declarations and init function are correct and initialize necessary precision multipliers and other constants.


63-95: LGTM!

The utility functions for precision multipliers are well-defined and provide necessary precision handling.


97-137: LGTM!

The LegacyNewDec and related functions are well-defined and provide necessary constructors for LegacyDec.


139-211: LGTM!

The LegacyNewDecFromStr and related functions are well-defined and handle string conversion to LegacyDec correctly.


213-227: LGTM!

The LegacyDec methods for checking value properties are well-defined and provide necessary value property checks and operations.


229-246: LGTM!

The BigInt and BigIntMut methods are well-defined and provide necessary conversions to big.Int.


248-261: LGTM!

The ImmutOp, ImmutOpInt, and ImmutOpInt64 methods are well-defined and provide necessary immutable operations for LegacyDec.


263-267: LGTM!

The SetInt64 method is well-defined and provides necessary conversion from int64 to LegacyDec.


269-373: LGTM!

The arithmetic operation methods are well-defined and provide necessary arithmetic operations for LegacyDec.


375-449: LGTM!

The quotient operation methods are well-defined and provide necessary quotient operations for LegacyDec.


451-529: LGTM!

The ApproxRoot, Power, PowerMut, and ApproxSqrt methods are well-defined and provide necessary root and power operations for LegacyDec.


531-593: LGTM!

The IsInteger, Format, and String methods are well-defined and provide necessary string and format operations for LegacyDec.


596-610: LGTM!

The Float64 and MustFloat64 methods are well-defined and provide necessary float conversion operations for LegacyDec.


612-707: LGTM!

The precision chopping methods are well-defined and provide necessary precision chopping operations for LegacyDec.


684-727: LGTM!

The rounding and truncation methods are well-defined and provide necessary rounding and truncation operations for LegacyDec.


729-748: LGTM!

The Ceil method is well-defined and provides necessary ceiling operation for LegacyDec.


751-787: LGTM!

The LegacyMaxSortableDec, LegacyValidSortableDec, and LegacySortableDecBytes methods are well-defined and provide necessary sortable operations for LegacyDec.


789-893: LGTM!

The JSON and YAML marshal/unmarshal methods are well-defined and provide necessary serialization and deserialization operations for LegacyDec.

math/dec_legacy_test.go (30)

23-25: LGTM!

The test suite initialization is correctly implemented.


27-48: LGTM!

The test cases for approximate equality are well-defined and cover various scenarios.


50-56: LGTM!

The helper function for creating LegacyDec values from strings is correctly implemented.


58-119: LGTM!

The test cases for creating LegacyDec values from strings are comprehensive and well-defined.


122-139: LGTM!

The test cases for the string representation of LegacyDec values are well-defined and cover various scenarios.


141-161: LGTM!

The test cases for the float64 conversion of LegacyDec values are well-defined and cover various scenarios.


163-196: LGTM!

The test cases for comparisons of LegacyDec values are well-defined and cover various scenarios.


199-219: LGTM!

The test cases for the equality of slices of LegacyDec values are well-defined and cover various scenarios.


221-290: LGTM!

The test cases for arithmetic operations on LegacyDec values are comprehensive and well-defined.


293-306: LGTM!

The test cases for MulRoundUp and MulTruncate methods are well-defined and cover edge cases.


308-331: LGTM!

The test cases for the banker’s rounding method are well-defined and cover various scenarios.


334-357: LGTM!

The test cases for truncation behavior are well-defined and cover various scenarios.


360-371: LGTM!

The test case for string conversion involving large numbers is well-defined and correctly implemented.


373-387: LGTM!

The test cases for multiplication with integers are well-defined and cover various scenarios.


390-409: LGTM!

The test cases for the ceiling method are well-defined and cover various scenarios.


411-417: LGTM!

The test case for overflow scenarios in the ceiling method is well-defined and correctly implemented.


419-443: LGTM!

The test cases for the power method are well-defined and cover various scenarios.


446-473: LGTM!

The test cases for the approximate root method are well-defined and cover various scenarios.


476-498: LGTM!

The test cases for the approximate square root method are well-defined and cover various scenarios.


501-524: LGTM!

The test cases for the sortable byte representation are well-defined and cover various scenarios.


526-610: LGTM!

The test cases for encoding and decoding LegacyDec values are well-defined and cover various scenarios.


613-619: LGTM!

The test cases for different orders of operations are well-defined and correctly implemented.


621-650: LGTM!

The benchmark cases for the MarshalTo method are well-defined and correctly implemented.


654-667: LGTM!

The benchmark case for the QuoMut method is well-defined and correctly implemented.


669-682: LGTM!

The benchmark case for the QuoTruncateMut method is well-defined and correctly implemented.


684-695: LGTM!

The benchmark case for the ApproxSqrt method on a Mersenne prime is well-defined and correctly implemented.


698-711: LGTM!

The benchmark case for the QuoRoundupMut method is well-defined and correctly implemented.


713-729: LGTM!

The test cases for the FormatDec method are well-defined and cover various scenarios.


731-757: LGTM!

The test cases for handling invalid decimal strings are well-defined and correctly implemented.


760-763: LGTM!

The test case for negative precision values is well-defined and correctly implemented.

Copy link
Contributor

@alpe alpe left a comment

Choose a reason for hiding this comment

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

LGTM 👍

@samricotta samricotta merged commit 51596e9 into sam/dec-type Jul 3, 2024
6 of 8 checks passed
@samricotta samricotta deleted the sam/error-dec branch July 3, 2024 09:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants