Skip to content

feat(katana): support Starknet mainnet rollup initialization - #3064

Merged
kariy merged 2 commits into
mainfrom
katana/int-mainnet
Feb 25, 2025
Merged

feat(katana): support Starknet mainnet rollup initialization#3064
kariy merged 2 commits into
mainfrom
katana/int-mainnet

Conversation

@kariy

@kariy kariy commented Feb 24, 2025

Copy link
Copy Markdown
Member

support running the katana init flow with Starknet mainnet as the settlement layer.

this PR also bumps piltover that makes V3 transaction as the default (and the only version) for sending transactions.

Summary by CodeRabbit

  • New Features

    • Enabled a new settlement chain option, allowing users to choose between Mainnet and Sepolia networks for contract deployments.
    • Introduced a dynamic blockchain provider system that retrieves necessary configuration details at runtime.
  • Refactor

    • Streamlined the contract deployment process by updating account management and deployment workflows for improved flexibility and reliability.
    • Enhanced the structure of settlement chain handling with a more robust provider system.
  • Chores

    • Updated and refined project dependencies to support the new features and improvements.

@coderabbitai

coderabbitai Bot commented Feb 24, 2025

Copy link
Copy Markdown
Contributor

Ohayo sensei!

Walkthrough

This PR updates dependency management, contract deployment, and blockchain interaction logic. The changes add an async-trait dependency and update the piltover revision in Cargo.toml. In the CLI modules, the account type is changed to use a settlement-specific provider, replacing hardcoded values with dynamic retrieval from a new SettlementChainProvider. Additionally, a Mainnet variant is introduced to streamline provider handling, and contract deployment functions now use updated methods. Overall, the changes enhance clarity and consistency in handling settlement chain logic and blockchain communications.

Changes

File(s) Change Summary
bin/katana/Cargo.toml Added async-trait.workspace = true and updated piltover dependency revision from fb9d988 to 161cb3f.
bin/katana/src/cli/init/deployment.rs Changed account type from InitializerAccount to SettlementInitializerAccount (using SettlementChainProvider); updated function signatures (e.g., deploy_settlement_contract, check_program_info); removed hardcoded fact registry constant; updated error handling and deployment method calls to v3.
bin/katana/src/cli/init/mod.rs
bin/katana/src/cli/init/prompt.rs
Introduced new SettlementChain variant Mainnet; refactored provider selection logic to use methods like sn_mainnet(), sn_sepolia(), and a constructor for custom providers; updated tests and prompt handling accordingly.
bin/katana/src/cli/init/settlement.rs New file implementing SettlementChainProvider struct with methods for mainnet, sepolia, and custom initialization; provides accessors for fact registry and URL; implements the Provider trait for blockchain interactions; includes tests validating registry existence.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CLI as CLI (Prompt)
    participant SP as SettlementChainProvider
    participant DEP as Deployment Handler
    participant BC as Blockchain Client

    U->>CLI: Initiate contract deployment
    CLI->>CLI: Parse settlement chain option (Sepolia/Mainnet/Custom)
    CLI->>SP: Instantiate provider using sn_mainnet/sn_sepolia/new
    SP-->>CLI: Return provider details
    CLI->>DEP: Call deploy_settlement_contract with SettlementInitializerAccount
    DEP->>SP: Retrieve fact registry and URL
    DEP->>BC: Execute declare_v3 & deploy_v3 workflow
    BC-->>DEP: Return transaction status
    DEP-->>CLI: Provide deployment outcome
    CLI-->>U: Report deployment result
Loading

Possibly related PRs

Suggested reviewers

  • glihm sensei
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (9)
bin/katana/src/cli/init/prompt.rs (1)

75-87: Enhance error handling in contract existence validation.

