Skip to content
This repository was archived by the owner on Dec 5, 2025. It is now read-only.

Add function to calculate estimated user rewards based on fees [PFT-2621]#108

Merged
racso2609 merged 3 commits intodevelopfrom
add-estimated-rewards
May 13, 2025
Merged

Add function to calculate estimated user rewards based on fees [PFT-2621]#108
racso2609 merged 3 commits intodevelopfrom
add-estimated-rewards

Conversation

@sudeepb02
Copy link
Contributor

@sudeepb02 sudeepb02 commented May 13, 2025

Summary by CodeRabbit

  • New Features
    • Added the ability to estimate user rewards for a specified period based on integrator fees.
  • Tests
    • Introduced a new test to verify the estimated rewards calculation for a user.

@notion-workspace
Copy link

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 13, 2025

Walkthrough

A new feature was introduced to estimate user rewards based on integrator fees within a specified time frame. This includes a public method in the Subgraph class, a helper function for reward calculation, a supporting GraphQL query generator, and a corresponding test to validate the new functionality.

Changes

File(s) Change Summary
src/subgraph/index.ts Added a public async method getEstimatedRewardsForUser to the Subgraph class, importing helper logic.
src/subgraph/scripts/index.ts Introduced getEstimatedRewardsForUser function to calculate user rewards from subgraph data.
src/subgraph/scripts/subgraphQueries.ts Added fetchIntegratorFeesWithTimestampQuery to generate a timestamp-filtered GraphQL query.
test/subgraph-tests/index.test.ts Added a test for getEstimatedRewardsForUser to verify user reward estimation over a recent week.

Sequence Diagram(s)

sequenceDiagram
    participant Test
    participant Subgraph
    participant Helper as getEstimatedRewardsForUser (helper)
    participant QueryGen as fetchIntegratorFeesWithTimestampQuery
    participant SubgraphAPI

    Test->>Subgraph: getEstimatedRewardsForUser(user, rewards, start, end)
    Subgraph->>Helper: getEstimatedRewardsForUser(endpoint, user, rewards, start, end)
    Helper->>QueryGen: fetchIntegratorFeesWithTimestampQuery(start, end)
    Helper->>SubgraphAPI: GraphQL query (with generated query)
    SubgraphAPI-->>Helper: Fee data
    Helper-->>Subgraph: Calculated user rewards
    Subgraph-->>Test: User rewards
Loading

Suggested reviewers

  • sudeepb02

Poem

In the warren of code, rewards hop anew,
With queries and helpers, the numbers accrue.
From timestamps to fees, the logic aligns,
Now rabbits can measure their share of the pines.
A test gives a cheer—“It works!”—in delight,
As carrots of data shine bright in the night.
🥕

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89f8913 and 51c555f.

📒 Files selected for processing (2)
  • src/subgraph/index.ts (2 hunks)
  • src/subgraph/scripts/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/subgraph/scripts/index.ts
  • src/subgraph/index.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

🧹 Nitpick comments (7)
src/subgraph/scripts/subgraphQueries.ts (3)

4-31: Consider pagination for large datasets

The query limits results to the first 1000 snxAccounts, which might not retrieve all relevant data if there are more than 1000 accounts in the system. This could lead to incomplete calculations of rewards.

Consider adding pagination support:

export const fetchIntegratorFeesWithTimestampQuery = (
  startTimeStamp: number, // unix timestamp
  endTimeStamp: number, //unix timestamp
+ skip: number = 0
) =>
  gql`{
    snxAccounts(
      first: 1000
+     skip: ${skip}
      where: { type: PERP, totalOrdersCount_gt: 0 }) {
      id
      integratorFeesGenerated
      accountId
      owner {
        id
      }
      orders(
        where: {
          status: SETTLED,
          createdTimestamp_gt: ${startTimeStamp},
          createdTimestamp_lt: ${endTimeStamp}
        }
    ) {
        id
        referralFees
        collectedFees
      }
    }
  }
`;

21-22: Consider inclusive timestamp boundaries

Using strictly greater than (_gt) and strictly less than (_lt) operators might exclude orders created exactly at the start or end timestamps.

