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

Fix typo and add test for invalid vaults. #2535

Merged
merged 1 commit into from
Oct 22, 2024

Conversation

vincentwschau
Copy link
Contributor

@vincentwschau vincentwschau commented Oct 22, 2024

Changelist

Had a typo when returning valid/invalid vaults. Updated a test to catch this.

Test Plan

Unit 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

    • Enhanced API functionality to handle multiple vault subaccounts, including validation for invalid entries.
  • Bug Fixes

    • Improved data integrity by filtering vault mappings to include only those corresponding to valid perpetual markets.
  • Tests

    • Added a new test case for scenarios involving two vault subaccounts, one being invalid, to ensure correct API behavior.

@vincentwschau vincentwschau requested a review from a team as a code owner October 22, 2024 19:48
Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Walkthrough

The changes in this pull request involve updates to the vault-controller test suite and the VaultController class within the megavault API. A new test case has been added to handle scenarios with multiple vault subaccounts, including one invalid entry. Additionally, the getVaultMapping function has been modified to return a filtered mapping of valid vaults, ensuring only those linked to valid perpetual markets are included. This enhances data integrity while maintaining existing method signatures and control flow.

Changes

File Change Summary
indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts Updated test case to handle three vault subaccounts, including one invalid. Renamed test case for clarity.
indexer/services/comlink/src/controllers/api/v4/vault-controller.ts Modified getVaultMapping function to return filtered validVaultMapping instead of vaultMapping, ensuring only valid entries are included.

Possibly related PRs

Suggested reviewers

  • shrenujb
  • tqin7

Poem

🐇 In the vaults where treasures lay,
A rabbit hops and starts to play.
With tests that check both strong and weak,
Valid paths are what we seek.
A mapping clear, no room for doubt,
In this code, we dance about! 🌟


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

🧹 Outside diff range and nitpick comments (3)
indexer/services/comlink/src/controllers/api/v4/vault-controller.ts (2)

Line range hint 642-665: Consider enhancing error handling for invalid vaults.

Currently, invalid vaults are silently filtered out. Consider one of these approaches:

  1. Throw an error if any invalid vaults are found (strict)
  2. Return both valid and invalid mappings (flexible)
  3. Add metrics to track invalid vault frequency (monitoring)

Example implementation for approach #2:

interface VaultMappingResult {
  validVaults: VaultMapping;
  invalidVaults: {
    subaccountId: string;
    clobPairId: string;
  }[];
}

async function getVaultMapping(): Promise<VaultMappingResult> {
  const vaults: VaultFromDatabase[] = await VaultTable.findAll({}, [], {});
  const vaultMapping: VaultMapping = _.zipObject(
    vaults.map((vault: VaultFromDatabase): string => SubaccountTable.uuid(vault.address, 0)),
    vaults.map((vault: VaultFromDatabase): string => vault.clobPairId),
  );
  
  const validVaultMapping: VaultMapping = {};
  const invalidVaults: {subaccountId: string; clobPairId: string}[] = [];
  
  for (const subaccountId of _.keys(vaultMapping)) {
    const perpetual = perpetualMarketRefresher.getPerpetualMarketFromClobPairId(
      vaultMapping[subaccountId],
    );
    
    if (perpetual === undefined) {
      logger.warning({
        at: 'VaultController#getVaultMapping',
        message: `Vault clob pair id ${vaultMapping[subaccountId]} does not correspond to a perpetual market.`,
        subaccountId,
      });
      invalidVaults.push({
        subaccountId,
        clobPairId: vaultMapping[subaccountId],
      });
      continue;
    }
    validVaultMapping[subaccountId] = vaultMapping[subaccountId];
  }
  
  return {
    validVaults: validVaultMapping,
    invalidVaults,
  };
}

Line range hint 642-665: Consider optimizing database query for vault retrieval.

The current implementation loads all vaults and then filters them in memory. Consider adding a database-level filter to retrieve only vaults with valid clob pair IDs.

Example optimization:

async function getVaultMapping(): Promise<VaultMapping> {
  // Get all valid clob pair IDs first
  const validClobPairIds = new Set(
    Object.keys(perpetualMarketRefresher.getPerpetualMarketsMap())
      .map(id => perpetualMarketRefresher.getPerpetualMarketFromId(id)?.clobPairId)
      .filter(Boolean)
  );
  
  // Query only vaults with valid clob pair IDs
  const vaults: VaultFromDatabase[] = await VaultTable.findAll(
    {
      clobPairId: Array.from(validClobPairIds),
    },
    [],
    {},
  );
  
  return _.zipObject(
    vaults.map((vault: VaultFromDatabase): string => SubaccountTable.uuid(vault.address, 0)),
    vaults.map((vault: VaultFromDatabase): string => vault.clobPairId),
  );
}
indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts (1)

Line range hint 454-470: LGTM! Consider improving the test name grammar.

