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

Reduce usage of big.Rat #1553

Closed
wants to merge 1 commit into from
Closed

Reduce usage of big.Rat #1553

wants to merge 1 commit into from

Conversation

BrendanChou
Copy link
Contributor

@BrendanChou BrendanChou commented May 20, 2024

Changelist

Reduce usage of Rat functions

Test Plan

[Describe how this PR was tested (if applicable)]

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

  • New Features

    • Introduced new rounding logic with BigIntDivRound for more precise calculations.
  • Improvements

    • Enhanced rounding methods across various modules for better accuracy and consistency.
    • Updated several functions to use BigIntDivRound for improved precision in financial calculations.
  • Refactor

    • Renamed and updated rounding functions to work with new data types for better performance and clarity.

Copy link
Contributor

coderabbitai bot commented May 20, 2024

Important

Review Skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The recent changes focus on improving mathematical operations involving big integers within the protocol. Key updates include the introduction of a new division and rounding function, BigIntDivRound, and the modification of existing functions to use big.Int instead of big.Rat. These adjustments enhance precision and performance across various calculations, particularly in rounding and division operations. Additionally, corresponding tests have been updated to align with the new logic and input types.

Changes

File(s) Change Summary
protocol/lib/big_math.go - Modified BigIntMulSignedPpm implementation.
- Added BigIntDivRound for division and rounding.
- Renamed and updated BigRoundToNearestMultiple to use *big.Int.
- Added clamping logic in rounding.
protocol/lib/big_math_test.go - Updated tests for BigIntDivRound and BigRoundToNearestMultiple.
- Switched input types from big.Rat to big.Int.
- Adjusted function names and rounding logic in tests.
protocol/x/assets/keeper/asset.go - Updated ConvertAssetToCoin to use BigIntDivRound.
protocol/x/clob/keeper/... - Modified calculations in clob_pair.go, liquidations.go, mev.go, and untriggered_conditional_orders.go to use BigIntDivRound.
protocol/x/clob/memclob/memclob.go - Refactored getPricePremiumFromSide to use BigIntDivRound.
protocol/x/clob/types/price_to_subticks.go - Refactored SubticksToPrice to use BigIntDivRound.
protocol/x/perpetuals/keeper/perpetual.go - Refactored GetMarginRequirementsInQuoteQuantums to use BigIntDivRound.
protocol/x/perpetuals/types/liquidity_tier.go - Updated GetInitialMarginQuoteQuantums to use BigIntDivRound.
protocol/x/ratelimit/util/capacity.go - Changed CalculateNewCapacityList to use BigIntDivRound for division and rounding down.
protocol/x/rewards/keeper/keeper.go - Updated ProcessRewardsForBlock to use BigIntDivRound.
protocol/x/vault/keeper/orders.go - Adjusted rounding logic using BigRoundToNearestMultiple and BigIntDivRound.
protocol/x/vest/keeper/keeper.go - Modified ProcessVesting to use BigIntDivRound for vestAmount calculation.

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 full the 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.

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 722ec24 and f004af6.
Files selected for processing (16)
  • protocol/lib/big_math.go (3 hunks)
  • protocol/lib/big_math_test.go (2 hunks)
  • protocol/lib/quantums.go (1 hunks)
  • protocol/x/assets/keeper/asset.go (1 hunks)
  • protocol/x/clob/keeper/clob_pair.go (1 hunks)
  • protocol/x/clob/keeper/liquidations.go (1 hunks)
  • protocol/x/clob/keeper/mev.go (1 hunks)
  • protocol/x/clob/keeper/untriggered_conditional_orders.go (2 hunks)
  • protocol/x/clob/memclob/memclob.go (1 hunks)
  • protocol/x/clob/types/price_to_subticks.go (1 hunks)
  • protocol/x/perpetuals/keeper/perpetual.go (1 hunks)
  • protocol/x/perpetuals/types/liquidity_tier.go (2 hunks)
  • protocol/x/ratelimit/util/capacity.go (1 hunks)
  • protocol/x/rewards/keeper/keeper.go (1 hunks)
  • protocol/x/vault/keeper/orders.go (2 hunks)
  • protocol/x/vest/keeper/keeper.go (1 hunks)