Consider using inclusive boundaries for either the start or end timestamp if needed:

  orders(
    where: {
      status: SETTLED,
-     createdTimestamp_gt: ${startTimeStamp},
-     createdTimestamp_lt: ${endTimeStamp}
+     createdTimestamp_gte: ${startTimeStamp},
+     createdTimestamp_lt: ${endTimeStamp}
    }

8-30: Add sorting for consistent results

The query doesn't specify a sorting order, which might lead to inconsistent results across multiple calls when paginating or analyzing the data.

Add an orderBy parameter to ensure consistent results:

  gql`{
    snxAccounts(
      first: 1000
-     where: { type: PERP, totalOrdersCount_gt: 0 }) {
+     where: { type: PERP, totalOrdersCount_gt: 0 }
+     orderBy: id
+     orderDirection: asc) {
      id
      integratorFeesGenerated
      accountId
      owner {
        id
      }
      orders(
        where: {
          status: SETTLED,
          createdTimestamp_gt: ${startTimeStamp},
          createdTimestamp_lt: ${endTimeStamp}
        }
+       orderBy: createdTimestamp
+       orderDirection: asc
    ) {
src/subgraph/scripts/index.ts (1)

34-40: Streamline number conversion

The code first converts to string and then to Number, which is unnecessary and less efficient.

Simplify the conversion:

  account.orders.forEach((order) => {
    const formattedFees = new Decimal(order.referralFees).div(WAD);
    if (account.owner.id == userAddress) {
-      userFeesForPeriod += Number(formattedFees.toString());
+      userFeesForPeriod += formattedFees.toNumber();
    }
-    totalFeesForPeriod += Number(formattedFees.toString());
+    totalFeesForPeriod += formattedFees.toNumber();
  });
test/subgraph-tests/index.test.ts (2)

46-47: Remove or limit console.log statements in tests

Console logs in tests can clutter the test output, making it harder to identify issues.

Consider removing the console.log or conditionally enabling it only when debugging:

-    console.log('User rewards : ', userRewards);
+    // Only log when debugging is enabled
+    if (process.env.DEBUG) {
+      console.log('User rewards : ', userRewards);
+    }

47-47: Enhance test assertions for reward calculations

The test only checks if the reward is greater than zero, which doesn't thoroughly validate the calculation logic.

Add more specific assertions to validate the reward calculation:

-    expect(userRewards).toBeGreaterThan(0);
+    // Basic validation
+    expect(userRewards).toBeGreaterThan(0);
+    expect(userRewards).toBeLessThanOrEqual(totalRewards);
+    
+    // Store a snapshot of the calculation for regression testing
+    expect(userRewards).toMatchSnapshot();
src/subgraph/index.ts (1)

301-304: Use a more specific section name

The "MISC" section label is generic and doesn't clearly indicate the feature's purpose.

Rename the section to better reflect its purpose:

-  ////////////////////////////////////////////////////////////////
-  ///////////////////////    MISC    /////////////////////////////
-  ////////////////////////////////////////////////////////////////
+  ////////////////////////////////////////////////////////////////
+  /////////////////    USER REWARDS    //////////////////////////
+  ////////////////////////////////////////////////////////////////
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b7226e3 and 89f8913.

📒 Files selected for processing (4)
  • src/subgraph/index.ts (2 hunks)
  • src/subgraph/scripts/index.ts (1 hunks)
  • src/subgraph/scripts/subgraphQueries.ts (1 hunks)
  • test/subgraph-tests/index.test.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
test/subgraph-tests/index.test.ts (3)
src/index.ts (1)
  • ParifiSdk (15-43)
test/index.ts (1)
  • getParifiSdkInstanceForTesting (5-33)
test/common/constants.ts (1)
  • TEST_USER_1 (8-8)
src/subgraph/index.ts (1)
src/subgraph/scripts/index.ts (1)
  • getEstimatedRewardsForUser (6-45)
🪛 GitHub Actions: Test contracts sdk
test/subgraph-tests/index.test.ts

[error] 26-26: Test failed: GraphQL 403 Forbidden error when fetching any valid query data in src/subgraph/index.ts at line 80.


[error] 40-40: Test failed: GraphQL 403 Forbidden error when fetching user estimated rewards for a period of time in src/subgraph/scripts/index.ts at line 25.

Comment on lines +30 to +48
it('should return user estimated rewards for a period of time', async () => {
if (!parifiSdk) throw new Error('Parifi SDK not initialized');

const totalRewards = 50000; // 50k esPRF
const userAddress = TEST_USER_1;

// Default to one week before current time
const startTimestamp = Math.floor((Date.now() - 7 * 24 * 60 * 60 * 1000) / 1000);
const endTimestamp = Math.floor(Date.now() / 1000);

const userRewards = await parifiSdk.subgraph.getEstimatedRewardsForUser(
userAddress,
totalRewards,
startTimestamp,
endTimestamp,
);
console.log('User rewards : ', userRewards);
expect(userRewards).toBeGreaterThan(0);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Fix the 403 Forbidden error in test

The pipeline failures show a 403 Forbidden error when accessing the subgraph, which means authentication is failing.

The test is failing with GraphQL 403 Forbidden errors. This might be due to:

  1. Missing authentication tokens in the test environment
  2. Incorrect subgraph endpoint URL
  3. IP restrictions on the subgraph endpoint

Verify the authentication setup and ensure environment variables are correctly configured. You might need to update the test to use the correct credentials:

  beforeAll(async () => {
    parifiSdk = await getParifiSdkInstanceForTesting();
+   // Verify that the subgraph endpoint and authentication are correctly configured
+   console.log(`Using subgraph endpoint: ${process.env.SUBGRAPH_ENDPOINT}`);
  });

🏁 Script executed:

#!/bin/bash
# Check if SUBGRAPH_ENDPOINT is set in the environment
echo "Checking environment configuration for tests:"
if [ -f ".env" ]; then
  echo "Found .env file:"
  grep -v "PASSWORD" .env | grep "SUBGRAPH\|RPC"
else
  echo "No .env file found"
fi

# Check for authentication-related files or configs
echo "Checking for authentication configurations:"
find . -type f -name "*.json" -size -1024k -exec grep -l "token\|auth\|key\|credential" {} \;

Length of output: 412


Ensure SUBGRAPH_ENDPOINT and auth are set for subgraph tests

Tests in test/subgraph-tests/index.test.ts are making real GraphQL calls, but there is no .env (and no SUBGRAPH_ENDPOINT or credentials) in the sandbox. The verification script confirms:

  • No .env file found
  • No auth tokens or keys in JSON configs

To fix:

  • Add a .env.test (or .env) containing at minimum:
    SUBGRAPH_ENDPOINT=https://your-subgraph-endpoint
    SUBGRAPH_API_KEY=your-api-key   # if your subgraph requires a token
    
  • Update CI to load those variables (or export them directly in the pipeline).
  • In your test setup, explicitly load and validate env vars before using the SDK:
    import dotenv from 'dotenv';
    dotenv.config({ path: '.env.test' }); // or '.env'
    
    beforeAll(async () => {
      const endpoint = process.env.SUBGRAPH_ENDPOINT;
      if (!endpoint) {
        throw new Error('SUBGRAPH_ENDPOINT is not defined');
      }
      parifiSdk = await getParifiSdkInstanceForTesting({
        subgraphEndpoint: endpoint,
        apiKey: process.env.SUBGRAPH_API_KEY,
      });
    });
  • (Optional) To avoid network calls in unit tests, consider mocking the subgraph (e.g. with nock or MSW) and asserting on stubbed responses.
🧰 Tools
🪛 GitHub Actions: Test contracts sdk

[error] 40-40: Test failed: GraphQL 403 Forbidden error when fetching user estimated rewards for a period of time in src/subgraph/scripts/index.ts at line 25.

racso2609 and others added 2 commits May 13, 2025 16:11
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@racso2609 racso2609 left a comment

Choose a reason for hiding this comment

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

LGTM

@racso2609 racso2609 merged commit 21c2f44 into develop May 13, 2025
2 checks passed
@racso2609 racso2609 deleted the add-estimated-rewards branch May 13, 2025 21:12
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants