Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(torii-grpc): retrieve balances #2777

Merged
merged 2 commits into from
Dec 9, 2024

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Dec 6, 2024

addresses #2771

Summary by CodeRabbit

  • New Features

    • Enhanced security for token retrieval with improved SQL query handling.
    • Added methods for updating existing subscriptions for entities and event messages.
  • Bug Fixes

    • Improved robustness of subscription management logic.

Copy link

coderabbitai bot commented Dec 6, 2024

Walkthrough

Ohayo, sensei! The pull request introduces significant updates to the DojoWorld struct in the crates/torii/grpc/src/server/mod.rs file. Key changes include the implementation of parameterized queries in the retrieve_tokens and retrieve_token_balances methods to enhance security against SQL injection. Additionally, subscription management methods such as subscribe_models, subscribe_entities, and subscribe_event_messages have been refined, with new methods added for updating subscriptions. These modifications improve both the security and maintainability of the code while keeping the overall control flow consistent.

Changes

File Path Change Summary
crates/torii/grpc/src/server/mod.rs Updated retrieve_tokens and retrieve_token_balances to use parameterized queries; added methods for updating subscriptions.

Possibly related PRs

Suggested reviewers

  • glihm

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 023d721 and 2dfc132.

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

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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

@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

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

808-811: Ohayo, sensei! Efficient parameter binding in retrieve_tokens.

Currently, parameters are being bound individually in a loop. While this works, consider checking if the SQL driver supports binding an array of parameters to optimize performance.

If not supported, the current implementation is acceptable.


848-850: Ohayo, sensei! Efficient parameter binding in retrieve_token_balances.

Binding parameters within a loop may affect performance for large datasets. If the SQL driver supports it, consider binding all parameters at once to optimize execution.

If such optimization isn't available, the current approach remains acceptable.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c5e7d6b and 023d721.

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

801-804: Ohayo, sensei! Secure parameterization in retrieve_tokens.

Great job implementing parameterized queries to enhance security against SQL injection attacks.

Comment on lines 828 to 852
let mut bind_values = Vec::new();
let mut conditions = Vec::new();

if !account_addresses.is_empty() {
conditions.push(format!(
"account_address IN ({})",
account_addresses
.iter()
.map(|address| format!("{:#x}", address))
.collect::<Vec<_>>()
.join(", ")
));
let placeholders = vec!["?"; account_addresses.len()].join(", ");
conditions.push(format!("account_address IN ({})", placeholders));
bind_values.extend(account_addresses.iter().map(|addr| format!("{:#x}", addr)));
}

if !contract_addresses.is_empty() {
conditions.push(format!(
"contract_address IN ({})",
contract_addresses
.iter()
.map(|address| format!("{:#x}", address))
.collect::<Vec<_>>()
.join(", ")
));
let placeholders = vec!["?"; contract_addresses.len()].join(", ");
conditions.push(format!("contract_address IN ({})", placeholders));
bind_values.extend(contract_addresses.iter().map(|addr| format!("{:#x}", addr)));
}

if !conditions.is_empty() {
query += &format!(" WHERE {}", conditions.join(" AND "));
}

let balances: Vec<TokenBalance> = sqlx::query_as(&query)
let mut query = sqlx::query_as(&query);
for value in bind_values {
query = query.bind(value);
}

let balances: Vec<TokenBalance> = query
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ohayo, sensei! Potential unintended data exposure in retrieve_token_balances.

When both account_addresses and contract_addresses are empty, the query retrieves all token balances, which may not be intended and could expose sensitive data. Consider adding input validation to handle this case.

Here's a suggested fix to add input validation:

 async fn retrieve_token_balances(
     &self,
     account_addresses: Vec<Felt>,
     contract_addresses: Vec<Felt>,
 ) -> Result<RetrieveTokenBalancesResponse, Status> {
+    if account_addresses.is_empty() && contract_addresses.is_empty() {
+        return Err(Status::invalid_argument("At least one address must be provided."));
+    }
     let mut query = "SELECT * FROM token_balances".to_string();
     let mut bind_values = Vec::new();
     let mut conditions = Vec::new();
📝 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
let mut bind_values = Vec::new();
let mut conditions = Vec::new();
if !account_addresses.is_empty() {
conditions.push(format!(
"account_address IN ({})",
account_addresses
.iter()
.map(|address| format!("{:#x}", address))
.collect::<Vec<_>>()
.join(", ")
));
let placeholders = vec!["?"; account_addresses.len()].join(", ");
conditions.push(format!("account_address IN ({})", placeholders));
bind_values.extend(account_addresses.iter().map(|addr| format!("{:#x}", addr)));
}
if !contract_addresses.is_empty() {
conditions.push(format!(
"contract_address IN ({})",
contract_addresses
.iter()
.map(|address| format!("{:#x}", address))
.collect::<Vec<_>>()
.join(", ")
));
let placeholders = vec!["?"; contract_addresses.len()].join(", ");
conditions.push(format!("contract_address IN ({})", placeholders));
bind_values.extend(contract_addresses.iter().map(|addr| format!("{:#x}", addr)));
}
if !conditions.is_empty() {
query += &format!(" WHERE {}", conditions.join(" AND "));
}
let balances: Vec<TokenBalance> = sqlx::query_as(&query)
let mut query = sqlx::query_as(&query);
for value in bind_values {
query = query.bind(value);
}
let balances: Vec<TokenBalance> = query
if account_addresses.is_empty() && contract_addresses.is_empty() {
return Err(Status::invalid_argument("At least one address must be provided."));
}
let mut query = "SELECT * FROM token_balances".to_string();
let mut bind_values = Vec::new();
let mut conditions = Vec::new();
if !account_addresses.is_empty() {
let placeholders = vec!["?"; account_addresses.len()].join(", ");
conditions.push(format!("account_address IN ({})", placeholders));
bind_values.extend(account_addresses.iter().map(|addr| format!("{:#x}", addr)));
}
if !contract_addresses.is_empty() {
let placeholders = vec!["?"; contract_addresses.len()].join(", ");
conditions.push(format!("contract_address IN ({})", placeholders));
bind_values.extend(contract_addresses.iter().map(|addr| format!("{:#x}", addr)));
}
if !conditions.is_empty() {
query += &format!(" WHERE {}", conditions.join(" AND "));
}
let mut query = sqlx::query_as(&query);
for value in bind_values {
query = query.bind(value);
}
let balances: Vec<TokenBalance> = query

Copy link

codecov bot commented Dec 6, 2024

Codecov Report

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

Project coverage is 56.03%. Comparing base (c5e7d6b) to head (2dfc132).
Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/grpc/src/server/mod.rs 0.00% 22 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2777      +/-   ##
==========================================
+ Coverage   56.01%   56.03%   +0.01%     
==========================================
  Files         434      434              
  Lines       55068    55057      -11     
==========================================
+ Hits        30849    30850       +1     
+ Misses      24219    24207      -12     

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

@Larkooo Larkooo changed the title fix: retrieve balances fix(torii-grpc): retrieve balances Dec 6, 2024
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.

Would be great to have tests ensuring the behavior is consistent across changes, could be tackled in subsequent PR.

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