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

Add/order count query#104

Merged
sudeepb02 merged 2 commits intodevelopfrom
add/orderCountQuery
May 8, 2025
Merged

Add/order count query#104
sudeepb02 merged 2 commits intodevelopfrom
add/orderCountQuery

Conversation

@iamamitkumar0512
Copy link
Contributor

@iamamitkumar0512 iamamitkumar0512 commented Apr 21, 2025

Summary by CodeRabbit

  • New Features
    • Added the ability to query the count of settled orders for a specific user within a selected time range.
  • Tests
    • Introduced a new test case to verify the settled orders count functionality for a user address and time range.
  • Chores
    • Updated the package version to 2.2.17.

@iamamitkumar0512 iamamitkumar0512 self-assigned this Apr 21, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 21, 2025

Walkthrough

The changes introduce a new feature to the subgraph querying capabilities of the SDK, enabling the retrieval of the count of settled orders for a specific user address within a given timestamp range. This is achieved by adding a new GraphQL query, a corresponding function to execute the query, and a public method in the Subgraph class to expose this functionality. Additionally, a targeted test case was created to verify the new method. The package version was incremented to reflect the update.

Changes

File(s) Summary
package.json Incremented the package version from 2.2.16 to 2.2.17.
src/subgraph/index.ts Added a new public async method getSettledOrdersCountBasedOnTimeStampByUserAddress to the Subgraph class.
src/subgraph/orders/index.ts Added a function to fetch the count of settled orders by user and time range using a new GraphQL query.
src/subgraph/orders/subgraphQueries.ts Introduced a new GraphQL query for settled orders count filtered by user and timestamp.
test/subgraph-tests/orders.test.ts Added a test case to verify the new settled orders count query for a user within a timestamp range.

Sequence Diagram(s)

sequenceDiagram
    participant Test
    participant SDK (Subgraph)
    participant Orders Module
    participant Subgraph API

    Test->>SDK (Subgraph): getSettledOrdersCountBasedOnTimeStampByUserAddress(user, count, skip, start, end)
    SDK (Subgraph)->>Orders Module: getSettledOrdersCountBasedOnTimeStampByUserAddress(endpoint, user, count, skip, start, end)
    Orders Module->>Subgraph API: fetchSettledOrdersCountBasedOnTimeStampByUserQuery(user, count, skip, start, end)
    Subgraph API-->>Orders Module: Settled orders data
    Orders Module-->>SDK (Subgraph): Settled orders count
    SDK (Subgraph)-->>Test: Settled orders count
Loading

Suggested reviewers

  • sudeepb02

Poem

In the warren of code, a new path appears,
Counting settled orders across the trading years.
With timestamps and queries, the data hops through,
A test checks the count—just two, not a few!
The version now nudges, a hare’s leap ahead,
As bunnies in code-land keep hopping instead.
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ 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.
    • 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 generate docstrings to generate docstrings for 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 (3)
src/subgraph/orders/subgraphQueries.ts (1)

55-55: Update comment to match the function's purpose.

The current comment "Fetch all orders by userAddress" is inaccurate since this query fetches only settled orders within a time range, not all orders.

-// Fetch all orders by `userAddress`
+// Fetch settled orders by `userAddress` within a specific timestamp range
test/subgraph-tests/orders.test.ts (1)

32-32: Remove console.log statement.

Debug logging should be removed before merging to production.

-    console.log(orderCount);
src/subgraph/index.ts (1)

151-167: Add default parameter values for consistency.

