Skip to content

feat(torii-grpc): pagination for tokens & order by & next cursor #3143

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

Merged
merged 12 commits into from
Apr 8, 2025

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Apr 4, 2025

#3142

Summary by CodeRabbit

  • New Features
    • Introduced subscription requests for token updates and token balance updates.
    • Enabled pagination for token and token balance retrieval by adding limit, offset, and cursor options.
    • Added a new struct for paginated data representation, including a list of items and a next cursor.
    • Updated methods to support controlled paging and consistent ordering of results.

Copy link
Contributor

coderabbitai bot commented Apr 4, 2025

Caution

Review failed

The head commit changed during the review from 85fa1c1 to 8146b8e.

Walkthrough

Ohayo, sensei! This change introduces new request messages for subscribing to token updates and balances, namely SubscribeTokensRequest and SubscribeTokenBalancesRequest. The existing retrieval requests, RetrieveTokensRequest and RetrieveTokenBalancesRequest, have been updated to include limit, offset, and cursor fields for pagination. Correspondingly, the server methods for retrieving tokens and balances have been modified to accept these parameters, enhancing the SQL queries to utilize LIMIT and OFFSET. This standardizes the way clients manage result ranges during token operations.

Changes

File Change Summary
crates/torii/grpc/proto/world.proto Added SubscribeTokensRequest and SubscribeTokenBalancesRequest. Updated RetrieveTokensRequest and RetrieveTokenBalancesRequest to include uint32 limit, uint32 offset, and string cursor. Updated RPC methods to use new request messages.
crates/torii/grpc/src/server/mod.rs Updated method signatures for retrieve_tokens, retrieve_token_balances, and retrieve_events to accept optional limit, offset, and cursor parameters; modified SQL queries to append LIMIT and OFFSET clauses. Removed events_all method.
crates/torii/grpc/src/client.rs Updated method signatures for retrieve_tokens and retrieve_token_balances to include limit, offset, and cursor. Changed request types in subscribe_tokens and subscribe_token_balances methods to new subscription requests.
crates/torii/client/src/client/mod.rs Updated method signatures for tokens and token_balances methods to include limit, offset, and cursor parameters for pagination. Modified calls to retrieve_tokens and retrieve_token_balances to pass these parameters.
crates/torii/grpc/src/types/mod.rs Added new struct Page<T> with fields items: Vec<T> and next_cursor: String for representing paginated data.

Possibly related PRs

Suggested reviewers

  • glihm

🪧 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 plan to trigger planning for file edits and PR creation.
  • @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.

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

🔭 Outside diff range comments (2)
crates/torii/grpc/src/server/mod.rs (2)

1411-1427: ⚠️ Potential issue

The WorldServer implementation doesn't pass the pagination parameters!

The retrieve_tokens method signature was updated, but this implementation doesn't pass the new limit and offset parameters.

async fn retrieve_tokens(
    &self,
    request: Request<RetrieveTokensRequest>,
) -> Result<Response<RetrieveTokensResponse>, Status> {
-    let RetrieveTokensRequest { contract_addresses, token_ids } = request.into_inner();
+    let RetrieveTokensRequest { contract_addresses, token_ids, limit, offset } = request.into_inner();
    let contract_addresses = contract_addresses
        .iter()
        .map(|address| Felt::from_bytes_be_slice(address))
        .collect::<Vec<_>>();
    let token_ids =
        token_ids.iter().map(|id| crypto_bigint::U256::from_be_slice(id)).collect::<Vec<_>>();

    let tokens = self
-        .retrieve_tokens(contract_addresses, token_ids)
+        .retrieve_tokens(contract_addresses, token_ids, limit, offset)
        .await
        .map_err(|e| Status::internal(e.to_string()))?;
    Ok(Response::new(tokens))
}

1464-1485: ⚠️ Potential issue

Missing pagination parameters in WorldServer implementation for token balances too!

