Skip to content

Enable custom account in deploying L1-L2 messaging contract #758

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

Merged
merged 10 commits into from
May 26, 2025

Conversation

FabijanC
Copy link
Contributor

@FabijanC FabijanC commented Apr 14, 2025

Usage related changes

  • Fixes Deploying a messaging L1-L2 contract should be doable using a custom account #727
  • Introduces validation on L1 messaging contract loading
    • In case an address of an already deployed contract is provided, it is asserted that there indeed is something deployed there (not checking ABI).
  • The preferred property for specifying the address of the messaging contract is now: messaging_contract_address (address still acceptable for backwards compatibility but deprecated).
  • Improve L1-L2 docs to include a complete messaging contract loading tutorial

Development related changes

Checklist:

  • Checked out the contribution guidelines
  • Applied formatting - ./scripts/format.sh
  • No linter errors - ./scripts/clippy_check.sh
  • No unused dependencies - ./scripts/check_unused_deps.sh
  • No spelling errors - ./scripts/check_spelling.sh
  • Performed code self-review
  • Rebased to the latest commit of the target branch (or merged it into my branch)
    • Once you make the PR reviewable, please avoid force-pushing
  • Updated the docs if needed - ./website/README.md
    • Update devnet_api.json
  • Linked the issues resolvable by this PR - linking info
  • Updated the tests if needed; all passing - execution info

Summary by CodeRabbit

  • New Features

    • Added support for specifying a deployer account private key when loading or deploying the L1 messaging contract, enabling custom signer configuration.
    • The messaging contract address is now validated to ensure it contains contract code before configuration proceeds.
  • API Changes

    • The /postman/load_l1_messaging_contract endpoint now accepts messaging_contract_address (renamed from address) and an optional deployer_account_private_key.
    • API documentation and schema updated to reflect these new parameters.
  • Bug Fixes

    • Improved error handling when loading a messaging contract that is not deployed or when using incorrect private keys.
  • Documentation

    • Updated user guides and API references to describe the new parameters and deployment logic for messaging contracts.
  • Tests

    • Added comprehensive tests for loading, deploying, and interacting with the L1 messaging contract, including custom key scenarios and error cases.

Copy link

coderabbitai bot commented Apr 14, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This change introduces support for specifying a custom deployer account private key when configuring or deploying the L1-L2 messaging contract in Starknet Devnet. The messaging configuration flow now accepts an optional private key parameter, which is passed through the API, internal configuration methods, and down to the Ethereum messaging core. The system validates that any provided messaging contract address actually contains contract code on-chain. Test infrastructure is updated to allow custom mnemonic and private key configuration for Ethereum providers. Integration tests are added to cover scenarios involving custom private keys, contract deployment, and address validation. Documentation and API schemas are updated to reflect the new parameter and renamed fields.

Assessment against linked issues

