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

[TRA-890] Return nearest hour PnL as final data point for vaults pnl. #2616

Merged
merged 3 commits into from
Nov 26, 2024

Conversation

vincentwschau
Copy link
Contributor

@vincentwschau vincentwschau commented Nov 26, 2024

Changelist

Fetch the latest pnl ticks for all sub-vaults when returning historical pnl.

Test Plan

Unit tests, deployed onto test env.

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

  • New Features

    • Introduced a new method to retrieve the latest Profit and Loss (PnL) ticks for vault subaccounts, enhancing historical PnL data accuracy.
  • Bug Fixes

    • Updated test cases to ensure correct handling of historical PnL data with precise tick references.
    • Corrected a typo in the method name for retrieving vault PnL start dates.
  • Documentation

    • Enhanced clarity in the logic for determining final ticks in test cases, ensuring alignment with updated response structures.

@vincentwschau vincentwschau requested a review from a team as a code owner November 26, 2024 20:27
Copy link

linear bot commented Nov 26, 2024

Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Walkthrough

The changes in this pull request involve modifications to the test cases for the vault-controller to improve the handling of historical Profit and Loss (PnL) data for vault subaccounts. A new parameter, currentTickIndex, has been introduced to enhance precision in test case validation. Additionally, a new method, getLatestPnlTicks, was added to the vault controller to retrieve and process the latest PnL ticks, integrating this functionality into the existing getVaultsHistoricalPnl method. These updates refine the logic for constructing expected responses in the tests.

Changes

File Change Summary
indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts Updated test cases for /vaults/historicalPnl to include currentTickIndex for single and multiple vault subaccounts.
indexer/services/comlink/src/controllers/api/v4/vault-controller.ts Added getLatestPnlTicks method to retrieve latest PnL ticks, integrated into getVaultsHistoricalPnl method. Corrected typo in getVaultPnlStartDate.

Possibly related PRs

Suggested labels

backport/indexer/v7.x

Suggested reviewers

  • tqin7

🐰 In the vaults so bright and fair,
New ticks and tests dance in the air.
With currentTickIndex in play,
Historical PnL finds its way.
Hopping through code, we refine and cheer,
For accurate data, we hold dear! 🌟


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

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

342-344: Consider adding edge case tests

While the test cases cover basic scenarios with different resolutions, consider adding tests for edge cases:

  • When currentTickIndex is out of bounds
  • When currentTickIndex points to an invalid tick

Also applies to: 350-351


Based on the findings, I can now provide the final response:

Add test coverage for error scenarios in vault-controller endpoints

The test suite needs additional test cases to cover error scenarios, specifically:

  • Invalid resolution parameter values (the API validates against PnlTickInterval enum values)
  • Error handling in /v1/megavault/positions endpoint
  • Request validation errors from the express-validator middleware

Example test cases to add:

  • Test with invalid resolution value (e.g., '?resolution=invalid')
  • Test error handling when database queries fail
  • Test rate limiter behavior
🔗 Analysis chain

Line range hint 1-650: Verify test coverage for error scenarios

The test suite thoroughly covers successful scenarios but could benefit from additional error case testing:

  • Invalid resolution parameter
  • Missing or malformed query parameters
  • Empty or invalid PNL data

Let me gather more information about the test file to verify error handling coverage.


Let me check the API implementation to understand what error cases should be tested.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check current test coverage for error handling
rg -A 2 "it\(.*(error|invalid|fail)" indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts

Length of output: 276


Script:

#!/bin/bash
# Check for test cases with invalid/error scenarios in query parameters and responses
rg -B 2 -A 5 "(resolution|queryParam|response.*status|response.*error)" indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts

Length of output: 3862


Script:

#!/bin/bash
# Check the API implementation for error handling
rg -A 10 "router\.(get|post)" indexer/services/comlink/src/controllers/api/v4/vault-controller.ts

Length of output: 1121

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

Line range hint 174-175: Fix variable name typo: 'pnlTickFromDatabsae' should be 'pnlTickFromDatabase'

The variable pnlTickFromDatabsae in the filter function is misspelled. It should be pnlTickFromDatabase to match the correct spelling.

