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

add megavault withdrawal msg #2288

Merged
merged 6 commits into from
Sep 19, 2024
Merged

add megavault withdrawal msg #2288

merged 6 commits into from
Sep 19, 2024

Conversation

tqin7
Copy link
Contributor

@tqin7 tqin7 commented Sep 18, 2024

Changelist

add megavault withdrawal msg

  • additionally, GetVaultWithdrawalSlippage is modified to be more stateless

Test Plan

unit + integration test

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 the ability to withdraw shares from a megavault to a specified subaccount, enhancing user control over assets.
    • Added new message types and interfaces for handling withdrawal requests and responses.
    • Implemented event tracking for deposit and withdrawal actions related to the megavault.
  • Bug Fixes

    • Improved error handling for withdrawal operations to ensure users receive accurate feedback on transaction statuses.
  • Tests

    • Expanded test coverage for withdrawal functionalities, validating various scenarios to ensure reliability.
  • Chores

    • Updated internal configurations to support new withdrawal functionalities and enhance overall system robustness.

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

linear bot commented Sep 18, 2024

Copy link
Contributor

coderabbitai bot commented Sep 18, 2024

Walkthrough

The changes introduce a new feature allowing users to withdraw shares from a megavault to a specified subaccount. This includes the addition of new message types, methods, and interfaces to handle withdrawal requests and responses. The modifications span across multiple files, enhancing the vault's functionality and error handling related to withdrawals, while also updating tests to ensure the robustness of the new feature.

Changes

File Path Change Summary
indexer/packages/v4-protos/src/codegen/dydxprotocol/vault/tx.rpc.msg.ts Added withdrawFromMegavault method to Msg interface and MsgClientImpl class for handling withdrawals.
indexer/packages/v4-protos/src/codegen/dydxprotocol/vault/tx.ts Introduced MsgWithdrawFromMegavault and MsgWithdrawFromMegavaultResponse interfaces for withdrawal operations.
proto/dydxprotocol/vault/tx.proto Added WithdrawFromMegavault RPC method and corresponding message types.
protocol/app/msgs/all_msgs.go Added new message types for withdrawal operations.
protocol/app/msgs/normal_msgs.go Updated message mappings to include withdrawal messages.
protocol/app/msgs/normal_msgs_test.go Added tests for new withdrawal message types.
protocol/x/vault/keeper/withdraw.go Enhanced withdrawal logic with new parameters and added WithdrawFromMegavault function.
protocol/x/vault/types/events.go Defined event types and constructors for deposit and withdrawal actions related to the megavault.
protocol/x/vault/keeper/msg_server_withdraw_from_megavault_test.go Added comprehensive tests for MsgWithdrawFromMegavault functionality.
protocol/x/vault/keeper/msg_server_allocate_to_vault.go Modified vault allocation logic to ensure proper registration upon creation.

Possibly related PRs

Suggested reviewers

  • vincentwschau

Poem

In the vault where shares do play,
A new path opens, hip-hip-hooray!
Withdrawals now, to subaccounts bright,
Bouncing bunnies, what a sight!
With every hop, our treasures grow,
In the megavault's warm, cozy glow! 🐇✨


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between af7a7f9 and 87e811e.

Files selected for processing (1)
  • protocol/x/vault/keeper/withdraw.go (4 hunks)
Additional comments not posted (4)
protocol/x/vault/keeper/withdraw.go (4)

109-109: Verify that marketParam is being used correctly.

The marketParam is now being passed directly into the vault.SpreadPpm function instead of using an intermediate variable. This change improves the accuracy of the slippage estimation.


301-309: LGTM!

The event emission for the WithdrawFromMegavault function looks good. It includes all the necessary information, such as the owner, shares withdrawn, total shares, megavault equity, and redeemed quote quantums.


Line range hint 18-47: Verify the new parameters are used correctly in the slippage calculation.

The function signature has been updated to include additional parameters: totalShares, leverage, perpetual, and marketParam. Ensure that these parameters are being used correctly in the slippage calculation logic.


119-312: Thoroughly test the new WithdrawFromMegavault function.

The new WithdrawFromMegavault function facilitates withdrawals from a megavault to a specified subaccount. It encompasses several critical steps:

  1. Verifies the owner's available shares for withdrawal
  2. Redeems equity from the main vault
  3. Iterates through sub vaults to compute slippage and execute fund transfers
  4. Manages the transfer of funds to the designated subaccount

Ensure that each step is thoroughly tested, including edge cases and error handling. Pay close attention to the calculations and ensure that the function behaves as expected under various scenarios.

Verification successful

To ensure thorough testing of the WithdrawFromMegavault function, we should verify if there are unit tests covering this function and its edge cases. Let's search for relevant unit tests.


To get a better understanding of the test coverage for the WithdrawFromMegavault function, we need to examine the content of the test function in more detail. Let's retrieve the full content of the TestMsgWithdrawFromMegavault function and any related helper functions or setup code.


The WithdrawFromMegavault function is thoroughly tested.

The test file contains a comprehensive TestMsgWithdrawFromMegavault function that covers a wide range of scenarios:

  • Successful withdrawals with different share amounts and vault configurations
  • Failure cases (e.g., withdrawing more than unlocked shares, zero shares, negative shares)
  • Behavior with sub-vaults in various states (quoting, stand-by, close-only)
  • Edge cases like withdrawing all shares and withdrawing with zero balance in the main vault
  • Correct share calculations, equity changes, and error handling
  • Scenarios with different leverage levels and slippage calculations

The test coverage appears to be extensive, addressing various aspects of the function's behavior and potential edge cases. This thorough testing helps ensure the reliability and correctness of the WithdrawFromMegavault function.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the `WithdrawFromMegavault` function.

# Test 1: Search for the verification of owner's available shares for withdrawal.
# Expect: Checks for positive `sharesToWithdraw` and compares with owner's unlocked shares.
rg --type go -A 10 $'ownerSharesAfterWithdrawal.Cmp\(ownerLockedShares\) < 0'

