Skip to content

refactor(torii-indexer): index only pending txns with specific contract - #3135

Merged
glihm merged 5 commits into
dojoengine:mainfrom
Larkooo:pending-index-tx-contract
Mar 31, 2025
Merged

refactor(torii-indexer): index only pending txns with specific contract#3135
glihm merged 5 commits into
dojoengine:mainfrom
Larkooo:pending-index-tx-contract

Conversation

@Larkooo

@Larkooo Larkooo commented Mar 31, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Refactor
    • Revised the transaction processing logic to handle only transactions with valid events.
    • Enhanced the mechanism to ensure consistent processing of entries with relevant event data.
    • Introduced a new structure for encapsulating transaction details, improving readability and modularity.
    • Streamlined parsing logic for transaction execution calls, enhancing overall clarity and maintainability.

@coderabbitai

coderabbitai Bot commented Mar 31, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Ohayo, sensei! This PR enhances the event processing logic within the Engine struct by adding a comment to clarify that events not originating from indexed contracts should be skipped. It modifies the control flow in the process_transaction_with_receipt method to ensure transactions are processed only when at least one relevant event exists, verified by checking the length of the unique_contracts set. Additionally, the event_id variable is now explicitly declared as a String to improve type clarity. The StoreTransactionProcessor now includes a new TransactionInfo struct and several async methods for better transaction handling.

Changes

File Change Summary
crates/torii/indexer/src/engine.rs - Added a comment to clarify skipping events not originating from an indexed contract
- Updated the condition to process transactions only if unique_contracts is non-empty
- Explicitly declared event_id as a String
crates/torii/indexer/src/processors/store_transaction.rs - Added new struct TransactionInfo to encapsulate transaction details
- Introduced method extract_transaction_info to extract transaction details
- Modified process method to use extract_transaction_info
- Added several new async methods for parsing and processing calls

Possibly related PRs

  • chore(torii): remove unused parameters #2360: The changes in this PR enhance the logic of the process_transaction_with_receipt method, while the retrieved PR focuses on removing unused parameters in the same method, indicating a direct relationship in their modifications.
  • fix: emit trace for unprocessed event only once #2352: The changes in this PR focus on refining the event processing logic within the Engine struct, while the retrieved PR modifies the control flow for handling unprocessed events in the same Engine implementation, indicating a direct relationship in their event processing logic.
  • feat(torii-indexer): relation between txns and contracts #3055: The changes in this PR are related to the modifications in the process_transaction_with_receipt method, as both PRs involve updates to the same method and its handling of transaction processing logic.

📜 Recent 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 1a02b9c and 37b5ccd.

📒 Files selected for processing (1)
  • crates/torii/indexer/src/engine.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/torii/indexer/src/engine.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build

🪧 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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

📥 Commits

Reviewing files that changed from the base of the PR and between ecf6889 and e789d79.

📒 Files selected for processing (1)
  • crates/torii/indexer/src/engine.rs (3 hunks)
🧰 Additional context used
🪛 GitHub Actions: ci
crates/torii/indexer/src/engine.rs

[error] 731-731: Rust formatting check failed. Missing opening brace on the line following the conditional statement.

🔇 Additional comments (2)
crates/torii/indexer/src/engine.rs (2)

710-711: Ohayo, sensei! Kudos for improving code clarity!

Nice addition of this explanatory comment that makes the purpose of the subsequent check more explicit. This helps other developers understand why certain events are being skipped.


719-720: Type annotation enhances code readability, sensei!

Explicitly specifying the String type for event_id improves clarity, though the compiler would have inferred it correctly from the format! macro. This is a good practice for important variables like identifiers.

Comment thread crates/torii/indexer/src/engine.rs Outdated
@codecov

codecov Bot commented Mar 31, 2025

Copy link
Copy Markdown

Codecov Report

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

Project coverage is 55.68%. Comparing base (ecf6889) to head (37b5ccd).
Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
.../torii/indexer/src/processors/store_transaction.rs 0.00% 186 Missing ⚠️
crates/torii/indexer/src/engine.rs 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3135      +/-   ##
==========================================
- Coverage   55.74%   55.68%   -0.07%     
==========================================
  Files         443      443              
  Lines       62750    62825      +75     
==========================================
- Hits        34983    34981       -2     
- Misses      27767    27844      +77     

☔ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
crates/torii/indexer/src/processors/store_transaction.rs (2)

47-55: Consider using an enum for transaction_type.

Storing the transaction_type as a &'static str might limit extensibility if more transaction types are added later. An enum could help ensure type safety and maintainability.


1-300: Formatting warnings detected.

Pipeline logs show multiple formatting issues (e.g., lines 100, 123, 147, 179, 191, 216, 228, 237, 263). Please run cargo fmt or rustfmt to resolve them.

🧰 Tools
🪛 GitHub Actions: ci

[warning] 100-100: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 123-123: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 147-147: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 179-179: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 191-191: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 216-216: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 228-228: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 237-237: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 263-263: Formatting issues detected in the file. Please run 'rustfmt' to format the code.

📜 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 cfa665a and 335ce0b.

