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

disable deactivating vaults with positive equity #2301

Merged
merged 4 commits into from
Sep 20, 2024
Merged

disable deactivating vaults with positive equity #2301

merged 4 commits into from
Sep 20, 2024

Conversation

tqin7
Copy link
Contributor

@tqin7 tqin7 commented Sep 19, 2024

Changelist

[Describe or list the changes made in this PR]

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 a validation check to prevent deactivation of vaults with positive equity.
    • Added specific error messages for failed vault deactivation attempts.
  • Bug Fixes

    • Enhanced error handling related to vault management, ensuring stricter compliance with deactivation rules.
  • Tests

    • Expanded test cases to cover new scenarios around vault deactivation and equity conditions.
    • Updated test structure for clarity and alignment with new naming conventions.

@tqin7 tqin7 requested a review from a team as a code owner September 19, 2024 20:47
Copy link

linear bot commented Sep 19, 2024

Copy link
Contributor

coderabbitai bot commented Sep 19, 2024

Walkthrough

The changes introduce a validation check in the SetVaultParams function to prevent deactivating vaults that still hold positive equity. The testing framework is refactored for clarity, with type names updated to reflect a new naming convention. New test scenarios are added to cover the deactivation logic and asset handling. Additionally, two new error variables related to vault deactivation are introduced to improve error handling.

Changes

File Path Change Summary
protocol/x/vault/keeper/params.go Added validation in SetVaultParams to prevent deactivation of vaults with positive equity.
protocol/x/vault/keeper/params_test.go Refactored tests to use vaulttypes, updated test cases for new scenarios, and improved error handling.
protocol/x/vault/types/errors.go Introduced ErrVaultDeactivation and ErrDeactivatePositiveEquityVault with error code 29 for vault deactivation conditions.
protocol/x/vault/keeper/msg_server_withdraw_from_megavault_test.go Modified vault status in tests from VAULT_STATUS_DEACTIVATED to VAULT_STATUS_STAND_BY.
protocol/x/vault/keeper/orders_test.go Updated test scenario descriptions and asset quantum values to reflect changes in vault activation conditions.
protocol/x/vault/keeper/vault_test.go Altered vault statuses and equity values in tests to refine handling of vault states and equity calculations.

Possibly related PRs

Suggested labels

indexer, proto

Poem

In the vaults where rabbits play,
New rules come hopping in today.
With equity, we must be wise,
Deactivate? Only if it lies!
So let us cheer, with a joyful thump,
For clearer paths and a safer jump! 🐇✨


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 67ec8f9 and a52c0bc.

Files selected for processing (2)
  • protocol/x/vault/keeper/orders_test.go (2 hunks)
  • protocol/x/vault/keeper/vault_test.go (3 hunks)
Additional comments not posted (6)
protocol/x/vault/keeper/vault_test.go (2)

40-40: LGTM!

The change in vault status from VAULT_STATUS_DEACTIVATED to VAULT_STATUS_STAND_BY is consistent with the expected behavior of not decommissioning the vault. The test case is aptly named "Decommission no vault" to reflect this behavior.


Line range hint 467-487: LGTM!

The change in the deactivated vault's equity from 5 to -5 is consistent with the expected behavior of not including the deactivated vault's negative equity in the megavault equity calculation. The test case description is updated to reflect this change, and the expected megavault equity remains unchanged at 1,345.

protocol/x/vault/keeper/orders_test.go (4)

Line range hint 69-80: LGTM!

The test case changes align with the updated test case name and expected behavior. The asset quantum update for the second vault correctly puts it below the activation threshold.


Line range hint 83-270:


Line range hint 272-626:


Line range hint 628-686:


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    -- I pushed a fix in commit <commit_id>, please review it.
    -- Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    -- @coderabbitai generate unit testing code for this file.
    -- @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    -- @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    -- @coderabbitai read src/utils.ts and generate unit testing code.
    -- @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    -- @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