# Test 2: Search for the redemption from the main vault.
# Expect: Calculates `redeemedQuoteQuantums` based on `megavaultEquity` and `sharesToWithdraw`.
rg --type go -A 5 $'redeemedQuoteQuantums.Mul\(redeemedQuoteQuantums, sharesToWithdraw\)'

# Test 3: Search for the iteration through sub vaults.
# Expect: Uses `getVaultParamsIterator` to iterate through all vaults.
rg --type go -A 5 $'vaultParamsIterator := k.getVaultParamsIterator\(ctx\)'

# Test 4: Search for the transfer of funds to the designated subaccount.
# Expect: Calls `TransferFundsFromSubaccountToSubaccount` with the correct parameters.
rg --type go -A 5 $'k.subaccountsKeeper.TransferFundsFromSubaccountToSubaccount\('

# Test 5: Search for the error handling when redeemed quantums are insufficient.
# Expect: Returns an error if `redeemedQuoteQuantums` are non-positive or less than `minQuoteQuantums`.
rg --type go -A 5 $'types.ErrInsufficientRedeemedQuoteQuantums'

Length of output: 5568


Script:

#!/bin/bash
# Search for unit tests related to WithdrawFromMegavault function

# Look for test functions related to WithdrawFromMegavault
rg --type go -A 10 'func.*Test.*WithdrawFromMegavault'

# Search for test cases within the test functions
rg --type go -A 20 'testCases.*WithdrawFromMegavault'

# Look for any assertions related to WithdrawFromMegavault
rg --type go 'assert.*WithdrawFromMegavault'

Length of output: 1209


Script:

#!/bin/bash
# Retrieve the full content of TestMsgWithdrawFromMegavault and related code

# Get the content of the test file
cat protocol/x/vault/keeper/msg_server_withdraw_from_megavault_test.go

# Search for any helper functions related to WithdrawFromMegavault testing
rg --type go -A 10 'func.*helper.*WithdrawFromMegavault'

# Look for any setup functions that might be used in the test
rg --type go -A 10 'func.*setup.*WithdrawFromMegavault'

Length of output: 20442


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 generate interesting stats about this repository and render them as a table.
    -- @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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e0b5afa and c741676.

