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

Merge katana/dev #2854

Merged
merged 12 commits into from
Dec 31, 2024
Merged

Merge katana/dev #2854

merged 12 commits into from
Dec 31, 2024

Conversation

kariy
Copy link
Member

@kariy kariy commented Dec 31, 2024

#2809
#2814
#2820
#2821
#2822
#2823
#2826
#2844
#2845
#2846
#2847
#2848

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for storage proofs in the Starknet JSON-RPC API
    • Introduced new trie management capabilities for classes, contracts, and storage
    • Enhanced state root and multiproof generation functionalities
  • Improvements

    • Streamlined trie-related operations across multiple components
    • Consolidated state management interfaces
    • Updated database versioning to version 6
  • Dependencies

    • Updated Bonsai Trie dependency with new branch and repository
    • Standardized dependency management using workspace references
  • Breaking Changes

    • Removed StateRootProvider from several implementations
    • Renamed and consolidated trie-related traits and methods

Copy link

coderabbitai bot commented Dec 31, 2024

Walkthrough

This pull request introduces a comprehensive refactoring of the Katana blockchain's state management and trie infrastructure. The changes focus on consolidating and enhancing the handling of tries, state roots, and proofs across multiple components of the system. Key modifications include introducing new traits for state proofs, streamlining trie operations, and adding support for multiproofs and historical state retrieval.

Changes

File/Group Change Summary
.gitmodules Added Piltover project submodule
Cargo.toml files Added procedural macro dependencies and workspace-level dependencies
bin/katana/src/cli New initialization module for blockchain environment setup
crates/katana/storage Refactored trie management, added TrieWriter, removed StateRootProvider
crates/katana/trie Introduced new trie structures for classes, contracts, and storage
crates/katana/rpc Added storage proof RPC method and related error handling

Possibly related PRs

Sequence Diagram

sequenceDiagram
    participant Client
    participant RPC
    participant StateProvider
    participant TrieManager
    participant Database

    Client->>RPC: Request Storage Proof
    RPC->>StateProvider: Get Multiproof
    StateProvider->>TrieManager: Generate Multiproof
    TrieManager->>Database: Retrieve Trie Data
    Database-->>TrieManager: Return Trie Entries
    TrieManager-->>StateProvider: Return Multiproof
    StateProvider-->>RPC: Return Proof
    RPC-->>Client: Send Storage Proof
Loading

Ohayo, sensei! This PR is a massive leap forward in our blockchain's state management capabilities. The new multiproof and trie infrastructure will make our system more robust and flexible. Enjoy the code! 🚀🔗


🪧 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. (Beta)
  • @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: 7

🧹 Nitpick comments (37)
crates/katana/trie/src/classes.rs (2)

14-20: Ohayo sensei! Consider validating proof results as part of verify.
Right now, verify delegates the entire result check to crate::verify_proof. If you need further post-check actions, centralize them here for better maintainability.


37-47: Ohayo sensei! Try to unify extra logs or debug statements if needed.
Methods new, root, and multiproof are well-defined. Consider adding some debug logs to track root changes or proof generation in large systems.

crates/katana/storage/db/src/models/trie.rs (2)

7-11: Ohayo sensei! TrieHistoryEntry is a clean data container.
Storing the key-value pair is straightforward. Consider whether debug logs might help for historical tracebacks.


95-97: Ohayo sensei! Safety net for short buffers.
You panic here instead of returning a custom error. Consider consistent error handling for better uniformity.

crates/katana/trie/src/lib.rs (6)

1-8: Ohayo sensei! Consolidate and reorder imports if necessary.

It might be more maintainable to keep imports from related crates grouped together.


10-13: Ohayo sensei! Check doc coverage for new modules.

Ensure unit tests exist for each module, covering internal logic.


20-25: Ohayo sensei! Improve doc references and usage examples.

Doc comments indicate usage but offering a short example snippet for each derived trie might be beneficial.


34-54: Ohayo sensei! Ensure error handling is consistent.

We see expect calls in the code. Consider returning results or logging gracefully to avoid panics in production.


56-69: Ohayo sensei! Watch for potential large vector conversions in multiproof.

Using into_iter().map(|key| key.to_bytes_be()...) might have performance implications for large inputs. Evaluate streaming or chunking if keys can be huge.


Line range hint 96-108: Ohayo sensei! Evaluate the cost of ephemeral HashMapDb.

compute_merkle_root uses an in-memory DB. If used heavily, performance might be impacted. Consider caching or reusing.

crates/katana/executor/src/abstraction/mod.rs (1)

227-243: Ohayo sensei! Root retrieval logic.

All methods pass through to self.0. Suggest integration tests to ensure consistent classes_root, contracts_root, storage_root, and state_root.

crates/katana/rpc/rpc-types/src/trie.rs (6)

10-16: Ohayo sensei! ContractStorageKeys is straightforward.

Ensure that any contract address and key size assumptions are well documented.


18-26: Ohayo sensei! GlobalRoots alignment.

The block hash plus the classes/contract tree roots is neat. Consider adding cross-reference to the block number as well.


66-77: Ohayo sensei! GetStorageProofResponse usage.

No immediate concerns. Make sure the fields are stable in the RPC schema.


79-83: Ohayo sensei! ClassesProof node usage.

Consider unit tests verifying data round trips for complicated proofs.


103-106: Ohayo sensei! A dedicated ContractStorageProofs.

Storing multiple Nodes vectors is fine. Keep an eye on large memory usage for huge multiproofs.


117-128: Ohayo sensei! Nodes as a transparent wrapper.

Using Deref and DerefMut is helpful. Ensure no confusion arises from hidden methods.

crates/katana/storage/db/src/trie/snapshot.rs (1)

4-8: Ohayo sensei! Additional references.

anyhow::Result is used widely. Keep in mind more specific error types might offer clarity.

crates/katana/core/src/backend/mod.rs (1)

169-177: Ohayo sensei! Consider generic naming.

trie_providerprovider is okay. Make sure code references are updated consistently.

crates/katana/core/src/backend/storage.rs (1)

50-50: Ohayo sensei! Trait Database now includes TrieWriter.
Merging trie operations is a step toward a simpler architecture. Confirm older references to removed traits are fully removed.

crates/katana/rpc/rpc/src/starknet/mod.rs (1)

1132-1219: Ohayo sensei! The new get_proofs method is cohesive.
It validates the total requested keys against max_proof_keys and constructs proofs consistently. Consider logging if the user is close to exceeding the limit.

crates/katana/rpc/rpc-types-builder/src/state_update.rs (1)

4-4: Ohayo sensei! Consider removing the unused import if it's no longer needed.

StateRootProvider doesn't appear to be referenced anymore, which might be a leftover from the refactor. Clearing out unused imports prevents confusion and maintains tidiness.

crates/katana/primitives/src/contract.rs (1)

44-50: Ohayo sensei! Great job on enabling FromStr for ContractAddress.

This allows more intuitive string-to-address conversions. If you anticipate malformed input, consider custom error messages beyond the underlying Felt error to improve UX.

crates/dojo/test-utils/src/sequencer.rs (1)

13-13: Ohayo sensei! Good move using RpcModulesList.
Replacing hard-coded enum sets with RpcModulesList::all() is more flexible and scalable, especially as new modules are introduced. This approach is future-proof for dynamic RPC expansions.

crates/katana/executor/src/implementation/noop.rs (1)

173-197: Ohayo sensei! StateProofProvider methods look correct.
These no-op multiproof methods return default proofs and align with the concept of a “no-operation” provider. Ensure to document that they are placeholders, so consumers understand there's no actual data retrieval happening.

crates/katana/storage/db/src/abstraction/transaction.rs (1)

72-92: Ohayo sensei! Ensure consistent naming and doc alignment.
The DbTxRef trait is consistent with the existing naming scheme. However, consider clarifying the doc comments regarding lifetime 'a to ensure new contributors easily grasp the concept. You might also want to highlight typical usage examples to prevent confusion on the reference-based usage.

crates/katana/rpc/rpc-api/src/starknet.rs (2)

8-8: Ohayo sensei! Combined import of ContractAddress is practical.
Centralizing imports from katana_primitives helps maintain structure. Keep a lookout for potential naming collisions or re-exports across modules.


188-188: Ohayo sensei! It's wise to keep method docs referencing official specs.
Helps new devs find relevant authoritative references quickly.

crates/katana/rpc/rpc/src/starknet/read.rs (1)

270-282: Ohayo sensei! The get_storage_proof method logic is well laid out.
Recommended to add more error handling for edge cases (e.g. empty sets for class_hashes, contract_addresses) so it’s crystal-clear how the system responds.

crates/katana/node/src/lib.rs (1)

255-259: Ohayo sensei! max_proof_keys addition is forward-thinking.
Explaining in config docs why there’s a limit can prevent confusion for node operators. Provide a short rationale or default value in user documentation.

crates/katana/cli/src/options.rs (1)

100-105: Ohayo sensei, new http_modules field looks flexible.
Consider explaining how to configure modules for dev clarity.

crates/katana/executor/src/implementation/blockifier/state.rs (3)

241-249: Ohayo sensei, unimplemented class_multiproof stub.
When implemented, thoroughly test multiproof correctness and performance. Let me know if you need assistance.


250-257: Ohayo sensei, unimplemented contract_multiproof stub.
Recommended to add a clear error message so users know multiproofs are not yet available.