Outside diff range and nitpick comments (2)
protocol/x/vault/keeper/params_test.go (2)

155-190: Simplify Genesis State Initialization

The genesis state setup for both the vault and subaccounts modules involves conditional checks and updates. Consider refactoring this code to reduce complexity and improve maintainability, perhaps by extracting common logic into helper functions.


Line range hint 301-305: Add Validation for Empty Operator Address

Setting the operator address to an empty string should fail with a validation error. Consider adding explicit validation for the operator address to ensure it's a valid non-empty string.

Apply this diff to include address validation:

 // Set invalid operator and get.
 invalidParams := vaulttypes.OperatorParams{
     Operator: "",
 }
 err = k.SetOperatorParams(ctx, invalidParams)
 require.Error(t, err)
+// Verify that the error is due to an empty operator address.
+require.Equal(t, "operator address cannot be empty", err.Error())
 require.Equal(t, newParams, k.GetOperatorParams(ctx))
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cee80fc and ae86010.

Files selected for processing (3)
  • protocol/x/vault/keeper/params.go (1 hunks)
  • protocol/x/vault/keeper/params_test.go (10 hunks)
  • protocol/x/vault/types/errors.go (1 hunks)
Additional comments not posted (8)
protocol/x/vault/types/errors.go (1)

148-152: LGTM!

The introduction of the ErrVaultDeactivation error variable enhances the error handling capabilities of the vault module by providing a specific error condition related to vault deactivation. The error message clearly conveys the condition under which the error is triggered, i.e., when attempting to deactivate a vault with non-zero USDC balance.

The unique error code (29) allows for easy identification and handling of this specific error condition in the codebase. The error is registered under the appropriate ModuleName namespace, ensuring proper organization and scoping of errors within the module.

Overall, this addition improves the clarity and robustness of the code's logic regarding vault management, making it explicit that vaults can only be deactivated when their USDC balance is zero.

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

71-76: LGTM! The added validation check enhances the vault deactivation logic.

The new validation check in the SetVaultParams function prevents the deactivation of a vault if it still has a non-zero USDC position. This is a valuable safeguard that ensures vaults with active positions cannot be deactivated prematurely, maintaining the integrity of the vault system.

Returning the custom error types.ErrVaultDeactivation provides a clear indication of the specific reason for the validation failure, making it easier to handle and troubleshoot issues related to vault deactivation.

Overall, this change enhances the robustness and reliability of the vault management process.

protocol/x/vault/keeper/params_test.go (6)

17-19: Consistent Renaming of Imported Types

The aliases satypes and vaulttypes are correctly used for the subaccounts and vault types packages, respectively. This enhances code readability by clearly indicating which module the types are associated with.


98-113: Correct Handling of Vault Deactivation Without Positions

The test case "Success - Deactivate a vault with no quote quantums" appropriately checks that a vault without any quote quantums can be deactivated successfully. This ensures that vaults with no active positions can be cleanly deactivated.


202-208: Ensure Vault Params Remain Unchanged After Error

After an error occurs in SetVaultParams, the test correctly verifies that the existing vault parameters remain unchanged. This is important to maintain data integrity when an operation fails.


265-265: Default Quoting Params are Correctly Retrieved

The assertion require.Equal(t, vaulttypes.DefaultQuotingParams(), p) confirms that when no quoting parameters are set for a vault, the default parameters are used. This ensures that vaults have valid quoting parameters even when custom ones are not defined.


286-290: Verification of Default Operator Parameters

The test confirms that the operator defaults to the governance module account at genesis, which is essential for initializing the system with proper permissions.


6-6: Verify the Usage of CometBFT Package

The import statement "github.com/cometbft/cometbft/types" introduces the types package from CometBFT. Ensure that this package is compatible with the rest of your codebase and that there are no version conflicts or deprecation issues.

Run the following script to check for consistent usage of CometBFT types:

Verification successful