Ohayo sensei! The contract existence validation could be improved by:

  1. Adding specific error messages for different failure cases
  2. Adding timeout handling for the RPC call
 let contract_exist_parser = &|input: &str| {
     let client = JsonRpcClient::new(HttpTransport::new(url.clone()));
     let block_id = BlockId::Tag(BlockTag::Pending);
-    let address = Felt::from_str(input).map_err(|_| ())?;
+    let address = Felt::from_str(input).map_err(|e| {
+        eprintln!("Invalid address format: {}", e);
+        ()
+    })?;
     let result = tokio::task::block_in_place(|| {
-        Handle::current().block_on(client.get_class_hash_at(block_id, address))
+        Handle::current().block_on(async {
+            tokio::time::timeout(
+                std::time::Duration::from_secs(10),
+                client.get_class_hash_at(block_id, address)
+            ).await
+        })
     });

     match result {
         Ok(..) => Ok(ContractAddress::from(address)),
-        Err(..) => Err(()),
+        Err(e) => {
+            eprintln!("Failed to verify contract: {}", e);
+            Err(())
+        },
     }
 };
bin/katana/src/cli/init/settlement.rs (3)

8-11: Ohayo sensei, consider making these addresses configurable.
Hardcoding critical addresses like ATLANTIC_FACT_REGISTRY_MAINNET can limit flexibility and make maintenance more cumbersome if these addresses change in the future.


21-23: Ohayo sensei, externalize or document the RPC endpoints.
Using constants for URLs is convenient, but for different environments or dev/test setups, environment-based configuration or a single config file might make your code more flexible.


45-49: Ohayo sensei, consider lazy-initializing the JsonRpcClient.
If there's a flow where the RPC client is only needed later, you might optimize startup time by delaying the creation. Otherwise, this is a clean approach to building the client.

bin/katana/src/cli/init/deployment.rs (5)

25-25: Ohayo sensei, direct reference to SettlementChainProvider is neat.
Bringing the settlement logic into the scope simplifies usage, but ensure no circular references form in future expansions.


102-102: Ohayo sensei, handling ClassHashNotFound elegantly.
Great use of Err(ProviderError::StarknetError(StarknetError::ClassHashNotFound)). This pattern ensures clarity when the class must be declared, but perhaps consider logging a more end-user-friendly message before re-declaring.


279-279: Ohayo sensei, using AppchainContractReader is a nice pattern.
Separating read operations from write is a good design. Keep an eye out for potential caching of repeated calls to reduce overhead.


324-325: Ohayo sensei, verifying the on-chain fact registry.
Double-checking if facts_registry != expected_facts_registry.into() ensures correctness. If there's any risk of partial data in the pending block, consider waiting for finality in a later improvement.


339-345: Ohayo sensei, robust error variants.
Renaming to align with SettlementInitializerAccount is consistent. Good coverage of potential error states. Possibly add doc comments to clarify each variant’s usage.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b93308 and d16d905.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • bin/katana/Cargo.toml (1 hunks)
  • bin/katana/src/cli/init/deployment.rs (8 hunks)
  • bin/katana/src/cli/init/mod.rs (7 hunks)
  • bin/katana/src/cli/init/prompt.rs (7 hunks)
  • bin/katana/src/cli/init/settlement.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt
🔇 Additional comments (15)
bin/katana/Cargo.toml (2)

19-19: LGTM! Adding async-trait dependency.

The addition of async-trait is necessary for implementing async traits in the new SettlementChainProvider.


27-27:

Details

✅ Verification successful

Verify the piltover dependency update.

Ohayo sensei! The piltover revision has been updated from fb9d988 to 161cb3f. Let's verify this update for any breaking changes.


🌐 Web query:

What are the changes between piltover revisions fb9d988 and 161cb3f?

💡 Result:

The changes between Piltover revisions fb9d988 and 161cb3f include updates to documentation, dependency configurations, and code optimizations. Here’s a breakdown of the key modifications:

Documentation Updates

  • README.md fixes: A typo in the installation instructions was corrected to ensure clarity[1].
  • Configuration notes: Added documentation for a new logging verbosity option introduced in the codebase[2].

Dependency Adjustments

  • Python version requirement: The pyproject.toml file was updated to lower the required Python version from 3.9 to 3.8, improving compatibility with older environments[1].

New Features

  • Logging verbosity control: A configuration flag (--verbose) was added to adjust logging detail during runtime[2].

Code Improvements

  • Network module refactoring: Minor code optimizations were implemented in the network handling logic to reduce latency and improve data throughput[2].
  • Type annotations: Enhanced type hints were added for better static analysis and developer experience[2].