258-267: Ohayo sensei, storage_multiproof remains unimplemented.
Consider a feature flag to cleanly communicate that the functionality is under development.

bin/katana/Cargo.toml (1)

17-24: Consider version constraints for external dependencies

Ohayo! A few suggestions for the dependency versions:

  • byte-unit = "5.1.4": Consider using ^5.1 to allow minor updates
  • dirs = "5.0.1": Consider using ^5.0 for patch updates
  • inquire = "0.7.5": Consider using ^0.7 for patch updates

This helps with future maintenance while maintaining stability, sensei! 🍵

Cargo.toml (1)

281-284: Ohayo! Consider workspace versioning for macro dependencies, sensei!

While the macro dependencies are essential for procedural macro development, consider using workspace versioning for consistency with other dependencies:

-proc-macro2 = "1.0"
-quote = "1.0"
-syn = { version = "2.0", default-features = false }
+proc-macro2.workspace = true
+quote.workspace = true
+syn = { workspace = true, default-features = false }
crates/katana/rpc/rpc/tests/test_data/test_sierra_contract.json (1)

1-1: Ohayo! Consider using a more descriptive filename for the test contract.

The relative path ../../../../contracts/build/account_with_dummy_validate.sierra.json suggests this is a dummy account contract for testing, but the filename could be more descriptive.

-../../../../contracts/build/account_with_dummy_validate.sierra.json
+../../../../contracts/build/test_account_with_dummy_validate_v0_1_0.sierra.json
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd8afc8 and 699f57c.