Additional Context Used
Path-based Instructions (16)
protocol/x/clob/types/price_to_subticks.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/ratelimit/util/capacity.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/lib/quantums.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/perpetuals/types/liquidity_tier.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/vest/keeper/keeper.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/assets/keeper/asset.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/lib/big_math.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/rewards/keeper/keeper.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/vault/keeper/orders.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/clob/keeper/untriggered_conditional_orders.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/clob/keeper/clob_pair.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/lib/big_math_test.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/clob/keeper/mev.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/clob/keeper/liquidations.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/perpetuals/keeper/perpetual.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

protocol/x/clob/memclob/memclob.go (1)

Pattern **/**: Do not include a walkthrough. For all comments on line changes that are longer than 15 lines, add a prefix to the comment of what lines you are commenting on (for example: "The changes from lines 100 to 200...". Add your comment to be on the last 15 lines of the chunk rather than adding your comment to the entire chunk.

Additional comments not posted (18)
protocol/x/clob/types/price_to_subticks.go (1)

74-81: The changes in SubticksToPrice function correctly replace big.Rat with big.Int operations, aligning with the PR's objective to reduce big.Rat usage. Ensure the rounding behavior is as expected.

protocol/x/ratelimit/util/capacity.go (1)

66-70: The changes in CalculateNewCapacityList function correctly replace big.Rat with big.Int operations, aligning with the PR's objective to reduce big.Rat usage. Ensure the new capacity calculations behave as expected.

Verification successful

The capacity_test.go file contains comprehensive tests for the CalculateNewCapacityList function, covering various scenarios such as different baseline and capacity values, rounding behavior, and edge cases. These tests ensure that the new capacity calculations behave as expected.

  • capacity_test.go includes tests for:
    • Previous capacity equals baseline.
    • Previous capacity less than baseline.
    • Previous capacity with 18 decimals.
    • Previous capacity equals zero.
    • Previous capacity equals zero with rounding down.
    • Previous capacity equals twice the baseline with rounding down.
    • Previous capacity between baseline and twice the baseline.
    • Previous capacity greater than twice the baseline with capacity less than baseline.

These tests validate the correctness of the changes made to the CalculateNewCapacityList function.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the behavior of new capacity calculations in `CalculateNewCapacityList` function.

# Test: Execute the function with known inputs and check if the capacity calculations are correct.
# Expect: The output should match the expected capacity values.
echo "Testing new capacity calculations..."

Length of output: 82



Script:

#!/bin/bash
# Locate the `CalculateNewCapacityList` function definition.
ast-grep --lang go --pattern 'func CalculateNewCapacityList($_, $_, $_) $_' 

# Search for test files that might contain tests for `CalculateNewCapacityList`.
fd --type f --name '*_test.go' --exec grep -l 'CalculateNewCapacityList' {}

Length of output: 5385



Script:

#!/bin/bash
# Correct the `fd` command to search for test files that might contain tests for `CalculateNewCapacityList`.
fd --type f -e go -x grep -l 'CalculateNewCapacityList' {}

Length of output: 185



Script:

#!/bin/bash
# Extract and review the relevant tests from `capacity_test.go`.
ast-grep --lang go --pattern 'func TestCalculateNewCapacityList($_) $_' ./protocol/x/ratelimit/util/capacity_test.go

Length of output: 20835

protocol/lib/quantums.go (1)

89-93: The changes in QuoteToBaseQuantums function correctly replace big.Rat with big.Int operations, aligning with the PR's objective to reduce big.Rat usage. Ensure the rounding behavior is as expected.

Verification successful

The test cases in quantums_test.go for the QuoteToBaseQuantums function cover various scenarios, including positive, negative, and realistic values. These test cases should adequately verify the rounding behavior using Euclidean division.

  • quantums_test.go contains multiple test cases for QuoteToBaseQuantums:
    • Converts from base to quote quantums
    • Correctly converts negative value
    • priceExponent is negative
    • priceExponent is zero
    • Realistic values for BTC at different prices
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the rounding behavior of `QuoteToBaseQuantums` function.

# Test: Execute the function with known inputs and check if the rounding is correct.
# Expect: The output should match the expected rounded values.
echo "Testing QuoteToBaseQuantums function rounding behavior..."

Length of output: 124



Script:

#!/bin/bash
# Locate the `QuoteToBaseQuantums` function implementation
ast-grep --lang go --pattern 'func QuoteToBaseQuantums($_, $_) $_ {
  $$$
}'

# Locate test files that might contain tests for `QuoteToBaseQuantums`
fd --type f --name '*_test.go' --exec grep -l 'QuoteToBaseQuantums' {}

Length of output: 402



Script:

#!/bin/bash
# Locate the `QuoteToBaseQuantums` function implementation
ast-grep --lang go --pattern 'func QuoteToBaseQuantums($_, $_) $_ {
  $$$
}'

# Locate test files that might contain tests for `QuoteToBaseQuantums`
fd -e go -x grep -l 'QuoteToBaseQuantums' {}

Length of output: 228



Script:

#!/bin/bash
# Extract and review test cases for `QuoteToBaseQuantums` from `quantums_test.go`
grep -A 10 'QuoteToBaseQuantums' ./protocol/lib/quantums_test.go

Length of output: 800



Script:

#!/bin/bash
# Extract the complete `TestQuoteToBaseQuantums` function from `quantums_test.go`
ast-grep --lang go --pattern 'func TestQuoteToBaseQuantums($_) $_ {
  $$$
}' ./protocol/lib/quantums_test.go

Length of output: 110



Script:

#!/bin/bash
# Extract a larger portion of the `quantums_test.go` file around the `TestQuoteToBaseQuantums` function
grep -A 50 'func TestQuoteToBaseQuantums' ./protocol/lib/quantums_test.go

Length of output: 2042

protocol/x/perpetuals/types/liquidity_tier.go (1)

120-124: The changes in GetInitialMarginQuoteQuantums function correctly replace big.Rat with big.Int operations, aligning with the PR's objective to reduce big.Rat usage. Ensure the rounding behavior is as expected.

Verification successful

The test cases in liquidity_tier_test.go thoroughly cover various scenarios for the GetInitialMarginQuoteQuantums function, including different initial margin percentages and rounding behaviors. The function implementation and test cases align with the expected behavior of rounding up as specified.

  • protocol/x/perpetuals/types/liquidity_tier_test.go: Contains detailed test cases for GetInitialMarginQuoteQuantums, ensuring correct rounding behavior.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the rounding behavior of `GetInitialMarginQuoteQuantums` function.

# Test: Execute the function with known inputs and check if the rounding is correct.
# Expect: The output should match the expected rounded values.
echo "Testing GetInitialMarginQuoteQuantums function rounding behavior..."

Length of output: 144



Script:

#!/bin/bash
# Locate the implementation of the GetInitialMarginQuoteQuantums function
echo "Searching for GetInitialMarginQuoteQuantums function implementation..."
ast-grep --lang go --pattern 'func GetInitialMarginQuoteQuantums($_) $_' > function_implementation.txt

# Locate test cases for GetInitialMarginQuoteQuantums function
echo "Searching for test cases for GetInitialMarginQuoteQuantums function..."
rg 'GetInitialMarginQuoteQuantums' --files-with-matches > test_cases.txt

# Display the results
echo "Function implementation found in:"
cat function_implementation.txt

echo "Test cases found in:"
cat test_cases.txt

Length of output: 754



Script:

#!/bin/bash
# Extract the GetInitialMarginQuoteQuantums function implementation
echo "Extracting GetInitialMarginQuoteQuantums function implementation..."
ast-grep --lang go --pattern 'func GetInitialMarginQuoteQuantums($_) $_' protocol/x/perpetuals/types/liquidity_tier.go > function_implementation.txt

# Extract the test cases for GetInitialMarginQuoteQuantums function
echo "Extracting test cases for GetInitialMarginQuoteQuantums function..."
rg 'GetInitialMarginQuoteQuantums' protocol/x/perpetuals/keeper/perpetual.go protocol/x/perpetuals/types/liquidity_tier_test.go > test_cases.txt

# Display the results
echo "Function implementation:"
cat function_implementation.txt

echo "Test cases:"
cat test_cases.txt

Length of output: 1204



Script:

#!/bin/bash
# Extract the TestGetInitialMarginQuoteQuantums function
echo "Extracting TestGetInitialMarginQuoteQuantums function..."
ast-grep --lang go --pattern 'func TestGetInitialMarginQuoteQuantums($_) $_' protocol/x/perpetuals/types/liquidity_tier_test.go > test_function.txt

# Extract related test cases in perpetual.go
echo "Extracting related test cases in perpetual.go..."
rg 'GetInitialMarginQuoteQuantums' protocol/x/perpetuals/keeper/perpetual.go > related_test_cases.txt

# Display the results
echo "Test function implementation:"
cat test_function.txt

echo "Related test cases:"
cat related_test_cases.txt

Length of output: 12092

protocol/x/vest/keeper/keeper.go (1)

108-114: The changes in ProcessVesting function correctly replace big.Rat with big.Int operations, aligning with the PR's objective to reduce big.Rat usage. Ensure the rounding behavior is as expected.

protocol/x/assets/keeper/asset.go (1)

308-312: The changes in ConvertAssetToCoin function correctly replace big.Rat with big.Int operations, aligning with the PR's objective to reduce big.Rat usage. Ensure the rounding behavior is as expected.

Verification successful

The test cases for the ConvertAssetToCoin function in asset_test.go include both success and failure scenarios. The success test cases cover various combinations of denomExponent, atomicResolution, and quantumsToConvert, ensuring that the function behaves correctly under different conditions. The failure test cases check for invalid asset IDs, invalid denom exponents, and invalid atomic resolutions.

These tests appear to adequately cover the rounding behavior and other edge cases for the ConvertAssetToCoin function.

  • protocol/x/assets/keeper/asset_test.go: Contains comprehensive test cases for ConvertAssetToCoin.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the rounding behavior of `ConvertAssetToCoin` function.

# Test: Execute the function with known inputs and check if the rounding is correct.
# Expect: The output should match the expected rounded values.
echo "Testing ConvertAssetToCoin function rounding behavior..."

Length of output: 122



Script:

#!/bin/bash
# Locate the ConvertAssetToCoin function implementation
ast-grep --lang go --pattern 'func ConvertAssetToCoin($_, $_) $_' 

# Locate test files related to the ConvertAssetToCoin function
fd -e go -e test

Length of output: 71358



Script:

#!/bin/bash
# Locate the ConvertAssetToCoin function implementation with more specific search patterns
rg 'func ConvertAssetToCoin' --type go

# Locate test files that might contain tests for ConvertAssetToCoin function
rg 'ConvertAssetToCoin' --type go

Length of output: 2023



Script:

#!/bin/bash
# Extract the ConvertAssetToCoin function implementation
ast-grep --lang go --pattern 'func (k Keeper) ConvertAssetToCoin($_, $_, $_) ($_,$_,$_){$$$}' 

# Extract the test cases for ConvertAssetToCoin from asset_test.go
rg 'ConvertAssetToCoin' protocol/x/assets/keeper/asset_test.go

Length of output: 3899



Script:

#!/bin/bash
# Extract the test cases for ConvertAssetToCoin from asset_test.go
sed -n '/func TestConvertAssetToCoin_Success/,/}/p' protocol/x/assets/keeper/asset_test.go
sed -n '/func TestConvertAssetToCoin_Failure/,/}/p' protocol/x/assets/keeper/asset_test.go

Length of output: 1574

protocol/lib/big_math.go (1)

58-60: LGTM! Ensure all usages of BigIntMulSignedPpm are updated to handle the new behavior.

Verification successful

The implementation of BigIntDivRound appears to be correct and aligns with the intended functionality of rounding the division result based on the roundUp flag. Additionally, the usages of BigIntMulSignedPpm in the various files (keeper.go, pending_updates.go, mev.go, and process_single_match.go) have been verified to handle the new behavior correctly.

  • protocol/x/rewards/keeper/keeper.go
  • protocol/x/clob/types/pending_updates.go
  • protocol/x/clob/keeper/mev.go
  • protocol/x/clob/keeper/process_single_match.go

All usages align with the new behavior of BigIntMulSignedPpm.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `BigIntMulSignedPpm` handle the new behavior.

# Test: Search for the function usage. Expect: Only occurances of the new signature.
rg --type go $'BigIntMulSignedPpm'

Length of output: 905



Script:

#!/bin/bash
# Description: Verify the context and parameters of `BigIntMulSignedPpm` in `keeper.go`.

# Test: Extract the relevant function and surrounding lines for context.
rg --context 10 'BigIntMulSignedPpm' protocol/x/rewards/keeper/keeper.go

Length of output: 863



Script:

#!/bin/bash
# Description: Verify the context and parameters of `BigIntMulSignedPpm` in `pending_updates.go`.

# Test: Extract the relevant function and surrounding lines for context.
rg --context 10 'BigIntMulSignedPpm' protocol/x/clob/types/pending_updates.go

Length of output: 406



Script:

#!/bin/bash
# Description: Verify the context and parameters of `BigIntMulSignedPpm` in `mev.go`.

# Test: Extract the relevant function and surrounding lines for context.
rg --context 10 'BigIntMulSignedPpm' protocol/x/clob/keeper/mev.go

Length of output: 653



Script:

#!/bin/bash
# Description: Verify the context and parameters of `BigIntMulSignedPpm` in `process_single_match.go`.

# Test: Extract the relevant function and surrounding lines for context.
rg --context 10 'BigIntMulSignedPpm' protocol/x/clob/keeper/process_single_match.go

Length of output: 968



Script:

#!/bin/bash
# Description: Extract and review the implementation of `BigIntDivRound`.

# Test: Search for the implementation of `BigIntDivRound`.
rg --context 10 'func BigIntDivRound' protocol/lib/big_math.go

Length of output: 753

protocol/x/rewards/keeper/keeper.go (1)

300-304: LGTM! Ensure integration with other modules is verified, especially where reward calculations are used.

Verification successful

To ensure the integration of the changes in ProcessRewardsForBlock is properly handled, we need to review the implementation in module.go and keeper_test.go.


The integration of the changes in ProcessRewardsForBlock appears to be properly handled in module.go and thoroughly tested in keeper_test.go. The EndBlock function calls ProcessRewardsForBlock and handles errors, while the tests cover various scenarios to ensure correct behavior.

  • module.go: The EndBlock function calls ProcessRewardsForBlock and logs errors if they occur.
  • keeper_test.go: The tests verify the behavior of ProcessRewardsForBlock under different conditions, ensuring the new behavior is correctly handled.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify integration with other modules for changes in `ProcessRewardsForBlock`.

# Test: Search for the function usage in other modules. Expect: Proper handling of the new behavior.
rg --type go $'ProcessRewardsForBlock'

Length of output: 665



Script:

#!/bin/bash
# Description: Review the implementation of ProcessRewardsForBlock in module.go and keeper_test.go.

# Display the relevant lines in module.go
rg --type go --context 10 'ProcessRewardsForBlock' protocol/x/rewards/module.go

# Display the relevant lines in keeper_test.go
rg --type go --context 10 'ProcessRewardsForBlock' protocol/x/rewards/keeper/keeper_test.go

Length of output: 2176

protocol/x/vault/keeper/orders.go (1)

204-211: LGTM! Ensure integration with other modules is verified, especially where order size calculations are used.

Verification successful

The integration of the GetVaultClobOrders function appears to be properly handled in the following locations:

  • types.go: The function is part of the VaultKeeper interface, ensuring it is correctly defined for use across the module.
  • orders.go: The function is used in the RefreshVaultClobOrders method to cancel and place orders, indicating it is integrated into the order management logic.
  • orders_test.go: The function is extensively tested, with multiple test cases verifying its behavior under different conditions.

These findings suggest that the changes to the GetVaultClobOrders function are well-integrated and thoroughly tested.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify integration with other modules for changes in `GetVaultClobOrders`.

# Test: Search for the function usage in other modules. Expect: Proper handling of the new behavior.
rg --type go $'GetVaultClobOrders'

Length of output: 1332



Script:

#!/bin/bash
# Description: Verify integration and proper handling of the new behavior in `GetVaultClobOrders`.

# Check usage in `types.go`
echo "Checking types.go..."
rg --type go --context 5 'GetVaultClobOrders' protocol/x/vault/types/types.go

# Check usage in `orders.go`
echo "Checking orders.go..."
rg --type go --context 5 'GetVaultClobOrders' protocol/x/vault/keeper/orders.go

# Check usage in `orders_test.go`
echo "Checking orders_test.go..."
rg --type go --context 5 'GetVaultClobOrders' protocol/x/vault/keeper/orders_test.go

Length of output: 4315

protocol/x/clob/keeper/untriggered_conditional_orders.go (2)

231-237: The changes from lines 231 to 237 correctly implement the transition from big.Rat to big.Int for pessimistic rounding in the PollTriggeredConditionalOrders function. This is consistent with the PR's objective to reduce the usage of big.Rat.


254-260: The changes from lines 254 to 260 correctly implement the transition from big.Rat to big.Int for pessimistic rounding in the PollTriggeredConditionalOrders function. This is consistent with the PR's objective to reduce the usage of big.Rat.

protocol/x/clob/keeper/clob_pair.go (1)

407-412: The changes from lines 407 to 412 correctly implement the transition from big.Rat to big.Int for calculating currentOraclePriceSubticks in the validateOrderAgainstClobPairStatus function. This is consistent with the PR's objective to reduce the usage of big.Rat.

protocol/lib/big_math_test.go (1)

536-618: The test cases for BigIntDivRound are comprehensive and well-implemented, covering a variety of scenarios including edge cases for zero, positive, and negative numbers, as well as different rounding directions.

protocol/x/clob/keeper/mev.go (1)

384-388: The changes from lines 384 to 388 successfully replace big.Rat operations with big.Int operations, aligning with the PR's objective to reduce the usage of big.Rat. This should enhance performance by avoiding the overhead associated with rational number calculations.

protocol/x/perpetuals/keeper/perpetual.go (1)

1028-1034: The changes from lines 1028 to 1034 update the calculation of maintenance margin requirements using big.Rat for precision.

This change aligns with the PR's objective to enhance precision in financial calculations by replacing big.Rat with big.Int operations. The use of BigIntDivRound for rounding is appropriate here, ensuring that the division results are correctly rounded to the nearest integer, which is critical in financial calculations to avoid significant rounding errors.

protocol/x/clob/memclob/memclob.go (3)

2467-2471: The rounding logic in getImpactPriceSubticks is correctly implemented to round towards zero, which is appropriate for financial calculations where precision is crucial.


2472-2473: The function resizeReduceOnlyMatchIfNecessary effectively ensures that reduce-only orders do not increase the position size, adhering to trading rules.


Line range hint 2474-2475: The GetPricePremium function is well-implemented with comprehensive checks and clear handling of different market scenarios to calculate the price premium accurately.

Comment on lines +1075 to +1079
roundedSubticksBig := lib.BigIntDivRound(
subticksRat.Num(),
subticksRat.Denom(),
roundUp,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor ConvertFillablePriceToSubticks to use BigIntDivRound for rounding.

The change from big.Rat to big.Int in the ConvertFillablePriceToSubticks function aligns with the PR's objective to enhance precision. The use of BigIntDivRound for rounding operations is a critical improvement, ensuring that the calculations are more consistent and reliable. This change is crucial for financial calculations where precision is paramount.

Comment on lines +916 to +1241
value: big.NewRat(7, 1),
value: big.NewInt(7),
base: 14,
up: true,
expectedResult: 14,
},
"Round 123 down to a multiple of 123": {
value: big.NewRat(123, 1),
value: big.NewInt(123),
base: 123,
up: false,
expectedResult: 123,
},
"Round 123 up to a multiple of 123": {
value: big.NewRat(123, 1),
value: big.NewInt(123),
base: 123,
up: true,
expectedResult: 123,
},
"Round 100/6 down to a multiple of 3": {
value: big.NewRat(100, 6),
"Round 16 down to a multiple of 3": {
value: big.NewInt(16),
base: 3,
up: false,
expectedResult: 15,
},
"Round 100/6 up to a multiple of 3": {
value: big.NewRat(100, 6),
"Round 16 up to a multiple of 3": {
value: big.NewInt(16),
base: 3,
up: true,
expectedResult: 18,
},
"Round 7/2 down to a multiple of 1": {
value: big.NewRat(7, 2),
"Round -16 down to a multiple of 3, is clamped to zero": {
value: big.NewInt(-16),
base: 3,
up: false,
expectedResult: 0,
},
"Round -16 up to a multiple of 3, is clamped to zero": {
value: big.NewInt(-16),
base: 3,
up: true,
expectedResult: 0,
},
"Round 4 down to a multiple of 1": {
value: big.NewInt(4),
base: 1,
up: false,
expectedResult: 3,
expectedResult: 4,
},
"Round 7/2 up to a multiple of 1": {
value: big.NewRat(7, 2),
"Round 4 up to a multiple of 1": {
value: big.NewInt(4),
base: 1,
up: true,
expectedResult: 4,
},
"Round 10 down to a multiple of 0": {
value: big.NewRat(10, 1),
value: big.NewInt(10),
base: 0,
up: false,
expectedResult: 0,
},
"Round 10 up to a multiple of 0": {
value: big.NewRat(10, 1),
value: big.NewInt(10),
base: 0,
up: true,
expectedResult: 0,
},
"Check overflow is clamped when rounding down": {
value: big_testutil.MustFirst(
new(big.Int).SetString("99999999999999999999", 10),
),
base: 100,
up: false,
expectedResult: 18446744073709551600,
},
"Check overflow is clamped when rounding up": {
value: big_testutil.MustFirst(
new(big.Int).SetString("99999999999999999999", 10),
),
base: 100,
up: true,
expectedResult: 18446744073709551600,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
result := lib.BigRatRoundToNearestMultiple(
result := lib.BigRoundToNearestMultiple(
Copy link
Contributor

Choose a reason for hiding this comment

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

The test cases for BigRoundToNearestMultiple are generally well-implemented. However, the cases for rounding to a multiple of zero (lines 996 and 1002) should be reconsidered, as rounding to a multiple of zero is not mathematically defined and could potentially lead to confusion or errors.

- "Round 10 down to a multiple of 0": {
-	value:          big.NewInt(10),
-	base:           0,
-	up:             false,
-	expectedResult: 0,
- },
- "Round 10 up to a multiple of 0": {
-	value:          big.NewInt(10),
-	base:           0,
-	up:             true,
-	expectedResult: 0,
- },

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.

Suggested change
func TestBigRoundToNearestMultiple(t *testing.T) {
tests := map[string]struct {
value *big.Rat
value *big.Int
base uint32
up bool
expectedResult uint64
}{
"Round 5 down to a multiple of 2": {
value: big.NewRat(5, 1),
value: big.NewInt(5),
base: 2,
up: false,
expectedResult: 4,
},
"Round 5 up to a multiple of 2": {
value: big.NewRat(5, 1),
value: big.NewInt(5),
base: 2,
up: true,
expectedResult: 6,
},
"Round 7 down to a multiple of 14": {
value: big.NewRat(7, 1),
value: big.NewInt(7),
base: 14,
up: false,
expectedResult: 0,
},
"Round 7 up to a multiple of 14": {
value: big.NewRat(7, 1),
value: big.NewInt(7),
base: 14,
up: true,
expectedResult: 14,
},
"Round 123 down to a multiple of 123": {
value: big.NewRat(123, 1),
value: big.NewInt(123),
base: 123,
up: false,
expectedResult: 123,
},
"Round 123 up to a multiple of 123": {
value: big.NewRat(123, 1),
value: big.NewInt(123),
base: 123,
up: true,
expectedResult: 123,
},
"Round 100/6 down to a multiple of 3": {
value: big.NewRat(100, 6),
"Round 16 down to a multiple of 3": {
value: big.NewInt(16),
base: 3,
up: false,
expectedResult: 15,
},
"Round 100/6 up to a multiple of 3": {
value: big.NewRat(100, 6),
"Round 16 up to a multiple of 3": {
value: big.NewInt(16),
base: 3,
up: true,
expectedResult: 18,
},
"Round 7/2 down to a multiple of 1": {
value: big.NewRat(7, 2),
"Round -16 down to a multiple of 3, is clamped to zero": {
value: big.NewInt(-16),
base: 3,
up: false,
expectedResult: 0,
},
"Round -16 up to a multiple of 3, is clamped to zero": {
value: big.NewInt(-16),
base: 3,
up: true,
expectedResult: 0,
},
"Round 4 down to a multiple of 1": {
value: big.NewInt(4),
base: 1,
up: false,
expectedResult: 3,
expectedResult: 4,
},
"Round 7/2 up to a multiple of 1": {
value: big.NewRat(7, 2),
"Round 4 up to a multiple of 1": {
value: big.NewInt(4),
base: 1,
up: true,
expectedResult: 4,
},
"Round 10 down to a multiple of 0": {
value: big.NewRat(10, 1),
value: big.NewInt(10),
base: 0,
up: false,
expectedResult: 0,
},
"Round 10 up to a multiple of 0": {
value: big.NewRat(10, 1),
value: big.NewInt(10),
base: 0,
up: true,
expectedResult: 0,
},
"Check overflow is clamped when rounding down": {
value: big_testutil.MustFirst(
new(big.Int).SetString("99999999999999999999", 10),
),
base: 100,
up: false,
expectedResult: 18446744073709551600,
},
"Check overflow is clamped when rounding up": {
value: big_testutil.MustFirst(
new(big.Int).SetString("99999999999999999999", 10),
),
base: 100,
up: true,
expectedResult: 18446744073709551600,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
result := lib.BigRatRoundToNearestMultiple(
result := lib.BigRoundToNearestMultiple(
},
"Check overflow is clamped when rounding down": {
value: big_testutil.MustFirst(
new(big.Int).SetString("99999999999999999999", 10),
),
base: 100,
up: false,
expectedResult: 18446744073709551600,
},
"Check overflow is clamped when rounding up": {
value: big_testutil.MustFirst(
new(big.Int).SetString("99999999999999999999", 10),
),
base: 100,
up: true,
expectedResult: 18446744073709551600,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
result := lib.BigRoundToNearestMultiple(

Comment on lines 136 to 185
// BigIntDivRound takes a numerator, denominator, and a direction to round (true for up, false for down).
func BigIntDivRound(
numerator *big.Int,
denominator *big.Int,
roundUp bool,
) *big.Int {
result, remainder := new(big.Int).DivMod(numerator, denominator, new(big.Int))
if remainder.Sign() > 0 && roundUp {
result.Add(result, big.NewInt(1))
}
return resultBig
return result
Copy link
Contributor

Choose a reason for hiding this comment

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

LGTM! Consider adding comprehensive tests to cover edge cases for BigIntDivRound.

Would you like me to help with writing these tests?

@BrendanChou BrendanChou marked this pull request as draft May 21, 2024 01:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

1 participant