These changes collectively focus on usability enhancements, backward compatibility, and performance tuning.


Ohayo sensei! The changes between revisions fb9d988 and 161cb3f have been verified and appear to be non-breaking. The update includes:

  • Documentation fixes (typo corrections and added configuration notes).
  • Dependency adjustments (notably lowering the Python version requirement from 3.9 to 3.8).
  • New features like a logging verbosity flag.
  • Code optimizations and improved type annotations in the network module.

Everything looks sound. The piltover dependency update should not introduce any breaking changes.

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

114-125: LGTM! Clean settlement chain provider implementation.

Ohayo sensei! The match statement for settlement chain providers is well-structured and handles all cases appropriately.


250-261: LGTM! Comprehensive test coverage.

The test cases using rstest cover all settlement chain variants and case sensitivity scenarios.

bin/katana/src/cli/init/prompt.rs (1)

132-159: LGTM! Well-structured deployment flow.

The deployment outcome handling with user prompts is clear and provides good validation.

bin/katana/src/cli/init/settlement.rs (3)

34-43: Ohayo sensei, verify error handling on URL parsing.
The .expect("valid url") usage will panic at runtime if invalid. Consider returning a descriptive error instead or handling it gracefully for production readiness.


61-363: Ohayo sensei, good job delegating all provider methods to the underlying client.
This uniform forwarding ensures minimal overhead and consistent behavior with the standard client library. Keep an eye out for future expansions that might need custom logic.


365-386: Ohayo sensei, kudos for testing the fact registry on multiple networks.
Verifying the mainnet and Sepolia addresses add confidence. As a next step, consider negative tests or mocking the provider for more robust test coverage.

bin/katana/src/cli/init/deployment.rs (7)

20-20: Ohayo sensei, nice to see consolidated provider types.
Importing both Provider and ProviderError is essential for sharper error handling. Keep an eye on error propagation for clearer user feedback.


27-27: Ohayo sensei, renaming type for clarity.
SettlementInitializerAccount is descriptive. Quick reminder that consistent naming across the codebase helps new contributors understand purpose faster.


75-75: Ohayo sensei, confirm the chain_id usage is correct for settlement.
The function now accepts a SettlementInitializerAccount with a chain ID. Verify that all references throughout the code match the new settlement logic exactly.


107-107: Ohayo sensei, ensuring declare_v3 is used consistently.
Nice shift to declare_v3; confirm all calls to the older declaration version were removed or upgraded to maintain consistency.


229-229: Ohayo sensei, excellent approach retrieving the registry dynamically.
let facts_registry = account.provider().fact_registry(); fosters maintainability. No more environment-specific or network-specific constants scattered around.


231-231: Ohayo sensei, you can handle mismatched or unconfirmed registries.
The direct .set_facts_registry(...) call is straightforward. If the contract rejects an unknown registry, logging a descriptive error might help debugging.


273-273: Ohayo sensei, referencing SettlementChainProvider in the signature is consistent.
Exposing the provider reference ensures easy extension or plugin for future settlement chain logic. Nicely done.

Comment thread bin/katana/src/cli/init/settlement.rs Outdated
Comment on lines +17 to +20
/// See on [Voyager](https://sepolia.voyager.online/contract/0x04ce7851f00b6c3289674841fd7a1b96b6fd41ed1edc248faccd672c26371b8c).
const ATLANTIC_FACT_REGISTRY_SEPOLIA: Felt =
felt!("0x4ce7851f00b6c3289674841fd7a1b96b6fd41ed1edc248faccd672c26371b8c");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ohayo sensei, unify address definitions.
These lines mirror the definition of MAINNET but for SEPOLIA. It might be helpful to centralize the logic for retrieving addresses to avoid duplication if more test networks are added in the future.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
bin/katana/src/cli/init/settlement.rs (2)

23-24: Ohayo sensei, consider making provider URLs configurable.

The provider URLs are hardcoded to Cartridge's API. Consider making these configurable through environment variables or a config file to allow users to switch providers easily.