⛔ Files ignored due to path filters (3)
  • Cargo.lock is excluded by !**/*.lock
  • spawn-and-move-db.tar.gz is excluded by !**/*.gz
  • types-test-db.tar.gz is excluded by !**/*.gz
📒 Files selected for processing (62)
  • .gitmodules (1 hunks)
  • Cargo.toml (1 hunks)
  • bin/katana/Cargo.toml (1 hunks)
  • bin/katana/src/cli/init/mod.rs (1 hunks)
  • bin/katana/src/cli/mod.rs (3 hunks)
  • crates/dojo/test-utils/src/sequencer.rs (2 hunks)
  • crates/katana/cli/src/args.rs (5 hunks)
  • crates/katana/cli/src/options.rs (5 hunks)
  • crates/katana/contracts/Makefile (1 hunks)
  • crates/katana/contracts/piltover (1 hunks)
  • crates/katana/core/src/backend/mod.rs (3 hunks)
  • crates/katana/core/src/backend/storage.rs (5 hunks)
  • crates/katana/executor/Cargo.toml (1 hunks)
  • crates/katana/executor/src/abstraction/mod.rs (2 hunks)
  • crates/katana/executor/src/implementation/blockifier/state.rs (2 hunks)
  • crates/katana/executor/src/implementation/noop.rs (2 hunks)
  • crates/katana/node/Cargo.toml (1 hunks)
  • crates/katana/node/src/config/rpc.rs (4 hunks)
  • crates/katana/node/src/lib.rs (3 hunks)
  • crates/katana/primitives/src/contract.rs (2 hunks)
  • crates/katana/primitives/src/lib.rs (1 hunks)
  • crates/katana/rpc/rpc-api/src/starknet.rs (3 hunks)
  • crates/katana/rpc/rpc-types-builder/src/state_update.rs (3 hunks)
  • crates/katana/rpc/rpc-types/Cargo.toml (1 hunks)
  • crates/katana/rpc/rpc-types/src/error/starknet.rs (6 hunks)
  • crates/katana/rpc/rpc-types/src/lib.rs (1 hunks)
  • crates/katana/rpc/rpc-types/src/trie.rs (1 hunks)
  • crates/katana/rpc/rpc/Cargo.toml (2 hunks)
  • crates/katana/rpc/rpc/src/starknet/config.rs (1 hunks)
  • crates/katana/rpc/rpc/src/starknet/mod.rs (3 hunks)
  • crates/katana/rpc/rpc/src/starknet/read.rs (3 hunks)
  • crates/katana/rpc/rpc/tests/proofs.rs (1 hunks)
  • crates/katana/rpc/rpc/tests/test_data/test_sierra_contract.json (1 hunks)
  • crates/katana/runner/macro/Cargo.toml (1 hunks)
  • crates/katana/storage/codecs/derive/Cargo.toml (1 hunks)
  • crates/katana/storage/db/Cargo.toml (1 hunks)
  • crates/katana/storage/db/src/abstraction/transaction.rs (1 hunks)
  • crates/katana/storage/db/src/mdbx/tx.rs (1 hunks)
  • crates/katana/storage/db/src/models/trie.rs (3 hunks)
  • crates/katana/storage/db/src/tables.rs (10 hunks)
  • crates/katana/storage/db/src/trie/class.rs (0 hunks)
  • crates/katana/storage/db/src/trie/contract.rs (0 hunks)
  • crates/katana/storage/db/src/trie/mod.rs (5 hunks)
  • crates/katana/storage/db/src/trie/snapshot.rs (1 hunks)
  • crates/katana/storage/db/src/version.rs (2 hunks)
  • crates/katana/storage/provider/src/lib.rs (2 hunks)
  • crates/katana/storage/provider/src/providers/db/mod.rs (1 hunks)
  • crates/katana/storage/provider/src/providers/db/state.rs (3 hunks)
  • crates/katana/storage/provider/src/providers/db/trie.rs (2 hunks)
  • crates/katana/storage/provider/src/providers/fork/backend.rs (2 hunks)
  • crates/katana/storage/provider/src/providers/fork/mod.rs (4 hunks)
  • crates/katana/storage/provider/src/providers/fork/state.rs (5 hunks)
  • crates/katana/storage/provider/src/traits/state.rs (2 hunks)
  • crates/katana/storage/provider/src/traits/trie.rs (1 hunks)
  • crates/katana/storage/provider/tests/block.rs (7 hunks)
  • crates/katana/trie/Cargo.toml (1 hunks)
  • crates/katana/trie/src/classes.rs (1 hunks)
  • crates/katana/trie/src/contracts.rs (1 hunks)
  • crates/katana/trie/src/id.rs (1 hunks)
  • crates/katana/trie/src/lib.rs (3 hunks)
  • crates/katana/trie/src/storages.rs (1 hunks)
  • crates/saya/core/src/blockchain/mod.rs (1 hunks)
💤 Files with no reviewable changes (2)
  • crates/katana/storage/db/src/trie/class.rs
  • crates/katana/storage/db/src/trie/contract.rs
✅ Files skipped from review due to trivial changes (1)
  • crates/katana/contracts/piltover
🔇 Additional comments (253)
crates/katana/trie/src/classes.rs (6)

1-8: Ohayo sensei! Imports look organized and purposeful.
No apparent issues with these new dependencies.


11-13: Ohayo sensei! Good approach bundling the MultiProof.
Structuring the proof under ClassesMultiProof helps maintain domain clarity.


22-26: Ohayo sensei! Conversion trait usage is straightforward.
This ensures easy handling of MultiProof anywhere ClassesMultiProof is expected.


28-31: Ohayo sensei! ClassesTrie will keep your class state neat.
No immediate concerns. The struct is well-defined for the job.


53-65: Ohayo sensei! Insert and commit logic looks correct.
Just be mindful of concurrency if multiple processes commit simultaneously. Always ensure transaction boundaries are well-managed.


67-71: Ohayo sensei! The compute_classes_trie_value is neat.
This constant-based approach with Poseidon aligns with your specs. No issues here.

crates/katana/storage/provider/src/traits/state.rs (5)

5-7: Ohayo sensei! Additional imports for MultiProof and hashing.
These are necessary for the new multiproof functionalities—looking good.


14-23: Ohayo sensei! The state root approach is cohesive.
Bundling contracts_root and classes_root is a clear approach. Just ensure they remain consistent across the codebase.


24-31: Ohayo sensei! Contract and storage roots are well-defined.
Watch out for potential overuse of Option<Felt>. If missing roots are common, consider better diagnostics for debugging.


35-37: Ohayo sensei! Combining StateProofProvider and StateRootProvider in StateProvider.
This unifies state management nicely. Keep an eye on trait expansions to avoid confusion.


88-99: Ohayo sensei! The brand-new StateProofProvider trait.
The multiproof interface is thorough. Just ensure typical edge cases (e.g. empty vectors) are handled gracefully.

crates/katana/storage/db/src/models/trie.rs (10)

4-4: Ohayo sensei! Re-exporting traits from codecs.
This centralizes compression and decompression logic. No issues.


13-22: Ohayo sensei! Compress implementation looks good.
Concatenating the encoded key with the compressed value is logical. Watch for potential buffer overflows if data is extremely large.
[approve]


24-35: Ohayo sensei! Decompress logic is clear.
Ensure that invalid slices or truncated input is robustly handled, as partial data can cause confusion. Right now it’s safe with your checks.


38-38: Ohayo sensei! The #[repr(u8)] for TrieDatabaseKeyType is wise.
It keeps potential expansions manageable. Nicely done.


45-47: Ohayo sensei! Custom error for unknown key type is helpful.
This fosters better debugging instead of panics.


49-60: Ohayo sensei! The try_from pattern elegantly handles invalid values.
No suggestions. Crisp, minimal code.


62-62: Ohayo sensei! Adding Hash derive to TrieDatabaseKey.
Helpful for storing keys in hashed structures or sets.


85-88: Ohayo sensei! The decode function checks for minimal buffer length.
Cautious approach to avoid out-of-bounds. Good job.


91-93: Ohayo sensei! The type conversion ensures valid key type.
Very neat usage of try_from. No improvements needed.


99-99: Ohayo sensei! Slicing the final key.
All good. The logic is straightforward.

crates/katana/storage/provider/src/providers/db/trie.rs (13)

5-5: Ohayo sensei! New table references.
tables::ClassesTrie is relevant for declared classes insertion. Looks consistent.


11-11: Ohayo sensei! Unified access to ClassesTrie, ContractsTrie, and StoragesTrie.
Bundling them fosters a consistent mental model for all trie-based updates.


16-17: Ohayo sensei! Great rename to TrieWriter.
This consolidated trait is clearer for devs reading the code.


26-27: Ohayo sensei! Implementing TrieWriter for DbProvider.
Sensible approach; ensures consistent DB usage for all trie ops.


31-41: Ohayo sensei! The new trie_insert_declared_classes is straightforward.
Inserting class data, then committing. The logic is correct.


48-49: Ohayo sensei! trie_insert_contract_updates clarifies usage.
Breaking out contract updates from class updates is well-structured.


50-51: Ohayo sensei! Transactional update within self.0.update(|tx| ...).
Ensures atomic commits. Good DB usage.


53-67: Ohayo sensei! Handling storage updates with StoragesTrie.
Well-organized insertion logic. Just watch performance if storage entries grow large.


72-74: Ohayo sensei! Nonce updates in a single pass.
Your BTreeMap approach is tidy. No concerns.


76-82: Ohayo sensei! Deployed contracts and replaced classes logic.
Combining them is wise; keep an eye on collisions or duplication.


84-100: Ohayo sensei! Constructing leaf_hashes through iteration is a neat approach.
Ensure the final state is consistent if commits partially fail. Typically the transaction ensures atomicity.


102-103: Ohayo sensei! Inserting each contract leaf hash.
No immediate issues. The loop is straightforward.


106-107: Ohayo sensei! Final commit on contract trie.
Commits are correct, returning the new root. Good job.

crates/katana/node/src/config/rpc.rs (18)

5-5: Ohayo sensei! Bringing Serialize and Deserialize for RPC config.
Essential for user-friendly config serialization.


14-15: Ohayo sensei! DEFAULT_RPC_MAX_PROOF_KEYS = 100.
This cap seems sensible. If things scale, consider user override.


17-17: Ohayo sensei! Documenting module usage is helpful.
Clear doc comments promote clarity.


19-35: Ohayo sensei! Renamed ApiKind to RpcModuleKind.
This is more explicit and prevents confusion. Good.


44-44: Ohayo sensei! pub apis: RpcModulesList is a nice shift.
We get typed grouping of modules instead of raw sets.


46-47: Ohayo sensei! max_event_page_size and max_proof_keys.
They allow flexible runtime constraints. Looks good.


63-63: Ohayo sensei! Default instance sets apis to RpcModulesList::default().
Having Starknet as the default is consistent with typical usage.


66-67: Ohayo sensei! Setting max_proof_keys to DEFAULT_RPC_MAX_PROOF_KEYS.
Reasonable limit for safety.


71-73: Ohayo sensei! InvalidRpcModuleError.
A dedicated error type for parse failures always helps.


75-79: Ohayo sensei! RpcModulesList as a transparent wrapper.
This pattern is a good alternative to a raw HashSet.


80-84: Ohayo sensei! new() method produces an empty set.
This is intuitive and matches typical builder patterns.


85-94: Ohayo sensei! .all() method enumerates all modules.
Convenient for testing or broad usage scenarios.


95-99: Ohayo sensei! add method to unify sets.
Straight to the point.


100-104: Ohayo sensei! Checking membership with contains.
No remarks—straightforward set usage.


105-109: Ohayo sensei! len and is_empty methods.
Typical convenience methods, all good.


115-133: Ohayo sensei! parse with comma splitting is user-friendly.
Trimming ensures robust input. Just ensure no overhead in repeated calls.


135-139: Ohayo sensei! Default provides Starknet module alone.
A neat baseline for the typical user.


141-183: Ohayo sensei! Tests are comprehensive.
Covers empty, single, multiple, invalid, and duplicates. Great coverage.

crates/katana/trie/src/lib.rs (4)

15-18: Ohayo sensei! Re-exporting modules is neat.

No immediate issues found. Great approach to simplify usage for external crates.


26-32: Ohayo sensei! Consider immutability vs. mutability.

BonsaiTrie wraps BonsaiStorage which is generally mutable. Make sure concurrency usage is well-coordinated if needed.


86-95: Ohayo sensei! Debug trait is nice.

No issues here. Keep it: it’s useful for logging the internals in dev/test.


133-140: Ohayo sensei! Verify multiproof correctness.

verify_proof function uses .unwrap(). Ensure the proof verification and error handling is robust.

crates/katana/executor/src/abstraction/mod.rs (2)

14-16: Ohayo sensei! Additional import usage.

Make sure the new traits (StateProofProvider, StateRootProvider) are invoked in test coverage.


208-225: Ohayo sensei! Multiproof additions look correct.

No immediate concerns. Recheck boundary cases for empty contract/class sets.

crates/katana/rpc/rpc-types/src/trie.rs (13)

1-9: Ohayo sensei! Basic imports.

Everything looks fine. Great usage of bitvec and internal primitives.


27-49: Ohayo sensei! MerkleNode enum.

Watch out for large path values in Edge. Keep consistent length checks. Possibly validate input length before storing.


51-64: Ohayo sensei! compute_hash() enumerations.

The approach with Edge and Binary is correct. Reminder: if new node variants appear, revisit compute_hash.


84-91: Ohayo sensei! ContractsProof logic.

contract_leaves_data is well structured. Double-check ordering constraints in multi-proofs.


93-101: Ohayo sensei! ContractLeafData structure.

No issues. Good approach to store storage_root, nonce, and class_hash in a single leaf structure.


107-115: Ohayo sensei! NodeWithHash.

This is a neat approach. Make sure no collisions happen if multiple identical node_hash occur.


130-142: Ohayo sensei! impl From<MultiProof> for Nodes.

Looks correct. Good for bridging your internal structures.


144-148: Ohayo sensei! impl From<Nodes> for MultiProof.

Symmetry is important. Great to see you can map back & forth.


150-158: Ohayo sensei! impl From<ProofNode> for MerkleNode.

Properly transforms Binary and Edge. Keep test coverage for boundary edge paths.


160-169: Ohayo sensei! impl From<MerkleNode> for ProofNode.

Implementation looks consistent. Duplicate comment: you’re maintaining symmetrical conversions well.


172-193: Ohayo sensei! felt_to_path zero-padding logic

Preserving leading zeros is correct for path indexing. Great job.


195-199: Ohayo sensei! path_to_felt bridging logic

Also handles zero-padding properly. Make sure lengths never exceed 251 bits.


201-224: Ohayo sensei! Test coverage is comprehensive.

The property-based tests are well done.

crates/katana/storage/db/src/trie/snapshot.rs (7)

1-3: Ohayo sensei! Imports are straightforward.


9-14: Ohayo sensei! DB references and key conversions.

to_db_key usage is crucial. Confirm consistent usage across the codebase.


15-23: Ohayo sensei! SnapshotTrieDb struct.

This is well-structured. Snapshots are effectively read-only references to the DB.


25-33: Ohayo sensei! Debug trait is neat.

Helps in logging the transaction reference.


35-47: Ohayo sensei! recent_change_from_block logic.

Double-check edge cases if block_list is empty or smaller than target.


49-57: Ohayo sensei! new constructor

Simple and effective. No issues found.


125-244: Ohayo sensei! The property-based tests are thorough.

Nicely verifies snapshots across multiple blocks.

crates/katana/core/src/backend/mod.rs (3)

16-16: Ohayo sensei! Import for TrieWriter.

Be sure it remains consistent with the design in other crates.


161-166: Ohayo sensei! UncommittedBlock with TrieWriter generic.

Great approach to unify multiple trie operations under one trait.


255-263: Ohayo sensei! Summation of contract_trie_root and class_trie_root.

Check for collisions if the same block number is used multiple times before final commit.

crates/katana/storage/provider/src/lib.rs (4)

19-19: Ohayo sensei! Great imports for state traits.
No major concerns here; adding these trait references ensures a cohesive interface for state-related logic.


22-22: Ohayo sensei! Additional import check.
Bringing StateWriter in is straightforward. Looks good.


24-24: Ohayo sensei! Another import for transaction traits.
All consistent with the codebase’s approach to modular trait usage.


353-370: Ohayo sensei! Impressive TrieWriter implementation.
The delegation to self.provider for trie_insert_declared_classes and trie_insert_contract_updates keeps the code DRY. Everything looks aligned with the new trie-based design. Just ensure consistent usage across the rest of the codebase to avoid missed calls or partial updates.

crates/katana/rpc/rpc/tests/proofs.rs (4)

25-75: Ohayo sensei! Thorough coverage in proofs_limit test.
This method tests large proof requests to ensure an error is correctly thrown when the limit is exceeded. Code flow and JSON-RPC usage appear correct. The approach is sound.


77-184: Ohayo sensei! Solid end-to-end validations in genesis_states.
Verifying classes, contracts, and storage at genesis is crucial for ensuring correctness. The multi-proof verification steps look thorough. Keep an eye on potential expansions to other specialized checks if your genesis complexity grows.


186-271: Ohayo sensei! Nice set of checks in classes_proofs.
You’re confirming that each declared class is properly recorded in the trie. The test approach is practical. Great usage of multi-proof verifications for multiple classes in a single call.


273-292: Ohayo sensei! Helper function declare is neat.
It centralizes the logic for preparing contract declarations and waiting for transactions, reducing redundancy in your tests. This is a good pattern.

bin/katana/src/cli/init/mod.rs (8)

1-47: Ohayo sensei! Good start with InitInput struct.
Capturing config details (chain ID, settlement contract) keeps the initialization logic well-structured. No apparent issues here.


49-92: Ohayo sensei! Settlement and init configuration definitions look tidy.
The layering of SettlementLayer within InitConfiguration is well-organized. Keep ensuring that this separation of concerns remains consistent in future expansions.


94-119: Ohayo sensei! execute method approach is straightforward.
The use of a tokio runtime creation ensures async readiness. Writing TOML configs is a practical approach. Good job.


121-199: Ohayo sensei! Interactive prompt method is well-thought-out.
It gathers user input with minimal friction and does an upfront check for class hash existence. This flow is a user-friendly approach to init logic. Watch for potential expansions like validating contract identity beyond existence alone.


202-281: Ohayo sensei! Detailed settlement contract deployment flow in init_core_contract.
The usage of Spinner for feedback is a nice user experience. Great job verifying class declarations before deployment. Consider standardizing logs or confirmations if further steps are planned.


283-302: Ohayo sensei! Helper functions for contract declaration parameters are well modularized.
This set of utilities (for flattening class and computing compiled class hash) will likely help avoid duplication. Looks solid.


303-319: Ohayo sensei! Directory path management is clear.
Creating config directories if they don’t exist is beneficial for user-friendliness. The error handling approach is good.


321-335: Ohayo sensei! Simple Path wrapper is a helpful addition.
Ensuring consistent I/O handling with a typed path is a beneficial pattern. Approved.

crates/katana/storage/provider/src/providers/db/state.rs (8)

8-8: Ohayo sensei! TrieDbFactory import is well-aligned with the new trie structure.
No concerns here.


14-14: Ohayo sensei! Introducing Felt import.
Keeping it consistent with the core Katana primitives. Looks good to me.


19-19: Ohayo sensei! Additional trait references.
All these combined state traits unify the code around proofs, providers, and roots. Good call.


165-193: Ohayo sensei! Latest state proof methods look neat.
Implementations for class_multiproof, contract_multiproof, and storage_multiproof ensure your code can generate multi-proofs with minimal overhead. No immediate issues found.


195-213: Ohayo sensei! StateRootProvider for the latest state is a nice addition.
Straightforward root retrieval logic for classes, contracts, and storage. The approach is consistent with your new TrieDb usage.


348-385: Ohayo sensei! Historical state proof logic is on point.
Ensuring multi-proofs are available for older blocks is quite valuable for proving historical states. Looks well-structured.


387-422: Ohayo sensei! Historical StateRootProvider is handled effectively.
Accurate retrieval of older block roots fosters robust verifications. Great job hooking into block headers for state_root.


426-429: Ohayo sensei! Great doc comment for recent_change_from_block.
The detailed note helps others quickly understand how changesets are identified by block rank. Good clarity.

crates/katana/storage/db/src/trie/mod.rs (7)

29-47: Ohayo sensei! Good introduction of TrieDbFactory.
The latest() and historical() constructor methods provide a clear interface for state-level trie operations, bridging the block number context. Approved.


49-80: Ohayo sensei! GlobalTrie structure is straightforward.
These helper methods for retrieving specific tries keep your design modular. No major suggestions here.


82-121: Ohayo sensei! Pleasing approach in HistoricalGlobalTrie.
Exposing block-based snapshots is fundamental to historical queries. The usage of CommitId::new(self.block) is a consistent pattern. Nicely done.


123-207: Ohayo sensei! TrieDb read-only design.
Applying Bonsai’s read logic in a “snapshot” style stands out. Coupled with your specialized table usage, it’s well aligned. Keep it up.


Line range hint 209-281: Ohayo sensei! TrieDbMut effectively handles writes.
Tracking key-value pairs in a write cache fosters easy snapshot creation. Just ensure concurrency is managed if you expand multi-thread usage. Great job.


Line range hint 283-327: Ohayo sensei! Snapshot logic in TrieDbMut is well-executed.
Storing block-based entries in the changeset paves the way for robust historical lookups. The code is consistent with the rest of the design. Bravo.


388-488: Ohayo sensei! Thorough test coverage for trie snapshots.
Combining multi-commit checks with proof verifications is an efficient approach. This builds confidence in the new design. Approved.

crates/katana/storage/provider/src/providers/fork/state.rs (10)

10-10: Ohayo sensei! Good addition of StateProofProvider and StateRootProvider.
No concerns here; importing them aligns with the broader refactoring of state-related traits.


Line range hint 79-104: Ohayo sensei! Contract class retrieval strategy looks consistent.
This code checks local data first and falls back on the underlying db, which should optimize retrieval performance while keeping forked data in sync.


105-108: Ohayo sensei! Default multiproof might require further validation.
Returning a blank multiproof is fine as a placeholder, but ensure the final implementation populates the proof data.


110-115: Ohayo sensei! Similar note for contract multiproof.
The approach parallels the class multiproof. Make sure to confirm that returning an empty proof meets your downstream requirements.


117-123: Ohayo sensei! Storage multiproof placeholder.
Same reasoning: you’re returning a default multiproof; confirm the behavior once the actual proof logic is integrated.


126-138: Ohayo sensei! Using Felt::ZERO as class/contract/storage roots.
If zero is a temporary placeholder for roots, remember to replace it once real computations are ready. Otherwise, it may indicate an unset or empty state.


181-200: Ohayo sensei! Multiproof methods for LatestStateProvider also default to empty.
This maintains consistency with ForkedStateDb. Keep track of future expansions where the proofs may need real data.


202-214: Ohayo sensei! Zero-based roots in LatestStateProvider.
Mirroring the approach in ForkedStateDb fosters uniformity. Just be sure final logic reflects actual root computations.


288-307: Ohayo sensei! Default multiproof for ForkedSnapshot.
The pattern is consistent with the other providers. Validate usage and finalize the proof structure as required.


309-321: Ohayo sensei! Returning zero within ForkedSnapshot might be transitional.
If these zero-value returns are placeholders, ensure they are properly replaced and tested in production.

crates/katana/core/src/backend/storage.rs (9)

10-10: Ohayo sensei! Introduction of StarkHash import.
Looks good for any upcoming hashing operations. No issues spotted.


19-19: Ohayo sensei! Removed StateRootProvider reference in favor of new traits.
This aligns with the consolidation effort. Everything looks consistent so far.


25-25: Ohayo sensei! Great to see the introduction of TrieWriter.
It unifies class and contract trie updates. This fosters maintainability.


30-30: Ohayo sensei! Short string import from macros.
Nothing special to note; presumably it’s used for chain or network IDs.


73-73: Ohayo sensei! Extended impl<T> Database with TrieWriter.
The generics remain straightforward. This is consistent with the new trait structure.


221-223: Ohayo sensei! Prepping block before computing trie roots.
Small chunk but no issues spotted. Ensure that block details are complete at this stage.


224-231: Ohayo sensei! Declared classes face insertion via trie_insert_declared_classes.
Keep close tabs on error handling and rollback states if insertion fails mid-process.


232-237: Ohayo sensei! Combining trie roots in genesis_state_root.
This is succinct. Double-check hashing array composition for correctness.


238-239: Ohayo sensei! Overwriting block’s state_root with computed genesis_state_root.
Check that the subsequent indexing or references to this root stay in sync.

crates/katana/rpc/rpc-types/src/error/starknet.rs (8)

6-6: Ohayo sensei! BlockNumber import looks appropriate for new error variants.
No problems seen. Ensure usage remains consistent across the codebase.


85-91: Ohayo sensei! New StorageProofNotSupported error variant.
Helpful for clarifying unsupported proof requests. The block fields can guide user feedback.


92-98: Ohayo sensei! Introducing ProofLimitExceeded.
This is a welcome addition for user-friendly handling when keys exceed your set limit.


119-119: Ohayo sensei! Assigning code 42 to StorageProofNotSupported.
The code fits well among the existing error codes. Just stay consistent when referencing them in docs and logs.


134-134: Ohayo sensei! Switching to error code 1000 for ProofLimitExceeded.
No conflict spotted. This is a clearer and more relevant range than the previous 10000.


146-148: Ohayo sensei! Adding StorageProofNotSupported and ProofLimitExceeded under data().
Ensures extra context for these errors is returned. Great for debugging.


390-401: Ohayo sensei! Tests for StorageProofNotSupported.
Excellent coverage. Make sure older blocks are tested to confirm correct error triggers.


402-413: Ohayo sensei! Tests for ProofLimitExceeded.
Tests appear thorough. Verify real usage in integration tests as well.

crates/katana/storage/db/src/tables.rs (18)

14-14: Ohayo sensei! Added TrieHistoryEntry.
This new type likely ties into historical trie data. Looks like a good extension for versioned storage.


23-23: Ohayo sensei! Updated Table trait to 'static.
No immediate issues here. Lifetimes remain straightforward.


40-45: Ohayo sensei! New Trie trait with History and Changeset.
It’s a concise, well-defined interface for capturing trie state transitions.


56-56: Ohayo sensei! Increasing NUM_TABLES to 33.
Check for logic in code that references or enumerates these table definitions to ensure it’s synchronized.


180-189: Ohayo sensei! Adding 10 new tables for classes, contracts, and storage tries and changes.
Clear naming. Confirm each table’s usage is thoroughly tested.


250-250: Ohayo sensei! ClassesTrie.
Maps keys to TrieDatabaseValue. Straightforward.


252-252: Ohayo sensei! ContractsTrie.
Same approach as ClassesTrie. Consistency is good.


254-255: Ohayo sensei! StoragesTrie.
Uniform design here as well. No issues.


256-262: Ohayo sensei! ClassesTrieHistory, ContractsTrieHistory, StoragesTrieHistory.
DupSort usage for historical entries is nicely structured.


263-269: Ohayo sensei! ClassesTrieChangeSet, ContractsTrieChangeSet, StoragesTrieChangeSet.
Capturing block-based deltas is helpful for rolling back changes.


270-275: Ohayo sensei! impl Trie for ClassesTrie.
Methods tie directly to the newly declared types. Implementation is consistent.


276-279: Ohayo sensei! impl Trie for ContractsTrie.
Good job reusing the same pattern. Keep it DRY.


281-284: Ohayo sensei! impl Trie for StoragesTrie.
Same approach, ensuring uniform design across all trie types.


317-326: Ohayo sensei! Extended table existence checks in test.
Nice thoroughness. Doing a direct name assert helps detect any mismatch.


352-360: Ohayo sensei! Verifying the table types for new trie tables.
Everything is consistent: the correct ones are Table vs. DupSort.


380-382: Ohayo sensei! Expanded import for TrieDatabaseKey, TrieDatabaseKeyType, etc.
Neat. This keeps the test coverage consistent with the new structures.


450-456: Ohayo sensei! Additional fields in InvokeTxReceipt.
Collected data sets remain standard. No issues perceived.


457-460: Ohayo sensei! Confirming TrieDatabaseValue and TrieHistoryEntry compress/decompress.
Ensures new trie types integrate nicely with existing serialization flows.

crates/katana/storage/provider/src/providers/fork/mod.rs (5)

36-36: Ohayo sensei! Adding StateWriter to the imports.
This complements the changes to unify write operations across the code.


42-42: Ohayo sensei! Bringing TrieWriter into scope.
We can expect consolidated trie operations using this trait. Looking good.


413-423: Ohayo sensei! Removing StateRootProvider for ForkedProvider.
It’s definitely in line with the new architecture. Just confirm no residual references remain.


602-605: Ohayo sensei! Implementing trie_insert_declared_classes.
Currently returns Felt::ZERO. If you plan on storing data, track it for a final integration pass.


613-616: Ohayo sensei! Implementing trie_insert_contract_updates.
Same placeholder approach with zero. Confirm the real logic is set soon.

crates/katana/cli/src/args.rs (7)

7-7: Ohayo sensei! Good use of bail macro.
It's consistent with the error handling approach further down in the file.


16-16: Ohayo sensei! Adding RpcConfig, RpcModuleKind, and RpcModulesList imports looks neat.
They align with the new RPC module handling.


171-171: Ohayo sensei! Properly using rpc_config() returning Result is tidy.
Ensures any RPC config errors are surfaced immediately.


199-218: Ohayo sensei! Returning Result<RpcConfig> with an early bail is well-structured.
The dev mode check is logical to prevent misconfigurations.


219-226: Ohayo sensei! Including max_proof_keys in RpcConfig looks consistent.
The optional limit will help keep storage proofs in check.


231-231: Ohayo sensei! The fallback to a default RpcConfig when feature server is disabled is smooth.
Makes the code more flexible.


648-671: Ohayo sensei! The http_modules test is thorough.
It covers default modules, custom modules, and restricted dev usage.

crates/katana/rpc/rpc/src/starknet/mod.rs (3)

20-20: Ohayo sensei! The ProviderError import is now used effectively for block retrieval.
No issues found.


24-24: Ohayo sensei! Importing StateFactoryProvider, StateProvider, and StateRootProvider is consistent.
This is well-aligned with the new proofs implementation.


38-41: Ohayo sensei! New proof-related imports are all grouped logically.
Makes sense for get_proofs usage.

crates/katana/rpc/rpc/src/starknet/config.rs (1)

7-11: Ohayo sensei! Introducing max_proof_keys fosters safer proof retrieval.
It pairs nicely with max_event_page_size.

crates/katana/primitives/src/lib.rs (1)

27-27: Ohayo sensei! Re-exporting hash helps unify hashing usage across modules.
No issues.

crates/katana/storage/provider/src/traits/trie.rs (1)

11-18: Ohayo sensei! Renaming methods to trie_insert_declared_classes and trie_insert_contract_updates is clearer.
This unification under TrieWriter improves maintainability.

crates/katana/trie/src/id.rs (6)

1-2: Ohayo sensei, the imports look correct!
No issues found with these import statements.


5-6: Ohayo sensei, struct definition is concise!
The derivations are well-selected for block-number-based ID handling.


8-12: Ohayo sensei, constructor is straightforward!
This new method is good for clarity in creation.


14-26: Ohayo sensei, trait implementation looks complete!
All methods in Id are properly implemented, and big-endian bytes usage for to_bytes is consistent.


28-32: Ohayo sensei, conversions from BlockNumber are handy!
This is a clean From impl that ensures easy usage across modules.


34-38: Ohayo sensei, conversion back to BlockNumber is perfect!
This complements the forward conversion, ensuring round-trip correctness.

crates/katana/trie/src/storages.rs (4)

1-5: Ohayo sensei, imports and type aliases are well-organized!
No issues found.


7-15: Ohayo sensei, StoragesTrie struct looks good!
Storing the contract address and using BonsaiTrie with Pedersen is consistent with the standard hashing approach.


16-28: Ohayo sensei, constructor and basic ops are clear!
new, root, and multiproof provide essential functionality with minimal complexity.


30-41: Ohayo sensei, persistent database support is well-structured!
The insert and commit methods are straightforward and align with the block-based commit logic.

bin/katana/src/cli/mod.rs (4)

7-9: Ohayo sensei, the new init module is integrated cleanly!
This helps keep code modular and maintainable.


26-26: Ohayo sensei, Commands::Init execution is a great addition!
The execute workflow is consistent with existing commands.


36-37: Ohayo sensei, Init subcommand is clearly described.
This is helpful for users needing a chain initialization routine.


42-43: Ohayo sensei, Completions command is well-placed!
Reordering does not affect functionality, but keeps commands logically grouped.

crates/katana/trie/src/contracts.rs (5)

1-5: Ohayo sensei, imports are properly declared!
They accurately reflect dependencies needed for this trie.


6-7: Ohayo sensei, CommitId usage ensures consistent block references!
Binding ContractsTrie to CommitId fosters consistency across the codebase.


8-11: Ohayo sensei, ContractsTrie struct is well-defined!
It’s a neat wrapper around BonsaiTrie for contract management.


17-34: Ohayo sensei, base implementation fosters essential trie operations!
new, root, and multiproof provide a flexible foundation for contract state retrieval.


36-47: Ohayo sensei, persistence layer integration is well-thought-out!
insert and commit handle contract state changes seamlessly, with a straightforward block-based interface.

crates/katana/rpc/rpc-types-builder/src/state_update.rs (3)

24-24: Ohayo sensei! Double-check all references to the old trait.

Replacing StateRootProvider with StateFactoryProvider is a big change. Please ensure that any calls referencing StateRootProvider methods have been fully updated throughout the codebase to avoid misconfigurations.


33-37: Ohayo sensei! Validate the fallback logic in the historical data call.

This code grabs a historical state for the given block. Make sure historical(self.block_id) is guaranteed to succeed under all valid query conditions, and the .expect(...) usage won't mask potential errors during normal operation.


45-49: Ohayo sensei! Confirm the boundary case for block 0 is handled safely.

Your code returns Felt::ZERO for block 0 and uses historical data for block_num - 1 otherwise. This approach seems correct, but please verify it doesn’t fetch an invalid block number for scenarios near the chain genesis.

crates/katana/rpc/rpc-types/src/lib.rs (1)

16-16: Ohayo sensei! Ensure tests cover the new trie module.

Adding pub mod trie is a welcome addition. Confirm that integration or unit tests exist to validate the new trie functionality, ensuring correct handling of proof generation and state queries.

crates/katana/primitives/src/contract.rs (2)

2-2: Ohayo sensei! Kudos on adding FromStr.

Bringing FromStr into scope paves the way for user-friendly parsing of contract addresses. Make sure you handle invalid parsing inputs gracefully in higher-level logic.


58-62: Ohayo sensei! The AsRef<Felt> implementation adds flexibility.

Referencing the underlying Felt directly from a ContractAddress is convenient. Keep an eye on usage in places that might require further type checks or validations.

crates/katana/storage/db/src/version.rs (1)

8-8: Ohayo sensei! Database version bumped to 6 successfully.

Make sure to update any relevant migration scripts or documentation referencing version 5. This ensures developers and ops teams are aware of the new versioning requirements.

Also applies to: 84-84

crates/saya/core/src/blockchain/mod.rs (1)

9-9: Ohayo sensei! Excellent switch to the new state traits.
By removing StateRootProvider and importing StateFactoryProvider, StateProvider, and StateWriter here, you've streamlined the interface. This better aligns with the consolidated approach to handling state operations.

crates/dojo/test-utils/src/sequencer.rs (3)

7-7: Ohayo sensei! Using constants from rpc config is a clean approach.
Bringing in DEFAULT_RPC_ADDR and DEFAULT_RPC_MAX_CONNECTIONS helps maintain consistent configuration defaults across the codebase. Great job keeping everything centralized.


125-125: Ohayo sensei! Adopting RpcModulesList::all().
This is consistent with the shift toward a more extensible RPC configuration. Keep in mind that if certain modules should remain disabled in some environments, providing a filtered list might be preferable.


128-128: Ohayo sensei! Introducing max_proof_keys is a neat addition.
Setting Some(100) ensures large proof requests are capped, preventing excessive resource consumption. Verify that 100 is sufficient for real-world scenarios or consider making it configurable via CLI flags.

crates/katana/storage/db/src/mdbx/tx.rs (1)

36-36: Ohayo sensei! Good clarity on db_handles initialization.
Using RwLock::new([None; NUM_TABLES]) explicitly clarifies the intended initial state. This approach removes ambiguity from relying on Default::default().

crates/katana/executor/src/implementation/noop.rs (2)

9-9: Ohayo sensei! Excellent inclusion of the new state traits.
Importing both StateProofProvider and StateRootProvider opens up more comprehensive coverage for verifying and retrieving state proofs and roots.


199-211: Ohayo sensei! Straightforward StateRootProvider stubs.
Providing root values of zero for classes, contracts, and storage is consistent with the no-op design. This setup is convenient for testing scenarios that do not rely on actual state data.

crates/katana/storage/db/src/abstraction/transaction.rs (4)

69-70: Ohayo sensei! Nice grouping of reference-based traits.
This comment is mostly about commending the introduction of code references. It's beneficial for memory usage and clarity, as it enables operations on borrowed transactions without always needing ownership. The addition is neatly modular.


94-128: Ohayo sensei! Verify concurrency aspects here.
The DbTxMutRef trait carefully extends DbTxRef with mutable database operations. Yet, if the underlying database engine or usage pattern doesn't fully support concurrent mutations, ensure these trait methods are used safely. A clarifying doc comment about concurrency or locking requirements might help.


130-149: Ohayo sensei! Implementation detail using trait forwarding is well done.
Forwarding calls via impl<'a, Tx: DbTx> DbTxRef<'a> for &'a Tx looks neat. This maintains DRY principles, reusing the existing DbTx implementation, and the design helps keep the code maintainable.


151-180: Ohayo sensei! Validate that references won’t outlive transactions.
Because we’re referencing Tx in the implementation for DbTxMutRef, watch for potential lifetime pitfalls if the underlying transaction can be invalidated. Ensure no hidden footguns like using these references after transactions are dropped.

crates/katana/rpc/rpc-api/src/starknet.rs (3)

6-6: Ohayo sensei! Great addition of ClassHash import.
This provides more clarity about the typed nature of class hashes. Confirm that only relevant parts of katana_primitives::class are imported to avoid bloat.


22-22: Ohayo sensei! ContractStorageKeys import complements the new proof functionality neatly.
No immediate concerns. Just ensure consistent usage with the rest of the codebase.


189-199: Ohayo sensei! New method get_storage_proof elevates the API’s introspection capabilities.
Fetching proofs is crucial for trustless verification. Check for input validation and limits around class_hashes, contract_addresses, etc., to guard against malicious requests.

crates/katana/rpc/rpc/src/starknet/read.rs (3)

4-4: Ohayo sensei! Good choice to import ClassHash for clarity.
It’s consistent with the new proof approach, though confirm that the next maintainers are aware of the difference between Felt and ClassHash usage.


6-6: Ohayo sensei! The combined import of ContractAddress and Felt keeps the code DRY.
No issues found; it’s neatly done.


19-19: Ohayo sensei! ContractStorageKeys import completes the puzzle for multiproof logic.
Looks aligned with the rest of the code changes for verifying contract states.

crates/katana/node/src/lib.rs (4)

14-14: Ohayo sensei! The rename from ApiKind to RpcModuleKind is a neat improvement.
This naming is more intuitive for new devs. Keep an eye out for references in doc comments or config scripts.


278-278: Ohayo sensei! Condition for Dev module is straightforward.
No major remarks here; keep an eye on whether Dev-specific endpoints remain well-isolated from production.


283-283: Ohayo sensei! Condition for Torii endpoints is consistent.
Ensures Torii is only exposed when specifically included.


288-288: Ohayo sensei! Saya API gating looks good.
Just confirm each additional RPC module is tested to ensure it doesn’t break the runtime if toggled off.

crates/katana/storage/provider/tests/block.rs (7)

14-14: Ohayo sensei, consider confirming removal of StateRootProvider.
Removing this import aligns with the broader changes. If it's still needed elsewhere, you might want to revisit.


32-32: Ohayo sensei, ignoring forked-mode tests.
These tests are crucial for comprehensive coverage. Please ensure you re-enable them once forked-mode consistency is established.


49-49: Ohayo sensei, ignoring test for empty forked blocks.
Similar note as above—ensure these tests get restored or supplemented later to maintain coverage.


70-70: Ohayo sensei, neat extension of trait bounds with StateFactoryProvider.
This broadens the provider's functionality seamlessly.


124-125: Ohayo sensei, watch out for potential None from historical lookups.
When None is returned, ensure you handle it gracefully to avoid panics or unexpected logic flows.


180-180: Ohayo sensei, consistent trait usage with StateFactoryProvider.
This inclusion keeps your code aligned with the rest of the refactor.


231-232: Ohayo sensei, double-check the map and transpose usage for potential edge cases.
The historical(...) call must handle scenarios with no data for the given block_id.

crates/katana/cli/src/options.rs (4)

15-15: Ohayo sensei, good import addition of RpcModulesList and DEFAULT_RPC_MAX_PROOF_KEYS.
This centralizes RPC configuration constants in one place.


117-122: Ohayo sensei, max_proof_keys can potentially grow large.
Validate if there should be upper-bound checks to avoid over-allocation or performance regressions.


132-133: Ohayo sensei, default values for http_modules and max_proof_keys are well-chosen.
This ensures consistent behavior straight out of the box.

Also applies to: 135-135


398-402: Ohayo sensei, default_proof_keys() is a tidy way to unify defaults.
This function fosters maintainable code in case the default value changes in the future.

crates/katana/executor/src/implementation/blockifier/state.rs (2)

13-13: Ohayo sensei, centralized imports for state-related traits.
Looks consistent with the broader design pattern shift.


269-281: Ohayo sensei, StateRootProvider trait is unimplemented here.
If future expansions require state roots, modularizing a partial implementation or mock might help.

crates/katana/storage/provider/src/providers/db/mod.rs (1)

42-42: Ohayo sensei, dropping StateRootProvider from imports.
Verify that all references to this trait have been safely removed to avoid broken references.

.gitmodules (1)

4-6: Ohayo sensei! Let's verify the new submodule configuration~

The piltover submodule addition looks properly configured, but let's make sure everything is set up correctly!

✅ Verification successful

Ohayo sensei! The piltover submodule is properly integrated and accessible! ✨

The verification shows that:

  • The submodule URL is accessible and valid
  • The piltover integration is actively used in the codebase:
    • Core functionality in crates/saya/core/src/dojo_os/piltover.rs for state updates
    • Initialization setup in bin/katana/src/cli/init/mod.rs
    • Proper imports and references in other core modules
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify submodule accessibility and integration
echo "Checking submodule URL accessibility..."
git ls-remote https://github.com/cartridge-gg/piltover.git > /dev/null

# Check if submodule is referenced in other files
echo "Checking submodule usage..."
rg -l "piltover" --type rust

Length of output: 424


Script:

#!/bin/bash
# Let's check the actual usage of piltover in the files
echo "Checking piltover usage in core files..."
rg "piltover" crates/saya/core/src/dojo_os/piltover.rs -A 5

echo "\nChecking initialization usage..."
rg "piltover" bin/katana/src/cli/init/mod.rs -A 5

Length of output: 1302

crates/katana/runner/macro/Cargo.toml (1)

11-13: Sugoi work on the workspace dependencies, sensei! ✨

The migration to workspace-level dependency management is clean and follows Rust best practices.

crates/katana/storage/codecs/derive/Cargo.toml (1)

12-15: Konnichiwa! Let's check the dependency configuration~

The workspace dependency updates look great! However, I noticed serde is both in the workspace dependencies and cargo-udeps ignore list.

✅ Verification successful

Ohayo! The serde dependency is actively used across the codebase, sensei~

The verification shows extensive usage of serde attributes and derive macros throughout the codebase, particularly in:

  • Serialization/deserialization of RPC types in katana/rpc/rpc-types
  • Configuration handling in various options.rs files
  • Data structures in core primitives
  • GraphQL types and test fixtures
  • CLI configuration and options

The serde workspace dependency is justified and correctly configured.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify serde usage in the codebase
echo "Checking direct serde derive usage..."
ast-grep --pattern 'derive($$$, Serialize, $$$)' || ast-grep --pattern 'derive($$$, Deserialize, $$$)'

echo "Checking serde attribute usage..."
rg '#\[serde' --type rust

Length of output: 20469

crates/katana/trie/Cargo.toml (1)

20-23: Ohayo sensei! Please verify the dependency configuration.

The switch to a specific branch kariy/indexmap from the dojoengine fork needs careful consideration:

  1. Using a specific branch rather than a tagged release could lead to stability issues
  2. The repository change from madara-alliance to dojoengine is significant

Let's check the branch status:

crates/katana/rpc/rpc-types/Cargo.toml (1)

16-16: LGTM! The trie dependency addition looks good, sensei!

The addition of katana-trie as a workspace dependency aligns well with the state management refactoring objectives.

bin/katana/Cargo.toml (1)

10-14: Ohayo! New workspace dependencies look good, sensei! 🎋

The addition of katana-cairo and katana-primitives aligns well with the state management refactoring objectives.

crates/katana/storage/db/Cargo.toml (1)

37-39: Nice testing setup enhancement, sensei! 🎯

The addition of proptest and rstest will improve the testing capabilities. Moving starknet to dev-dependencies is a good architectural decision that reduces production dependencies.

crates/katana/executor/Cargo.toml (1)

12-12: Consider making katana-trie optional, sensei! 🤔

The katana-trie addition aligns with the state management refactoring. However, other components like blockifier and starknet are marked as optional. Should we consider making katana-trie optional as well for consistency?

Let's check how other crates use this dependency:

crates/katana/rpc/rpc/Cargo.toml (2)

36-39: Dev dependencies are well chosen, sensei!

The addition of testing-related dependencies with workspace versioning will help maintain consistency across the project.


Line range hint 20-34: Ohayo! Dependencies look well-structured, sensei!

The new dependencies align well with enhancing RPC capabilities. The consistent use of workspace versioning is a good practice.

Let's verify the usage of these new dependencies:

✅ Verification successful

Ohayo! Dependencies are well-utilized, sensei!

All the new dependencies in the Cargo.toml are actively used throughout the codebase:

  • metrics is used for RPC server metrics tracking
  • serde_json is used extensively for JSON handling in tests and types
  • starknet is heavily used across the codebase for core functionality
  • tokio is used for async operations and mutex handling
  • tower and tower-http are used for service building and CORS functionality
  • tracing is used for logging and debugging
  • url is used in forking-related functionality

The dependencies are not just added but are properly integrated into the codebase, showing good engineering practices.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the new dependencies are actually used in the codebase
for dep in "metrics" "serde_json" "starknet" "thiserror" "tokio" "tower" "tower-http" "tracing" "url"; do
    echo "Checking usage of $dep..."
    rg --type rust "use.*$dep|extern.*$dep" crates/katana/rpc/
done

Length of output: 10778

crates/katana/node/Cargo.toml (2)

Line range hint 38-44: Optional dependencies are well organized!

The modular approach with optional dependencies allows for flexible feature selection.


Line range hint 28-32: Ohayo! Consider the implications of full feature sets, sensei!

While using the "full" feature sets for tower and tower-http provides comprehensive functionality, it might increase binary size. Consider using specific features instead if you don't need all capabilities.

Let's check the impact:

crates/katana/rpc/rpc/tests/test_data/test_sierra_contract.json (4)

Line range hint 2-114: Sierra program bytecode looks good, sensei!

The bytecode array contains valid hex values and follows the expected format.


Line range hint 115-119: Empty debug information may impact testing.

The debug information arrays are empty, which could make debugging test failures more difficult.

Would you like me to help generate meaningful debug information for type names, library functions, and user functions?


Line range hint 120-138: Entry points configuration is properly structured.

The EXTERNAL entry points are well-defined with proper selectors and function indices. The empty L1_HANDLER and CONSTRUCTOR arrays are appropriate for this test contract.


Line range hint 139-219: ABI definition is comprehensive and well-structured.

The ABI includes all necessary functions:

  • validate_deploy
  • validate_declare
  • validate
  • execute
    And includes proper struct definitions with correct types.
crates/katana/storage/provider/src/providers/fork/backend.rs (1)

31-31: Import statement updated correctly, sensei!

The import statement properly includes the new StateProofProvider and StateRootProvider traits.

Comment on lines +76 to 77
encoded.push(self.key.len() as u8); // Encode key length
encoded.extend(self.key);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ohayo sensei! Encoding the key length as a single byte.
Watch out for keys longer than 255 bytes. Possibly expand to bigger sizes if needed.

- encoded.push(self.key.len() as u8);
+ encoded.extend_from_slice(&(self.key.len() as u32).to_le_bytes());
📝 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
encoded.push(self.key.len() as u8); // Encode key length
encoded.extend(self.key);
encoded.extend_from_slice(&(self.key.len() as u32).to_le_bytes()); // Encode key length
encoded.extend(self.key);

Comment on lines +71 to +84
impl<DB, Hash> BonsaiTrie<DB, Hash>
where
DB: BonsaiDatabase + BonsaiPersistentDatabase<CommitId>,
Hash: StarkHash + Send + Sync,
{
pub fn insert(&mut self, id: &[u8], key: Felt, value: Felt) {
let key: BitVec = key.to_bytes_be().as_bits()[5..].to_owned();
self.storage.insert(id, &key, &value).unwrap();
}

pub fn commit(&mut self, id: CommitId) {
self.storage.commit(id).expect("failed to commit trie");
}
}
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! Gracefully handle .unwrap() calls in insert and commit.

Any DB insertion or commit can fail in real scenarios; using unwrap() might cause unwarranted panics.

- self.storage.insert(id, &key, &value).unwrap();
+ self.storage.insert(id, &key, &value)
+     .expect("Insert failed. Please handle this error gracefully.");

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

Comment on lines +59 to +123
impl<'tx, Tb, Tx> BonsaiDatabase for SnapshotTrieDb<'tx, Tb, Tx>
where
Tb: Trie,
Tx: DbTxRef<'tx> + fmt::Debug,
{
type Batch = ();
type DatabaseError = Error;

fn create_batch(&self) -> Self::Batch {}

fn remove_by_prefix(&mut self, _: &DatabaseKey<'_>) -> Result<(), Self::DatabaseError> {
unimplemented!("modifying trie snapshot is not supported")
}

fn get(&self, key: &DatabaseKey<'_>) -> Result<Option<ByteVec>, Self::DatabaseError> {
let key = to_db_key(key);
let block_number = self.snapshot_id.into();

let change_set = self.tx.get::<Tb::Changeset>(key.clone())?;
if let Some(num) = change_set.and_then(|set| recent_change_from_block(block_number, &set)) {
let mut cursor = self.tx.cursor_dup::<Tb::History>()?;
let entry = cursor
.seek_by_key_subkey(num, key.clone())?
.expect("entry should exist if in change set");

if entry.key == key {
return Ok(Some(entry.value));
}
}

Ok(None)
}

fn get_by_prefix(
&self,
_: &DatabaseKey<'_>,
) -> Result<Vec<(ByteVec, ByteVec)>, Self::DatabaseError> {
todo!()
}

fn insert(
&mut self,
_: &DatabaseKey<'_>,
_: &[u8],
_: Option<&mut Self::Batch>,
) -> Result<Option<ByteVec>, Self::DatabaseError> {
unimplemented!("modifying trie snapshot is not supported")
}

fn remove(
&mut self,
_: &DatabaseKey<'_>,
_: Option<&mut Self::Batch>,
) -> Result<Option<ByteVec>, Self::DatabaseError> {
unimplemented!("modifying trie snapshot is not supported")
}

fn contains(&self, _: &DatabaseKey<'_>) -> Result<bool, Self::DatabaseError> {
todo!()
}

fn write_batch(&mut self, _: Self::Batch) -> Result<(), Self::DatabaseError> {
unimplemented!("modifying trie snapshot is not supported")
}
}
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! BonsaiDatabase impl for SnapshotTrieDb.

Modifying snapshot is unimplemented, which is consistent. Please confirm that unimplemented methods cannot be triggered from external calls.

- unimplemented!("modifying trie snapshot is not supported")
+ return Err(Error::UnsupportedOperation("Modifying trie snapshot is not supported".into()));
📝 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
impl<'tx, Tb, Tx> BonsaiDatabase for SnapshotTrieDb<'tx, Tb, Tx>
where
Tb: Trie,
Tx: DbTxRef<'tx> + fmt::Debug,
{
type Batch = ();
type DatabaseError = Error;
fn create_batch(&self) -> Self::Batch {}
fn remove_by_prefix(&mut self, _: &DatabaseKey<'_>) -> Result<(), Self::DatabaseError> {
unimplemented!("modifying trie snapshot is not supported")
}
fn get(&self, key: &DatabaseKey<'_>) -> Result<Option<ByteVec>, Self::DatabaseError> {
let key = to_db_key(key);
let block_number = self.snapshot_id.into();
let change_set = self.tx.get::<Tb::Changeset>(key.clone())?;
if let Some(num) = change_set.and_then(|set| recent_change_from_block(block_number, &set)) {
let mut cursor = self.tx.cursor_dup::<Tb::History>()?;
let entry = cursor
.seek_by_key_subkey(num, key.clone())?
.expect("entry should exist if in change set");
if entry.key == key {
return Ok(Some(entry.value));
}
}
Ok(None)
}
fn get_by_prefix(
&self,
_: &DatabaseKey<'_>,
) -> Result<Vec<(ByteVec, ByteVec)>, Self::DatabaseError> {
todo!()
}
fn insert(
&mut self,
_: &DatabaseKey<'_>,
_: &[u8],
_: Option<&mut Self::Batch>,
) -> Result<Option<ByteVec>, Self::DatabaseError> {
unimplemented!("modifying trie snapshot is not supported")
}
fn remove(
&mut self,
_: &DatabaseKey<'_>,
_: Option<&mut Self::Batch>,
) -> Result<Option<ByteVec>, Self::DatabaseError> {
unimplemented!("modifying trie snapshot is not supported")
}
fn contains(&self, _: &DatabaseKey<'_>) -> Result<bool, Self::DatabaseError> {
todo!()
}
fn write_batch(&mut self, _: Self::Batch) -> Result<(), Self::DatabaseError> {
unimplemented!("modifying trie snapshot is not supported")
}
}
impl<'tx, Tb, Tx> BonsaiDatabase for SnapshotTrieDb<'tx, Tb, Tx>
where
Tb: Trie,
Tx: DbTxRef<'tx> + fmt::Debug,
{
type Batch = ();
type DatabaseError = Error;
fn create_batch(&self) -> Self::Batch {}
fn remove_by_prefix(&mut self, _: &DatabaseKey<'_>) -> Result<(), Self::DatabaseError> {
return Err(Error::UnsupportedOperation("Modifying trie snapshot is not supported".into()));
}
fn get(&self, key: &DatabaseKey<'_>) -> Result<Option<ByteVec>, Self::DatabaseError> {
let key = to_db_key(key);
let block_number = self.snapshot_id.into();
let change_set = self.tx.get::<Tb::Changeset>(key.clone())?;
if let Some(num) = change_set.and_then(|set| recent_change_from_block(block_number, &set)) {
let mut cursor = self.tx.cursor_dup::<Tb::History>()?;
let entry = cursor
.seek_by_key_subkey(num, key.clone())?
.expect("entry should exist if in change set");
if entry.key == key {
return Ok(Some(entry.value));
}
}
Ok(None)
}
fn get_by_prefix(
&self,
_: &DatabaseKey<'_>,
) -> Result<Vec<(ByteVec, ByteVec)>, Self::DatabaseError> {
todo!()
}
fn insert(
&mut self,
_: &DatabaseKey<'_>,
_: &[u8],
_: Option<&mut Self::Batch>,
) -> Result<Option<ByteVec>, Self::DatabaseError> {
return Err(Error::UnsupportedOperation("Modifying trie snapshot is not supported".into()));
}
fn remove(
&mut self,
_: &DatabaseKey<'_>,
_: Option<&mut Self::Batch>,
) -> Result<Option<ByteVec>, Self::DatabaseError> {
return Err(Error::UnsupportedOperation("Modifying trie snapshot is not supported".into()));
}
fn contains(&self, _: &DatabaseKey<'_>) -> Result<bool, Self::DatabaseError> {
todo!()
}
fn write_batch(&mut self, _: Self::Batch) -> Result<(), Self::DatabaseError> {
return Err(Error::UnsupportedOperation("Modifying trie snapshot is not supported".into()));
}
}

Comment on lines +16 to +17
ORIGINAL_CLASS_NAME := piltover_appchain$(CONTRACT_CLASS_SUFFIX)
CLASS_NAME := appchain_core_contract.json
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! Variable naming needs attention, sensei.

The reuse of ORIGINAL_CLASS_NAME and CLASS_NAME variables could lead to conflicts with the previous section's values.

Consider using unique variable names:

-ORIGINAL_CLASS_NAME := piltover_appchain$(CONTRACT_CLASS_SUFFIX)
-CLASS_NAME := appchain_core_contract.json
+PILTOVER_ORIGINAL_CLASS_NAME := piltover_appchain$(CONTRACT_CLASS_SUFFIX)
+PILTOVER_CLASS_NAME := appchain_core_contract.json
📝 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
ORIGINAL_CLASS_NAME := piltover_appchain$(CONTRACT_CLASS_SUFFIX)
CLASS_NAME := appchain_core_contract.json
PILTOVER_ORIGINAL_CLASS_NAME := piltover_appchain$(CONTRACT_CLASS_SUFFIX)
PILTOVER_CLASS_NAME := appchain_core_contract.json

Comment on lines +19 to +21
$(BUILD_DIR): ./piltover/src/*
cd piltover && scarb build
mv target/dev/$(ORIGINAL_CLASS_NAME) $(BUILD_DIR)/$(CLASS_NAME)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Build target needs refinement.

The build process changes directory which could affect the build context.

Consider this improved approach:

-$(BUILD_DIR): ./piltover/src/*
-	cd piltover && scarb build
-	mv target/dev/$(ORIGINAL_CLASS_NAME) $(BUILD_DIR)/$(CLASS_NAME)
+$(BUILD_DIR)/$(PILTOVER_CLASS_NAME): ./piltover/src/*
+	cd piltover && scarb build
+	mkdir -p $(BUILD_DIR)
+	mv piltover/target/dev/$(PILTOVER_ORIGINAL_CLASS_NAME) $(BUILD_DIR)/$(PILTOVER_CLASS_NAME)

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

Comment on lines +665 to +688
impl StateProofProvider for SharedStateProvider {
fn class_multiproof(&self, classes: Vec<ClassHash>) -> ProviderResult<katana_trie::MultiProof> {
let _ = classes;
unimplemented!("not supported in forked mode")
}

fn contract_multiproof(
&self,
addresses: Vec<ContractAddress>,
) -> ProviderResult<katana_trie::MultiProof> {
let _ = addresses;
unimplemented!("not supported in forked mode")
}

fn storage_multiproof(
&self,
address: ContractAddress,
key: Vec<StorageKey>,
) -> ProviderResult<katana_trie::MultiProof> {
let _ = address;
let _ = key;
unimplemented!("not supported in forked mode")
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

StateProofProvider implementation needs actual implementation.

The trait implementation currently returns unimplemented!() for all methods. While the "not supported in forked mode" message is helpful, we should either:

  1. Implement proper functionality
  2. Return a more specific error type instead of panicking

Consider this implementation:

fn class_multiproof(&self, classes: Vec<ClassHash>) -> ProviderResult<katana_trie::MultiProof> {
    Err(ProviderError::Custom("Multiproof generation not supported in forked mode".into()))
}

fn contract_multiproof(&self, addresses: Vec<ContractAddress>) -> ProviderResult<katana_trie::MultiProof> {
    Err(ProviderError::Custom("Multiproof generation not supported in forked mode".into()))
}

fn storage_multiproof(&self, address: ContractAddress, key: Vec<StorageKey>) -> ProviderResult<katana_trie::MultiProof> {
    Err(ProviderError::Custom("Multiproof generation not supported in forked mode".into()))
}

Comment on lines +690 to +702
impl StateRootProvider for SharedStateProvider {
fn classes_root(&self) -> ProviderResult<Felt> {
unimplemented!("not supported in forked mode")
}

fn contracts_root(&self) -> ProviderResult<Felt> {
unimplemented!("not supported in forked mode")
}

fn storage_root(&self, _: ContractAddress) -> ProviderResult<Option<Felt>> {
unimplemented!("not supported in forked mode")
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

StateRootProvider implementation needs actual implementation.

Similar to the StateProofProvider implementation, this also uses unimplemented!(). We should return proper errors instead of panicking.

Consider this implementation:

fn classes_root(&self) -> ProviderResult<Felt> {
    Err(ProviderError::Custom("State root retrieval not supported in forked mode".into()))
}

fn contracts_root(&self) -> ProviderResult<Felt> {
    Err(ProviderError::Custom("State root retrieval not supported in forked mode".into()))
}

fn storage_root(&self, _: ContractAddress) -> ProviderResult<Option<Felt>> {
    Err(ProviderError::Custom("State root retrieval not supported in forked mode".into()))
}

Copy link

codecov bot commented Dec 31, 2024

Codecov Report

Attention: Patch coverage is 56.25000% with 567 lines in your changes missing coverage. Please review.

Project coverage is 55.83%. Comparing base (bd8afc8) to head (699f57c).
Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
bin/katana/src/cli/init/mod.rs 0.00% 180 Missing ⚠️
...atana/storage/provider/src/providers/fork/state.rs 0.00% 75 Missing ⚠️
crates/katana/storage/db/src/trie/mod.rs 73.26% 50 Missing ⚠️
crates/katana/storage/db/src/trie/snapshot.rs 44.28% 39 Missing ⚠️
.../katana/storage/provider/src/providers/db/state.rs 66.66% 31 Missing ⚠️
crates/katana/executor/src/implementation/noop.rs 0.00% 29 Missing ⚠️
...na/executor/src/implementation/blockifier/state.rs 0.00% 26 Missing ⚠️
crates/katana/executor/src/abstraction/mod.rs 0.00% 25 Missing ⚠️
...ana/storage/provider/src/providers/fork/backend.rs 0.00% 23 Missing ⚠️
...s/katana/storage/db/src/abstraction/transaction.rs 48.48% 17 Missing ⚠️
... and 12 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2854      +/-   ##
==========================================
- Coverage   56.18%   55.83%   -0.36%     
==========================================
  Files         440      446       +6     
  Lines       56691    57725    +1034     
==========================================
+ Hits        31850    32228     +378     
- Misses      24841    25497     +656     

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

@kariy kariy merged commit 38b3c2a into main Dec 31, 2024
13 of 14 checks passed
@kariy kariy deleted the katana/dev branch December 31, 2024 20:48
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.

1 participant