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

Include getting main subaccount equity / pnl for megavault PnL query. #2376

Merged

Conversation

vincentwschau
Copy link
Contributor

@vincentwschau vincentwschau commented Sep 26, 2024

Changelist

Get main subaccount PnL ticks + main subaccount USDC balance for equity calculations.
Misc.

  • add ordering for aggregated Pnl ticks by time

Test Plan

Unit tests.

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 constants for MEGAVAULT_MODULE_ADDRESS and MEGAVAULT_SUBACCOUNT_ID to enhance vault functionality.
    • Added a new function to fetch the equity of the main vault subaccount, improving financial metrics accuracy.
    • Updated the vault controller to include main subaccount equity in calculations.
  • Bug Fixes

    • Adjusted test cases to reflect changes in equity calculations for the main vault subaccount.
  • Refactor

    • Enhanced logic for aggregating equity from vault positions to include main subaccount data.

@vincentwschau vincentwschau requested a review from a team as a code owner September 26, 2024 19:20
Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

Walkthrough

The changes introduce new constants related to the megavault functionality in the codebase, specifically MEGAVAULT_MODULE_ADDRESS and MEGAVAULT_SUBACCOUNT_ID. These constants are integrated into various components, including test cases and the vault controller, to enhance equity calculations and support the handling of subaccounts. Additionally, a new method for fetching the main subaccount's equity is added, improving the overall accuracy of financial metrics related to vaults.

Changes

Files Change Summary
indexer/packages/postgres/src/constants.ts Added constants MEGAVAULT_MODULE_ADDRESS and MEGAVAULT_SUBACCOUNT_ID, and imported the SubaccountTable.
indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts Updated test suite to accommodate the main vault subaccount, including new variable mainVaultEquity and modified test cases for /megavault/historicalPnl. Updated createPnlTicks function to accept a boolean parameter.
indexer/services/comlink/src/controllers/api/v4/vault-controller.ts Modified getVaultSubaccountPnlTicks to accept an array of subaccount IDs, introduced getMainSubaccountEquity for fetching main subaccount equity, and updated equity aggregation logic to include the main subaccount's equity.

Possibly related PRs

Suggested reviewers

  • shrenujb

Poem

🐰 In the vault where numbers dance,
Constants added, take a chance!
Equity flows, subaccounts gleam,
In the code, we build our dream.
With every tick and every call,
The megavault stands proud and tall! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1698310 and 6390a41.

📒 Files selected for processing (1)
  • indexer/packages/postgres/src/constants.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • indexer/packages/postgres/src/constants.ts

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

🧹 Outside diff range and nitpick comments (4)
indexer/packages/postgres/src/constants.ts (2)

134-135: LGTM: MEGAVAULT_MODULE_ADDRESS constant.

The constant is correctly defined and exported. The comment provides valuable context about the source of this constant.

Consider updating the comment to include the specific version of the protocol, as it currently references a development branch:

-// From https://github.com/dydxprotocol/v4-chain/blob/protocol/v7.0.0-dev0/protocol/app/module_accounts_test.go#L41
+// From https://github.com/dydxprotocol/v4-chain/blob/main/protocol/app/module_accounts_test.go#L41

This will ensure the reference remains valid even if the development branch is deleted or renamed.


136-136: LGTM: MEGAVAULT_SUBACCOUNT_ID constant.

The constant is correctly defined using the uuid function and MEGAVAULT_MODULE_ADDRESS.

Consider adding a brief comment to explain the significance of the 0 passed to the uuid function:

-export const MEGAVAULT_SUBACCOUNT_ID: string = uuid(MEGAVAULT_MODULE_ADDRESS, 0);
+// Generate the subaccount ID for the main (0th) subaccount of the megavault module
+export const MEGAVAULT_SUBACCOUNT_ID: string = uuid(MEGAVAULT_MODULE_ADDRESS, 0);

This will provide context for future developers about why 0 is used here.

indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts (2)

Line range hint 158-182: Fix the typo in the comment for clarity

There's a minor typo in the comment when calling createPnlTicks:

-true, // createMainSubaccounPnlTicks
+true, // createMainSubaccountPnlTicks

Correcting the typo improves code readability and prevents confusion.


Line range hint 467-548: Refactor createPnlTicks to reduce code duplication

The code for creating PnL ticks for different subaccounts is repetitive. Consider refactoring to parameterize the subaccount ID and shared properties.

Here's how you can refactor the function:

async function createPnlTicks(
  createMainSubaccountPnlTicks: boolean = false,
): Promise<PnlTicksFromDatabase[]> {
  const createdTicks: PnlTicksFromDatabase[] = [];

  const subaccounts = [
    testConstants.defaultSubaccountId,
    testConstants.vaultSubaccountId,
  ];

  if (createMainSubaccountPnlTicks) {
    subaccounts.push(MEGAVAULT_SUBACCOUNT_ID);
  }

  for (const subaccountId of subaccounts) {
    const ticks = await Promise.all([
      PnlTicksTable.create({
        ...testConstants.defaultPnlTick,
        subaccountId,
      }),
      PnlTicksTable.create({
        ...testConstants.defaultPnlTick,
        subaccountId,
        blockTime: twoDaysAgo.toISO(),
        createdAt: twoDaysAgo.toISO(),
        blockHeight: twoDayBlockHeight,
      }),
      PnlTicksTable.create({
        ...testConstants.defaultPnlTick,
        subaccountId,
        blockTime: twoHoursAgo.toISO(),
        createdAt: twoHoursAgo.toISO(),
        blockHeight: twoHourBlockHeight,
      }),
      PnlTicksTable.create({
        ...testConstants.defaultPnlTick,
        subaccountId,
        blockTime: currentTime.toISO(),
        createdAt: currentTime.toISO(),
        blockHeight: currentBlockHeight,
      }),
    ]);
    createdTicks.push(...ticks);
  }

  return createdTicks;
}