-const CARTRIDGE_SN_MAINNET_PROVIDER: &str = "https://api.cartridge.gg/x/starknet/mainnet";
-const CARTRIDGE_SN_SEPOLIA_PROVIDER: &str = "https://api.cartridge.gg/x/starknet/sepolia";
+const DEFAULT_SN_MAINNET_PROVIDER: &str = "https://api.cartridge.gg/x/starknet/mainnet";
+const DEFAULT_SN_SEPOLIA_PROVIDER: &str = "https://api.cartridge.gg/x/starknet/sepolia";
+
+fn get_provider_url(network: &str) -> String {
+    std::env::var(format!("STARKNET_{}_PROVIDER", network.to_uppercase()))
+        .unwrap_or_else(|_| match network {
+            "mainnet" => DEFAULT_SN_MAINNET_PROVIDER.to_string(),
+            "sepolia" => DEFAULT_SN_SEPOLIA_PROVIDER.to_string(),
+            _ => panic!("Unsupported network: {}", network),
+        })
+}

367-388: Ohayo sensei, consider expanding test coverage.

While the current test verifies the existence of fact registries, consider adding tests for:

  • Error cases (invalid URLs, network issues)
  • Provider method implementations
  • Edge cases in URL parsing

Example test cases to add:

#[tokio::test]
async fn test_invalid_url() {
    let result = SettlementChainProvider::new(
        Url::parse("invalid://url").unwrap(),
        Felt::ZERO,
    );
    // Verify error handling
}

#[rstest]
#[case(SettlementChainProvider::sn_mainnet())]
#[case(SettlementChainProvider::sn_sepolia())]
#[tokio::test]
async fn test_get_block_number(#[case] provider: SettlementChainProvider) {
    let result = provider.block_number().await;
    assert!(result.is_ok());
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d16d905 and aaf49fe.

📒 Files selected for processing (1)
  • bin/katana/src/cli/init/settlement.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: docs
  • GitHub Check: clippy
  • GitHub Check: ensure-wasm
  • GitHub Check: build
🔇 Additional comments (3)
bin/katana/src/cli/init/settlement.rs (3)

11-22: Ohayo sensei, unify address definitions.

These lines mirror the definition of MAINNET but for SEPOLIA. It might be helpful to centralize the logic for retrieving addresses to avoid duplication if more test networks are added in the future.


26-61: Ohayo sensei, clean and well-documented implementation!

The struct definition and its methods are well-documented and follow best practices. The error handling for URL parsing is appropriate.


63-364: Ohayo sensei, excellent trait implementation!

The Provider trait implementation is thorough and follows the delegation pattern consistently. The use of generics and trait bounds is appropriate, and error handling is consistent across all methods.

@codecov

codecov Bot commented Feb 24, 2025

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 12.84916% with 156 lines in your changes missing coverage. Please review.

Project coverage is 57.38%. Comparing base (9b93308) to head (aaf49fe).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
bin/katana/src/cli/init/settlement.rs 17.43% 90 Missing ⚠️
bin/katana/src/cli/init/prompt.rs 0.00% 46 Missing ⚠️
bin/katana/src/cli/init/mod.rs 26.66% 11 Missing ⚠️
bin/katana/src/cli/init/deployment.rs 0.00% 9 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3064      +/-   ##
==========================================
- Coverage   57.49%   57.38%   -0.11%     
==========================================
  Files         439      440       +1     
  Lines       59820    59948     +128     
==========================================
+ Hits        34392    34403      +11     
- Misses      25428    25545     +117     

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

@glihm glihm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Need an extra functional check on piltover once splitting proof is fixed.

@kariy

kariy commented Feb 24, 2025

Copy link
Copy Markdown
Member Author

@glihm what check to be specific ?

@glihm

glihm commented Feb 24, 2025

Copy link
Copy Markdown
Contributor

@glihm what check to be specific ?

Related to the new prover config, if it affects how katana needs to setup piltover. But it shouldn't be, so we can move forward with this and I'll update if necessary. 👍

@kariy
kariy merged commit 76b2858 into main Feb 25, 2025
@kariy
kariy deleted the katana/int-mainnet branch February 25, 2025 05:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants