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

Add/starknet hive with custom acc #269

Merged
merged 2 commits into from
Jan 29, 2025
Merged

Conversation

piotr-stec
Copy link
Collaborator

@piotr-stec piotr-stec commented Jan 29, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a new method for creating Starknet accounts with custom parameters
    • Introduced a function to retrieve compiled contract data from string inputs
  • Improvements

    • Enhanced error handling in contract declaration process
    • Improved flexibility in contract data processing
  • Refactoring

    • Corrected struct name from StarkneHive to StarknetHive
    • Updated implementation signatures to match new struct name

Copy link

coderabbitai bot commented Jan 29, 2025

Walkthrough

The pull request introduces modifications to the StarknetHive struct and contract declaration utilities in the Starknet testing framework. The primary changes include renaming the StarkneHive struct to StarknetHive, adding a new asynchronous method new_with_custom_account for creating a StarknetHive instance with custom account parameters, and introducing a new function get_compiled_contract_from_string to retrieve compiled contract data from string inputs. These changes enhance the flexibility and error handling of contract declaration and account creation processes.

Changes

File Changes
openrpc-testgen/src/utils/starknet_hive.rs - Renamed StarkneHive to StarknetHive in struct and implementation definitions
- Added new_with_custom_account method for creating a StarknetHive instance with custom account parameters
openrpc-testgen/src/utils/v7/endpoints/declare_contract.rs - Added get_compiled_contract_from_string method to retrieve compiled contract data from string inputs
- Updated get_compiled_contract to use ? for error handling instead of unwrap()

Sequence Diagram

sequenceDiagram
    participant Client
    participant StarknetHive
    participant ContractDeclaration
    participant AccountCreation

    Client->>StarknetHive: new_with_custom_account(node_url, paymaster_address, paymaster_key, sierra, casm)
    StarknetHive->>ContractDeclaration: get_compiled_contract_from_string(sierra, casm)
    ContractDeclaration-->>StarknetHive: Return compiled contract
    StarknetHive->>AccountCreation: Create custom account
    AccountCreation-->>StarknetHive: Account created
    StarknetHive-->>Client: Return StarknetHive instance
Loading

Possibly related PRs

Poem

🐰 In the realm of Starknet's might,
A hive of code takes gentle flight
Renaming structs with careful care
Custom accounts now dance with flair
Errors caught, no panic in sight! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@piotr-stec piotr-stec merged commit 256b794 into main Jan 29, 2025
4 checks passed
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: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc368ac and 51320aa.

📒 Files selected for processing (2)
  • openrpc-testgen/src/utils/starknet_hive.rs (5 hunks)
  • openrpc-testgen/src/utils/v7/endpoints/declare_contract.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run cargo_clippy - rust stable
  • GitHub Check: Build project - rust stable
🔇 Additional comments (7)
openrpc-testgen/src/utils/v7/endpoints/declare_contract.rs (2)

146-150: LGTM! Improved error handling.

The change from unwrap() to the ? operator enhances error propagation and makes the code more robust.


152-161: LGTM! Well-structured new function.

The new function get_compiled_contract_from_string follows good practices:

  • Reuses existing logic
  • Maintains consistent error handling
  • Provides flexibility by accepting string inputs
openrpc-testgen/src/utils/starknet_hive.rs (5)

6-8: LGTM! Clean import organization.

The new imports are well-organized and necessary for the added functionality.

Also applies to: 22-25


44-44: Verify impact of struct rename.

The struct has been renamed from StarkneHive to StarknetHive to fix the typo. This is a breaking change that could affect downstream code.

✅ Verification successful

Rename from StarkneHive to StarknetHive is safe to proceed

The struct rename is contained within a single file and there are no external references to the old name. This is a non-breaking change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to the old struct name
rg "StarkneHive" -l

Length of output: 19


Script:

#!/bin/bash
# Search for current struct usage
echo "=== Current StarknetHive usage ==="
rg "StarknetHive" -A 2

# Check git history for this file
echo -e "\n=== Git history for the file ==="
git log -p -- openrpc-testgen/src/utils/starknet_hive.rs | head -n 50