📒 Files selected for processing (1)
  • crates/torii/indexer/src/processors/store_transaction.rs (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
crates/torii/indexer/src/processors/store_transaction.rs (1)
crates/torii/sqlite/src/cache.rs (1)
  • get_entrypoint_name_from_class (235-265)
🪛 GitHub Actions: ci
crates/torii/indexer/src/processors/store_transaction.rs

[warning] 100-100: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 123-123: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 147-147: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 179-179: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 191-191: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 216-216: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 228-228: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 237-237: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 263-263: Formatting issues detected in the file. Please run 'rustfmt' to format the code.

🔇 Additional comments (6)
crates/torii/indexer/src/processors/store_transaction.rs (6)

3-3: Ohayo sensei! This new import is fine.

Using anyhow::Result is consistent with the rest of the codebase for error handling.


60-60: Great addition of the impl block.

Defining methods under StoreTransactionProcessor improves code organization.


61-92: Verify omitted fields for V3 & confirm ignoring other transaction types is intentional.

  1. For V3, you currently set max_fee to Felt::ZERO. If InvokeTransaction::V3 supports non-zero max_fee, consider capturing it to maintain data integrity.
  2. You return None for other transaction variants like Declare, Deploy, or DeployAccount. Double-check if you intend to skip them.

Would you like to handle these scenarios, sensei, or keep the current approach?


94-115: Looks good to me.

This parsing logic cleanly retrieves the contract class, retrieves the entrypoint name, and populates a ParsedCall. Straightforward, ohayo sensei!

🧰 Tools
🪛 GitHub Actions: ci

[warning] 100-100: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


204-246: Clean and modular approach to parsing execute calls.

This method nicely aggregates calls and any outside calls for processing. Good job maintaining clarity, sensei!

🧰 Tools
🪛 GitHub Actions: ci

[warning] 216-216: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 228-228: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 237-237: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


249-295: Request confirmation on skipping other transactions & empty call lists.

  1. Currently, only INVOKE transactions parse execute calls. Others (e.g., L1 handlers) skip the parse logic. Please confirm if that’s intentional.
  2. When ExecuteTransaction or LegacyExecuteTransaction parsing fails, we store an empty calls vector. Verify if partial transaction info should still be stored or if an error is more appropriate.
🧰 Tools
🪛 GitHub Actions: ci

[warning] 263-263: Formatting issues detected in the file. Please run 'rustfmt' to format the code.

Comment on lines +167 to +202
async fn process_outside_calls<P: Provider + Send + Sync + std::fmt::Debug>(
contract_class_cache: &ContractClassCache<P>,
call: &ParsedCall,
) -> Result<Vec<ParsedCall>> {
let mut outside_calls = Vec::new();

match call.entrypoint.as_str() {
"execute_from_outside_v3" => {
let outside_calls_len: usize = call.calldata[5].try_into().unwrap();
for _ in 0..outside_calls_len {
let outside_call = Self::parse_outside_call(
contract_class_cache,
&call.calldata,
6,
call.contract_address,
).await?;
outside_calls.push(outside_call);
}
}
"execute_from_outside_v2" => {
let outside_calls_len: usize = call.calldata[4].try_into().unwrap();
for _ in 0..outside_calls_len {
let outside_call = Self::parse_outside_call(
contract_class_cache,
&call.calldata,
5,
call.contract_address,
).await?;
outside_calls.push(outside_call);
}
}
_ => {}
}

Ok(outside_calls)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Confirm multiple calls are not parsed from the same offset.

For each iteration, base_offset remains constant. This leads to identical slices unless the calls are truly all at the same position. Verify if this is correct or if the offset needs incrementing on each pass.

🧰 Tools
🪛 GitHub Actions: ci

[warning] 179-179: Formatting issues detected in the file. Please run 'rustfmt' to format the code.


[warning] 191-191: Formatting issues detected in the file. Please run 'rustfmt' to format the code.

Comment on lines +116 to +137
async fn parse_legacy_execute_call<P: Provider + Send + Sync + std::fmt::Debug>(
contract_class_cache: &ContractClassCache<P>,
call: &LegacyExecuteCall,
full_calldata: &[Felt],
caller_address: Felt,
call_type: CallType,
) -> Result<ParsedCall> {
let contract_class = contract_class_cache
.get(call.contract_address, BlockId::Tag(BlockTag::Pending))
.await?;

let entrypoint = get_entrypoint_name_from_class(&contract_class, call.selector)
.unwrap_or(format!("{:#x}", call.selector));

Ok(ParsedCall {
contract_address: call.contract_address,
entrypoint,
calldata: full_calldata[call.data_offset..call.data_offset + call.data_length].to_vec(),
call_type,
caller_address,
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Guard against potential out-of-range slicing.

Accessing full_calldata[call.data_offset..call.data_offset + call.data_length] can panic if the slice boundaries are invalid. Consider validating the bounds before slicing to avoid runtime errors.

 fn parse_legacy_execute_call(...) -> Result<ParsedCall> {
     ...
-    calldata: full_calldata[call.data_offset..call.data_offset + call.data_length].to_vec(),
+    let end = call.data_offset.saturating_add(call.data_length);
+    if end > full_calldata.len() {
+        return Err(anyhow!("Out-of-range calldata slicing"));
+    }
+    calldata: full_calldata[call.data_offset..end].to_vec(),
     ...
 }

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

🧰 Tools
🪛 GitHub Actions: ci

[warning] 123-123: Formatting issues detected in the file. Please run 'rustfmt' to format the code.

Comment on lines +139 to +165
async fn parse_outside_call<P: Provider + Send + Sync + std::fmt::Debug>(
contract_class_cache: &ContractClassCache<P>,
calldata: &[Felt],
base_offset: usize,
caller_address: Felt,
) -> Result<ParsedCall> {
let to_offset = base_offset;
let selector_offset = to_offset + 1;
let calldata_offset = selector_offset + 2;
let calldata_len: usize = calldata[selector_offset + 1].try_into().unwrap();
let contract_address = calldata[to_offset];

let contract_class = contract_class_cache
.get(contract_address, BlockId::Tag(BlockTag::Pending))
.await?;

let entrypoint = get_entrypoint_name_from_class(&contract_class, calldata[selector_offset])
.unwrap_or(format!("{:#x}", calldata[selector_offset]));

Ok(ParsedCall {
contract_address,
entrypoint,
calldata: calldata[calldata_offset..calldata_offset + calldata_len].to_vec(),
call_type: CallType::ExecuteFromOutside,
caller_address,
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent panic from unchecked indexes and try_into().unwrap().

Indices like calldata[selector_offset + 1] risk out-of-bounds. Also, try_into().unwrap() can panic if the Felt value doesn't fit a usize. Both cases should be handled gracefully to avoid crashes.

 let calldata_len: usize = match calldata.get(selector_offset + 1) {
-    Some(val) => val.try_into().unwrap(),
-    None => return Err(anyhow!("Missing length value in calldata")),
+    Some(val) => val.try_into().map_err(|_| anyhow!("Felt does not fit in usize"))?,
+    None => return Err(anyhow!("Missing length value in calldata")),
 };
 
-Ok(ParsedCall {
-    calldata: calldata[calldata_offset..calldata_offset + calldata_len].to_vec(),
-    ...
-})
+if calldata_offset + calldata_len > calldata.len() {
+    return Err(anyhow!("Out-of-bounds for outside call calldata"));
+}
📝 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
async fn parse_outside_call<P: Provider + Send + Sync + std::fmt::Debug>(
contract_class_cache: &ContractClassCache<P>,
calldata: &[Felt],
base_offset: usize,
caller_address: Felt,
) -> Result<ParsedCall> {
let to_offset = base_offset;
let selector_offset = to_offset + 1;
let calldata_offset = selector_offset + 2;
let calldata_len: usize = calldata[selector_offset + 1].try_into().unwrap();
let contract_address = calldata[to_offset];
let contract_class = contract_class_cache
.get(contract_address, BlockId::Tag(BlockTag::Pending))
.await?;
let entrypoint = get_entrypoint_name_from_class(&contract_class, calldata[selector_offset])
.unwrap_or(format!("{:#x}", calldata[selector_offset]));
Ok(ParsedCall {
contract_address,
entrypoint,
calldata: calldata[calldata_offset..calldata_offset + calldata_len].to_vec(),
call_type: CallType::ExecuteFromOutside,
caller_address,
})
}
async fn parse_outside_call<P: Provider + Send + Sync + std::fmt::Debug>(
contract_class_cache: &ContractClassCache<P>,
calldata: &[Felt],
base_offset: usize,
caller_address: Felt,
) -> Result<ParsedCall> {
let to_offset = base_offset;
let selector_offset = to_offset + 1;
let calldata_offset = selector_offset + 2;
let calldata_len: usize = match calldata.get(selector_offset + 1) {
Some(val) => val.try_into().map_err(|_| anyhow!("Felt does not fit in usize"))?,
None => return Err(anyhow!("Missing length value in calldata")),
};
let contract_address = calldata[to_offset];
let contract_class = contract_class_cache
.get(contract_address, BlockId::Tag(BlockTag::Pending))
.await?;
let entrypoint = get_entrypoint_name_from_class(&contract_class, calldata[selector_offset])
.unwrap_or(format!("{:#x}", calldata[selector_offset]));
if calldata_offset + calldata_len > calldata.len() {
return Err(anyhow!("Out-of-bounds for outside call calldata"));
}
Ok(ParsedCall {
contract_address,
entrypoint,
calldata: calldata[calldata_offset..calldata_offset + calldata_len].to_vec(),
call_type: CallType::ExecuteFromOutside,
caller_address,
})
}
🧰 Tools
🪛 GitHub Actions: ci

[warning] 147-147: Formatting issues detected in the file. Please run 'rustfmt' to format the code.

@glihm glihm changed the title refactor(torii-indexer): index only pending txns with speciifce contr… refactor(torii-indexer): index only pending txns with specific contract Mar 31, 2025
@glihm
glihm enabled auto-merge (squash) March 31, 2025 17:14
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