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

test(katana-rpc): get starknet pending block #2772

Merged
merged 2 commits into from
Dec 5, 2024
Merged

Conversation

kariy
Copy link
Member

@kariy kariy commented Dec 5, 2024

ref #2763

Summary by CodeRabbit

  • New Features

    • Introduced asynchronous test functions to validate the retrieval of pending blocks and transactions.
    • Added a test for the gas oracle to ensure dynamic gas pricing behavior.
  • Tests

    • Implemented fetch_pending_blocks and fetch_pending_blocks_in_instant_mode tests for pending block verification.
    • Added test_gas_oracle to assess the functionality of the gas oracle.

Copy link

coderabbitai bot commented Dec 5, 2024

Walkthrough

Ohayo, sensei! This pull request introduces two new asynchronous test functions in the StarkNet testing suite. The first function, fetch_pending_blocks, verifies the correct behavior of fetching pending blocks along with their transactions and receipts. The second function, fetch_pending_blocks_in_instant_mode, tests the fetching of pending blocks specifically in instant mining mode. Additionally, new types for handling responses related to pending blocks are added to enhance the functionality of these tests. A new test function for the gas oracle is also included, validating its dynamic pricing behavior.

Changes

File Path Change Summary
crates/katana/rpc/rpc/tests/starknet.rs - Added new test function: async fn fetch_pending_blocks()
- Added new test function: async fn fetch_pending_blocks_in_instant_mode()
- Added types: MaybePendingBlockWithReceipts, MaybePendingBlockWithTxHashes, MaybePendingBlockWithTxs
crates/katana/core/src/backend/gas_oracle.rs - Added new test function: async fn test_gas_oracle()

Possibly related PRs


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
crates/katana/rpc/rpc/tests/starknet.rs (2)

956-1056: Ohayo! Well-structured test with comprehensive coverage, sensei!

The test effectively verifies pending block behavior across different scenarios. However, consider these improvements:

  1. Replace .unwrap() calls with proper error handling using ? operator for better test maintenance.
  2. Consider extracting the verification logic into helper functions to reduce code duplication across the three block types.

Example helper function:

async fn verify_pending_block<T>(
    block: &T,
    expected_txs: &[Felt],
    expected_parent_hash: Felt,
) where
    T: HasTransactions + HasParentHash,
{
    assert_eq!(block.transactions().len(), expected_txs.len());
    assert_eq!(block.parent_hash(), expected_parent_hash);
    // Add transaction verification logic
}

1060-1148: Consider improving error handling and test organization.

Similar to the previous test:

  1. Replace .unwrap() calls with ? operator
  2. Consider extracting common verification logic into helper functions
  3. Add assertions to verify block numbers in instant mode

Example improvement:

// Replace unwraps with proper error handling
let res = contract.transfer(&recipient, &amount)
    .send()
    .await?;
dojo_utils::TransactionWaiter::new(res.transaction_hash, &provider)
    .await?;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9be17f3 and 01310d4.

📒 Files selected for processing (1)
  • crates/katana/rpc/rpc/tests/starknet.rs (2 hunks)
🔇 Additional comments (2)
crates/katana/rpc/rpc/tests/starknet.rs (2)

26-28: Ohayo! The new imports look good, sensei!

The pending block types are properly imported and will be used effectively in the new test functions.


1058-1059: Excellent documentation of instant mining mode behavior, sensei!

The comment clearly explains the expected behavior, which helps future maintainers understand the test's purpose.

@kariy kariy force-pushed the katana/pending-block-test branch from 01310d4 to ca65ff7 Compare December 5, 2024 20:12
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: 0

🧹 Outside diff range and nitpick comments (4)
crates/katana/core/src/backend/gas_oracle.rs (2)

286-286: Consider documenting the external assumption in the ignore attribute.

The #[ignore] attribute should include more specific information about what external assumption is required.

-#[ignore = "Requires external assumption"]
+#[ignore = "Requires external L1 node at eth.merkle.io"]

Line range hint 287-324: Test could be more robust with additional scenarios.

While the test covers basic functionality, consider:

  1. The 9-second sleep might be too short for real-world block times
  2. Missing error case testing (e.g., unavailable L1 provider)
  3. No validation of STRK price updates

Consider adding error case testing:

+#[tokio::test]
+#[ignore = "Requires external L1 node"]
+async fn test_gas_oracle_error_cases() {
+    let url = Url::parse("https://invalid-url.example.com").expect("Invalid URL");
+    let oracle = L1GasOracle::sampled(url.clone());
+    let shared_prices = match &oracle {
+        L1GasOracle::Sampled(sampled) => sampled.prices.clone(),
+        _ => panic!("Expected sampled oracle"),
+    };
+    
+    let mut worker = GasOracleWorker::new(shared_prices.clone(), url);
+    let result = worker.update_once().await;
+    assert!(result.is_err(), "Should fail with invalid URL");
+}
crates/katana/rpc/rpc/tests/starknet.rs (2)

956-1056: Ohayo sensei! Consider adding error case testing.

The test thoroughly covers the happy path but could benefit from testing error scenarios:

  1. Invalid block IDs
  2. Network issues
  3. Race conditions

Consider adding error case tests:

+#[tokio::test]
+async fn fetch_pending_blocks_error_cases() {
+    let config = get_default_test_config(SequencingConfig { no_mining: true, ..Default::default() });
+    let sequencer = TestSequencer::start(config).await;
+    let provider = sequencer.provider();
+
+    // Test invalid block ID
+    let block_id = BlockId::Number(u64::MAX);
+    let result = provider.get_block_with_txs(block_id).await;
+    assert!(result.is_err(), "Should fail with invalid block number");
+}

1059-1148: Consider adding more assertions for block metadata.

While the test covers the core functionality well, it could benefit from additional assertions:

  1. Block timestamps
  2. Block numbers
  3. Gas prices

Add more assertions to strengthen the test:

 if let MaybePendingBlockWithTxs::Block(block) = block_with_txs {
     assert_eq!(block.transactions.len(), 1);
     assert_eq!(block.parent_hash, latest_block_hash);
     assert_eq!(*block.transactions[0].transaction_hash(), res.transaction_hash);
+    assert!(block.timestamp > 0, "Block timestamp should be set");
+    assert_eq!(block.block_number, latest_block_hash_n_num.block_number + 1);
 } else {
     panic!("expected pending block with transactions")
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 01310d4 and ca65ff7.

📒 Files selected for processing (2)
  • crates/katana/core/src/backend/gas_oracle.rs (1 hunks)
  • crates/katana/rpc/rpc/tests/starknet.rs (2 hunks)

Copy link

codecov bot commented Dec 5, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 55.67%. Comparing base (9be17f3) to head (ca65ff7).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2772      +/-   ##
==========================================
+ Coverage   55.57%   55.67%   +0.09%     
==========================================
  Files         434      434              
  Lines       54536    54536              
==========================================
+ Hits        30311    30364      +53     
+ Misses      24225    24172      -53     

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

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