CometBFT Package Usage Verified

The import of "github.com/cometbft/cometbft/types" in protocol/x/vault/keeper/params_test.go is consistent with its usage across the codebase. This package is widely used in both test and production code across various modules, indicating it's an integral part of the project. No inconsistencies or potential conflicts were identified.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all Go files importing CometBFT types.

rg --type go --glob '*.go' '"github.com/cometbft/cometbft/types"'

Length of output: 4950

Comment on lines 114 to 130
"Failure - Deactivate a vault with non-zero quote quantums": {
vaultId: constants.Vault_Clob1,
existingVaultParams: &constants.VaultParams,
assetQuoteQuantums: 1,
vaultParams: &vaulttypes.VaultParams{
Status: vaulttypes.VaultStatus_VAULT_STATUS_DEACTIVATED,
},
expectedIndexerEvents: []*indexerevents.UpsertVaultEventV1{
{
Address: constants.Vault_Clob1.ToModuleAccountAddress(),
ClobPairId: constants.Vault_Clob1.Number,
Status: v1.VaultStatusToIndexerVaultStatus(
vaulttypes.VaultStatus_VAULT_STATUS_DEACTIVATED,
),
},
},
expectedErr: vaulttypes.ErrVaultDeactivation,
Copy link
Contributor

Choose a reason for hiding this comment

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

Adjust Expected Indexer Events for Failed Operations

In the test case "Failure - Deactivate a vault with non-zero quote quantums", even though an error is expected due to existing quote quantums, expectedIndexerEvents are still populated. Since the operation fails, no indexer events should be emitted.

Apply this diff to remove the expectedIndexerEvents from the failure test case:

 "Failure - Deactivate a vault with non-zero quote quantums": {
     vaultId:             constants.Vault_Clob1,
     existingVaultParams: &constants.VaultParams,
     assetQuoteQuantums:  1,
     vaultParams: &vaulttypes.VaultParams{
         Status: vaulttypes.VaultStatus_VAULT_STATUS_DEACTIVATED,
     },
-    expectedIndexerEvents: []*indexerevents.UpsertVaultEventV1{
-        {
-            Address:    constants.Vault_Clob1.ToModuleAccountAddress(),
-            ClobPairId: constants.Vault_Clob1.Number,
-            Status: v1.VaultStatusToIndexerVaultStatus(
-                vaulttypes.VaultStatus_VAULT_STATUS_DEACTIVATED,
-            ),
-        },
-    },
     expectedErr: vaulttypes.ErrVaultDeactivation,
 },
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.

Suggested change
"Failure - Deactivate a vault with non-zero quote quantums": {
vaultId: constants.Vault_Clob1,
existingVaultParams: &constants.VaultParams,
assetQuoteQuantums: 1,
vaultParams: &vaulttypes.VaultParams{
Status: vaulttypes.VaultStatus_VAULT_STATUS_DEACTIVATED,
},
expectedIndexerEvents: []*indexerevents.UpsertVaultEventV1{
{
Address: constants.Vault_Clob1.ToModuleAccountAddress(),
ClobPairId: constants.Vault_Clob1.Number,
Status: v1.VaultStatusToIndexerVaultStatus(
vaulttypes.VaultStatus_VAULT_STATUS_DEACTIVATED,
),
},
},
expectedErr: vaulttypes.ErrVaultDeactivation,
"Failure - Deactivate a vault with non-zero quote quantums": {
vaultId: constants.Vault_Clob1,
existingVaultParams: &constants.VaultParams,
assetQuoteQuantums: 1,
vaultParams: &vaulttypes.VaultParams{
Status: vaulttypes.VaultStatus_VAULT_STATUS_DEACTIVATED,
},
expectedErr: vaulttypes.ErrVaultDeactivation,

@tqin7 tqin7 changed the title cannot deactivate vaults that have usdc positions disable deactivating vaults with positive equity Sep 19, 2024
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.

2 participants