The test effectively validates the handling of invalid vaults while maintaining backward compatibility for valid vaults. The setup and assertions are comprehensive and well-structured.

Consider updating the test name to be more grammatically correct:

-    it('Get /megavault/positions with 2 vault subaccount, 1 with no perpetual, 1 invalid', async () => {
+    it('Get /megavault/positions with 2 vault subaccounts, 1 with no perpetual and 1 invalid', async () => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9c214d0 and 1ecbdcd.

📒 Files selected for processing (2)
  • indexer/services/comlink/tests/controllers/api/v4/vault-controller.test.ts (2 hunks)
  • indexer/services/comlink/src/controllers/api/v4/vault-controller.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
indexer/services/comlink/src/controllers/api/v4/vault-controller.ts (2)

665-665: ⚠️ Potential issue

Fix incorrect function name in warning message.

The warning message references VaultController#getVaultPositions, but it should be VaultController#getVaultMapping since the warning is logged in the getVaultMapping function.

Apply this diff:

-        at: 'VaultController#getVaultPositions',
+        at: 'VaultController#getVaultMapping',

Likely invalid or redundant comment.


Line range hint 642-665: Verify test coverage for invalid vault handling.

Let's ensure the test suite properly covers the invalid vault filtering logic.

✅ Verification successful

Let's examine the test file content to verify the test coverage for invalid vault handling.


Let's check the implementation of the vault controller to find where the invalid vault handling is tested.


Based on the test file content, I can see there is a test case "Get /megavault/positions with 2 vault subaccount, 1 with no perpetual, 1 invalid" that covers the invalid vault scenario. Let's verify the complete test case and its assertions.


Based on the evidence from the test file and implementation, I can now provide a final response about the test coverage for invalid vault handling.

Test coverage for invalid vault handling is sufficient

The code has proper test coverage for invalid vault handling:

  1. There is a specific test case "Get /megavault/positions with 2 vault subaccount, 1 with no perpetual, 1 invalid" that verifies:

    • A valid vault with a perpetual position
    • A valid vault without a perpetual position
    • An invalid vault with non-existent clob pair id ('999')
  2. The implementation in getVaultMapping properly handles invalid vaults by:

    • Logging a warning message when a vault's clob pair id doesn't correspond to a perpetual market
    • Excluding invalid vaults from the validVaultMapping return value
    • Continuing execution for valid vaults

The test coverage adequately verifies that the invalid vault filtering logic works as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test files related to vault-controller
echo "Searching for vault controller test files..."
fd -e spec.ts -e test.ts vault-controller

# Search for test cases covering invalid vault scenarios
echo "Searching for invalid vault test cases..."
rg -l "invalid.*vault|vault.*invalid" -g "*.spec.ts" -g "*.test.ts"

# Search for specific test assertions related to invalid vaults
echo "Searching for invalid vault assertions..."
rg "expect.*vault.*invalid|invalid.*vault.*expect" -g "*.spec.ts" -g "*.test.ts"

Length of output: 639


Script:

#!/bin/bash
# Get the content of the vault controller test file
echo "Content of vault controller test file:"
cat "indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts"

# Search for test cases specifically around getVaultMapping
echo -e "\nTest cases for getVaultMapping:"
rg -A 10 "describe.*getVaultMapping|test.*getVaultMapping" "indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts"

Length of output: 24529


Script:

#!/bin/bash
# Search for tests related to invalid vaults in the megavault/positions endpoint
echo "Searching for invalid vault tests in positions endpoint..."
rg -B 5 -A 10 "invalid.*vault|vault.*invalid" "indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts"

# Search for the implementation of getVaultMapping
echo -e "\nSearching for getVaultMapping implementation..."
ast-grep --pattern 'getVaultMapping($$$) {
  $$$
}' "indexer/services/comlink/src/controllers/api/v4/vault-controller.ts"

Length of output: 1049


Script:

#!/bin/bash
# Get the complete test case for invalid vault handling
echo "Getting complete test case for invalid vault handling..."
rg -B 2 -A 50 "2 vault subaccount.*1 invalid" "indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts"

# Get the implementation of getVaultPositions
echo -e "\nGetting getVaultPositions implementation..."
rg -B 10 -A 30 "getVaultPositions" "indexer/services/comlink/src/controllers/api/v4/vault-controller.ts"

Length of output: 8524

@vincentwschau vincentwschau merged commit 317a74e into main Oct 22, 2024
16 checks passed
@vincentwschau vincentwschau deleted the vincentc/fix-typo-add-test branch October 22, 2024 20:07
@vincentwschau
Copy link
Contributor Author

@Mergifyio backport release/indexer/v7.x

Copy link
Contributor

mergify bot commented Oct 22, 2024

backport release/indexer/v7.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Oct 22, 2024
vincentwschau added a commit that referenced this pull request Oct 22, 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