Objective Addressed Explanation
Allow specifying a custom deployer account/private key when deploying/loading the L1-L2 messaging contract (#727)
Accept and pass through the deployer account private key from API to messaging configuration (#727)
Validate that provided messaging contract address contains contract code (#727)
Update documentation and API schema to reflect new parameter and field renaming (#727)

Possibly related PRs

  • 0xSpaceShard/starknet-devnet#740: Adds a funded account private key parameter for deploying the messaging contract, directly modifying EthereumMessaging::new to accept a private key, which is closely related to the main PR's changes.
  • 0xSpaceShard/starknet-devnet#726: Focuses on improving L1-L2 messaging documentation, which is related to the main PR's implementation of deployer private key support, though it does not directly modify code or API schemas.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@FabijanC FabijanC changed the title Custom account in deploying L1-L2 messaging contract Enable custom account in deploying L1-L2 messaging contract Apr 14, 2025
FabijanC and others added 6 commits May 22, 2025 15:32
* [skip ci]

* feat: add private key parameter in loading l1 contract

* replace dummy private key

* update docs for postman load contract

* add incorrect private key tests

* formatting changes

* Improve predeclaration/predeployment startup log (#734)

* Abstract public+private key as KeyPair: reduce number of fn args

* fix tests revert anvil changes

* update incorrect test assert code

---------

Co-authored-by: FabijanC <[email protected]>
@FabijanC
Copy link
Contributor Author

@coderabbitai review

Copy link

coderabbitai bot commented May 26, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@FabijanC FabijanC marked this pull request as ready for review May 26, 2025 11:42
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (5)
tests/integration/common/constants.rs (1)

105-108: Consider adding documentation for test constants.

These test constants look good. Consider adding doc comments to clarify that these are standard test values and should never be used in production environments.

+/// Standard test mnemonic phrase for Anvil - DO NOT USE IN PRODUCTION
 pub const DEFAULT_ANVIL_MNEMONIC_PHRASE: &str =
     "test test test test test test test test test test test junk";
+/// Test private key corresponding to the first account from DEFAULT_ANVIL_MNEMONIC_PHRASE - DO NOT USE IN PRODUCTION  
 pub const DEFAULT_ETH_ACCOUNT_PRIVATE_KEY: &str =
     "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
website/static/devnet_api.json (1)

133-141: Consider adding format validation for the private key parameter.

The parameter addition is correct, but consider adding a pattern constraint to validate the private key format (e.g., 64 hex characters with 0x prefix).

         {
           "name": "deployer_account_private_key",
           "description": "The private key of the account that shall be used for deploying the messaging contract. Not applicable if `messaging_contract_address` is specified.",
           "required": false,
           "schema": {
             "title": "Deployer account private key",
-            "type": "string"
+            "type": "string",
+            "pattern": "^0x[a-fA-F0-9]{64}$"
           }
         }
crates/starknet-devnet-core/src/messaging/ethereum.rs (1)

68-85: Simplify the empty code validation logic.

The validation correctly checks for contract existence, but the condition can be simplified.

-    if &messaging_contract_code.to_string() == "0x" || messaging_contract_code.len() <= 2 {
+    if messaging_contract_code.is_empty() {
         return Err(Error::MessagingError(MessagingError::EthersError(format!(
             "The specified address ({address:#x}) contains no contract"
         ))));
     }

Note: Bytes::is_empty() properly handles the case where the code is just "0x".

tests/integration/test_messaging.rs (2)

378-402: Consider adding explicit assertions after loading the contract.

While the test implicitly verifies success through the unwrap() call, it would be more robust to add explicit assertions to verify the loaded contract's state or address.

Consider adding an assertion after line 401 to verify the loaded contract:

 second_devnet
     .send_custom_rpc(
         "devnet_postmanLoad",
         json!({ "network_url": anvil.url, "address": MESSAGING_L1_ADDRESS }),
     )
     .await
     .unwrap();
+
+// Verify the contract was loaded successfully
+let load_result = second_devnet
+    .send_custom_rpc(
+        "devnet_postmanLoad", 
+        json!({ "network_url": anvil.url, "address": MESSAGING_L1_ADDRESS }),
+    )
+    .await
+    .unwrap();
+assert_eq!(
+    load_result.get("messaging_contract_address").unwrap().as_str().unwrap(),
+    MESSAGING_L1_ADDRESS
+);

440-467: Consider making the expected contract address more maintainable.

The test hardcodes the expected contract address "0xca945eebf408d4a73e5d330fc8f6b55cd1e419ff". While this is valid for deterministic deployments, consider extracting it as a constant for better maintainability.

Add a constant for the expected address:

+const EXPECTED_CONTRACT_ADDRESS_WITH_SEED_42: &str = "0xca945eebf408d4a73e5d330fc8f6b55cd1e419ff";
+
 #[tokio::test]
 async fn deploy_l1_messaging_contract_with_custom_key() {

Then use it in the assertion:

     assert_eq!(
         body.get("messaging_contract_address").unwrap().as_str().unwrap(),
-        "0xca945eebf408d4a73e5d330fc8f6b55cd1e419ff"
+        EXPECTED_CONTRACT_ADDRESS_WITH_SEED_42
     );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 537ddbe and 6665b89.

📒 Files selected for processing (10)
  • crates/starknet-devnet-core/src/messaging/ethereum.rs (4 hunks)
  • crates/starknet-devnet-core/src/messaging/mod.rs (1 hunks)
  • crates/starknet-devnet-server/src/api/http/endpoints/postman.rs (1 hunks)
  • crates/starknet-devnet-server/src/api/http/models.rs (1 hunks)
  • tests/integration/common/background_anvil.rs (5 hunks)
  • tests/integration/common/background_devnet.rs (1 hunks)
  • tests/integration/common/constants.rs (1 hunks)
  • tests/integration/test_messaging.rs (2 hunks)
  • website/docs/postman.md (4 hunks)
  • website/static/devnet_api.json (2 hunks)
🧰 Additional context used
🪛 LanguageTool
website/docs/postman.md

[uncategorized] ~44-~44: The grammatical number of this noun doesn’t look right. Consider replacing it.
Context: ...a new one, which is used for exchanging message between L1 and L2. ### L1 network The...

(AI_EN_LECTOR_REPLACEMENT_NOUN_NUMBER)


[style] ~61-~61: To strengthen your wording, consider replacing the phrasal verb “leave out”.
Context: ...simplify wish to deploy a new instance, leave out the messaging_contract_address proper...

(OMIT_EXCLUDE)


[style] ~62-~62: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ssaging_contract_address` property. - If your L1 network is a local testnet (e.g...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

🔇 Additional comments (19)
tests/integration/common/background_devnet.rs (1)

136-136: Intentional debugging change looks good.

The commented stdout piping allows developers to see devnet output during test runs, which is helpful for debugging. The inline comment clearly explains the purpose.

crates/starknet-devnet-server/src/api/http/endpoints/postman.rs (1)

23-29: Implementation correctly adds custom deployer support.

The addition of data.deployer_account_private_key.as_deref() as the third parameter to configure_messaging properly implements the PR's objective of enabling custom account deployment for L1-L2 messaging contracts. Using as_deref() ensures the parameter is optional, maintaining backward compatibility.

crates/starknet-devnet-server/src/api/http/models.rs (1)

32-37: LGTM! Good backward compatibility approach.

The renaming of address to messaging_contract_address with the #[serde(alias = "address")] attribute ensures backward compatibility while making the field name more descriptive. The addition of the optional deployer_account_private_key field properly supports custom account deployment as intended.

website/docs/postman.md (1)

56-63: Clear and helpful deployment instructions!

The documentation clearly explains the different scenarios for messaging contract deployment and when each parameter should be used. This will help users understand how to properly configure their setup based on their L1 network type.

🧰 Tools
🪛 LanguageTool

[style] ~61-~61: To strengthen your wording, consider replacing the phrasal verb “leave out”.
Context: ...simplify wish to deploy a new instance, leave out the messaging_contract_address proper...

(OMIT_EXCLUDE)


[style] ~62-~62: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...ssaging_contract_address` property. - If your L1 network is a local testnet (e.g...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

crates/starknet-devnet-core/src/messaging/mod.rs (1)

100-115:

✅ Verification successful

LGTM! The new parameter is properly integrated.

The addition of the optional deployer_account_private_key parameter is well-documented and correctly passed through to the EthereumMessaging constructor. This enables custom account deployment as intended by the PR.

Let me verify that the EthereumMessaging::new method properly handles the new parameter:


🏁 Script executed:

#!/bin/bash
# Description: Verify that EthereumMessaging::new accepts and uses the deployer_account_private_key parameter

# Check the EthereumMessaging::new method signature and implementation
ast-grep --pattern $'impl EthereumMessaging {
  $$$
  pub async fn new($$$) -> $_ {
    $$$
  }
  $$$
}'

# Also check for any usage of the private key parameter in the ethereum module
rg -A 10 "deployer_account_private_key" crates/starknet-devnet-core/src/messaging/

Length of output: 26354


✅ Verified: deployer_account_private_key is correctly handled

Verification of EthereumMessaging::new shows:

  • In crates/starknet-devnet-core/src/messaging/ethereum.rs (lines 121–124), the deployer_account_private_key parameter is matched and used to initialize the signer’s private key, falling back to ETH_ACCOUNT_DEFAULT.private_key when None.

No further changes required.

tests/integration/common/background_anvil.rs (5)

12-12: LGTM!

The import of DEFAULT_ANVIL_MNEMONIC_PHRASE is correctly added alongside other constants.


33-35: LGTM!

The delegation pattern maintains backward compatibility while simplifying the code.


37-76: LGTM!

The new method correctly implements custom signer support by:

  • Passing the mnemonic phrase to Anvil via command-line arguments
  • Forwarding the private key to setup_ethereum_provider for wallet creation
  • Maintaining the existing error handling and retry logic

78-87: LGTM!

The refactored method correctly delegates to the new implementation with default constants, maintaining backward compatibility. The documentation clearly states the assumptions about the CLI arguments.


182-203: LGTM!

The function signature update correctly parameterizes the private key, making the provider setup more flexible. The wallet creation properly uses the provided private key parameter.

website/static/devnet_api.json (2)

126-132: LGTM!

The parameter rename from address to messaging_contract_address improves API clarity. The description clearly indicates the parameter's purpose and behavior.


152-152: LGTM!

The response schema correctly uses the ETH_ADDRESS reference, maintaining consistency with the parameter schema.

crates/starknet-devnet-core/src/messaging/ethereum.rs (4)

106-111: LGTM!

The updated method signature correctly adds support for custom deployer accounts while maintaining backward compatibility with the optional parameter.


121-124: LGTM!

The private key selection logic correctly implements the fallback pattern, maintaining backward compatibility when no custom key is provided.


132-132: LGTM!

Wrapping the provider in Arc is consistent with the provider_signer field and enables safe sharing across threads.


145-146: LGTM!

The contract validation ensures that the provided address actually contains deployed contract code, preventing runtime errors when attempting to interact with a non-existent contract.

tests/integration/test_messaging.rs (3)

404-407: LGTM! Test constants are well-named and appropriate.

The mnemonic and private key constants are clearly named to indicate they're derived from seed 42, making their purpose obvious for testing custom signer functionality.


350-376: LGTM! Test correctly validates the contract existence check.

This test properly verifies that the system rejects loading a messaging contract from an address where no contract is deployed, which aligns with the PR's validation improvements.


410-438:

❓ Verification inconclusive

Test name doesn't fully describe the test scenarios.

The test name setup_anvil_incorrect_eth_private_key is misleading as it tests two scenarios:

  1. Loading without providing a private key (lines 421-426)
  2. Loading with an incorrect private key (lines 427-438)

Additionally, the error message CallGasCostMoreThanGasLimit seems unexpected for a private key mismatch issue.

Consider renaming the test to better reflect both scenarios:

-async fn setup_anvil_incorrect_eth_private_key() {
+async fn test_loading_messaging_contract_with_invalid_credentials() {

Also, please verify if CallGasCostMoreThanGasLimit is the expected error for authentication failures:


🌐 Web query:

What error is typically thrown when using an incorrect private key for Ethereum contract deployment?

💡 Result:

When using an incorrect private key for Ethereum contract deployment, several specific errors can occur depending on the exact issue with the private key. These errors typically relate to validation problems, authentication failures, or deployment issues.

Common Private Key Errors During Deployment

Invalid Length or Format Errors

One of the most common errors is related to the private key's format or length. Ethereum private keys must be 256 bits (32 bytes) in length and typically start with "0x"[2]. When the private key doesn't meet these requirements, you'll encounter errors like:

  • "Invalid private key: invalid length, need 256 bits"[2]
  • "Make sure the private key string begins with 0x"[7]

Contract Deployment Failures

Using an incorrect private key often leads to deployment failures, which can manifest as:

  • "Error deploying contract: invalid private key"[2]
  • "Deployment Failed" errors in various deployment tools like Truffle[5]
  • "Contract Creation Code Storage Out of Gas" - which can occur when the transaction signing fails due to private key issues[4]

Authentication Issues

When a private key is missing or not properly set in environment variables, you might see:

  • "Failed to connect to the Ethereum client"[6]
  • "No contract code at given address" - this often happens when contract deployment silently fails due to private key issues[6]

Transaction Verification Failures

If the private key doesn't match the intended deployer address:

  • "Transaction was not mined within expected time"[5]
  • "Execution reverted" errors during contract initialization[3]

Troubleshooting Tips

To resolve private key related issues:

  1. Verify that your private key is correctly formatted with 32 bytes and begins with "0x"[7]
  2. Ensure the private key environment variable is properly set and accessible to your deployment script[2][8]
  3. Check that the private key corresponds to an address with sufficient funds to cover deployment gas costs[4]
  4. Confirm you're not running deployment commands with different permissions (like sudo) that might prevent access to environment variables[2]
  5. Validate that the nonce is correct for the address associated with your private key[8]

If deployment silently fails, you can use transaction inspection tools like eth.getTransaction("hash") on the geth console to determine the exact cause of failure[6].

Citations:


Rename test for clarity and confirm expected error for invalid credentials

The name setup_anvil_incorrect_eth_private_key suggests only an incorrect key, but the test actually covers both a missing key and a wrong key. Consider renaming for accuracy:

-async fn setup_anvil_incorrect_eth_private_key() {
+async fn test_loading_messaging_contract_with_invalid_credentials() {

Also verify whether CallGasCostMoreThanGasLimit is truly the expected error when credentials are missing or incorrect. If the failure should indicate a key‐validation or authentication error, update the assertion to match:

-    assert_contains(&body.message, "CallGasCostMoreThanGasLimit");
+    assert_contains(&body.message, "Invalid private key");

Locations to update:

  • tests/integration/test_messaging.rs → lines 410–438

@FabijanC FabijanC merged commit 8321f9b into main May 26, 2025
2 checks passed
@FabijanC FabijanC deleted the custom-l1-acc branch May 26, 2025 12:26
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.

Deploying a messaging L1-L2 contract should be doable using a custom account
2 participants