# Look for struct usage patterns
echo -e "\n=== Struct usage patterns ==="
ast-grep --pattern 'struct StarknetHive'

Length of output: 1510


Script:

#!/bin/bash
# Check if the struct is imported anywhere
echo "=== Checking imports ==="
rg "use.*StarknetHive" -A 1

# Check git history with a different approach
echo -e "\n=== Checking file history ==="
git log --oneline -- openrpc-testgen/src/utils/starknet_hive.rs

# Check if file exists in main/master branch
echo -e "\n=== Checking file in main branch ==="
git show main:openrpc-testgen/src/utils/starknet_hive.rs 2>&1 || echo "File not in main"

Length of output: 6462


6-8: LGTM! Import changes are well-organized.

The new imports are correctly structured and necessary for the added functionality.

Also applies to: 22-25


44-44: LGTM! Fixed typo in struct name.

The struct name has been correctly updated from StarkneHive to StarknetHive.


Line range hint 235-337: LGTM! Implementation blocks are correctly updated.

The trait implementations have been properly updated to use the new struct name StarknetHive.

)
.await?;

let transfer_amount = Felt::from_hex("0xfffffffffffffff")?;
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Document magic numbers.

The hardcoded value 0xfffffffffffffff should be documented to explain its significance.

+ // Maximum transfer amount for initial account funding
  let transfer_amount = Felt::from_hex("0xfffffffffffffff")?;
📝 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
let transfer_amount = Felt::from_hex("0xfffffffffffffff")?;
// Maximum transfer amount for initial account funding
let transfer_amount = Felt::from_hex("0xfffffffffffffff")?;

🧹 Nitpick (assertive)

Consider extracting magic number as a constant.

The transfer amount 0xfffffffffffffff should be defined as a named constant at the module level for better maintainability and documentation.

+ const DEFAULT_TRANSFER_AMOUNT: &str = "0xfffffffffffffff";

- let transfer_amount = Felt::from_hex("0xfffffffffffffff")?;
+ let transfer_amount = Felt::from_hex(DEFAULT_TRANSFER_AMOUNT)?;

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

Comment on lines +115 to +232
paymaster_account.set_block_id(BlockId::Tag(BlockTag::Pending));

let (flattened_sierra_class, compiled_class_hash) =
get_compiled_contract_from_string(sierra, casm).await?;

let custom_account_class_hash = match paymaster_account
.declare_v3(flattened_sierra_class.clone(), compiled_class_hash)
.send()
.await
{
Ok(result) => {
wait_for_sent_transaction(result.transaction_hash, &paymaster_account).await?;
Ok(result.class_hash)
}
Err(AccountError::Signing(sign_error)) => {
if sign_error.to_string().contains("is already declared") {
Ok(parse_class_hash_from_error(&sign_error.to_string())?)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
sign_error
)),
))
}
}

Err(AccountError::Provider(ProviderError::Other(starkneterror))) => {
if starkneterror.to_string().contains("is already declared") {
Ok(parse_class_hash_from_error(&starkneterror.to_string())?)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
starkneterror
)),
))
}
}
Err(e) => {
let full_error_message = format!("{:?}", e);

if full_error_message.contains("is already declared") {
Ok(extract_class_hash_from_error(&full_error_message)?)
} else {
let full_error_message = format!("{:?}", e);

return Err(OpenRpcTestGenError::AccountError(AccountError::Other(
full_error_message,
)));
}
}
};

let account_data = create_account(
&provider,
AccountType::Oz,
Option::None,
Some(custom_account_class_hash?),
)
.await?;

let transfer_amount = Felt::from_hex("0xfffffffffffffff")?;

let transfer_execution = paymaster_account
.execute_v3(vec![Call {
to: STRK,
selector: get_selector_from_name("transfer")?,
calldata: vec![account_data.address, transfer_amount, Felt::ZERO],
}])
.send()
.await?;

wait_for_sent_transaction(transfer_execution.transaction_hash, &paymaster_account).await?;

let wait_config = WaitForTx {
wait: true,
wait_params: ValidatedWaitParams::default(),
};