Files ignored due to path filters (1)
  • protocol/x/vault/types/tx.pb.go is excluded by !**/*.pb.go
Files selected for processing (15)
  • indexer/packages/v4-protos/src/codegen/dydxprotocol/vault/tx.rpc.msg.ts (3 hunks)
  • indexer/packages/v4-protos/src/codegen/dydxprotocol/vault/tx.ts (3 hunks)
  • proto/dydxprotocol/vault/tx.proto (2 hunks)
  • protocol/app/module/interface_registry.go (1 hunks)
  • protocol/app/msgs/all_msgs.go (1 hunks)
  • protocol/app/msgs/normal_msgs.go (1 hunks)
  • protocol/app/msgs/normal_msgs_test.go (1 hunks)
  • protocol/testutil/encoding/utils.go (1 hunks)
  • protocol/x/vault/keeper/msg_server_withdraw_from_megavault.go (1 hunks)
  • protocol/x/vault/keeper/msg_server_withdraw_from_megavault_test.go (1 hunks)
  • protocol/x/vault/keeper/orders.go (1 hunks)
  • protocol/x/vault/keeper/vault.go (1 hunks)
  • protocol/x/vault/keeper/withdraw.go (4 hunks)
  • protocol/x/vault/keeper/withdraw_test.go (15 hunks)
  • protocol/x/vault/types/errors.go (1 hunks)
Additional comments not posted (49)
protocol/x/vault/keeper/msg_server_withdraw_from_megavault.go (1)

12-31: LGTM!

The WithdrawFromMegavault function is implemented correctly and aligns with the PR objective. It enhances the functionality of the vault system by allowing users to withdraw assets from a megavault, thereby improving the overall usability and flexibility of the protocol.

The function correctly:

  • Unwraps the SDK context.
  • Calls the keeper's WithdrawFromMegavault method with the provided parameters.
  • Constructs and returns an appropriate response based on the success or failure of the withdrawal operation.
  • Handles errors by returning them to the caller.

Great job!

protocol/x/vault/types/errors.go (2)

138-142: LGTM!

The new error variable ErrInsufficientWithdrawableShares is declared correctly using the errorsmod.Register function. The error code is unique, and the error message accurately describes the error condition related to insufficient withdrawable shares.

This addition enhances the error handling capabilities of the module by providing specific feedback to the caller.


143-147: LGTM!

The new error variable ErrInsufficientRedeemedQuoteQuantums is declared correctly using the errorsmod.Register function. The error code is unique, and the error message accurately describes the error condition related to insufficient redeemed quote quantums.

This addition enhances the error handling capabilities of the module by providing specific feedback to the caller.

protocol/testutil/encoding/utils.go (1)

96-96: LGTM!

The addition of &vaulttypes.MsgWithdrawFromMegavault{} to the msgInterfacesToRegister slice is a valuable enhancement to the test encoding configuration. It enables more comprehensive testing scenarios involving both deposits and withdrawals from the megavault, improving the overall utility of the encoding configuration for testing purposes.

The change is consistent with the existing pattern and does not introduce any breaking changes or compatibility issues.

protocol/app/module/interface_registry.go (1)

98-100: LGTM!

The addition of the dydxprotocol.vault.MsgWithdrawFromMegavault entry in the NewInterfaceRegistry function is consistent with the existing code structure and patterns. It enables the handling of withdrawal messages from the Megavault, expanding the interface registry's functionality.

The usage of the getLegacyMsgSignerFn function with the subaccount_id and owner parameters aligns with the other entries, indicating that the message type has a similar structure and signer requirements.

Overall, the change is well-integrated and unlikely to introduce any issues or inconsistencies.

indexer/packages/v4-protos/src/codegen/dydxprotocol/vault/tx.rpc.msg.ts (4)

3-3: LGTM!

The import statement has been correctly updated to include the necessary types for the new withdrawFromMegavault method.


9-11: LGTM!

The new withdrawFromMegavault method has been correctly defined in the Msg interface with the appropriate request and response types. The method documentation provides a clear description of its purpose.


37-37: LGTM!

The withdrawFromMegavault method has been correctly bound to the class instance in the constructor, ensuring that it can be called correctly.


51-55: LGTM!

The withdrawFromMegavault method has been correctly implemented in the MsgClientImpl class. The method follows the same pattern as the other methods in the class, correctly encoding the request, sending it to the RPC server, and decoding the response.

proto/dydxprotocol/vault/tx.proto (3)

20-22: LGTM!

The addition of the WithdrawFromMegavault RPC method to the Msg service looks good. It follows the standard RPC definition format and expands the functionality to support megavault withdrawals.


68-89: Approve the MsgWithdrawFromMegavault message definition.

The MsgWithdrawFromMegavault message is well-defined and includes the necessary fields for the megavault withdrawal operation:

  • subaccount_id: Identifies the subaccount to credit the withdrawn funds.
  • shares: Specifies the number of shares to withdraw.
  • min_quote_quantums: Sets a minimum threshold for the withdrawn shares in terms of quote quantums, providing a safety check.

Additionally, the (cosmos.msg.v1.signer) option enforces that only the subaccount owner can initiate the withdrawal, enhancing security.


91-100: LGTM!

The MsgWithdrawFromMegavaultResponse message is well-defined and includes the quote_quantums field, which represents the number of quote quantums redeemed from the withdrawal. This information is valuable for clients to confirm the withdrawal outcome and reconcile balances.

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

66-66: LGTM!

The added comment provides valuable information about the equity value and clearly communicates the caller's responsibility to handle different scenarios, including negative equity values. This improves the function's documentation and sets the right expectations for the caller.

protocol/app/msgs/normal_msgs_test.go (1)

156-157: LGTM!

The addition of the new message types for megavault withdrawal enhances the test coverage and aligns with the existing naming convention. Good job!

protocol/x/vault/keeper/withdraw.go (2)

Line range hint 18-117: LGTM! The refined slippage calculation enhances the accuracy of the withdrawal process.

The changes to the GetVaultWithdrawalSlippage function introduce several improvements:

  • The additional parameters (totalShares, leverage, perpetual, and marketParam) allow for a more nuanced calculation of slippage based on the current market conditions and vault parameters.
  • The refined formula for estimated slippage provides a more accurate estimation of the slippage incurred during partial withdrawals by considering factors such as posterior leverage, skew factor, and spread.
  • The function handles edge cases, such as zero leverage and 100% withdrawals, appropriately.

These enhancements contribute to a more precise and reliable calculation of slippage during the withdrawal process.


119-282: Excellent addition! The WithdrawFromMegavault function provides a robust and comprehensive mechanism for withdrawals.

The new WithdrawFromMegavault function introduces a well-structured and thorough process for withdrawing funds from a megavault to a specified subaccount. The function encompasses several key steps:

  1. Checking the owner's share availability to ensure sufficient unlocked shares for withdrawal.
  2. Redeeming equity from the main vault based on the proportion of shares being withdrawn.
  3. Iterating through sub vaults to calculate slippage and transfer the appropriate amount of funds from each sub vault to the main vault.
  4. Handling the transfer of redeemed funds from the main vault to the destination subaccount.
  5. Decrementing the total and owner shares accordingly.

The function includes robust error handling for various failure scenarios, such as insufficient shares, failed transfers, and insufficient redeemed quantums. This ensures the integrity and reliability of the withdrawal process.

Overall, the WithdrawFromMegavault function is a valuable addition that enhances the functionality and security of the megavault withdrawal process.

protocol/app/msgs/normal_msgs.go (1)

249-256: LGTM!

The addition of the new message types for megavault withdrawal operations is consistent with the existing pattern and expands the vault-related functionality as intended.

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

173-173: LGTM! The changes enhance performance and reliability.

  • Passing perpetual and marketPrice by reference is an optimization that avoids unnecessary copies of large data structures.
  • The new check for positive equity ensures that the function only proceeds with the calculation if the equity is valid. This check enhances the robustness of the function.
  • Returning a specific error type types.ErrNonPositiveEquity when equity is non-positive is a good practice. It allows the caller to handle this specific error case differently if needed.

Also applies to: 177-182

protocol/x/vault/keeper/withdraw_test.go (19)

Line range hint 33-49: LGTM!

The changes to the test case struct fields look good. The leverage field is now a *big.Rat type, which simplifies the test case structure by focusing on the leverage directly.


56-63: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly.


78-85: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly.


101-108: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly.


123-130: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly.


146-153: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly.


169-176: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly.


192-200: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly. The test case also verifies that the slippage is the same for positive and negative leverage values with the same absolute value.


216-223: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly.


238-245: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly. The test case also verifies the slippage when withdrawing 100% of the shares.


250-257: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly. The test case verifies the slippage when withdrawing a small amount of shares from a large total share pool.


273-280: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly. The test case verifies the slippage when withdrawing a significant portion of the total shares.


297-304: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly. The test case verifies the slippage when withdrawing 50% of the total shares.


321-328: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the expected slippage calculation is updated accordingly. The test case verifies the slippage when withdrawing a very high percentage (99.9999%) of the total shares.


344-352: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the test case expects an error when the vault is not found.


355-363: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the test case expects an error when the shares to withdraw is negative.


366-374: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the test case expects an error when the shares to withdraw is zero.


377-385: LGTM!

The changes to the test case look good. The leverage field is set correctly, and the test case expects an error when the shares to withdraw is greater than the total shares.


441-449: LGTM!

The changes to the GetVaultWithdrawalSlippage function call look good. The leverage parameter is now passed instead of assetQuoteQuantums and positionBaseQuantums, which aligns with the changes made to the function signature.

protocol/app/msgs/all_msgs.go (1)

265-266: Approve the addition of the new message types for withdrawing from the megavault.

The addition of MsgWithdrawFromMegavault and MsgWithdrawFromMegavaultResponse message types under the dydxprotocol.vault namespace is a valid change to support the new functionality of withdrawing assets from the megavault.

To ensure the new message types are properly handled, run the following script:

The script performs the following verifications:

  1. Checks if the message handler WithdrawFromMegavault exists for processing MsgWithdrawFromMegavault.
  2. Checks if the message handler is registered in the message server.
  3. Checks if the proto definitions exist for the new message types.

If the script produces relevant results, it confirms that the new message types are properly integrated into the codebase. If not, further investigation and fixes may be required.

Verification successful

Confirm proper integration of new megavault withdrawal message types

The verification process has confirmed that the new message types for withdrawing from the megavault are correctly integrated into the codebase:

  1. The WithdrawFromMegavault function is properly implemented in the message server (protocol/x/vault/keeper/msg_server_withdraw_from_megavault.go).
  2. A dedicated test file (protocol/x/vault/keeper/msg_server_withdraw_from_megavault_test.go) exists, containing the TestMsgWithdrawFromMegavault function to ensure the new functionality is thoroughly tested.
  3. The vault module has comprehensive test coverage, indicating good development practices and helping to ensure the reliability of the new features.

These findings confirm that the addition of MsgWithdrawFromMegavault and MsgWithdrawFromMegavaultResponse message types is well-implemented and properly tested within the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash

# Check if the message handler for MsgWithdrawFromMegavault exists
ast-grep --lang go --pattern $'func (k Keeper) WithdrawFromMegavault(goCtx sdk.Context, msg *types.MsgWithdrawFromMegavault) (*types.MsgWithdrawFromMegavaultResponse, error) {
  $$$
}'

# Check if the message handler is registered in the message server
rg --type go -A 5 $'&types.MsgWithdrawFromMegavault'

# Check if the proto definitions exist for the new message types  
fd --extension proto --exec rg $'MsgWithdrawFromMegavault|MsgWithdrawFromMegavaultResponse'

Length of output: 1041


Script:

#!/bin/bash

# Check for any function that handles MsgWithdrawFromMegavault
ast-grep --lang go --pattern 'func $_($_) $_($_ *types.MsgWithdrawFromMegavault) ($_, error) {
  $$$
}'

# Check the content of msg_server_withdraw_from_megavault.go
cat protocol/x/vault/keeper/msg_server_withdraw_from_megavault.go

# Check if the message handler is registered in the message server
rg --type go 'server.RegisterMsgService\(' -A 10

Length of output: 1520


Script:

#!/bin/bash

# Check for the setup of the msgServer struct
rg --type go 'type msgServer struct'

# Look for the registration of the vault module's message server
rg --type go 'RegisterMsgServer\(' -A 5

# Check for tests related to WithdrawFromMegavault
rg --type go 'func TestWithdrawFromMegavault' -A 5

Length of output: 20166


Script:

#!/bin/bash

# Check if WithdrawFromMegavault is handled in the message server
rg --type go 'func \(k msgServer\) WithdrawFromMegavault' -A 5

# Look for any tests related to withdrawing from megavault
rg --type go 'func Test.*Withdraw.*Megavault' -A 5

# Check for any tests in the vault keeper test files
rg --type go 'func Test' protocol/x/vault/keeper/*_test.go -A 5

Length of output: 18423

protocol/x/vault/keeper/msg_server_withdraw_from_megavault_test.go (5)

23-33: LGTM!

The VaultSetup struct is well-defined and encapsulates all the necessary parameters for setting up a vault in the test cases. It provides a clear and organized structure for configuring vaults and their associated entities.


35-281: Excellent test coverage!

The TestMsgWithdrawFromMegavault function and its associated test cases provide comprehensive coverage for the MsgWithdrawFromMegavault functionality. The test cases are well-structured, clearly defined, and cover a wide range of scenarios, including successful and failed withdrawals, different vault configurations, and varying share amounts.

The inclusion of edge cases and boundary conditions ensures that the functionality is thoroughly tested and robust. Great work on creating a comprehensive test suite!


283-511: Robust test case execution logic!

The test case execution logic is well-implemented and follows a clear and structured flow. The custom genesis document function allows for flexible initialization of the application state based on the test case parameters, ensuring that each test case has the required setup.

The CheckTx and DeliverTx phases are properly invoked, and the results are validated against the expected outcomes, ensuring end-to-end testing of the functionality. The test case execution logic covers all the necessary steps, from message construction to state validation.

Great job on creating a robust and comprehensive test case execution logic!


286-401: Flexible and modular genesis document initialization!

The custom genesis document function provides a flexible and modular way to initialize the application state for each test case. It allows for fine-grained control over the initial state of various modules and entities, such as subaccounts, vaults, prices, perpetuals, and clob pairs.

The function is well-structured and organized, with separate sections for each module's initialization. The initialization logic is based on the test case parameters, ensuring that each test case has the required setup.

This approach enhances the maintainability and extensibility of the test suite, as new modules or entities can be easily added or modified without affecting the existing code.

Great work on creating a flexible and modular genesis document initialization function!


482-509: Comprehensive equity validation logic!

The equity validation logic is a crucial part of the test suite, ensuring the correctness of the withdrawal functionality. It verifies that the equity of the owner, megavault, and sub-vaults is updated correctly based on the withdrawal amount and the test case parameters.

The validation logic covers both successful and failed withdrawal scenarios, providing comprehensive testing. The comparisons are made using the require.Equal assertions, which provide clear error messages in case of mismatches, making it easier to identify and debug any issues.

This validation logic gives confidence that the withdrawal functionality is working as expected and that the equity values are being updated correctly.

Great job on implementing a comprehensive equity validation logic!

indexer/packages/v4-protos/src/codegen/dydxprotocol/vault/tx.ts (6)

48-60: LGTM!

The MsgWithdrawFromMegavault interface is well-defined with appropriate properties and types to represent the request for withdrawing shares from a megavault to a subaccount.


84-87: LGTM!

The MsgWithdrawFromMegavaultResponse interface is well-defined with an appropriate property and type to represent the response for withdrawing shares from a megavault to a subaccount.


364-370: LGTM!

The createBaseMsgWithdrawFromMegavault function correctly creates a base MsgWithdrawFromMegavault object with appropriate default values for the properties.


373-387: LGTM!

The MsgWithdrawFromMegavault.encode function correctly encodes a MsgWithdrawFromMegavault message by checking for defined properties and encoding them using the appropriate methods.


389-417: LGTM!

The MsgWithdrawFromMegavault.decode function correctly decodes a MsgWithdrawFromMegavault message by iterating over the reader, identifying the tags, and decoding the corresponding properties using the appropriate methods.


419-425: LGTM!

The MsgWithdrawFromMegavault.fromPartial function correctly creates a MsgWithdrawFromMegavault message from a plain object by assigning the properties from the object parameter and handling undefined and null values appropriately.

Comment on lines +70 to +71
perpetual *perptypes.Perpetual,
marketPrice *pricestypes.MarketPrice,
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Add nil pointer checks to GetVaultLeverageAndEquity function

The verification process has revealed two important points:

  1. The GetVaultLeverageAndEquity function does not explicitly check for nil pointers, which could lead to runtime panics if nil values are passed for perpetual or marketPrice.

  2. All callers of the function have been correctly updated to pass pointers instead of values, matching the new function signature.

To improve the robustness of the code:

  • Add nil checks for both perpetual and marketPrice parameters at the beginning of the GetVaultLeverageAndEquity function.
  • Review the function implementation to ensure safe usage of these pointer parameters throughout the function body.

Example of nil checks to add:

func (k Keeper) GetVaultLeverageAndEquity(
    ctx sdk.Context,
    vaultId types.VaultId,
    perpetual *perptypes.Perpetual,
    marketPrice *pricestypes.MarketPrice,
) (
    leverage *big.Rat,
    equity *big.Int,
    err error,
) {
    if perpetual == nil {
        return nil, nil, errors.New("perpetual cannot be nil")
    }
    if marketPrice == nil {
        return nil, nil, errors.New("marketPrice cannot be nil")
    }
    // ... rest of the function implementation
}
Analysis chain

Verify the handling of pointer parameters and ensure caller updates.

The parameters for perpetual and marketPrice have been changed from value types to pointer types. This change introduces the following considerations:

  1. Verify that the function correctly handles the new pointer parameters to avoid potential nil pointer dereferences. Ensure that appropriate nil checks are in place before accessing the pointed-to values.

  2. Ensure that all callers of this function have been updated to pass pointers instead of values to match the new function signature.

To verify the handling of pointer parameters and the impact on callers, run the following script:

The first ast-grep command searches for nil checks on the perpetual and marketPrice parameters within the GetVaultLeverageAndEquity function. If no results are found, it indicates that the function might not be handling nil pointers correctly.

The second rg command searches for all occurrences of GetVaultLeverageAndEquity in Go files and includes five lines of context after each match. Review the results to ensure that all callers are passing pointers instead of values to match the updated function signature.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash

# Check if the function correctly handles nil pointers
ast-grep --lang go --pattern $'func (k Keeper) GetVaultLeverageAndEquity(
  ctx sdk.Context,
  vaultId types.VaultId,
  perpetual *perptypes.Perpetual,
  marketPrice *pricestypes.MarketPrice,
) (
  leverage *big.Rat,
  equity *big.Int,
  err error,
) {
  $$$
  if perpetual == nil {
    $$$
  }
  $$$
  if marketPrice == nil {
    $$$
  }
  $$$
}'

# Check if all callers have been updated to pass pointers
rg --type go -A 5 $'GetVaultLeverageAndEquity'

Length of output: 1940


_, perpetual, marketParam, marketPrice, err := k.GetVaultClobPerpAndMarket(ctx, *vaultId)
if err != nil {
log.ErrorLogWithError(ctx, "Failed to get perpetual and market", err, "Vault ID", vaultId)
Copy link
Contributor

@vincentwschau vincentwschau Sep 18, 2024

Choose a reason for hiding this comment

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

nit: These errors maybe should also surface that they are happening during withdrawal?

continue
}

slippage, err := k.GetVaultWithdrawalSlippage(
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Possibly add metric emission of slippage per vault at withdrawals for analytics?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yeah definitely a good idea to monitor slippage. however, we need to know both "percentage of withdrawal" and "slippage"

let me think more about how to monitor slippage efficiently

Copy link
Contributor Author

Choose a reason for hiding this comment

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

this is what i'm thinking: once queries are more built out, chameleon can monitor "how much slippage to withdraw x% from megavault"

i think monitoring slippage per vault is a bit too granular at the moment. what are your thoughts

Copy link
Contributor

Choose a reason for hiding this comment

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

Yea, probably. More wondering how we catch withdrawals with high slippage.

// Owner shares after withdrawal.
expectedOwnerShares uint64
}{
"Success: Withdraw some unlocked shares (5% of total), No sub-vaults, Redeemed quantums = Min quantums": {
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Test case where withdrawing > unlocked shares = failure?

}

// 4. Return error if less than min quote quantums are redeemed.
if redeemedQuoteQuantums.Cmp(minQuoteQuantums) < 0 {
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Emit some event for withdrawals (tendermint events)?

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

Outside diff range and nitpick comments (1)
protocol/x/vault/keeper/withdraw.go (1)

178-196: Consider adding a metric to monitor the slippage per vault at withdrawals.

It would be valuable to track the slippage incurred at each vault during withdrawals. This could help identify any unusual behavior or optimize the withdrawal process.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 39a75df and 411394e.

Files selected for processing (4)
  • protocol/x/vault/keeper/deposit.go (1 hunks)
  • protocol/x/vault/keeper/msg_server_withdraw_from_megavault_test.go (1 hunks)
  • protocol/x/vault/keeper/withdraw.go (4 hunks)
  • protocol/x/vault/types/events.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • protocol/x/vault/keeper/msg_server_withdraw_from_megavault_test.go
Additional comments not posted (6)
protocol/x/vault/types/events.go (2)

23-35: LGTM!

The function correctly constructs a new deposit_to_megavault event with the relevant attributes. The logic is sound, and the implementation is accurate.


37-51: LGTM!

The function correctly constructs a new withdraw_from_megavault event with the relevant attributes. The logic is sound, and the implementation is accurate.

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

47-53: LGTM!

The event emission for the deposit operation is implemented correctly:

  • The event is emitted at the right place, i.e., after the successful transfer.
  • The event captures all the relevant details about the deposit transaction.
  • The event name and fields are named appropriately and convey the necessary information.
  • The event is created using the NewDepositToMegavaultEvent function from the types package, which ensures consistency and type safety.

This change enhances the functionality by providing a mechanism to notify other components of the system about the deposit event, improving traceability and potentially enabling further actions based on this event.

protocol/x/vault/keeper/withdraw.go (3)

119-287: Excellent work! The WithdrawFromMegavault function provides a robust and secure way to withdraw from a megavault to a subaccount.

The function is well-structured and includes all the necessary steps to perform a withdrawal. The error handling and logging are thorough and will help with debugging and monitoring.


Line range hint 18-118: LGTM! The changes improve the accuracy and maintainability of the slippage calculation.

The modifications to the function signature and the use of additional parameters directly in the calculation make the function more self-contained and accurate. The logic is well-structured and easy to follow.

Verify that all calls to GetVaultWithdrawalSlippage have been updated to provide the new parameters:

Verification successful

Verification successful: All calls to GetVaultWithdrawalSlippage have been updated correctly.

The function call in protocol/x/vault/keeper/withdraw.go has been properly updated to include all the new parameters:

slippage, err := k.GetVaultWithdrawalSlippage(
    ctx,
    *vaultId,
    sharesToWithdraw,
    totalShares,
    leverage,
    &perpetual,
    &marketParam,
)

This, combined with our previous observations from the test file, confirms that all usages of the function have been correctly updated to match the new signature.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `GetVaultWithdrawalSlippage` provide the new parameters.

# Test: Search for the function usage. Expect: Only occurrences with the new signature.
rg --type go -A 5 $'GetVaultWithdrawalSlippage'

Length of output: 2293


Script:

#!/bin/bash
# Description: Verify the complete function call to GetVaultWithdrawalSlippage in withdraw.go

# Display 15 lines of context after the function call
rg --type go -A 15 'slippage, err := k.GetVaultWithdrawalSlippage\(' protocol/x/vault/keeper/withdraw.go

Length of output: 422


119-287: Verify the error handling and logging.

The function interacts with several other modules, so it's crucial to ensure that any errors returned by these modules are properly handled and logged.

Verify the error handling and logging:

Verification successful

Error handling and logging verified successfully.

The WithdrawFromMegavault function demonstrates consistent and appropriate error handling throughout its implementation. Critical errors that should halt the process are returned immediately, while less critical errors are logged to allow continued execution where possible. This approach balances robustness with the ability to process as much as possible in complex operations.

Key points:

  • Proper use of log.ErrorLogWithError for logging errors
  • Immediate returns for critical errors (e.g., GetSubaccountEquity, final transfer)
  • Logged errors with continued execution for non-critical operations (e.g., processing individual vaults)
  • Correct construction and return of the ErrInsufficientRedeemedQuoteQuantums error
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the error handling and logging in `WithdrawFromMegavault`.

# Test 1: Check if errors returned by `GetOwnerShares` are handled.
rg --type go -A 5 $'GetOwnerShares'

# Test 2: Check if errors returned by `GetSubaccountEquity` are handled and logged.
rg --type go -A 10 $'GetSubaccountEquity'

# Test 3: Check if errors returned by `GetVaultClobPerpAndMarket` are handled and logged.
rg --type go -A 10 $'GetVaultClobPerpAndMarket'

# Test 4: Check if errors returned by `GetVaultLeverageAndEquity` are handled and logged.
rg --type go -A 10 $'GetVaultLeverageAndEquity'

# Test 5: Check if errors returned by `GetVaultWithdrawalSlippage` are handled and logged.
rg --type go -A 10 $'GetVaultWithdrawalSlippage'

# Test 6: Check if errors returned by `TransferFundsFromSubaccountToSubaccount` are handled and logged.
rg --type go -A 15 $'TransferFundsFromSubaccountToSubaccount'

# Test 7: Check if the "insufficient redeemed quote quantums" error is constructed and returned correctly.
rg --type go -A 10 $'ErrInsufficientRedeemedQuoteQuantums'

Length of output: 39511

}

// NewWithdrawFromMegavaultEvent constructs a new withdraw_from_megavault sdk.Event.
func NewWithdrawFromMegavaultEvent(
Copy link
Contributor

Choose a reason for hiding this comment

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

non-blocking, could add in total equity of the megavault in the event, so that on it's own we can calculate the aggregate slippage of the withdraw.

for ; vaultParamsIterator.Valid(); vaultParamsIterator.Next() {
vaultId, err := types.GetVaultIdFromStateKey(vaultParamsIterator.Key())
if err != nil {
log.ErrorLogWithError(ctx, "Megavault withdrawal: failed to get vault ID from state key", err)
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: In the log message note that withdrawing from this vault is being skipped?

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

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

Line range hint 37-52: Consider extracting the vault initialization logic into a separate function.

To improve code readability and reusability, consider extracting the vault initialization logic (setting vault params and adding to address store) into a separate function, e.g., InitializeVault(ctx, vaultID). This will make the AllocateToVault function more concise and allow the initialization logic to be reused in other places if needed.

Here's how you can refactor the code:

func (k msgServer) InitializeVault(ctx sdk.Context, vaultID types.VaultId) error {
    err := k.Keeper.SetVaultParams(
        ctx,
        vaultID,
        types.VaultParams{
            Status: types.VaultStatus_VAULT_STATUS_STAND_BY,
        },
    )
    if err != nil {
        return err
    }
    k.Keeper.AddVaultToAddressStore(ctx, vaultID)
    return nil
}

func (k msgServer) AllocateToVault(
    goCtx context.Context,
    msg *types.MsgAllocateToVault,
) (*types.MsgAllocateToVaultResponse, error) {
    // ...

    _, exists = k.Keeper.GetVaultParams(ctx, msg.VaultId)
    if !exists {
        if err := k.InitializeVault(ctx, msg.VaultId); err != nil {
            return nil, err
        }
    }

    // ...
}

Line range hint 1-73: Add a log message for the successful allocation.

To improve observability and debugging, consider adding a log message using the ctx.Logger().Info() function after a successful allocation to the vault. This will help in tracking and monitoring the allocations.

Here's how you can add the log message:

// ...

// Transfer from main vault to the specified vault.
if err := k.Keeper.subaccountsKeeper.TransferFundsFromSubaccountToSubaccount(
    ctx,
    types.MegavaultMainSubaccount,
    *msg.VaultId.ToSubaccountId(),
    assetstypes.AssetUsdc.Id,
    msg.QuoteQuantums.BigInt(),
); err != nil {
    return nil, err
}

ctx.Logger().Info("Allocated funds to vault", "vault_id", msg.VaultId, "amount", msg.QuoteQuantums)

return &types.MsgAllocateToVaultResponse{}, nil
protocol/x/vault/keeper/withdraw.go (1)

109-109: Nitpick: Consider renaming vault.SpreadPpm to vault.GetSpreadPpm for clarity.

To improve readability and maintain consistency with other function names, consider renaming vault.SpreadPpm to vault.GetSpreadPpm.

Apply this diff to rename the function:

-		vault.SpreadPpm(&quotingParams, marketParam),
+		vault.GetSpreadPpm(&quotingParams, marketParam),
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d4d9745 and 79d9ea7.

Files selected for processing (3)
  • protocol/x/vault/keeper/msg_server_allocate_to_vault.go (2 hunks)
  • protocol/x/vault/keeper/withdraw.go (4 hunks)
  • protocol/x/vault/types/events.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • protocol/x/vault/types/events.go
Additional comments not posted (4)
protocol/x/vault/keeper/msg_server_allocate_to_vault.go (1)

Line range hint 37-52: Verify the impact of adding a new vault to the address store.

The changes look good in terms of initializing the vault parameters and adding the vault to the address store when it doesn't exist. However, please ensure that adding a new vault to the address store in this scenario does not have any unintended side effects or break any assumptions in other parts of the codebase that rely on the address store.

To verify the impact, run the following script:

Verification successful

Verification successful: Adding new vault to address store has no apparent side effects

The changes to initialize vault parameters and add the vault to the address store when it doesn't exist are consistent with existing usage patterns in the codebase. There's no evidence of code making assumptions about vaults in the address store that could be violated by this new behavior. The impact of adding a new vault to the address store in this scenario appears to be minimal and aligned with the intended functionality.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash

# Description: 
# - Verify if adding a new vault to the address store has any unintended side effects.
# - Check if other parts of the codebase rely on the address store and if their assumptions still hold.

# Test 1: Search for usages of the `AddVaultToAddressStore` function.
# Expect: Only legitimate usages that align with the new behavior.
rg --type go -A 5 $'AddVaultToAddressStore'

# Test 2: Search for code that reads from the address store and makes assumptions about the stored vaults.
# Expect: No code that assumes vaults in the address store must have a specific status or properties.
rg --type go -A 10 $'GetVaultFromAddressStore|GetVaultsFromAddressStore'

Length of output: 4173

protocol/x/vault/keeper/withdraw.go (3)

119-306: LGTM! The WithdrawFromMegavault function is well-structured and handles errors appropriately.

The new WithdrawFromMegavault function is implemented correctly and follows best practices:

  • It performs necessary checks, such as verifying the owner's available shares for withdrawal.
  • It handles the withdrawal process step-by-step, including redeeming equity from the main vault, iterating through sub vaults to compute slippage and execute fund transfers, and managing the transfer of funds to the designated subaccount.
  • It includes robust error handling, logging errors and skipping vaults when necessary.
  • It emits an event upon successful withdrawal.

Great job on this implementation!


247-247: As mentioned by @vincentwschau in a previous review:

nit: Emit some event for withdrawals (tendermint events)?

This has been addressed by emitting the WithdrawFromMegavaultEvent event on lines 295-303.


Line range hint 18-47: Verify the function signature change in the codebase.

The function signature has been updated to include additional parameters: totalShares, leverage, perpetual, and marketParam. This change is beneficial as it allows for a more accurate calculation of slippage by directly utilizing the marketParam instead of relying on an intermediate variable.

However, ensure that all calls to GetVaultWithdrawalSlippage have been updated to match the new signature throughout the codebase.

Run the following script to verify the function usage:

Verification successful

To ensure we haven't missed any potential uses of the function, let's perform one more comprehensive search:


Function signature change verified successfully

The comprehensive search confirms that the GetVaultWithdrawalSlippage function signature has been consistently updated throughout the codebase. All occurrences of the function, including its definition, calls, and test cases, are using the new signature with the additional parameters (totalShares, leverage, perpetual, marketParam).

No instances of the old signature or partially updated calls were found, indicating a thorough and consistent implementation of the change.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `GetVaultWithdrawalSlippage` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type go -A 5 $'GetVaultWithdrawalSlippage'

Length of output: 2293


Script:

#!/bin/bash
# Description: Comprehensive search for any uses of GetVaultWithdrawalSlippage

# Search for any occurrence of GetVaultWithdrawalSlippage, including comments and string literals
rg --type go -i "GetVaultWithdrawalSlippage"

# Search for any occurrence of just "WithdrawalSlippage" to catch any potential renamed or similarly named functions
rg --type go -i "WithdrawalSlippage"

Length of output: 1039

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

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

301-309: Consider emitting Tendermint events for withdrawals.

In addition to the custom event, consider emitting Tendermint events for withdrawals. This can help with indexing and querying withdrawal transactions.

ctx.EventManager().EmitEvent(
    sdk.NewEvent(
        types.EventTypeWithdrawFromMegavault,
        sdk.NewAttribute(types.AttributeKeyOwner, toSubaccount.Owner),
        sdk.NewAttribute(types.AttributeKeySharesWithdrawn, sharesToWithdraw.String()),
        sdk.NewAttribute(types.AttributeKeyTotalShares, totalShares.String()),
        sdk.NewAttribute(types.AttributeKeyMegavaultEquity, megavaultEquity.String()),
        sdk.NewAttribute(types.AttributeKeyRedeemedQuoteQuantums, redeemedQuoteQuantums.String()),
    ),
)

174-175: Consider logging when skipping a vault.

When an error occurs while processing a vault and it is skipped, consider adding a log message to indicate that the vault is being skipped. This can help with debugging and monitoring.

log.InfoLog(
    ctx,
    "Megavault withdrawal: Skipping vault due to error",
    "Vault ID",
    vaultId,
)
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 79d9ea7 and af7a7f9.

Files selected for processing (2)
  • protocol/x/vault/keeper/msg_server_withdraw_from_megavault_test.go (1 hunks)
  • protocol/x/vault/keeper/withdraw.go (4 hunks)
Files skipped from review as they are similar to previous changes (1)
  • protocol/x/vault/keeper/msg_server_withdraw_from_megavault_test.go
Additional comments not posted (4)
protocol/x/vault/keeper/withdraw.go (4)

202-220: ****

nit: Possibly add metric emission of slippage per vault at withdrawals for analytics?


228-234: ****

question, why not just transfer from the vault to the destination subaccount rather than all to the main vault first, then the subaccount.
Might be minor, but would reduce gas usage.
Non-blocking: On this note, simply calculating the quote quantums to redeem and then bulk transferring if redeemed > min would be slightly more efficient.


Line range hint 18-47: Verify the new parameters are used correctly in the slippage calculation.

The function signature has been updated to include additional parameters: totalShares, leverage, perpetual, and marketParam. Ensure that these parameters are being used correctly in the slippage calculation logic.

Verification successful

New parameters are correctly used in the slippage calculation

The verification process confirms that the new parameters (totalShares, leverage, perpetual, and marketParam) are indeed used correctly in the GetVaultWithdrawalSlippage function:

  • totalShares is used for input validation and in calculations for posterior leverage and estimated slippage.
  • leverage is used for input validation, simple slippage calculation, and in calculations for posterior leverage and estimated slippage.
  • perpetual is used to retrieve the liquidity tier for the simple slippage calculation.
  • marketParam is used in the spread calculation for estimated slippage.

The implementation aligns with the expected usage of these parameters in the slippage calculation logic.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of new parameters in the slippage calculation.

# Test 1: Search for the usage of `totalShares`. Expect: Used in the calculation of `posteriorLeverage`.
rg --type go -A 5 $'totalShares\b'

# Test 2: Search for the usage of `leverage`. Expect: Used in the calculation of `posteriorLeverage` and `estimatedSlippage`.
rg --type go -A 5 $'leverage\b'

# Test 3: Search for the usage of `perpetual`. Expect: Used to retrieve the liquidity tier for calculating `simpleSlippage`.
rg --type go -A 5 $'perpetual\b'

# Test 4: Search for the usage of `marketParam`. Expect: Used in the calculation of `estimatedSlippage`.
rg --type go -A 5 $'marketParam\b'

Length of output: 142


Script:

#!/bin/bash
# Verify file existence and content

# Find the withdraw.go file
fd withdraw.go

# If found, display its content
fd withdraw.go -x cat {}

# If cat works, try searching with grep instead of rg
fd withdraw.go -x grep -n "totalShares" {}
fd withdraw.go -x grep -n "leverage" {}
fd withdraw.go -x grep -n "perpetual" {}
fd withdraw.go -x grep -n "marketParam" {}

Length of output: 13385


119-312: Ensure proper error handling and logging throughout the withdrawal process.

The new WithdrawFromMegavault function performs several critical steps, including share verification, equity redemption, slippage calculation, and fund transfers. Verify that appropriate error handling and logging are in place to handle potential failures at each step.

Verification successful

Error handling and logging in the withdrawal process are generally well-implemented, with one minor inconsistency.

The WithdrawFromMegavault function demonstrates robust error handling and logging practices throughout most of its implementation. Errors are properly wrapped with context-specific error types, and appropriate logging is in place. The sub vault redemption process shows good error management, logging errors with context and skipping problematic vaults.

However, there is one instance of inconsistent error handling:

if err != nil {
    log.ErrorLogWithError(ctx, "Megavault withdrawal: failed to get megavault main vault equity", err)
    return nil, err
}

Consider wrapping this error for consistency with the rest of the function, e.g.:

if err != nil {
    log.ErrorLogWithError(ctx, "Megavault withdrawal: failed to get megavault main vault equity", err)
    return nil, errorsmod.Wrap(err, "failed to get megavault main vault equity")
}

This minor adjustment would improve the overall consistency of error handling in the function.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling and logging in the withdrawal process.

# Test 1: Search for error handling when checking shares to withdraw. Expect: Relevant error handling and logging.
rg --type go -A 10 $'sharesToWithdraw.Sign\(\) <= 0'

# Test 2: Search for error handling when redeeming from the main vault. Expect: Relevant error handling and logging.
rg --type go -A 10 $'redeemedQuoteQuantums = new\(big.Int\).Set\(megavaultEquity\)'

# Test 3: Search for error handling when redeeming from sub vaults. Expect: Relevant error handling and logging for each potential failure point (getting vault ID, perpetual, market, leverage, equity, slippage, and fund transfer).
rg --type go -A 10 $'for ; vaultParamsIterator.Valid\(\); vaultParamsIterator.Next\(\) {'

# Test 4: Search for error handling when transferring funds to the destination subaccount. Expect: Relevant error handling and logging.
rg --type go -A 10 $'err = k.subaccountsKeeper.TransferFundsFromSubaccountToSubaccount\('

Length of output: 4857


Script:

#!/bin/bash
# Description: Verify error handling and logging in the withdrawal process, focusing on sub vault redemption and consistency in error wrapping.

# Test 1: Search for error handling when redeeming from sub vaults.
rg --type go -A 20 'vaultParamsIterator := k.getVaultParamsIterator\(ctx\)'

# Test 2: Search for direct error returns in WithdrawFromMegavault function.
rg --type go -C 5 'return nil, err' protocol/x/vault/keeper/withdraw.go

Length of output: 10610

@tqin7 tqin7 merged commit e2727fe into main Sep 19, 2024
39 checks passed
@tqin7 tqin7 deleted the tq/tra-586 branch September 19, 2024 14:58
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