Apply the following diff to correct the variable name:

       .filter((pnlTickFromDatabsae: PnlTicksFromDatabase): boolean => {
-        return vaultSubaccounts[pnlTickFromDatabsae.subaccountId] !== undefined;
+        return vaultSubaccounts[pnlTickFromDatabase.subaccountId] !== undefined;

Line range hint 764-768: Correct the logged value in the warning message

In the warning log within getVaultMapping, you are logging vaultMapping[subaccountId], which is an object. You should log vaultMapping[subaccountId].clobPairId to correctly display the Clob Pair ID that does not correspond to a perpetual market.

Apply the following diff to fix the log message:

       logger.warning({
         at: 'VaultController#getVaultPositions',
-        message: `Vault clob pair id ${vaultMapping[subaccountId]} does not correspond to a ` +
+        message: `Vault clob pair id ${vaultMapping[subaccountId].clobPairId} does not correspond to a ` +
           'perpetual market.',
         subaccountId,
       });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5553dc8 and 00808b2.

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

301-303: LGTM: Test case parameters properly updated

The addition of currentTickIndex parameter improves test clarity by explicitly specifying which tick should be used as the final data point.

Also applies to: 308-308

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)
indexer/services/comlink/src/controllers/api/v4/vault-controller.ts (1)

562-589: Refactor to eliminate code duplication between 'getLatestPnlTicks' and 'getVaultSubaccountPnlTicks'

Both getLatestPnlTicks and getVaultSubaccountPnlTicks functions perform similar operations in fetching and adjusting PnL ticks. Consider abstracting the common logic into a helper function to enhance maintainability and reduce code duplication.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 00808b2 and 014315c.

📒 Files selected for processing (2)
  • indexer/services/comlink/__tests__/controllers/api/v4/vault-controller.test.ts (4 hunks)
  • indexer/services/comlink/src/controllers/api/v4/vault-controller.ts (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • indexer/services/comlink/tests/controllers/api/v4/vault-controller.test.ts
🔇 Additional comments (1)
indexer/services/comlink/src/controllers/api/v4/vault-controller.ts (1)

563-564: Add a check for empty 'vaultSubaccountIds' array

The previous review comment about adding a check for an empty vaultSubaccountIds array in the getLatestPnlTicks function is still applicable.

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

Reviewing files that changed from the base of the PR and between 014315c and 8ff8d07.

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

24-24: LGTM! Good test setup and cleanup.

The DateTime mock setup and cleanup ensures deterministic test behavior and prevents test pollution.

Also applies to: 127-127, 137-137


303-305: LGTM! Improved test case parameterization.

The addition of explicit currentTickIndex parameters makes the test cases more maintainable and clearer about which PnL tick should be used for assertions.

Also applies to: 310-310, 344-346, 352-353


319-319: Previous review comment is still applicable.

The fixes for the variable names and consistent usage of tick indices have been implemented as suggested.

Also applies to: 369-369, 376-376

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

38-38: LGTM!

The addition of the Dictionary type from lodash improves type safety for the latestTicksBySubaccountId mapping.


837-840: Function name correction looks good

The typo in the function name has been fixed as suggested in the previous review.


562-588: 🛠️ Refactor suggestion

Add input validation for empty vaultSubaccountIds array

The function should return early if vaultSubaccountIds is empty to prevent unnecessary database queries.

Add this check at the start of the function:

 export async function getLatestPnlTicks(
   vaultSubaccountIds: string[],
 ): Promise<PnlTicksFromDatabase[]> {
+  if (vaultSubaccountIds.length === 0) {
+    return [];
+  }
   const [
     latestPnlTicks,
     adjustByPnlTicks,
   ] : [

Likely invalid or redundant comment.

Comment on lines +155 to +170
latestTicks,
] : [
PnlTicksFromDatabase[],
Map<string, VaultPosition>,
BlockFromDatabase,
PnlTicksFromDatabase[],
] = await Promise.all([
getVaultSubaccountPnlTicks(_.keys(vaultSubaccounts), getResolution(resolution)),
getVaultPositions(vaultSubaccounts),
BlockTable.getLatest(),
getLatestPnlTicks(_.keys(vaultSubaccounts)),
]);
const latestTicksBySubaccountId: Dictionary<PnlTicksFromDatabase> = _.keyBy(
latestTicks,
'subaccountId',
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for undefined latest ticks

While the Dictionary organization is good, accessing latestTicksBySubaccountId[subaccountId] directly could be unsafe if the subaccountId doesn't exist in the dictionary.

Consider adding a null check or using optional chaining:

-          latestTicksBySubaccountId[subaccountId],
+          latestTicksBySubaccountId[subaccountId] ?? undefined,

Committable suggestion skipped: line range outside the PR's diff.

@vincentwschau vincentwschau merged commit 4d9f2d0 into main Nov 26, 2024
16 checks passed
@vincentwschau vincentwschau deleted the vincentc/tra-890-current-vault-pnl branch November 26, 2024 23:07
@vincentwschau
Copy link
Contributor Author

@Mergifyio backport release/indexer/v7.x

Copy link
Contributor

mergify bot commented Nov 26, 2024

backport release/indexer/v7.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Nov 26, 2024
vincentwschau added a commit that referenced this pull request Nov 27, 2024
… (backport #2616) (#2617)

Co-authored-by: vincentwschau <99756290+vincentwschau@users.noreply.github.com>
@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.

3 participants