let deployment_hash = deploy_account(
&provider,
chain_id,
wait_config,
account_data,
DeployAccountVersion::V3,
)
.await?;

wait_for_sent_transaction(deployment_hash, &paymaster_account).await?;

let account = SingleOwnerAccount::new(
provider.clone(),
LocalWallet::from(account_data.signing_key),
account_data.address,
chain_id,
ExecutionEncoding::New,
);
Ok(Self { account })
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Refactor error handling to reduce duplication.

The error handling logic in new_with_custom_account contains duplicated patterns. Consider extracting the common error handling logic into a separate function.

+ fn handle_declaration_error(error: AccountError) -> Result<Felt, OpenRpcTestGenError> {
+     match error {
+         AccountError::Signing(sign_error) => {
+             if sign_error.to_string().contains("is already declared") {
+                 Ok(parse_class_hash_from_error(&sign_error.to_string())?)
+             } else {
+                 Err(OpenRpcTestGenError::RunnerError(
+                     RunnerError::AccountFailure(format!(
+                         "Transaction execution error: {}",
+                         sign_error
+                     )),
+                 ))
+             }
+         }
+         AccountError::Provider(ProviderError::Other(starkneterror)) => {
+             if starkneterror.to_string().contains("is already declared") {
+                 Ok(parse_class_hash_from_error(&starkneterror.to_string())?)
+             } else {
+                 Err(OpenRpcTestGenError::RunnerError(
+                     RunnerError::AccountFailure(format!(
+                         "Transaction execution error: {}",
+                         starkneterror
+                     )),
+                 ))
+             }
+         }
+         e => {
+             let full_error_message = format!("{:?}", e);
+             if full_error_message.contains("is already declared") {
+                 Ok(extract_class_hash_from_error(&full_error_message)?)
+             } else {
+                 Err(OpenRpcTestGenError::AccountError(AccountError::Other(
+                     full_error_message,
+                 )))
+             }
+         }
+     }
+ }

  pub async fn new_with_custom_account(
      node_url: Url,
      paymaster_account_address: Felt,
      paymaster_private_key: Felt,
      sierra: String,
      casm: String,
  ) -> Result<Self, OpenRpcTestGenError> {
      // ... existing setup code ...

      let custom_account_class_hash = match paymaster_account
          .declare_v3(flattened_sierra_class.clone(), compiled_class_hash)
          .send()
          .await
      {
          Ok(result) => {
              wait_for_sent_transaction(result.transaction_hash, &paymaster_account).await?;
              Ok(result.class_hash)
          }
-         Err(AccountError::Signing(sign_error)) => {
-             if sign_error.to_string().contains("is already declared") {
-                 Ok(parse_class_hash_from_error(&sign_error.to_string())?)
-             } else {
-                 Err(OpenRpcTestGenError::RunnerError(
-                     RunnerError::AccountFailure(format!(
-                         "Transaction execution error: {}",
-                         sign_error
-                     )),
-                 ))
-             }
-         }
-         Err(AccountError::Provider(ProviderError::Other(starkneterror))) => {
-             if starkneterror.to_string().contains("is already declared") {
-                 Ok(parse_class_hash_from_error(&starkneterror.to_string())?)
-             } else {
-                 Err(OpenRpcTestGenError::RunnerError(
-                     RunnerError::AccountFailure(format!(
-                         "Transaction execution error: {}",
-                         starkneterror
-                     )),
-                 ))
-             }
-         }
-         Err(e) => {
-             let full_error_message = format!("{:?}", e);
-             if full_error_message.contains("is already declared") {
-                 Ok(extract_class_hash_from_error(&full_error_message)?)
-             } else {
-                 Err(OpenRpcTestGenError::AccountError(AccountError::Other(
-                     full_error_message,
-                 )))
-             }
-         }
+         Err(e) => handle_declaration_error(e)
      };

      // ... rest of the implementation ...
  }
