Conversation
WalkthroughThe 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 Changes
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
Suggested reviewers
Poem
Tip ⚡💬 Agentic Chat (Pro Plan, General Availability)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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 rangetest/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
countandskipparameters 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
⛔ Files ignored due to path filters (1)
package-lock.jsonis 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:
- The test environment has the correct credentials
- The error handling in the underlying implementation is appropriate
Note that while the implementation in
orders/index.tshandles 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
fetchSettledOrdersCountBasedOnTimeStampByUserQuerywhich is required for the new functionality.
| const startTime = 1744771331; | ||
| const endTime = 1745223131; | ||
| const orderCount = await parifiSdk.subgraph.getSettledOrdersCountBasedOnTimeStampByUserAddress( | ||
| address, | ||
| 50, | ||
| 0, | ||
| startTime, | ||
| endTime, | ||
| ); |
There was a problem hiding this comment.
💡 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 tsLength 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 () => { |
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
💡 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:
- 1: https://www.apollographql.com/docs/apollo-server/data/errors
- 2: https://www.apollographql.com/docs/graphos/reference/federation/errors
- 3: 403 Forbidden when accessing the graphql server wp-graphql/wp-graphql#262
- 4: https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/graphql-error-403-forbidden/m-p/675212
- 5: https://community.prismic.io/t/request-with-graphql-with-403/10168
- 6: https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/graphql-error-403-forbidden/m-p/675155
- 7: https://tyk.io/docs/api-management/graphql/
- 8: https://inigo.io/blog/graphql_error_handling
- 9: https://www.apollographql.com/docs/graphos/routing/cloud/lattice-troubleshooting
- 10: https://www.apollographql.com/docs/react/data/error-handling
🏁 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.tsLength of output: 1405
🏁 Script executed:
#!/bin/bash
# Find implementation of getParifiSdkInstanceForTesting
rg "getParifiSdkInstanceForTesting" -nLength of output: 3030
🏁 Script executed:
#!/bin/bash
# Show implementation of getParifiSdkInstanceForTesting
sed -n '1,200p' test/index.tsLength 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.
|
|
||
| // 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; | ||
| } | ||
| }; |
There was a problem hiding this comment.
🛠️ 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:
-
The default
countvalue (50) differs from the similar functiongetAllOrdersByUserAddress(10). Consider aligning these defaults for consistency. -
There's no validation for
startTimeStampandendTimeStamp. You should verify that start is less than or equal to end to prevent logical errors. -
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.
-
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.
| // 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); |
There was a problem hiding this comment.
💡 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:
- Authentication issues with the subgraph endpoint
- Incorrect query structure for the specific endpoint
- 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 10Length 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.
Summary by CodeRabbit