The method should include default values for count and skip parameters to maintain consistency with other methods in the class.

  public async getSettledOrdersCountBasedOnTimeStampByUserAddress(
    userAddress: string,
-    count: number,
-    skip: number,
+    count: number = 50,
+    skip: number = 0,
    startTime: number,
    endTime: number,
  ): Promise<number> {
    const subgraphEndpoint = this.getSubgraphEndpoint(this.rpcConfig.chainId);
    return await getSettledOrdersCountBasedOnTimeStampByUserAddress(
      subgraphEndpoint,
      userAddress,
      count,
      skip,
      startTime,
      endTime,
    );
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a57913b and 7ffb061.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • package.json (1 hunks)
  • src/subgraph/index.ts (2 hunks)
  • src/subgraph/orders/index.ts (2 hunks)
  • src/subgraph/orders/subgraphQueries.ts (1 hunks)
  • test/subgraph-tests/orders.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
test/subgraph-tests/orders.test.ts (1)
test/index.ts (1)
  • getParifiSdkInstanceForTesting (5-33)
src/subgraph/index.ts (1)
src/subgraph/orders/index.ts (1)
  • getSettledOrdersCountBasedOnTimeStampByUserAddress (44-69)
🪛 Biome (1.9.4)
test/subgraph-tests/orders.test.ts

[error] 20-20: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

🪛 GitHub Actions: Test contracts sdk
test/subgraph-tests/orders.test.ts

[error] 33-33: Test failure: Expected settled order count to be 2 but received 0 due to GraphQL 403 error.

src/subgraph/orders/index.ts

[error] 66-66: Error fetching orders: GraphQL Error (Code: 403) caused ClientError during subgraph query.

src/subgraph/index.ts

[error] 79-79: Error executing subgraph query: GraphQL Error (Code: 403) caused ClientError.

🔇 Additional comments (5)
package.json (1)

3-3: Version update is appropriate for the new feature.

The version bump from 2.2.16 to 2.2.17 correctly reflects the addition of a new non-breaking feature to the SDK.

src/subgraph/orders/subgraphQueries.ts (1)

56-80: LGTM! Well-structured GraphQL query for the specific use case.

The query is properly implemented to fetch only settled orders within the specified timestamp range, with appropriate filtering and field selection. The parameter handling with defaults for pagination is well done.

src/subgraph/index.ts (2)

21-21: Import statement updated correctly.

The import statement has been properly updated to include the new function.


151-167: Address GraphQL 403 error in pipeline.

There's a GraphQL 403 error showing in the pipeline. This might be related to authentication issues with the subgraph endpoint. Ensure that the function handles authentication errors gracefully and check credentials in CI environment.

The pipeline shows a GraphQL 403 error, which often indicates authentication or permission issues with the subgraph endpoint. Verify that:

  1. The test environment has the correct credentials
  2. The error handling in the underlying implementation is appropriate

Note that while the implementation in orders/index.ts handles errors by returning 0, this doesn't address the root cause of the authentication issue.

src/subgraph/orders/index.ts (1)

2-6: Correctly imported the new GraphQL query.

The import statement has been properly updated to include the new query fetchSettledOrdersCountBasedOnTimeStampByUserQuery which is required for the new functionality.

Comment on lines +23 to +31
const startTime = 1744771331;
const endTime = 1745223131;
const orderCount = await parifiSdk.subgraph.getSettledOrdersCountBasedOnTimeStampByUserAddress(
address,
50,
0,
startTime,
endTime,
);
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

Test is using future timestamps and failing with 403 error.

The timestamps (1744771331 and 1745223131) appear to be for July 2025, which is in the future. This might be contributing to the GraphQL 403 error seen in the pipeline. Consider using historical timestamps where you know data exists.


🏁 Script executed:

#!/bin/bash
# Convert timestamps to human-readable dates to verify they are indeed in the future
echo "Start timestamp converted to date:"
date -d @1744771331 2>/dev/null || date -r 1744771331 2>/dev/null || echo "Around July 2025 (future date)"
echo "End timestamp converted to date:"
date -d @1745223131 2>/dev/null || date -r 1745223131 2>/dev/null || echo "Around July 2025 (future date)"

# Check if the user address exists in the repo, which might help determine if the test is using valid data
echo "Checking if this user address appears elsewhere in the codebase:"
rg "0x680f7cF1C802F5C1C5A93e3657AAA3a1152ccd44" --type ts

Length of output: 553


Update test timestamps to a historical range to prevent future‑dated queries

The two constants currently resolve to April 16 and April 21, 2025—not July—so depending on when your CI job runs they may still fall in the future and trigger a 403 from the subgraph. Please update these values to a past window where you know settled orders exist (or compute them dynamically relative to “now”) to ensure the count query succeeds.

Affected location:

  • test/subgraph-tests/orders.test.ts: lines ~23–31

Suggested change (example):

-   // Future‑dated: April 16–21, 2025
-   const startTime = 1744771331;
-   const endTime   = 1745223131;
+   // Historical range: e.g. September 1–7, 2023
+   const startTime = 1693526400; // 2023‑09‑01T00:00:00Z
+   const endTime   = 1694131200; // 2023‑09‑07T00:00:00Z

—or—

// Dynamically use "now" minus a buffer window
const now       = Math.floor(Date.now() / 1000);
const startTime = now - 7 * 24 * 60 * 60; // one week ago
const endTime   = now - 1 * 24 * 60 * 60; // one day ago

expect(order.status).toBe(status.SETTLED);
});