📝 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
pub async fn new_with_custom_account(
node_url: Url,
paymaster_account_address: Felt,
paymaster_private_key: Felt,
sierra: String,
casm: String,
) -> Result<Self, OpenRpcTestGenError> {
let provider = JsonRpcClient::new(HttpTransport::new(node_url.clone()));
let chain_id = get_chain_id(&provider).await?;
let paymaster_private_key = SigningKey::from_secret_scalar(paymaster_private_key);
let mut paymaster_account = SingleOwnerAccount::new(
provider.clone(),
LocalWallet::from(paymaster_private_key),
paymaster_account_address,
chain_id,
ExecutionEncoding::New,
);
paymaster_account.set_block_id(BlockId::Tag(BlockTag::Pending));
let (flattened_sierra_class, compiled_class_hash) =
get_compiled_contract_from_string(sierra, casm).await?;
let custom_account_class_hash = match paymaster_account
.declare_v3(flattened_sierra_class.clone(), compiled_class_hash)
.send()
.await
{
Ok(result) => {
wait_for_sent_transaction(result.transaction_hash, &paymaster_account).await?;
Ok(result.class_hash)
}
Err(AccountError::Signing(sign_error)) => {
if sign_error.to_string().contains("is already declared") {
Ok(parse_class_hash_from_error(&sign_error.to_string())?)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
sign_error
)),
))
}
}
Err(AccountError::Provider(ProviderError::Other(starkneterror))) => {
if starkneterror.to_string().contains("is already declared") {
Ok(parse_class_hash_from_error(&starkneterror.to_string())?)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
starkneterror
)),
))
}
}
Err(e) => {
let full_error_message = format!("{:?}", e);
if full_error_message.contains("is already declared") {
Ok(extract_class_hash_from_error(&full_error_message)?)
} else {
let full_error_message = format!("{:?}", e);
return Err(OpenRpcTestGenError::AccountError(AccountError::Other(
full_error_message,
)));
}
}
};
let account_data = create_account(
&provider,
AccountType::Oz,
Option::None,
Some(custom_account_class_hash?),
)
.await?;
let transfer_amount = Felt::from_hex("0xfffffffffffffff")?;
let transfer_execution = paymaster_account
.execute_v3(vec![Call {
to: STRK,
selector: get_selector_from_name("transfer")?,
calldata: vec![account_data.address, transfer_amount, Felt::ZERO],
}])
.send()
.await?;
wait_for_sent_transaction(transfer_execution.transaction_hash, &paymaster_account).await?;
let wait_config = WaitForTx {
wait: true,
wait_params: ValidatedWaitParams::default(),
};
let deployment_hash = deploy_account(
&provider,
chain_id,
wait_config,
account_data,
DeployAccountVersion::V3,
)
.await?;
wait_for_sent_transaction(deployment_hash, &paymaster_account).await?;
let account = SingleOwnerAccount::new(
provider.clone(),
LocalWallet::from(account_data.signing_key),
account_data.address,
chain_id,
ExecutionEncoding::New,
);
Ok(Self { account })
}
fn handle_declaration_error(error: AccountError) -> Result<Felt, OpenRpcTestGenError> {
match error {
AccountError::Signing(sign_error) => {
if sign_error.to_string().contains("is already declared") {
Ok(parse_class_hash_from_error(&sign_error.to_string())?)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
sign_error
)),
))
}
}
AccountError::Provider(ProviderError::Other(starkneterror)) => {
if starkneterror.to_string().contains("is already declared") {
Ok(parse_class_hash_from_error(&starkneterror.to_string())?)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
starkneterror
)),
))
}
}
e => {
let full_error_message = format!("{:?}", e);
if full_error_message.contains("is already declared") {
Ok(extract_class_hash_from_error(&full_error_message)?)
} else {
Err(OpenRpcTestGenError::AccountError(AccountError::Other(
full_error_message,
)))
}
}
}
}
pub async fn new_with_custom_account(
node_url: Url,
paymaster_account_address: Felt,
paymaster_private_key: Felt,
sierra: String,
casm: String,
) -> Result<Self, OpenRpcTestGenError> {
let provider = JsonRpcClient::new(HttpTransport::new(node_url.clone()));
let chain_id = get_chain_id(&provider).await?;
let paymaster_private_key = SigningKey::from_secret_scalar(paymaster_private_key);
let mut paymaster_account = SingleOwnerAccount::new(
provider.clone(),
LocalWallet::from(paymaster_private_key),
paymaster_account_address,
chain_id,
ExecutionEncoding::New,
);
paymaster_account.set_block_id(BlockId::Tag(BlockTag::Pending));
let (flattened_sierra_class, compiled_class_hash) =
get_compiled_contract_from_string(sierra, casm).await?;
let custom_account_class_hash = match paymaster_account
.declare_v3(flattened_sierra_class.clone(), compiled_class_hash)
.send()
.await
{
Ok(result) => {
wait_for_sent_transaction(result.transaction_hash, &paymaster_account).await?;
Ok(result.class_hash)
}
Err(e) => handle_declaration_error(e)
};
let account_data = create_account(
&provider,
AccountType::Oz,
Option::None,
Some(custom_account_class_hash?),
)
.await?;
let transfer_amount = Felt::from_hex("0xfffffffffffffff")?;
let transfer_execution = paymaster_account
.execute_v3(vec![Call {
to: STRK,
selector: get_selector_from_name("transfer")?,
calldata: vec![account_data.address, transfer_amount, Felt::ZERO],
}])
.send()
.await?;
wait_for_sent_transaction(transfer_execution.transaction_hash, &paymaster_account).await?;
let wait_config = WaitForTx {
wait: true,
wait_params: ValidatedWaitParams::default(),
};
let deployment_hash = deploy_account(
&provider,
chain_id,
wait_config,
account_data,
DeployAccountVersion::V3,
)
.await?;
wait_for_sent_transaction(deployment_hash, &paymaster_account).await?;
let account = SingleOwnerAccount::new(
provider.clone(),
LocalWallet::from(account_data.signing_key),
account_data.address,
chain_id,
ExecutionEncoding::New,
);
Ok(Self { account })
}

