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

Introduce StarknetCommandError for declare, deploy, invoke and call #1710

Merged
merged 7 commits into from
Feb 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/sncast/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ tokio.workspace = true
url.workspace = true
rand.workspace = true
scarb-metadata.workspace = true
thiserror.workspace = true
primitive-types = "0.12.1"
shellexpand = "3.1.0"
toml = "0.8.9"
Expand Down
134 changes: 91 additions & 43 deletions crates/sncast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use serde_json::Value;
use starknet::core::types::{
BlockId,
BlockTag::{Latest, Pending},
FieldElement,
ContractErrorData, FieldElement,
StarknetError::{
BlockNotFound, ClassAlreadyDeclared, ClassHashNotFound, CompilationFailed,
CompiledClassHashMismatch, ContractClassSizeIsTooLarge, ContractError, ContractNotFound,
Expand Down Expand Up @@ -37,6 +37,7 @@ use std::collections::HashMap;
use std::thread::sleep;
use std::time::Duration;
use std::{env, fs};
use thiserror::Error;

pub mod helpers;
pub mod response;
Expand Down Expand Up @@ -234,7 +235,7 @@ async fn verify_account_address(account: impl ConnectedAccount + std::marker::Sy
if let StarknetError(ContractNotFound) = error {
Err(anyhow!("Invalid account address"))
} else {
handle_rpc_error::<()>(error)
Err(handle_rpc_error(error))
}
}
}
Expand Down Expand Up @@ -330,18 +331,58 @@ pub fn get_block_id(value: &str) -> Result<BlockId> {
}
}

#[derive(Debug)]
pub struct ErrorData {
pub data: String,
}

impl ErrorData {
#[must_use]
pub fn new(data: String) -> Self {
ErrorData { data }
}
}

impl From<ContractErrorData> for ErrorData {
fn from(value: ContractErrorData) -> Self {
ErrorData {
data: value.revert_error,
}
}
}

#[derive(Error, Debug)]
pub enum TransactionError {
#[error("Transaction has been rejected")]
Rejected,
#[error("Transaction has been reverted = {}", .0.data)]
Reverted(ErrorData),
}