This refactoring improves maintainability by reducing duplication and making it easier to add or remove subaccounts in the future.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 59b6b7a and f52ca5d.

📒 Files selected for processing (3)
  • indexer/packages/postgres/src/constants.ts (2 hunks)
  • indexer/services/comlink/tests/controllers/api/v4/vault-controller.test.ts (7 hunks)
  • indexer/services/comlink/src/controllers/api/v4/vault-controller.ts (6 hunks)
🔇 Additional comments (9)
indexer/packages/postgres/src/constants.ts (2)

26-26: LGTM: Import statement for uuid function.

The import statement for the uuid function from the local module is correct and necessary for the new constant MEGAVAULT_SUBACCOUNT_ID.


26-26: Summary: Changes align with PR objectives.

The introduced changes (new import and two new constants) are consistent with the PR objectives of enhancing functionality related to the main subaccount's PnL calculations within the megavault system. The MEGAVAULT_MODULE_ADDRESS and MEGAVAULT_SUBACCOUNT_ID constants provide necessary identifiers for the megavault functionality, which will be crucial for accurate equity calculations as mentioned in the PR summary.

To ensure these constants are used appropriately in the codebase, run the following script:

This will help confirm that the new constants are being utilized as intended across the project.

Also applies to: 134-136

✅ Verification successful

Verified: Constants are being used appropriately across the codebase.

The constants MEGAVAULT_MODULE_ADDRESS and MEGAVAULT_SUBaccount_ID are correctly imported and utilized in the relevant controller and test files, ensuring they align with the PR objectives to enhance megavault functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of new megavault constants in the codebase.

echo "Searching for MEGAVAULT_MODULE_ADDRESS usage:"
rg --type typescript "MEGAVAULT_MODULE_ADDRESS"

echo "\nSearching for MEGAVAULT_SUBACCOUNT_ID usage:"
rg --type typescript "MEGAVAULT_SUBACCOUNT_ID"

Length of output: 368


Script:

#!/bin/bash
# Description: Verify the usage of new megavault constants in the codebase.

echo "Searching for MEGAVAULT_MODULE_ADDRESS usage:"
rg "MEGAVAULT_MODULE_ADDRESS" --type ts

echo "\nSearching for MEGAVAULT_SUBACCOUNT_ID usage:"
rg "MEGAVAULT_SUBACCOUNT_ID" --type ts

Length of output: 2084

indexer/services/comlink/src/controllers/api/v4/vault-controller.ts (4)

27-27: Approved: Importing MEGAVAULT_SUBACCOUNT_ID

The addition of MEGAVAULT_SUBACCOUNT_ID to the import statement ensures that the constant is available for use in the module.


110-110: Approved: Sorting PnL ticks by block time

The use of _.sortBy to sort pnlTicksWithCurrentTick by blockTime ensures that the PnL ticks are chronologically ordered, which is essential for accurate historical data representation.


88-91: Ensure consistent inclusion of the main subaccount

When calling getVaultSubaccountPnlTicks, verify that all necessary subaccount IDs, including the main subaccount, are included in other parts of the code where applicable.

Run the following script to check for other invocations:


446-453: Verify the uniqueness of the main subaccount's USDC balance retrieval

Ensure that the findUsdcPositionForSubaccounts method correctly retrieves the USDC balance for the main subaccount and that there are no discrepancies in the data.

Run the following script to validate the USDC balance retrieval:

Expected result: Confirm that the method is called with the correct subaccount ID and that the returned balance is as expected.

✅ Verification successful

USDC balance retrieval is correctly implemented and uniquely defined.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the USDC balance for the main subaccount is retrieved correctly.

# Test: Check for multiple entries or missing entries for the main subaccount.
ast-grep --lang typescript --pattern $'AssetPositionTable.findUsdcPositionForSubaccounts($_)'

Length of output: 537


Script:

#!/bin/bash
# Description: Verify the uniqueness and correct usage of MEGAVAULT_SUBACCOUNT_ID and findUsdcPositionForSubaccounts.

# Check all definitions of MEGAVAULT_SUBACCOUNT_ID
ast-grep --lang typescript --pattern $'const MEGAVAULT_SUBACCOUNT_ID = $_'

# Check all usages of findUsdcPositionForSubaccounts to ensure it's only called with MEGAVAULT_SUBACCOUNT_ID
ast-grep --lang typescript --pattern $'AssetPositionTable.findUsdcPositionForSubaccounts($_)' | grep 'MEGAVAULT_SUBACCOUNT_ID'

Length of output: 306

indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts (3)

16-17: Imports added correctly

The addition of MEGAVAULT_MODULE_ADDRESS and MEGAVAULT_SUBACCOUNT_ID to the imports is appropriate and necessary for the subsequent usage in the test cases.


37-37: Declaration of mainVaultEquity is appropriate

The declaration of mainVaultEquity with a value of 10000 accurately reflects the equity for the main vault in the test scenarios.


75-80: Creating the main vault subaccount correctly

The creation of the main vault subaccount with the MEGAVAULT_MODULE_ADDRESS and subaccountNumber: 0 is correctly implemented and aligns with the test requirements.

@vincentwschau vincentwschau merged commit 11fcc4e into main Sep 26, 2024
16 checks passed
@vincentwschau vincentwschau deleted the vincentc/inlude-main-vault-subaccount-for-equity-pnl branch September 26, 2024 20:03
mergify bot pushed a commit that referenced this pull request Sep 26, 2024
vincentwschau added a commit that referenced this pull request Sep 26, 2024
@coderabbitai coderabbitai bot mentioned this pull request Dec 17, 2024
6 tasks
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