Comment on lines +138 to +185
let custom_account_class_hash = match paymaster_account
.declare_v3(flattened_sierra_class.clone(), compiled_class_hash)
.send()
.await
{
Ok(result) => {
wait_for_sent_transaction(result.transaction_hash, &paymaster_account).await?;
Ok(result.class_hash)
}
Err(AccountError::Signing(sign_error)) => {
if sign_error.to_string().contains("is already declared") {
Ok(parse_class_hash_from_error(&sign_error.to_string())?)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
sign_error
)),
))
}
}

Err(AccountError::Provider(ProviderError::Other(starkneterror))) => {
if starkneterror.to_string().contains("is already declared") {
Ok(parse_class_hash_from_error(&starkneterror.to_string())?)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
starkneterror
)),
))
}
}
Err(e) => {
let full_error_message = format!("{:?}", e);

if full_error_message.contains("is already declared") {
Ok(extract_class_hash_from_error(&full_error_message)?)
} else {
let full_error_message = format!("{:?}", e);

return Err(OpenRpcTestGenError::AccountError(AccountError::Other(
full_error_message,
)));
}
}
};
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Simplify error handling logic.

The error handling for contract declaration could be simplified to reduce code duplication. Consider extracting the common error handling pattern into a helper function.

+ fn handle_declaration_error(error: &impl std::fmt::Display) -> Result<Felt, OpenRpcTestGenError> {
+     let error_message = error.to_string();
+     if error_message.contains("is already declared") {
+         parse_class_hash_from_error(&error_message)
+     } else {
+         Err(OpenRpcTestGenError::RunnerError(
+             RunnerError::AccountFailure(format!(
+                 "Transaction execution error: {}",
+                 error_message
+             )),
+         ))
+     }
+ }
+
  let custom_account_class_hash = match paymaster_account
      .declare_v3(flattened_sierra_class.clone(), compiled_class_hash)
      .send()
      .await
  {
      Ok(result) => {
          wait_for_sent_transaction(result.transaction_hash, &paymaster_account).await?;
          Ok(result.class_hash)
      }
-     Err(AccountError::Signing(sign_error)) => {
-         if sign_error.to_string().contains("is already declared") {
-             Ok(parse_class_hash_from_error(&sign_error.to_string())?)
-         } else {
-             Err(OpenRpcTestGenError::RunnerError(
-                 RunnerError::AccountFailure(format!(
-                     "Transaction execution error: {}",
-                     sign_error
-                 )),
-             ))
-         }
-     }
-     Err(AccountError::Provider(ProviderError::Other(starkneterror))) => {
-         if starkneterror.to_string().contains("is already declared") {
-             Ok(parse_class_hash_from_error(&starkneterror.to_string())?)
-         } else {
-             Err(OpenRpcTestGenError::RunnerError(
-                 RunnerError::AccountFailure(format!(
-                     "Transaction execution error: {}",
-                     starkneterror
-                 )),
-             ))
-         }
-     }
-     Err(e) => {
-         let full_error_message = format!("{:?}", e);
-         if full_error_message.contains("is already declared") {
-             Ok(extract_class_hash_from_error(&full_error_message)?)
-         } else {
-             let full_error_message = format!("{:?}", e);
-             return Err(OpenRpcTestGenError::AccountError(AccountError::Other(
-                 full_error_message,
-             )));
-         }
-     }
+     Err(AccountError::Signing(sign_error)) => handle_declaration_error(&sign_error),
+     Err(AccountError::Provider(ProviderError::Other(starkneterror))) => {
+         handle_declaration_error(&starkneterror)
+     }
+     Err(e) => {
+         let full_error_message = format!("{:?}", e);
+         if full_error_message.contains("is already declared") {
+             Ok(extract_class_hash_from_error(&full_error_message)?)
+         } else {
+             Err(OpenRpcTestGenError::AccountError(AccountError::Other(
+                 full_error_message,
+             )))
+         }
+     }
  };