#[derive(Error, Debug)]
pub enum WaitForTransactionError {
#[error(transparent)]
TransactionError(TransactionError),
#[error("sncast timed out while waiting for transaction to succeed")]
TimedOut,
#[error(transparent)]
ProviderError(#[from] ProviderError),
}

pub async fn wait_for_tx(
provider: &JsonRpcClient<HttpTransport>,
tx_hash: FieldElement,
wait_params: ValidatedWaitParams,
) -> Result<&str> {
) -> Result<&str, WaitForTransactionError> {
println!("Transaction hash = {tx_hash:#x}");

let retries = wait_params.get_retries();
for i in (1..retries).rev() {
match provider.get_transaction_status(tx_hash).await {
Ok(starknet::core::types::TransactionStatus::Rejected) => {
return Err(anyhow!("Transaction has been rejected"));
return Err(WaitForTransactionError::TransactionError(
TransactionError::Rejected,
));
}
Ok(
starknet::core::types::TransactionStatus::AcceptedOnL2(execution_status)
Expand All @@ -359,78 +400,85 @@ pub async fn wait_for_tx(
let remaining_time = wait_params.remaining_time(i);
println!("Waiting for transaction to be accepted ({i} retries / {remaining_time}s left until timeout)");
}
Err(ProviderError::RateLimited) => {
println!("Request rate limited while waiting for transaction to be accepted");
sleep(Duration::from_secs(wait_params.get_retry_interval().into()));
}
Err(err) => return Err(err.into()),
};

sleep(Duration::from_secs(wait_params.get_retry_interval().into()));
}

Err(anyhow!(
"Failed to get transaction with hash = {tx_hash:#x}; Transaction rejected, not received or sncast timed out"
))
Err(WaitForTransactionError::TimedOut)
}

async fn get_revert_reason(
provider: &JsonRpcClient<HttpTransport>,
tx_hash: FieldElement,
) -> Result<&str> {
) -> Result<&str, WaitForTransactionError> {
let receipt = provider.get_transaction_receipt(tx_hash).await?;

if let starknet::core::types::ExecutionResult::Reverted { reason } = receipt.execution_result()
{
Err(anyhow!("Transaction has been reverted = {reason}"))
Err(WaitForTransactionError::TransactionError(
TransactionError::Reverted(ErrorData {
data: reason.clone(),
}),
))
} else {
unreachable!();
}
}

pub fn handle_rpc_error<T>(error: ProviderError) -> std::result::Result<T, Error> {
#[must_use]
pub fn handle_rpc_error(error: ProviderError) -> Error {
match error {
StarknetError(FailedToReceiveTransaction) => {
Err(anyhow!("Node failed to receive transaction"))
anyhow!("Node failed to receive transaction")
}
StarknetError(ContractNotFound) => {
Err(anyhow!("There is no contract at the specified address"))
anyhow!("There is no contract at the specified address")
}
StarknetError(BlockNotFound) => anyhow!("Block was not found"),
StarknetError(TransactionHashNotFound) => {
anyhow!("Transaction with provided hash was not found (does not exist)")
}
StarknetError(BlockNotFound) => Err(anyhow!("Block was not found")),
StarknetError(TransactionHashNotFound) => Err(anyhow!(
"Transaction with provided hash was not found (does not exist)"
)),
StarknetError(InvalidTransactionIndex) => {
Err(anyhow!("There is no transaction with such an index"))
anyhow!("There is no transaction with such an index")
}
StarknetError(ClassHashNotFound) => anyhow!("Provided class hash does not exist"),
StarknetError(ContractError(err)) => {
anyhow!("An error occurred in the called contract = {err:?}")
}
StarknetError(InvalidTransactionNonce) => anyhow!("Invalid transaction nonce"),
StarknetError(InsufficientMaxFee) => {
anyhow!("Max fee is smaller than the minimal transaction cost")
}
StarknetError(InsufficientAccountBalance) => {
anyhow!("Account balance is too small to cover transaction fee")
}
StarknetError(ClassAlreadyDeclared) => {
anyhow!("Contract with the same class hash is already declared")
}
StarknetError(ClassHashNotFound) => Err(anyhow!("Provided class hash does not exist")),
StarknetError(ContractError(err)) => Err(anyhow!(
"An error occurred in the called contract = {err:?}"
)),
StarknetError(InvalidTransactionNonce) => Err(anyhow!("Invalid transaction nonce")),
StarknetError(InsufficientMaxFee) => Err(anyhow!(
"Max fee is smaller than the minimal transaction cost"
)),
StarknetError(InsufficientAccountBalance) => Err(anyhow!(
"Account balance is too small to cover transaction fee"
)),
StarknetError(ClassAlreadyDeclared) => Err(anyhow!(
"Contract with the same class hash is already declared"
)),
StarknetError(TransactionExecutionError(err)) => {
Err(anyhow!("Transaction execution error = {err:?}"))
anyhow!("Transaction execution error = {err:?}")
}
StarknetError(ValidationFailure(err)) => {
Err(anyhow!("Contract failed the validation = {err}"))
anyhow!("Contract failed the validation = {err}")
}
StarknetError(CompilationFailed) => Err(anyhow!("Contract failed to compile in starknet")),
StarknetError(CompilationFailed) => anyhow!("Contract failed to compile in starknet"),
StarknetError(ContractClassSizeIsTooLarge) => {
Err(anyhow!("Contract class size is too large"))
anyhow!("Contract class size is too large")
}
StarknetError(NonAccount) => Err(anyhow!("No account")),
StarknetError(DuplicateTx) => Err(anyhow!("Transaction already exists")),
StarknetError(CompiledClassHashMismatch) => Err(anyhow!("Compiled class hash mismatch")),
StarknetError(UnsupportedTxVersion) => Err(anyhow!("Unsupported transaction version")),
StarknetError(NonAccount) => anyhow!("No account"),
StarknetError(DuplicateTx) => anyhow!("Transaction already exists"),
StarknetError(CompiledClassHashMismatch) => anyhow!("Compiled class hash mismatch"),
StarknetError(UnsupportedTxVersion) => anyhow!("Unsupported transaction version"),
StarknetError(UnsupportedContractClassVersion) => {
Err(anyhow!("Unsupported contract class version"))
anyhow!("Unsupported contract class version")
}
_ => Err(anyhow!("Unknown RPC error")),
_ => anyhow!("Unknown RPC error"),
}
}

Expand All @@ -439,11 +487,11 @@ pub async fn handle_wait_for_tx<T>(
transaction_hash: FieldElement,
return_value: T,
wait_config: WaitForTx,
) -> Result<T> {
) -> Result<T, WaitForTransactionError> {
if wait_config.wait {
return match wait_for_tx(provider, transaction_hash, wait_config.wait_params).await {
Ok(_) => Ok(return_value),
Err(message) => Err(anyhow!(message)),
Err(error) => Err(error),
};
}

Expand Down
13 changes: 9 additions & 4 deletions crates/sncast/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use sncast::helpers::scarb_utils::{
assert_manifest_path_exists, build_and_load_artifacts, get_package_metadata,
get_scarb_metadata_with_deps, BuildConfig,
};
use sncast::response::errors::handle_starknet_command_error;
use sncast::{
chain_id_to_network_name, get_account, get_block_id, get_chain_id, get_nonce, get_provider,
NumbersFormat, ValidatedWaitParams, WaitForTx,
Expand Down Expand Up @@ -180,7 +181,8 @@ async fn run_async_command(
&artifacts,
wait_config,
)
.await;
.await
.map_err(handle_starknet_command_error);
THenry14 marked this conversation as resolved.
Show resolved Hide resolved

print_command_result("declare", &mut result, numbers_format, &output_format)?;
Ok(())
Expand All @@ -203,7 +205,8 @@ async fn run_async_command(
deploy.nonce,
wait_config,
)
.await;
.await
.map_err(handle_starknet_command_error);

print_command_result("deploy", &mut result, numbers_format, &output_format)?;
Ok(())
Expand All @@ -218,7 +221,8 @@ async fn run_async_command(
&provider,
block_id.as_ref(),
)
.await;
.await
.map_err(handle_starknet_command_error);

print_command_result("call", &mut result, numbers_format, &output_format)?;
Ok(())
Expand All @@ -240,7 +244,8 @@ async fn run_async_command(
invoke.nonce,
wait_config,
)
.await;
.await
.map_err(handle_starknet_command_error);

print_command_result("invoke", &mut result, numbers_format, &output_format)?;
Ok(())
Expand Down
45 changes: 45 additions & 0 deletions crates/sncast/src/response/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use crate::{handle_rpc_error, ErrorData, WaitForTransactionError};
use anyhow;
use starknet::providers::ProviderError;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum StarknetCommandError {
#[error(transparent)]
Unrecoverable(anyhow::Error),
#[error(transparent)]
Recoverable(#[from] RecoverableStarknetCommandError),
}

#[derive(Error, Debug)]
pub enum RecoverableStarknetCommandError {
#[error("Failed to find {} artifact in starknet_artifacts.json file. Please make sure you have specified correct package using `--package` flag and that you have enabled sierra and casm code generation in Scarb.toml.", .0.data)]
ContractArtifactsNotFound(ErrorData),
#[error(transparent)]
WaitForTransactionError(#[from] WaitForTransactionError),
#[error(transparent)]
ProviderError(ProviderError),
}

impl From<anyhow::Error> for StarknetCommandError {
fn from(value: anyhow::Error) -> Self {
StarknetCommandError::Unrecoverable(value)
}
}

impl From<WaitForTransactionError> for StarknetCommandError {
fn from(value: WaitForTransactionError) -> Self {
StarknetCommandError::Recoverable(value.into())
}
}

#[must_use]
pub fn handle_starknet_command_error(error: StarknetCommandError) -> anyhow::Error {
match error {
StarknetCommandError::Unrecoverable(error) => error,
StarknetCommandError::Recoverable(error) => match error {
RecoverableStarknetCommandError::ProviderError(err) => handle_rpc_error(err),
_ => error.into(),
},
}
}
1 change: 1 addition & 0 deletions crates/sncast/src/response/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod errors;
pub mod print;
pub mod structs;
4 changes: 2 additions & 2 deletions crates/sncast/src/starknet_commands/account/deploy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ async fn deploy_oz_account(
} else {
match deployment.estimate_fee().await {
Ok(max_fee) => max_fee.overall_fee,
Err(AccountFactoryError::Provider(error)) => return handle_rpc_error(error),
Err(AccountFactoryError::Provider(error)) => return Err(handle_rpc_error(error)),
Err(error) => bail!(error),
}
};
Expand All @@ -286,7 +286,7 @@ async fn deploy_oz_account(
"Provided class hash {:#x} does not exist",
oz_class_hash,
)),
_ => handle_rpc_error(error),
_ => Err(handle_rpc_error(error)),
},
Err(_) => Err(anyhow!("Unknown RPC error")),
Ok(result) => {
Expand Down
8 changes: 5 additions & 3 deletions crates/sncast/src/starknet_commands/call.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use anyhow::{Context, Result};
use clap::Args;
use sncast::handle_rpc_error;
use sncast::response::errors::{RecoverableStarknetCommandError, StarknetCommandError};
use sncast::response::structs::{CallResponse, Felt};
use starknet::core::types::{BlockId, FieldElement, FunctionCall};
use starknet::core::utils::get_selector_from_name;
Expand Down Expand Up @@ -36,7 +36,7 @@ pub async fn call(
calldata: Vec<FieldElement>,
provider: &JsonRpcClient<HttpTransport>,
block_id: &BlockId,
) -> Result<CallResponse> {
) -> Result<CallResponse, StarknetCommandError> {
let function_call = FunctionCall {
contract_address,
entry_point_selector: get_selector_from_name(func_name)
Expand All @@ -50,6 +50,8 @@ pub async fn call(

match res {
Ok(response) => Ok(CallResponse { response }),
Err(error) => handle_rpc_error(error),
Err(error) => Err(StarknetCommandError::Recoverable(
RecoverableStarknetCommandError::ProviderError(error),
)),
}
}
Loading
Loading