it.only('should return an settled order count for a user', async () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove .only from the test.

Using .only prevents other tests from running in the test suite, which can lead to incomplete testing in CI/CD pipelines. Remove it before merging to production.

-  it.only('should return an settled order count for a user', async () => {
+  it('should return an settled order count for a user', async () => {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it.only('should return an settled order count for a user', async () => {
it('should return an settled order count for a user', async () => {
🧰 Tools
🪛 Biome (1.9.4)

[error] 20-20: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

endTime,
);
console.log(orderCount);
expect(orderCount).toBe(2);
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

Test failure in CI pipeline.

The test is failing with a GraphQL 403 error, which suggests authentication or permission issues with the subgraph endpoint. Consider using a mock or ensuring the test environment has proper access configured.


🌐 Web query:

What causes GraphQL 403 errors when querying a subgraph?

💡 Result:

Causes of GraphQL 403 Errors When Querying a Subgraph

A 403 Forbidden error in a GraphQL context generally means the server has received your request but refuses to authorize it. When querying a subgraph, this can arise from several common issues:

1. Authentication Failure

  • If your GraphQL request lacks the required authentication (such as missing or invalid tokens/headers), the server may respond with a 403 status code. This means that while public data may still be accessible, any protected operations or fields cannot be accessed without proper authentication[3][6].
  • For example, WordPress WPGraphQL returns 403 for unauthenticated requests, even if the response can include some public data[3].

2. Insufficient Permissions (Authorization Failure)

  • Even if a user is authenticated, they may not have the necessary permissions (roles or scopes) to perform the requested operation within a subgraph. For instance, attempting to access or mutate fields you are not authorized for will lead to a 403 error[4][6].
  • This is common when trying to create, update, or delete resources without the required authorization grants or user roles associated with your account.

3. API Gateway or Infrastructure Policies

  • Some API gateways or platforms enforce their own access policies. For example, if the underlying infrastructure (like AWS VPC Lattice or similar managed environments) is not configured to allow traffic from your client or GraphQL router, a 403 error will result[9].
  • In federated GraphQL systems, subgraph endpoints may have their own access controls (e.g., IAM policies) that must explicitly permit requests from the router or orchestrator[9].

4. Query Validation or Depth Limits

  • Some GraphQL servers implement query validation and security controls, such as limiting the allowed query depth to prevent resource exhaustion or abuse. If your request exceeds the configured depth limit, the server may reject it with a 403 Forbidden error[7].
  • Example: Tyk.io returns a 403 error with "error": "depth limit exceeded" if a query is too deeply nested[7].

5. Stale or Incorrect References (Refs)

  • In certain content platforms (e.g., Prismic), using an outdated reference (ref) token in your query can result in a 403 error, as only recent or valid refs are allowed to fetch current data[5].

6. Unsupported Protocols or Operations

  • When attempting actions not supported by the subgraph's hosting environment (e.g., WebSockets subscriptions in environments that don't support them), a 403 may be returned to indicate the forbidden action[9].

Summary Table

Cause Description Example/Detail
Authentication Failure Missing or invalid credentials (tokens/headers) No auth header provided
Insufficient Permissions (Authorization) Authenticated, but lacks required roles/scopes for operation Trying to write data as read-only user
API Gateway/Infrastructure Policy Gateway or host policy denies request VPC/IAM incorrectly configured
Query Validation or Depth Limit Query exceeds allowed complexity or depth Query too deeply nested
Stale or Incorrect Reference Reference used to fetch data is outdated/invalid Old ref in Prismic
Unsupported Protocols/Operations Action attempted is not supported by the platform Subscriptions via WebSockets in AWS Lattice

Troubleshooting Steps

  • Ensure your authentication token is present and valid in the request headers.
  • Check your user and project permissions for the operation you are attempting.
  • Review gateway or hosting environment policies, especially in federated or cloud-managed environments.
  • Inspect your queries for excessive nesting or complexity that may violate depth limits.
  • Make sure to use up-to-date reference tokens if required by your platform.
  • Consult API documentation for supported operations and protocols for your subgraph[3][4][5][6][7][9].

A 403 error is almost always about lack of authorization—either at the user, infrastructure, or request validation level. Review the relevant configuration and permissions to resolve.

Citations:


🏁 Script executed:

#!/bin/bash
# Display the first 200 lines of the orders.test.ts to inspect authentication setup
sed -n '1,200p' test/subgraph-tests/orders.test.ts

Length of output: 1405


🏁 Script executed:

#!/bin/bash
# Find implementation of getParifiSdkInstanceForTesting
rg "getParifiSdkInstanceForTesting" -n

Length of output: 3030


🏁 Script executed:

#!/bin/bash
# Show implementation of getParifiSdkInstanceForTesting
sed -n '1,200p' test/index.ts

Length of output: 1057


Provide a mock or valid subgraph endpoint for CI to avoid 403

The failure (“GraphQL 403 Forbidden”) is coming from getParifiSdkInstanceForTesting picking up process.env.SUBGRAPH_ENDPOINT (with no auth headers) and hitting a protected endpoint in CI. You need to either stub out all subgraph calls in your tests or ensure the test environment can successfully reach and authenticate against the live subgraph.

• In test/index.ts – getParifiSdkInstanceForTesting uses SUBGRAPH_ENDPOINT without any fallback or auth headers.
• In test/subgraph-tests/orders.test.ts (around the it.only block) – live queries to the subgraph are unauthenticated, triggering 403.

Recommended fixes:

  • Mock the subgraph layer (e.g. use msw, nock, or a Jest mock) so tests don’t perform real GraphQL calls.
  • Or configure CI to set SUBGRAPH_ENDPOINT (and any required token or header) to an endpoint that allows anonymous read access.
🧰 Tools
🪛 GitHub Actions: Test contracts sdk

[error] 33-33: Test failure: Expected settled order count to be 2 but received 0 due to GraphQL 403 error.

Comment on lines +42 to +69

// Get count of settled orders by a user address
export const getSettledOrdersCountBasedOnTimeStampByUserAddress = async (
subgraphEndpoint: string,
userAddress: string,
count = 50,
skip = 0,
startTimeStamp: number,
endTimeStamp: number,
): Promise<number> => {
try {
const response: any = await request(
subgraphEndpoint,
fetchSettledOrdersCountBasedOnTimeStampByUserQuery(userAddress, count, skip, startTimeStamp, endTimeStamp),
);

const snxAccounts = mapResponseToSnxAccountArray(response?.snxAccounts) ?? [];

if (!snxAccounts.length) return 0;

const orderCount = snxAccounts.reduce((total, account) => total + (account.orders?.length || 0), 0);

return orderCount;
} catch (error) {
console.error('Error fetching orders:', error);
return 0;
}
};
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

Consider adding validation and consistency improvements to the new function.

The implementation correctly fetches and calculates the settled orders count. However, I recommend a few improvements:

  1. The default count value (50) differs from the similar function getAllOrdersByUserAddress (10). Consider aligning these defaults for consistency.

  2. There's no validation for startTimeStamp and endTimeStamp. You should verify that start is less than or equal to end to prevent logical errors.

  3. The error handling returns 0, which doesn't distinguish between "no orders found" and "error occurred". Consider returning a more descriptive error or implementing a different return type.

  4. The pipeline failure indicates a 403 error during testing, which suggests an authentication issue with the GraphQL request.

export const getSettledOrdersCountBasedOnTimeStampByUserAddress = async (
  subgraphEndpoint: string,
  userAddress: string,
-  count = 50,
+  count = 10, // Match the default in getAllOrdersByUserAddress
  skip = 0,
  startTimeStamp: number,
  endTimeStamp: number,
): Promise<number> => {
  try {
+    // Validate inputs
+    if (!userAddress) {
+      console.error('Error: userAddress is required');
+      return 0;
+    }
+    
+    if (startTimeStamp > endTimeStamp) {
+      console.error('Error: startTimeStamp must be less than or equal to endTimeStamp');
+      return 0;
+    }
+    
    const response: any = await request(
      subgraphEndpoint,
      fetchSettledOrdersCountBasedOnTimeStampByUserQuery(userAddress, count, skip, startTimeStamp, endTimeStamp),
    );

    const snxAccounts = mapResponseToSnxAccountArray(response?.snxAccounts) ?? [];

    if (!snxAccounts.length) return 0;

    const orderCount = snxAccounts.reduce((total, account) => total + (account.orders?.length || 0), 0);

    return orderCount;
  } catch (error) {
-    console.error('Error fetching orders:', error);
+    console.error('Error fetching settled orders count:', error);
    return 0;
  }
};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Get count of settled orders by a user address
export const getSettledOrdersCountBasedOnTimeStampByUserAddress = async (
subgraphEndpoint: string,
userAddress: string,
count = 50,
skip = 0,
startTimeStamp: number,
endTimeStamp: number,
): Promise<number> => {
try {
const response: any = await request(
subgraphEndpoint,
fetchSettledOrdersCountBasedOnTimeStampByUserQuery(userAddress, count, skip, startTimeStamp, endTimeStamp),
);
const snxAccounts = mapResponseToSnxAccountArray(response?.snxAccounts) ?? [];
if (!snxAccounts.length) return 0;
const orderCount = snxAccounts.reduce((total, account) => total + (account.orders?.length || 0), 0);
return orderCount;
} catch (error) {
console.error('Error fetching orders:', error);
return 0;
}
};
// Get count of settled orders by a user address
export const getSettledOrdersCountBasedOnTimeStampByUserAddress = async (
subgraphEndpoint: string,
userAddress: string,
count = 10, // Match the default in getAllOrdersByUserAddress
skip = 0,
startTimeStamp: number,
endTimeStamp: number,
): Promise<number> => {
try {
// Validate inputs
if (!userAddress) {
console.error('Error: userAddress is required');
return 0;
}
if (startTimeStamp > endTimeStamp) {
console.error('Error: startTimeStamp must be less than or equal to endTimeStamp');
return 0;
}
const response: any = await request(
subgraphEndpoint,
fetchSettledOrdersCountBasedOnTimeStampByUserQuery(
userAddress,
count,
skip,
startTimeStamp,
endTimeStamp
),
);
const snxAccounts = mapResponseToSnxAccountArray(response?.snxAccounts) ?? [];
if (!snxAccounts.length) return 0;
const orderCount = snxAccounts.reduce(
(total, account) => total + (account.orders?.length || 0),
0
);
return orderCount;
} catch (error) {
console.error('Error fetching settled orders count:', error);
return 0;
}
};
🧰 Tools
🪛 GitHub Actions: Test contracts sdk

[error] 66-66: Error fetching orders: GraphQL Error (Code: 403) caused ClientError during subgraph query.


return orderCount;
} catch (error) {
console.error('Error fetching orders:', error);
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 GraphQL 403 error reported in the pipeline.

The test pipeline is reporting a GraphQL 403 error (permission denied) during query execution. This could be due to:

  1. Authentication issues with the subgraph endpoint
  2. Incorrect query structure for the specific endpoint
  3. Rate limiting or IP restrictions on the endpoint used in testing

🏁 Script executed:

#!/bin/bash
# Check for other similar GraphQL requests in tests to see how they're handling authentication
echo "Checking test files for GraphQL request patterns..."
rg "request\s*\(\s*.*subgraph" --type ts test/ -A 3 -B 3

# Look for any environment variables or config that might be related to authentication
echo "Checking for authentication-related configurations..."
rg "auth|token|api.*key|bearer" --type ts test/ -A 2 -B 2

# Check the subgraph queries file to understand the structure of the new query
echo "Examining the new query structure..."
rg "fetchSettledOrdersCountBasedOnTimeStampByUserQuery" --type ts src/ -A 10

Length of output: 3409


Fix GraphQL 403 permission error on subgraph queries

Your request(subgraphEndpoint, query) call isn’t supplying any authentication headers, so the subgraph rejects it with a 403. Update your implementation and tests to include the required API key (or token) in the GraphQL request.

• In src/subgraph/orders/index.ts around the request(...) call (line 66):
– Import and use GraphQLClient from graphql-request, passing Authorization in headers.
– Example replacement:

- const response = await request(
-   subgraphEndpoint,
-   fetchSettledOrdersCountBasedOnTimeStampByUserQuery(userAddress, count, skip, startTimeStamp, endTimeStamp)
- );
+ import { GraphQLClient } from 'graphql-request';
+
+ const client = new GraphQLClient(subgraphEndpoint, {
+   headers: { Authorization: `Bearer ${process.env.SUBGRAPH_API_KEY}` },
+ });
+
+ const response = await client.request(
+   fetchSettledOrdersCountBasedOnTimeStampByUserQuery(
+     userAddress,
+     count,
+     skip,
+     startTimeStamp,
+     endTimeStamp
+   )
+ );

• Ensure your CI/pipeline and local .env include SUBGRAPH_API_KEY (or whatever env var your subgraph requires).

• In your tests, either mock the GraphQL call or inject a dummy API key so that authentication doesn’t block them.

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

🧰 Tools
🪛 GitHub Actions: Test contracts sdk

[error] 66-66: Error fetching orders: GraphQL Error (Code: 403) caused ClientError during subgraph query.

@sudeepb02 sudeepb02 merged commit a09ccc9 into develop May 8, 2025
2 checks passed
@sudeepb02 sudeepb02 deleted the add/orderCountQuery branch May 8, 2025 10:23
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