Similar to the retrieve_tokens method, this implementation doesn't pass the new limit and offset parameters.

async fn retrieve_token_balances(
    &self,
    request: Request<RetrieveTokenBalancesRequest>,
) -> Result<Response<RetrieveTokenBalancesResponse>, Status> {
-    let RetrieveTokenBalancesRequest { account_addresses, contract_addresses, token_ids } =
+    let RetrieveTokenBalancesRequest { account_addresses, contract_addresses, token_ids, limit, offset } =
        request.into_inner();
    let account_addresses = account_addresses
        .iter()
        .map(|address| Felt::from_bytes_be_slice(address))
        .collect::<Vec<_>>();
    let contract_addresses = contract_addresses
        .iter()
        .map(|address| Felt::from_bytes_be_slice(address))
        .collect::<Vec<_>>();
    let token_ids = token_ids.iter().map(|id| U256::from_be_slice(id)).collect::<Vec<_>>();

    let balances = self
-        .retrieve_token_balances(account_addresses, contract_addresses, token_ids)
+        .retrieve_token_balances(account_addresses, contract_addresses, token_ids, limit, offset)
        .await
        .map_err(|e| Status::internal(e.to_string()))?;
    Ok(Response::new(balances))
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 167f417 and c33e651.

📒 Files selected for processing (2)
  • crates/torii/grpc/proto/world.proto (2 hunks)
  • crates/torii/grpc/src/server/mod.rs (4 hunks)
🔇 Additional comments (4)
crates/torii/grpc/proto/world.proto (2)

102-105: Ohayo! The pagination fields added to RetrieveTokensRequest look good, sensei!

These pagination fields will allow clients to limit the number of results returned and skip records, which is great for performance when dealing with large datasets.


139-142: Pagination support for token balances - nice work!

Adding pagination to token balances follows the same pattern as tokens, which maintains consistency in the API.

crates/torii/grpc/src/server/mod.rs (2)

848-849: Method signature update for retrieve_tokens looks good!

Adding the optional pagination parameters is consistent with the proto file changes.


895-896: Method signature update for retrieve_token_balances looks good!

The optional pagination parameters match the proto changes.

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

♻️ Duplicate comments (1)
crates/torii/grpc/src/server/mod.rs (1)

825-834: ⚠️ Potential issue

Ohayo sensei! SQL clause ordering issue with LIMIT and OFFSET.
They appear before the WHERE clause. Standard SQL requires WHERE ... ORDER BY ... LIMIT ... OFFSET. Move the WHERE and ORDER BY before these clauses.

Apply a fix like this:

 if !conditions.is_empty() {
-    query += &format!(" WHERE {} ORDER BY id", conditions.join(" AND "));
 }
+if !conditions.is_empty() {
+    query += &format!(" WHERE {} ", conditions.join(" AND "));
+    query += "ORDER BY id";
+}
 if let Some(limit) = limit {
     query += &format!(" LIMIT {}", limit);
 }
 if let Some(offset) = offset {
     query += &format!(" OFFSET {}", offset);
 }
🧹 Nitpick comments (2)
crates/torii/grpc/proto/world.proto (2)

102-107: Ohayo sensei! Nice addition of pagination fields in RetrieveTokensRequest.
Including limit and offset is a solid approach to enable pagination. Consider ensuring in the server logic that zero or extremely large values are handled gracefully to prevent potential performance issues.


147-151: Ohayo sensei! Pagination fields for token balances look correct.
Just make sure the server properly bounds or rejects invalid limit or offset values so they don’t degrade performance.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between c33e651 and d004ad5.

📒 Files selected for processing (3)
  • crates/torii/grpc/proto/world.proto (3 hunks)
  • crates/torii/grpc/src/client.rs (7 hunks)
  • crates/torii/grpc/src/server/mod.rs (19 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (21)
crates/torii/grpc/proto/world.proto (4)

38-38: Ohayo sensei! Looks good on using the new subscription request.
Thank you for matching the new proto request type. This aligns with the updated usage in the server code.


44-44: Ohayo sensei! Smooth transition to the SubscribeTokensRequest.
Great job switching the RPC to the newly introduced request type for subscribing to tokens.


108-114: Ohayo sensei! The new SubscribeTokensRequest message is integrated well.
Everything looks consistent with the existing types, and field naming is clear.


153-161: Ohayo sensei! SubscribeTokenBalancesRequest is properly structured.
This new message aligns well with your subscription design and reuses field naming from other requests.

crates/torii/grpc/src/server/mod.rs (10)

66-69: Ohayo sensei! Updated imports for token subscription requests look consistent.
Referencing SubscribeTokenBalancesRequest and SubscribeTokensRequest matches the proto updates perfectly.


269-270: Ohayo sensei! Good job adding limit and offset to the entities_all/query_by_hashed_keys calls.
This further unifies pagination across entity queries. Verify that the final SQL statements place LIMIT and OFFSET after WHERE and ORDER BY as well.

Also applies to: 281-282


807-808: Ohayo sensei! Thanks for adding the limit and offset parameters to retrieve_tokens.
This syncs perfectly with the updated request.


854-855: Ohayo sensei! Consistent addition of pagination parameters to retrieve_token_balances.
This keeps the interface uniform across token retrieval endpoints.


1074-1105: Ohayo sensei! The new limit/offset logic for retrieve_events is well-placed.
Since you only add LIMIT and OFFSET after forming the ORDER BY id DESC clause, the query ordering is correct here. Good job.


1413-1428: Ohayo sensei! Retrieving tokens with explicit limit/offset is implemented cleanly.
Ensuring if limit > 0 { Some(limit) } else { None } is a nice pattern that seamlessly handles “no limit.”


1436-1438: Ohayo sensei! subscribe_tokens usage is consistent with the new SubscribeTokensRequest.
No issues spotted.


1473-1479: Ohayo sensei! Great job mapping the new RetrieveTokenBalancesRequest fields.
This mirrors the approach used for tokens, preserving a predictable structure.


1491-1497: Ohayo sensei! Correct holding pattern on limit/offset in retrieve_token_balances.
Same pattern: if limit > 0 { Some(limit) } else { None }. Makes the logic consistent.


1559-1561: Ohayo sensei! Alignment with SubscribeTokenBalancesRequest is on point.
Your final usage of contract_addresses, account_addresses, token_ids matches the updated proto.

crates/torii/grpc/src/client.rs (7)

21-24: Ohayo! Clean imports for new request types.

The imports have been updated to include the new subscription-specific request and response types for token operations, maintaining a clean organization of imports.


117-123: Added pagination support to retrieve_tokens method, sensei!

The method signature has been updated to include optional limit and offset parameters, which is the standard approach for implementing pagination. This will allow clients to request specific ranges of tokens.


131-132: Setting sensible defaults for pagination parameters.

Using unwrap_or(0) provides sensible defaults - a limit of 0 typically means "no limit" in database queries, and an offset of 0 means start from the beginning.


144-144: Transitioned from retrieve to subscribe request type.

Changed from using RetrieveTokensRequest to the more appropriate SubscribeTokensRequest for the subscription method, which better reflects the operation's intent.


195-202: Added pagination support to retrieve_token_balances method, sensei!

Similar to the tokens retrieval method, this adds optional limit and offset parameters to enable pagination for token balances.


214-215: Consistent default implementation for pagination parameters.

The same default approach used in the tokens retrieval method is applied here, maintaining consistency across the API.


394-394: Updated subscribe_token_balances to use subscription-specific request type.

Changed to use SubscribeTokenBalancesRequest instead of RetrieveTokenBalancesRequest, which is more semantically accurate for a subscription operation.

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

🧹 Nitpick comments (1)
crates/torii/client/src/client/mod.rs (1)

84-117: Consider adding documentation for the pagination parameters, sensei!

While the implementation is solid, it would be helpful to add documentation comments for the new parameters explaining their purpose and any constraints (e.g., maximum values or behavior when null).

 /// Retrieves tokens matching contract addresses.
 pub async fn tokens(
     &self,
     contract_addresses: Vec<Felt>,
     token_ids: Vec<U256>,
+    /// Maximum number of tokens to return
     limit: Option<u32>,
+    /// Number of tokens to skip
     offset: Option<u32>,
 ) -> Result<Vec<Token>, Error> {
 /// Retrieves token balances for account addresses and contract addresses.
 pub async fn token_balances(
     &self,
     account_addresses: Vec<Felt>,
     contract_addresses: Vec<Felt>,
     token_ids: Vec<U256>,
+    /// Maximum number of token balances to return
     limit: Option<u32>,
+    /// Number of token balances to skip
     offset: Option<u32>,
 ) -> Result<Vec<TokenBalance>, Error> {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between d004ad5 and 3927007.

📒 Files selected for processing (1)
  • crates/torii/client/src/client/mod.rs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (2)
crates/torii/client/src/client/mod.rs (2)

84-95: Ohayo! Nice addition of pagination support for tokens retrieval, sensei!

The implementation correctly adds optional limit and offset parameters to the method signature, allowing clients to paginate through token results. This change aligns perfectly with the PR objective of implementing pagination for tokens.


97-117: Clean implementation of pagination for token balances, sensei!

Similar to the tokens method, this implementation nicely adds pagination support with optional limit and offset parameters. I appreciate the multi-line formatting for improved readability with the increased number of parameters.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Nice, thanks also for the work on dojo.c mapped to this PR. 👍

glihm
glihm previously requested changes Apr 7, 2025
Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Actually making more test on filters, code rabbit issue is important to tackle since for now it only works when we don't provide any filter than limit and offset.

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

🧹 Nitpick comments (1)
crates/torii/grpc/src/server/mod.rs (1)

1081-1117: Binding limit/offset as strings vs integers
Ohayo sensei! Using strings in bind parameters is acceptable, but consider binding them as integers for extra clarity and consistency.

- bind_values.push(limit.to_string());
- bind_values.push(offset.to_string());
+ row_events = row_events.bind(limit);
+ row_events = row_events.bind(offset);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 3927007 and 9eef28c.

📒 Files selected for processing (1)
  • crates/torii/grpc/src/server/mod.rs (19 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (14)
crates/torii/grpc/src/server/mod.rs (14)

66-69: Ohayo sensei, new subscription requests introduced!
Your additions for token and token balance subscriptions align with the PR objectives. No issues found here.


269-270: Pagination parameters for entities_all
The new limit and offset fields are introduced cleanly, matching the rest of the pagination strategy with no concerns.

Also applies to: 281-282


807-808: Including limit/offset in retrieve_tokens
Nice addition to support pagination within this function. Implementation looks good.


829-837: SQL ordering is correct
Placing WHERE, then ORDER BY, followed by LIMIT and OFFSET is best practice for valid SQL.


856-858: Additional parameters in retrieve_token_balances
This signature change aligns well with the introduced pagination.


886-895: Maintaining correct clause order for token_balances
Confirmed the pagination clauses are appended properly after ORDER BY.


980-982: Extracting limit and offset from the query
Using Option to handle non-positive values is logical. No issues found.


1078-1080: Pagination for retrieve_events
Great inclusion of limit and offset for event retrieval.


1417-1418: Destructuring new fields in RetrieveTokensRequest
Implementation is seamless, no concerns.


1427-1432: Passing limit/offset to retrieve_tokens
Looks consistent with the newly introduced parameters.


1440-1440: Updated subscribe_tokens signature
Matches the request structure. Implementation looks correct, sensei.

Also applies to: 1442-1442


1477-1483: New pagination fields for RetrieveTokenBalancesRequest
No issues: the additions are coherent with the existing approach.


1495-1501: Applying pagination in retrieve_token_balances
Great job wiring up limit and offset arguments here.


1563-1563: subscribe_token_balances request
The subscription method structure looks clean with no concurrency pitfalls.

Also applies to: 1565-1565

Copy link

codecov bot commented Apr 8, 2025

Codecov Report

Attention: Patch coverage is 0% with 149 lines in your changes missing coverage. Please review.

Project coverage is 55.61%. Comparing base (167f417) to head (8146b8e).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/grpc/src/server/mod.rs 0.00% 108 Missing ⚠️
crates/torii/client/src/client/mod.rs 0.00% 27 Missing ⚠️
crates/torii/grpc/src/client.rs 0.00% 14 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3143      +/-   ##
==========================================
- Coverage   55.65%   55.61%   -0.05%     
==========================================
  Files         443      443              
  Lines       62878    62953      +75     
==========================================
+ Hits        34994    35010      +16     
- Misses      27884    27943      +59     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Larkooo Larkooo changed the title feat(torii-grpc): pagination for tokens & order by feat(torii-grpc): pagination for tokens & order by & next cursor Apr 8, 2025
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.yaml
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 9eef28c and c28740d.

📒 Files selected for processing (4)
  • crates/torii/client/src/client/mod.rs (2 hunks)
  • crates/torii/grpc/proto/world.proto (3 hunks)
  • crates/torii/grpc/src/client.rs (7 hunks)
  • crates/torii/grpc/src/server/mod.rs (18 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/torii/grpc/src/client.rs
  • crates/torii/grpc/proto/world.proto
🧰 Additional context used
🧬 Code Definitions (1)
crates/torii/grpc/src/server/mod.rs (2)
crates/torii/client/src/client/mod.rs (4)
  • tokens (84-95)
  • tokens (94-94)
  • new (38-43)
  • balances (116-116)
crates/torii/grpc/src/client.rs (3)
  • retrieve_token_balances (195-220)
  • new (61-74)
  • new (78-85)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (19)
crates/torii/client/src/client/mod.rs (4)

88-90: Ohayo, sensei! Great addition of pagination parameters to tokens method!

Adding the optional pagination parameters (limit, offset, cursor) to the tokens method allows clients to control result set size and implement proper pagination. This aligns well with the PR objectives.


93-95: Correctly passing pagination parameters to the underlying gRPC client

The implementation properly passes the new pagination parameters to the underlying gRPC client method.


105-107: Consistent implementation of pagination in token_balances method!

Good job implementing the same pagination pattern for token_balances as you did for tokens. This consistency makes the API more predictable for clients.


110-118: Well-structured parameter passing to retrieve_token_balances

The updated method call correctly passes all parameters to the underlying gRPC method. The code is well-formatted and easy to read.

crates/torii/grpc/src/server/mod.rs (15)

66-69: Ohayo, sensei! Good proto import updates to support new message types

The imports have been updated to include the new request and response types for token subscriptions.


269-270: Consistent pagination parameter addition across methods

Adding pagination parameters to the entities_all method maintains consistency with other query methods.


807-809: Good addition of pagination parameters to retrieve_tokens

The method signature now properly includes the pagination parameters that are standard across the codebase.


826-829: Well-implemented cursor-based pagination!

Adding cursor-based pagination alongside offset pagination gives clients flexibility in how they navigate through large result sets. The cursor implementation looks good.


835-845: Fixed SQL query construction order - looks good!

The SQL query construction now follows the correct order: WHERE clause, followed by ORDER BY, then LIMIT and OFFSET. Using bind parameters for limit and offset also prevents SQL injection.


854-857: Nice implementation of next_cursor in response

Including the next_cursor in the response allows clients to easily request the next page of results without having to calculate offsets manually.


865-867: Consistent pagination parameters in retrieve_token_balances

The method signature now properly includes the same pagination parameters as retrieve_tokens.


892-895: Good cursor implementation in token_balances

The cursor implementation for token_balances follows the same pattern as in retrieve_tokens, maintaining consistency.


918-921: Well-implemented next_cursor in token_balances response

Good job implementing next_cursor consistently across token-related responses.


1094-1095: Good addition of pagination to retrieve_events

Adding pagination to retrieve_events makes the API consistent across all data retrieval methods.


1104-1125: Well-structured SQL query construction for events

The query construction for events pagination is well-implemented with proper ordering of clauses and parameter binding.


1433-1449: Clean implementation of handler for retrieve_tokens

The handler properly extracts and passes all parameters to the underlying function, with good handling of default values.


1457-1459: Updated request type for subscribe_tokens

The handler has been updated to use the new request type, keeping the implementation in sync with the proto changes.


1494-1520: Well-structured handler for retrieve_token_balances

The handler properly extracts all parameters from the request and passes them to the implementation function.


1582-1584: Updated request type for subscribe_token_balances

The handler has been updated to use the new request type, maintaining consistency with the proto changes.

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

🧹 Nitpick comments (2)
crates/torii/grpc/src/types/mod.rs (2)

21-25: Ohayo, sensei! New pagination struct looks good but could benefit from documentation.

The new Page<T> struct is a clean, generic implementation for pagination which aligns perfectly with our PR objectives. The structure provides a reusable component for paginated data across different endpoints.

Consider adding documentation comments to explain:

  1. The purpose of this pagination structure
  2. How the next_cursor should be formatted and used
  3. Example usage in token-related operations
+/// Represents a paginated collection of items with cursor-based navigation.
+///
+/// # Example
+/// ```
+/// let page = Page {
+///     items: vec![token1, token2],
+///     next_cursor: "base64_encoded_cursor_value"
+/// };
+/// ```
 #[derive(Debug, Serialize, Deserialize, PartialEq, Hash, Eq, Clone)]
 pub struct Page<T> {
+    /// Collection of items for the current page
     pub items: Vec<T>,
+    /// Opaque cursor string to fetch the next page of results.
+    /// Pass this value to the `cursor` field in subsequent requests.
+    /// An empty string indicates there are no more results.
     pub next_cursor: String,
 }

21-25: Consider implementing helpful methods and conversion traits for the Page struct

While the current implementation works for basic pagination, adding a few helper methods would improve the developer experience.

Consider implementing:

  1. A method to check if there are more pages available
  2. Conversion traits to/from protobuf types for consistency with the rest of the codebase
 #[derive(Debug, Serialize, Deserialize, PartialEq, Hash, Eq, Clone)]
 pub struct Page<T> {
     pub items: Vec<T>,
     pub next_cursor: String,
 }
+
+impl<T> Page<T> {
+    /// Returns true if there are more pages available.
+    pub fn has_more(&self) -> bool {
+        !self.next_cursor.is_empty()
+    }
+
+    /// Creates a new page with the given items and next cursor.
+    pub fn new(items: Vec<T>, next_cursor: String) -> Self {
+        Self { items, next_cursor }
+    }
+}

You might also want to implement conversion traits between this Page struct and any corresponding protobuf message types that would be defined in your proto files.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 80e5716 and de8a618.

📒 Files selected for processing (2)
  • crates/torii/client/src/client/mod.rs (3 hunks)
  • crates/torii/grpc/src/types/mod.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/torii/client/src/client/mod.rs

@Larkooo Larkooo enabled auto-merge (squash) April 8, 2025 04:38
@Larkooo Larkooo dismissed glihm’s stale review April 8, 2025 05:17

Fixed token sql query when paginating & added cursor support

@Larkooo Larkooo requested a review from glihm April 8, 2025 05:17
@Larkooo Larkooo force-pushed the pagination-tokens-grpc branch from 85fa1c1 to 8146b8e Compare April 8, 2025 08:33
@Larkooo Larkooo merged commit 2348232 into dojoengine:main Apr 8, 2025
25 of 27 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants