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

Clean subaccounts/lib/updates.go codepaths #1767

Merged
merged 3 commits into from
Jun 25, 2024
Merged

Clean subaccounts/lib/updates.go codepaths #1767

merged 3 commits into from
Jun 25, 2024

Conversation

BrendanChou
Copy link
Contributor

@BrendanChou BrendanChou commented Jun 25, 2024

Changelist

  • lib/updates.go:
    • GetRiskForSubaccount now runs on the current state of a subaccount rather than also taking in updates
    • Remove ApplyUpdatesToPositions() function which was confusingly named and was only used in the GetRiskForSubaccount funciton
    • Add CalculateUpdatedSubaccount function which returns a deep copy of a subaccount, updated by updates. The name and functionality are clearer as it doesn't modify the passed-in struct in unexpected and inconsistent ways
    • Add CalculateUpdated{Asset,Perpetual}Positions() which are cleaned-up versions of the old logic in Update{Asset,Perpetual}Positions()
    • All of this allows the updating of subaccounts to use the same updating logic when calculating the risk of the new subaccount as it does when updating the subaccounts before writing them to state. For example, previously, multiple updates for the same ID were not handled gracefully in the risk calculation, but were in the state-update.
  • types/**go
    • Added DeepCopy() methods for AssetPosition, PerpetualPosition, and Subaccount

Test Plan

  • Added new tests for some new functions
  • Other functions in the library are now deleted or simpler which makes them easy to unit-test

Summary by CodeRabbit

  • New Features

    • Introduced deep copy functionality for AssetPosition, PerpetualPosition, and Subaccount types to improve data integrity during operations.
  • Bug Fixes

    • Updated handling of multiple updates for the same position to ensure they are processed gracefully.
    • Adjusted collateralization and margin requirements calculations to reflect real-time updates accurately.
  • Refactor

    • Consolidated updates to asset and perpetual positions into a single loop for efficiency.
    • Improved risk calculations by directly updating subaccount information.
  • Tests

    • Added new test cases to verify the newly introduced deep copy functionalities.
    • Updated existing tests to reflect changes in handling multiple updates and direct subaccount updates.
  • Chores

    • Removed outdated error codes and refactored error handling to align with new update mechanisms.

@BrendanChou BrendanChou requested a review from jayy04 June 25, 2024 03:26
Copy link
Contributor

coderabbitai bot commented Jun 25, 2024

Walkthrough

The changes focus on enhancing subaccount management by consolidating update loops, refining risk calculations, and improving test structures. Key updates include the direct passing of settledSubaccount in risk calculations, addition of deep copy methods, simplification of update loops for asset and perpetual positions, error handling improvements, and extensive test case refinements.

Changes

Files Change Summaries
…sub_task_runner.go Modified CheckSubaccountCollateralization function to pass settledSubaccount directly.
…subaccounts/keeper/subaccount.go Consolidated update loops, restructured risk calculations, and adjusted collateralization methods.
…subaccounts/keeper/subaccount_test.go Updated test cases for multiple updates handling, expected outcomes, and data structures.
…subaccounts/lib/updates.go Refactored asset and perpetual position update functions and introduced CalculateUpdatedSubaccount function.
…subaccounts/lib/updates_test.go Modified TestGetRiskForSubaccount to use types.Subaccount instead of types.SettledUpdate.
…types/asset_position.go Introduced DeepCopy function for AssetPosition type.
…types/asset_position_test.go Introduced tests for AssetPosition.DeepCopy functionality.
…types/errors.go Removed ErrNonUniqueUpdatesPosition and added ErrNonUniqueUpdatesSubaccount.
…types/perpetual_position.go Introduced DeepCopy function for PerpetualPosition type.
…types/perpetual_position_test.go Introduced tests for PerpetualPosition.DeepCopy functionality.
…types/subaccount.go Introduced DeepCopy method for Subaccount type.
…types/subaccount_test.go Refined test function names and methods to improve clarity and consistency.

Poem

In the code, a story unfolds,
Of subaccounts growing bold.
With loops refined and risks now neat,
Updates flow in a single beat.
Deep copies ensure no mistake,
For a stable system, we now partake.
🐇✨


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.

@BrendanChou BrendanChou changed the title modify how updates are done Clean subaccounts/lib/updates.go codepaths Jun 25, 2024
@BrendanChou BrendanChou marked this pull request as ready for review June 25, 2024 15:05
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 568e95a and 4d933c8.

Files selected for processing (12)
  • protocol/daemons/liquidation/client/sub_task_runner.go (1 hunks)
  • protocol/x/subaccounts/keeper/subaccount.go (5 hunks)
  • protocol/x/subaccounts/keeper/subaccount_test.go (5 hunks)
  • protocol/x/subaccounts/lib/updates.go (6 hunks)
  • protocol/x/subaccounts/lib/updates_test.go (4 hunks)
  • protocol/x/subaccounts/types/asset_position.go (1 hunks)
  • protocol/x/subaccounts/types/asset_position_test.go (1 hunks)
  • protocol/x/subaccounts/types/errors.go (1 hunks)
  • protocol/x/subaccounts/types/perpetual_position.go (1 hunks)
  • protocol/x/subaccounts/types/perpetual_position_test.go (1 hunks)
  • protocol/x/subaccounts/types/subaccount.go (1 hunks)
  • protocol/x/subaccounts/types/subaccount_test.go (5 hunks)
Files not reviewed due to errors (5)
  • protocol/x/subaccounts/types/asset_position.go (no review received)
  • protocol/x/subaccounts/types/perpetual_position.go (no review received)
  • protocol/x/subaccounts/types/subaccount.go (no review received)
  • protocol/x/subaccounts/types/errors.go (no review received)
  • protocol/x/subaccounts/lib/updates_test.go (no review received)
Files skipped from review due to trivial changes (2)
  • protocol/x/subaccounts/types/asset_position_test.go
  • protocol/x/subaccounts/types/perpetual_position_test.go
Additional comments not posted (19)
protocol/x/subaccounts/types/subaccount_test.go (8)

16-16: Renamed Test Functions for Clarity:
The renaming of the test function TestBaseQuantums_ToBigInt improves clarity and aligns with best practices for naming conventions in Go, which enhances maintainability.


23-23: Renamed Test Functions for Clarity:
The renaming of the test function TestBaseQuantums_ToUInt64 aligns with best practices for naming conventions in Go tests, making it easier to understand the test's purpose at a glance.


30-30: Comprehensive Test Coverage for SubaccountId Validation:
The test TestSubaccountId_Validate thoroughly checks various scenarios, including valid and invalid addresses and subaccount numbers. This is crucial for ensuring the robustness of subaccount ID validation logic.


80-80: Testing Error Handling with Panics:
The test TestSubaccountId_MustGetAccAccount appropriately checks for panics in scenarios where the subaccount ID is not valid, ensuring that the system robustly handles error conditions.


118-118: Deep Copy Test Ensures Integrity:
The addition of TestSubaccount_DeepCopy is crucial for ensuring that the deep copy functionality works as expected, preserving the integrity of data across operations that involve copying subaccount structures.


126-126: Test Coverage for Getting Perpetual Positions:
The test TestSubaccount_GetPerpetualPositionForId effectively ensures that perpetual positions can be retrieved correctly and handles cases where the position does not exist, which is vital for the reliability of the subaccount management system.


154-154: Comprehensive Testing of Quote Balance Retrieval:
The test TestSubaccount_GetUsdcPosition covers various scenarios, including edge cases like nil subaccounts and subaccounts without asset positions. This comprehensive testing is essential for ensuring the accuracy and reliability of the balance retrieval functionality.


211-211: Robust Testing of Quote Balance Setting:
The test TestSubaccount_SetUsdcAssetPosition provides extensive coverage for setting the USD Coin position in various scenarios, including edge cases of balance overflows. This is critical for ensuring that the system handles these operations without errors.

protocol/daemons/liquidation/client/sub_task_runner.go (1)

310-310: Direct Use of Settled Subaccount in Risk Calculation:
The function CheckSubaccountCollateralization now directly uses the settled subaccount for risk calculation, simplifying the flow and ensuring consistency in how subaccount data is processed across different parts of the system.

protocol/x/subaccounts/lib/updates.go (4)

238-238: Introduction of CalculateUpdatedAssetPositions Function:
The CalculateUpdatedAssetPositions function is a significant addition that enhances the clarity and modularity of asset position updates. By using a deep copy and applying updates explicitly, it prevents unintended side effects on the original data structures.


276-276: Introduction of CalculateUpdatedPerpetualPositions Function:
The CalculateUpdatedPerpetualPositions function, similar to its asset counterpart, provides a clear and isolated way to apply updates to perpetual positions. This addition is crucial for maintaining data integrity and simplifying the update logic.


317-317: New Function for Subaccount Updates:
The CalculateUpdatedSubaccount function consolidates updates to both asset and perpetual positions into a single, coherent operation. This structured approach enhances the maintainability and readability of the code related to subaccount updates.


344-344: Refined Risk Calculation Logic:
The refactoring of the GetRiskForSubaccount function to focus solely on the settled subaccount streamlines the risk assessment process, making it more straightforward and less prone to errors.

protocol/x/subaccounts/keeper/subaccount.go (2)

684-687: Ensure accuracy and efficiency in risk calculation

This method calculates the updated subaccount state and then retrieves the risk associated with that state. It's essential that the calculations here are both accurate and efficient, given they directly impact the system's financial assessments.

Consider adding more detailed comments explaining each step of the process, especially how the perpetual information influences the risk calculations. This would aid future maintainers or auditors in understanding the logic without digging through multiple function calls.

+ // Calculate the updated subaccount state based on the given updates and perpetual information.
+ // This state is then used to assess the risk, ensuring that the subaccount meets all financial requirements.

Line range hint 604-628: Check the error handling and logic in collateralization checks

This block of code is responsible for updating the subaccount based on the latest updates and then checking if the new state of the subaccount meets the initial collateralization requirements. If not, it checks the current state to determine if the transition is valid.

The logic here is critical for ensuring the financial integrity of the system, but it seems complex and could benefit from some refactoring for clarity. Additionally, ensure that all possible errors from proto.Marshal and salib.GetRiskForSubaccount are handled appropriately to avoid runtime panics or unhandled exceptions.

Verification successful

Check the error handling and logic in collateralization checks

The error handling for both proto.Marshal and salib.GetRiskForSubaccount is implemented correctly. The code appropriately checks for errors and returns them when they occur, ensuring that no runtime panics or unhandled exceptions will happen due to these functions.

  • proto.Marshal error handling is present and returns an error if proto.Marshal fails.
  • salib.GetRiskForSubaccount error handling is consistently applied across all instances, returning an error if the function fails.

Thus, the error handling and logic in the collateralization checks appear to be robust and well-implemented.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify error handling paths by simulating different failure scenarios in unit tests.

# Test: Check if all error paths are covered in unit tests.
rg --type go 'salib.GetRiskForSubaccount' 'protocol/x/subaccounts/keeper/subaccount.go' --context 5

Length of output: 957



Script:

#!/bin/bash
# Description: Verify error handling for `proto.Marshal` and `salib.GetRiskForSubaccount` in the specified code block.

# Check error handling for `proto.Marshal`
rg 'proto.Marshal' -A 5 protocol/x/subaccounts/keeper/subaccount.go

# Check error handling for `salib.GetRiskForSubaccount`
rg 'salib.GetRiskForSubaccount' -A 5 protocol/x/subaccounts/keeper/subaccount.go

Length of output: 646

protocol/x/subaccounts/keeper/subaccount_test.go (4)

5662-5679: Ensure accurate processing of simultaneous asset and perpetual updates.

The test case "multiple asset updates for the same position" and "multiple perpetual updates for the same position" involves complex interactions between different types of updates. It's crucial to verify that the test accurately reflects the expected outcomes and that all edge cases are covered.


4830-4831: Validate handling of multiple independent updates for the same account.

The test setup for "multiple updates are considered independently for same account" is crucial for ensuring robustness in update logic. It's important to verify that the test accurately checks for non-interference among updates.

Verification successful

Validate handling of multiple independent updates for the same account.

The test setup for "multiple updates are considered independently for same account" includes assertions that verify the expected outcomes for each update, ensuring non-interference among updates.

  • Assertions such as require.Equal(t, tc.expectedSuccessPerUpdate, successPerUpdate) and require.Equal(t, tc.expectedSuccess, success) confirm that the test checks for non-interference.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify if the test for independent updates checks for non-interference among updates.

# Test: Search for assertions in the test case. Expect: Assertions that confirm non-interference.
rg --type go --context 5 'multiple updates are considered independently for same account' protocol/x/subaccounts/keeper/subaccount_test.go

Length of output: 567



Script:

#!/bin/bash
# Description: Verify if the test for independent updates checks for non-interference among updates by searching for assertions within the test case.

# Test: Search for assertions in the test case related to "multiple updates are considered independently for same account".
rg --type go --context 10 '"multiple updates are considered independently for same account"' protocol/x/subaccounts/keeper/subaccount_test.go

Length of output: 835



Script:

#!/bin/bash
# Description: Verify if the test for independent updates checks for non-interference among updates by searching for assertions within the test file.

# Test: Search for common assertion patterns within the test file.
rg --type go 'require\.' protocol/x/subaccounts/keeper/subaccount_test.go

Length of output: 3195


515-550: Ensure proper handling of multiple updates for the same position.

The test setup for "multiple updates for same position handled gracefully" seems to correctly simulate the scenario where multiple updates are applied to a single perpetual position. However, ensure that the test verifies not only the final state but also intermediate states if necessary to fully validate the update logic.


5696-5699: Check handling of speculative updates to non-existent subaccounts.

The test setup for "speculative update to non-existent subaccount" is critical for ensuring the system's robustness against invalid or speculative updates. Ensure that the test accurately checks for the appropriate handling of such cases.

protocol/x/subaccounts/keeper/subaccount.go Show resolved Hide resolved
@BrendanChou BrendanChou merged commit ce92609 into main Jun 25, 2024
19 checks passed
@BrendanChou BrendanChou deleted the bc/updates branch June 25, 2024 20:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging this pull request may close these issues.

2 participants