📝 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
let custom_account_class_hash = match paymaster_account
.declare_v3(flattened_sierra_class.clone(), compiled_class_hash)
.send()
.await
{
Ok(result) => {
wait_for_sent_transaction(result.transaction_hash, &paymaster_account).await?;
Ok(result.class_hash)
}
Err(AccountError::Signing(sign_error)) => {
if sign_error.to_string().contains("is already declared") {
Ok(parse_class_hash_from_error(&sign_error.to_string())?)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
sign_error
)),
))
}
}
Err(AccountError::Provider(ProviderError::Other(starkneterror))) => {
if starkneterror.to_string().contains("is already declared") {
Ok(parse_class_hash_from_error(&starkneterror.to_string())?)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
starkneterror
)),
))
}
}
Err(e) => {
let full_error_message = format!("{:?}", e);
if full_error_message.contains("is already declared") {
Ok(extract_class_hash_from_error(&full_error_message)?)
} else {
let full_error_message = format!("{:?}", e);
return Err(OpenRpcTestGenError::AccountError(AccountError::Other(
full_error_message,
)));
}
}
};
fn handle_declaration_error(error: &impl std::fmt::Display) -> Result<Felt, OpenRpcTestGenError> {
let error_message = error.to_string();
if error_message.contains("is already declared") {
parse_class_hash_from_error(&error_message)
} else {
Err(OpenRpcTestGenError::RunnerError(
RunnerError::AccountFailure(format!(
"Transaction execution error: {}",
error_message
)),
))
}
}
let custom_account_class_hash = match paymaster_account
.declare_v3(flattened_sierra_class.clone(), compiled_class_hash)
.send()
.await
{
Ok(result) => {
wait_for_sent_transaction(result.transaction_hash, &paymaster_account).await?;
Ok(result.class_hash)
}
Err(AccountError::Signing(sign_error)) => handle_declaration_error(&sign_error),
Err(AccountError::Provider(ProviderError::Other(starkneterror))) => {
handle_declaration_error(&starkneterror)
}
Err(e) => {
let full_error_message = format!("{:?}", e);
if full_error_message.contains("is already declared") {
Ok(extract_class_hash_from_error(&full_error_message)?)
} else {
Err(OpenRpcTestGenError::AccountError(AccountError::Other(
full_error_message,
)))
}
}
};

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