diff --git a/crates/client/rpc/src/methods/read/estimate_fee.rs b/crates/client/rpc/src/methods/read/estimate_fee.rs index 324ba6952..d418f27bd 100644 --- a/crates/client/rpc/src/methods/read/estimate_fee.rs +++ b/crates/client/rpc/src/methods/read/estimate_fee.rs @@ -1,9 +1,10 @@ +use blockifier::transaction::account_transaction::AccountTransaction; use deoxys_runtime::opaque::DBlockT; use jsonrpsee::core::RpcResult; use mc_genesis_data_provider::GenesisProvider; use mp_hashers::HasherT; use mp_simulations::convert_flags; -use mp_transactions::UserTransaction; +use mp_transactions::from_broadcasted_transactions::ToAccountTransaction; use pallet_starknet_runtime_api::{ConvertTransactionRuntimeApi, StarknetRuntimeApi}; use sc_client_api::backend::{Backend, StorageProvider}; use sc_client_api::BlockBackend; @@ -49,13 +50,17 @@ where StarknetRpcApiError::BlockNotFound })?; - let transactions = - request.into_iter().map(|tx| tx.try_into()).collect::, _>>().map_err(|e| { - log::error!("Failed to convert BroadcastedTransaction to UserTransaction: {e}"); + let transactions = request + .into_iter() + .map(|tx| tx.to_account_transaction()) + .collect::, _>>() + .map_err(|e| { + log::error!("Failed to convert BroadcastedTransaction to AccountTransaction: {e}"); StarknetRpcApiError::InternalServerError })?; - let account_transactions: Vec = transactions.into_iter().map(UserTransaction::from).collect(); + let account_transactions: Vec = + transactions.into_iter().map(AccountTransaction::from).collect(); let simulation_flags = convert_flags(simulation_flags); diff --git a/crates/client/rpc/src/methods/read/get_transaction_receipt.rs b/crates/client/rpc/src/methods/read/get_transaction_receipt.rs index 722126281..f423a3b58 100644 --- a/crates/client/rpc/src/methods/read/get_transaction_receipt.rs +++ b/crates/client/rpc/src/methods/read/get_transaction_receipt.rs @@ -18,7 +18,6 @@ use mp_felt::Felt252Wrapper; use mp_hashers::pedersen::PedersenHasher; use mp_hashers::HasherT; use mp_transactions::compute_hash::ComputeTransactionHash; -use mp_transactions::tx_into_user_or_l1_vec; use pallet_starknet_runtime_api::{ConvertTransactionRuntimeApi, StarknetRuntimeApi}; use sc_client_api::backend::{Backend, StorageProvider}; use sc_client_api::BlockBackend; @@ -586,12 +585,7 @@ where let execution_infos = client .client .runtime_api() - .re_execute_transactions( - previous_block_hash, - tx_into_user_or_l1_vec(prev), - tx_into_user_or_l1_vec(last), - block_context, - ) + .re_execute_transactions(previous_block_hash, prev, last, block_context) .map_err(|e| { log::error!("Failed to execute runtime API call: {e}"); StarknetRpcApiError::InternalServerError diff --git a/crates/client/rpc/src/methods/trace/simulate_transactions.rs b/crates/client/rpc/src/methods/trace/simulate_transactions.rs index 22ac8edd0..ae8aed685 100644 --- a/crates/client/rpc/src/methods/trace/simulate_transactions.rs +++ b/crates/client/rpc/src/methods/trace/simulate_transactions.rs @@ -5,6 +5,7 @@ use mc_genesis_data_provider::GenesisProvider; use mc_storage::StorageOverride; use mp_hashers::HasherT; use mp_simulations::{PlaceHolderErrorTypeForFailedStarknetExecution, SimulationFlags}; +use mp_transactions::from_broadcasted_transactions::ToAccountTransaction; use mp_transactions::TxType; use pallet_starknet_runtime_api::{ConvertTransactionRuntimeApi, StarknetRuntimeApi}; use sc_client_api::{Backend, BlockBackend, StorageProvider}; @@ -43,11 +44,9 @@ where starknet.substrate_block_hash_from_starknet_block(block_id).map_err(|_e| StarknetRpcApiError::BlockNotFound)?; let tx_type_and_tx_iterator = transactions.into_iter().map(|tx| match tx { - BroadcastedTransaction::Invoke(invoke_tx) => invoke_tx.try_into().map(|tx| (TxType::Invoke, tx)), - BroadcastedTransaction::Declare(declare_tx) => declare_tx.try_into().map(|tx| (TxType::Declare, tx)), - BroadcastedTransaction::DeployAccount(deploy_account_tx) => { - deploy_account_tx.try_into().map(|tx| (TxType::DeployAccount, tx)) - } + BroadcastedTransaction::Invoke(_) => tx.to_account_transaction().map(|tx| (TxType::Invoke, tx)), + BroadcastedTransaction::Declare(_) => tx.to_account_transaction().map(|tx| (TxType::Declare, tx)), + BroadcastedTransaction::DeployAccount(_) => tx.to_account_transaction().map(|tx| (TxType::DeployAccount, tx)), }); let (tx_types, user_transactions) = itertools::process_results(tx_type_and_tx_iterator, |iter| iter.unzip::<_, _, Vec<_>, Vec<_>>()).map_err( diff --git a/crates/client/rpc/src/methods/trace/trace_block_transactions.rs b/crates/client/rpc/src/methods/trace/trace_block_transactions.rs index 0ec921815..e7148a718 100644 --- a/crates/client/rpc/src/methods/trace/trace_block_transactions.rs +++ b/crates/client/rpc/src/methods/trace/trace_block_transactions.rs @@ -3,6 +3,7 @@ use jsonrpsee::core::RpcResult; use mc_genesis_data_provider::GenesisProvider; use mp_felt::Felt252Wrapper; use mp_hashers::HasherT; +use mp_transactions::getters::{Getters, Hash}; use mp_transactions::TxType; use pallet_starknet_runtime_api::{ConvertTransactionRuntimeApi, StarknetRuntimeApi}; use sc_client_api::{Backend, BlockBackend, StorageProvider}; @@ -94,7 +95,7 @@ where &**storage_override, substrate_block_hash, // Safe to unwrap coz re_execute returns exactly one ExecutionInfo for each tx - TxType::from(block_transactions.get(tx_idx).unwrap().tx_type()), + TxType::from(block_transactions.get(tx_idx).unwrap()), &tx_exec_info, ) .map(|trace_root| TransactionTraceWithHash { diff --git a/crates/client/rpc/src/methods/trace/trace_transaction.rs b/crates/client/rpc/src/methods/trace/trace_transaction.rs index 08587104d..490d5d51d 100644 --- a/crates/client/rpc/src/methods/trace/trace_transaction.rs +++ b/crates/client/rpc/src/methods/trace/trace_transaction.rs @@ -4,6 +4,7 @@ use mc_db::DeoxysBackend; use mc_genesis_data_provider::GenesisProvider; use mp_felt::Felt252Wrapper; use mp_hashers::HasherT; +use mp_transactions::TxType; use pallet_starknet_runtime_api::{ConvertTransactionRuntimeApi, StarknetRuntimeApi}; use sc_client_api::{Backend, BlockBackend, StorageProvider}; use sc_transaction_pool::ChainApi; @@ -96,7 +97,7 @@ where let trace = tx_execution_infos_to_tx_trace( &**storage_override, substrate_block_hash, - tx_to_trace.get(0).unwrap().tx_type(), + TxType::from(tx_to_trace.get(0).unwrap()), &execution_infos[0], ) .unwrap(); diff --git a/crates/client/rpc/src/methods/trace/utils.rs b/crates/client/rpc/src/methods/trace/utils.rs index f6815102c..c57bf0f3a 100644 --- a/crates/client/rpc/src/methods/trace/utils.rs +++ b/crates/client/rpc/src/methods/trace/utils.rs @@ -5,6 +5,7 @@ use blockifier::execution::contract_class::{ClassInfo, ContractClass, ContractCl use blockifier::transaction as btx; use blockifier::transaction::account_transaction::AccountTransaction; use blockifier::transaction::objects::TransactionExecutionInfo; +use blockifier::transaction::transaction_execution::Transaction; use blockifier::transaction::transactions::L1HandlerTransaction; use deoxys_runtime::opaque::{DBlockT, DHashT}; use mc_db::DeoxysBackend; @@ -13,7 +14,7 @@ use mp_block::DeoxysBlock; use mp_felt::Felt252Wrapper; use mp_hashers::HasherT; use mp_transactions::compute_hash::ComputeTransactionHash; -use mp_transactions::{TxType, UserOrL1HandlerTransaction}; +use mp_transactions::TxType; use pallet_starknet_runtime_api::{ConvertTransactionRuntimeApi, StarknetRuntimeApi}; use sc_client_api::{Backend, BlockBackend, StorageProvider}; use sc_transaction_pool::ChainApi; @@ -263,7 +264,7 @@ pub fn map_transaction_to_user_transaction( substrate_block_hash: DHashT, chain_id: Felt252Wrapper, target_transaction_hash: Option, -) -> Result<(Vec, Vec), StarknetRpcApiError> +) -> Result<(Vec, Vec), StarknetRpcApiError> where A: ChainApi + 'static, C: HeaderBackend + BlockBackend + StorageProvider + 'static, @@ -296,7 +297,7 @@ fn convert_transaction( substrate_block_hash: DHashT, chain_id: Felt252Wrapper, block_number: u64, -) -> Result +) -> Result where A: ChainApi + 'static, C: HeaderBackend + BlockBackend + StorageProvider + 'static, @@ -311,7 +312,7 @@ where // TODO: Check if this is correct only_query: false, }; - Ok(UserOrL1HandlerTransaction::User(AccountTransaction::Invoke(tx))) + Ok(Transaction::AccountTransaction(AccountTransaction::Invoke(tx))) } stx::Transaction::DeployAccount(deploy_account_tx) => { let tx = btx::transactions::DeployAccountTransaction { @@ -322,7 +323,7 @@ where // TODO: Check if this is correct only_query: false, }; - Ok(UserOrL1HandlerTransaction::User(AccountTransaction::DeployAccount(tx))) + Ok(Transaction::AccountTransaction(AccountTransaction::DeployAccount(tx))) } stx::Transaction::Declare(declare_tx) => { let class_hash = ClassHash::from(Felt252Wrapper::from(*declare_tx.class_hash())); @@ -348,7 +349,7 @@ where ) .unwrap(); - Ok(UserOrL1HandlerTransaction::User(AccountTransaction::Declare(tx))) + Ok(Transaction::AccountTransaction(AccountTransaction::Declare(tx))) } stx::DeclareTransaction::V2(_tx) => { let contract_class = DeoxysBackend::sierra_classes() @@ -383,7 +384,7 @@ where ) .unwrap(); - Ok(UserOrL1HandlerTransaction::User(AccountTransaction::Declare(tx))) + Ok(Transaction::AccountTransaction(AccountTransaction::Declare(tx))) } stx::DeclareTransaction::V3(_) => todo!(), } @@ -397,7 +398,7 @@ where StarknetRpcApiError::InternalServerError })?; - Ok(UserOrL1HandlerTransaction::L1Handler(L1HandlerTransaction { + Ok(Transaction::L1HandlerTransaction(L1HandlerTransaction { tx: handle_l1_message_tx.clone(), tx_hash, paid_fee_on_l1, diff --git a/crates/pallets/starknet/runtime_api/src/lib.rs b/crates/pallets/starknet/runtime_api/src/lib.rs index 7d499d52a..20eeabca6 100644 --- a/crates/pallets/starknet/runtime_api/src/lib.rs +++ b/crates/pallets/starknet/runtime_api/src/lib.rs @@ -7,10 +7,11 @@ use blockifier::context::{BlockContext, FeeTokenAddresses}; use blockifier::execution::contract_class::ContractClass; +use blockifier::transaction::account_transaction::AccountTransaction; use blockifier::transaction::objects::TransactionExecutionInfo; +use blockifier::transaction::transaction_execution::Transaction; use blockifier::transaction::transactions::L1HandlerTransaction; use mp_felt::Felt252Wrapper; -use mp_transactions::{UserOrL1HandlerTransaction, UserTransaction}; use sp_api::BlockT; pub extern crate alloc; use alloc::vec::Vec; @@ -58,13 +59,13 @@ sp_api::decl_runtime_apis! { /// Returns the fee token address. fn fee_token_addresses() -> FeeTokenAddresses; /// Returns fee estimate - fn estimate_fee(transactions: Vec, simulation_flags: Vec,) -> Result, DispatchError>; + fn estimate_fee(transactions: Vec, simulation_flags: Vec,) -> Result, DispatchError>; /// Returns message fee estimate fn estimate_message_fee(message: L1HandlerTransaction) -> Result<(u128, u128, u128), DispatchError>; /// Simulates single L1 Message and returns its trace fn simulate_message(message: L1HandlerTransaction, simulation_flags: SimulationFlags) -> Result, DispatchError>; /// Simulates transactions and returns their trace - fn simulate_transactions(transactions: Vec, simulation_flags: SimulationFlags) -> Result>, DispatchError>; + fn simulate_transactions(transactions: Vec, simulation_flags: SimulationFlags) -> Result>, DispatchError>; /// Filters extrinsic transactions to return only Starknet transactions /// @@ -86,7 +87,7 @@ sp_api::decl_runtime_apis! { /// /// Idealy, the execution traces of all of `transactions_to_trace`. /// If any of the transactions (from both arguments) fails, an error is returned. - fn re_execute_transactions(transactions_before: Vec, transactions_to_trace: Vec, block_context: &BlockContext) -> Result, PlaceHolderErrorTypeForFailedStarknetExecution>, DispatchError>; + fn re_execute_transactions(transactions_before: Vec, transactions_to_trace: Vec, block_context: &BlockContext) -> Result, PlaceHolderErrorTypeForFailedStarknetExecution>, DispatchError>; fn get_events_for_tx_by_hash(tx_hash: TransactionHash) -> Vec; // fn get_index_and_tx_for_tx_hash(xts: Vec<::Extrinsic>, chain_id: Felt252Wrapper, tx_hash: TransactionHash) -> Option<(u32, Transaction)>; diff --git a/crates/pallets/starknet/src/simulations.rs b/crates/pallets/starknet/src/simulations.rs index d75477421..154794b41 100644 --- a/crates/pallets/starknet/src/simulations.rs +++ b/crates/pallets/starknet/src/simulations.rs @@ -11,7 +11,6 @@ use blockifier::transaction::transaction_execution::Transaction; use blockifier::transaction::transactions::{ExecutableTransaction, L1HandlerTransaction}; use frame_support::storage; use mp_simulations::{PlaceHolderErrorTypeForFailedStarknetExecution, SimulationFlagForEstimateFee, SimulationFlags}; -use mp_transactions::{user_or_l1_into_tx_vec, UserOrL1HandlerTransaction, UserTransaction}; use sp_core::Get; use sp_runtime::DispatchError; use starknet_api::core::{ContractAddress, EntryPointSelector}; @@ -22,7 +21,7 @@ use crate::{Config, Error, Pallet}; impl Pallet { pub fn estimate_fee( - transactions: Vec, + transactions: Vec, simulation_flags: &Vec, ) -> Result, DispatchError> { storage::transactional::with_transaction(|| { @@ -35,7 +34,7 @@ impl Pallet { } fn estimate_fee_inner( - transactions: Vec, + transactions: Vec, simulation_flags: &Vec, ) -> Result, DispatchError> { let transactions_len = transactions.len(); @@ -60,7 +59,7 @@ impl Pallet { } pub fn simulate_transactions( - transactions: Vec, + transactions: Vec, simulation_flags: &SimulationFlags, ) -> Result>, DispatchError> { @@ -74,7 +73,7 @@ impl Pallet { } fn simulate_transactions_inner( - transactions: Vec, + transactions: Vec, simulation_flags: &SimulationFlags, ) -> Result>, DispatchError> { @@ -83,7 +82,13 @@ impl Pallet { let tx_execution_results = transactions .into_iter() .map(|tx| { - Self::execute_account_transaction(tx.into(), &block_context, simulation_flags).map_err(|e| { + tx.execute( + &mut Self::init_cached_state(), + &block_context, + simulation_flags.charge_fee, + simulation_flags.validate, + ) + .map_err(|e| { log::error!("Transaction execution failed during simulation: {e}"); PlaceHolderErrorTypeForFailedStarknetExecution }) @@ -159,8 +164,8 @@ impl Pallet { } pub fn re_execute_transactions( - transactions_before: Vec, - transactions_to_trace: Vec, + transactions_before: Vec, + transactions_to_trace: Vec, block_context: &BlockContext, ) -> Result, PlaceHolderErrorTypeForFailedStarknetExecution>, DispatchError> { @@ -175,39 +180,33 @@ impl Pallet { } fn re_execute_transactions_inner( - transactions_before: Vec, - transactions_to_trace: Vec, + transactions_before: Vec, + transactions_to_trace: Vec, block_context: &BlockContext, ) -> Result, PlaceHolderErrorTypeForFailedStarknetExecution>, DispatchError> { - // desactivate fee charging for the first blocks - let simulation_flags = SimulationFlags { - charge_fee: if block_context.block_info().gas_prices.eth_l1_gas_price.get() == 1 { false } else { true }, - validate: false, - }; - - let _transactions_before_exec_infos = Self::execute_account_or_l1_handler_transactions( - user_or_l1_into_tx_vec(transactions_before), - &block_context, - &simulation_flags, - ); - let transactions_exec_infos = Self::execute_account_or_l1_handler_transactions( - user_or_l1_into_tx_vec(transactions_to_trace), - &block_context, - &simulation_flags, - ); + let charge_fee = if block_context.block_info().gas_prices.eth_l1_gas_price.get() == 1 { false } else { true }; + let mut cached_state = Self::init_cached_state(); - Ok(transactions_exec_infos) - } + transactions_before + .into_iter() + .map(|tx| tx.execute(&mut cached_state, block_context, charge_fee, false)) + .collect::, _>>() + .map_err(|e| { + log::error!("Transaction execution failed during re-execution: {e}"); + Error::::FailedToCreateATransactionalStorageExecution + })?; - fn execute_account_transaction( - transaction: AccountTransaction, - block_context: &BlockContext, - simulation_flags: &SimulationFlags, - ) -> Result { - let mut cached_state = Self::init_cached_state(); + let transactions_exec_infos = transactions_to_trace + .into_iter() + .map(|tx| tx.execute(&mut cached_state, block_context, charge_fee, false)) + .collect::, _>>() + .map_err(|e| { + log::error!("Transaction execution failed during re-execution: {e}"); + Error::::FailedToCreateATransactionalStorageExecution + })?; - transaction.execute(&mut cached_state, block_context, simulation_flags.charge_fee, simulation_flags.validate) + Ok(Ok(transactions_exec_infos)) } fn execute_fee_transaction( @@ -284,25 +283,6 @@ impl Pallet { transaction.execute(&mut cached_state, block_context, simulation_flags.charge_fee, simulation_flags.validate) } - - fn execute_account_or_l1_handler_transactions( - transactions: Vec, - block_context: &BlockContext, - simulation_flags: &SimulationFlags, - ) -> Result, PlaceHolderErrorTypeForFailedStarknetExecution> { - let mut cached_state = Self::init_cached_state(); - - transactions - .into_iter() - .map(|user_or_l1_tx| match user_or_l1_tx { - Transaction::AccountTransaction(tx) => { - Self::execute_account_transaction(tx, block_context, simulation_flags) - } - Transaction::L1HandlerTransaction(tx) => Self::execute_message(tx, block_context, simulation_flags), - }) - .collect::, _>>() - .map_err(|_| PlaceHolderErrorTypeForFailedStarknetExecution) - } } pub fn from_tx_info_and_gas_price( diff --git a/crates/primitives/transactions/src/compute_hash.rs b/crates/primitives/transactions/src/compute_hash.rs index 63b8b1a80..a25e7c125 100644 --- a/crates/primitives/transactions/src/compute_hash.rs +++ b/crates/primitives/transactions/src/compute_hash.rs @@ -14,7 +14,7 @@ use starknet_core::utils::starknet_keccak; use starknet_crypto::FieldElement; use super::SIMULATE_TX_VERSION_OFFSET; -use crate::{UserOrL1HandlerTransaction, LEGACY_BLOCK_NUMBER}; +use crate::LEGACY_BLOCK_NUMBER; const DECLARE_PREFIX: &[u8] = b"declare"; const DEPLOY_ACCOUNT_PREFIX: &[u8] = b"deploy_account"; diff --git a/crates/primitives/transactions/src/from_broadcasted_transactions.rs b/crates/primitives/transactions/src/from_broadcasted_transactions.rs index 0d199bd22..e43232d3f 100644 --- a/crates/primitives/transactions/src/from_broadcasted_transactions.rs +++ b/crates/primitives/transactions/src/from_broadcasted_transactions.rs @@ -4,6 +4,7 @@ use alloc::sync::Arc; use blockifier::execution::contract_class::{ ClassInfo, ContractClass, ContractClassV0, ContractClassV0Inner, ContractClassV1, }; +use blockifier::transaction::account_transaction::AccountTransaction; use blockifier::transaction::transactions as btx; use cairo_lang_starknet_classes::casm_contract_class::{ CasmContractClass, CasmContractEntryPoint, CasmContractEntryPoints, StarknetSierraCompilationError, @@ -35,8 +36,6 @@ use starknet_core::types::{ }; use starknet_crypto::FieldElement; use thiserror::Error; - -use super::UserTransaction; use crate::compute_hash::ComputeTransactionHash; #[derive(Debug, Error)] @@ -59,393 +58,383 @@ pub enum BroadcastedTransactionConversionError { UnsuportedTransactionVersion, } -impl TryFrom for UserTransaction { - type Error = BroadcastedTransactionConversionError; +pub trait ToAccountTransaction { + fn to_account_transaction(&self) -> Result; +} - fn try_from(tx: BroadcastedTransaction) -> Result { - match tx { - BroadcastedTransaction::Invoke(tx) => tx.try_into(), - BroadcastedTransaction::Declare(tx) => tx.try_into(), - BroadcastedTransaction::DeployAccount(tx) => tx.try_into(), +// TODO: remove clone() and change method with &self +impl ToAccountTransaction for BroadcastedTransaction { + fn to_account_transaction(&self) -> Result { + match self { + BroadcastedTransaction::Invoke(tx) => invoke_to_account_transaction(tx.clone()), + BroadcastedTransaction::Declare(tx) => declare_to_account_transaction(tx.clone()), + BroadcastedTransaction::DeployAccount(tx) => deploy_account_to_account_transaction(tx.clone()), } } } -impl TryFrom for UserTransaction { - type Error = BroadcastedTransactionConversionError; - - fn try_from(value: BroadcastedDeclareTransaction) -> Result { - let user_tx = match value { - BroadcastedDeclareTransaction::V1(BroadcastedDeclareTransactionV1 { - sender_address, - max_fee, - signature, - nonce, - contract_class, - is_query: _, - }) => { - // Create a GzipDecoder to decompress the bytes - let mut gz = GzDecoder::new(&contract_class.program[..]); - - // Read the decompressed bytes into a Vec - let mut decompressed_bytes = Vec::new(); - std::io::Read::read_to_end(&mut gz, &mut decompressed_bytes) - .map_err(|_| BroadcastedTransactionConversionError::ProgramDecompressionFailed)?; - - let class_hash = { - let legacy_contract_class = LegacyContractClass { - program: serde_json::from_slice(decompressed_bytes.as_slice()) - .map_err(|_| BroadcastedTransactionConversionError::ProgramDeserializationFailed)?, - abi: match contract_class.abi.as_ref() { - Some(abi) => Some(abi.iter().cloned().map(|entry| entry.into()).collect::>()), - None => vec![].into(), - }, - entry_points_by_type: to_raw_legacy_entry_points(contract_class.entry_points_by_type.clone()), - }; - - legacy_contract_class - .class_hash() - .map_err(|_| BroadcastedTransactionConversionError::ClassHashComputationFailed)? +fn declare_to_account_transaction( + value: BroadcastedDeclareTransaction, +) -> Result { + let user_tx = match value { + BroadcastedDeclareTransaction::V1(BroadcastedDeclareTransactionV1 { + sender_address, + max_fee, + signature, + nonce, + contract_class, + is_query: _, + }) => { + // Create a GzipDecoder to decompress the bytes + let mut gz = GzDecoder::new(&contract_class.program[..]); + + // Read the decompressed bytes into a Vec + let mut decompressed_bytes = Vec::new(); + std::io::Read::read_to_end(&mut gz, &mut decompressed_bytes) + .map_err(|_| BroadcastedTransactionConversionError::ProgramDecompressionFailed)?; + + let class_hash = { + let legacy_contract_class = LegacyContractClass { + program: serde_json::from_slice(decompressed_bytes.as_slice()) + .map_err(|_| BroadcastedTransactionConversionError::ProgramDeserializationFailed)?, + abi: match contract_class.abi.as_ref() { + Some(abi) => Some(abi.iter().cloned().map(|entry| entry.into()).collect::>()), + None => vec![].into(), + }, + entry_points_by_type: to_raw_legacy_entry_points(contract_class.entry_points_by_type.clone()), }; - let blockifier_contract_class = - instantiate_blockifier_contract_class(&contract_class, decompressed_bytes)?; - - let declare_tx = stx::DeclareTransaction::V1(stx::DeclareTransactionV0V1 { - max_fee: stx::Fee( - u128::try_from(Felt252Wrapper::from(max_fee)) - .map_err(|_| BroadcastedTransactionConversionError::MaxFeeTooBig) - .unwrap(), - ), - signature: stx::TransactionSignature( - signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), - ), - nonce: Felt252Wrapper::from(nonce).into(), - class_hash: Felt252Wrapper::from(class_hash).into(), - sender_address: Felt252Wrapper::from(sender_address).into(), - }); - - // TODO: defaulted chain id - let tx_hash = declare_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); - let class_info = ClassInfo::new( - &blockifier_contract_class, - contract_class.clone().program.len(), - contract_class.abi.clone().unwrap().len(), - ) - .unwrap(); - - let tx = btx::DeclareTransaction::new(declare_tx, tx_hash, class_info).unwrap(); - - UserTransaction::Declare(tx) + legacy_contract_class + .class_hash() + .map_err(|_| BroadcastedTransactionConversionError::ClassHashComputationFailed)? + }; + + let blockifier_contract_class = instantiate_blockifier_contract_class(&contract_class, decompressed_bytes)?; + + let declare_tx = stx::DeclareTransaction::V1(stx::DeclareTransactionV0V1 { + max_fee: stx::Fee( + u128::try_from(Felt252Wrapper::from(max_fee)) + .map_err(|_| BroadcastedTransactionConversionError::MaxFeeTooBig) + .unwrap(), + ), + signature: stx::TransactionSignature( + signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + nonce: Felt252Wrapper::from(nonce).into(), + class_hash: Felt252Wrapper::from(class_hash).into(), + sender_address: Felt252Wrapper::from(sender_address).into(), + }); + + // TODO: defaulted chain id + let tx_hash = declare_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); + let class_info = ClassInfo::new( + &blockifier_contract_class, + contract_class.clone().program.len(), + contract_class.abi.clone().unwrap().len(), + ) + .unwrap(); + + let tx = btx::DeclareTransaction::new(declare_tx, tx_hash, class_info).unwrap(); + + AccountTransaction::Declare(tx) + } + BroadcastedDeclareTransaction::V2(BroadcastedDeclareTransactionV2 { + sender_address, + compiled_class_hash, + max_fee, + signature, + nonce, + contract_class, + is_query: _, + }) => { + let casm_contract_class = flattened_sierra_to_casm_contract_class(&contract_class) + .map_err(|_| BroadcastedTransactionConversionError::SierraCompilationFailed)?; + + // ensure that the user has sign the correct class hash + if get_casm_contract_class_hash(&casm_contract_class) != compiled_class_hash { + return Err(BroadcastedTransactionConversionError::InvalidCompiledClassHash); } - BroadcastedDeclareTransaction::V2(BroadcastedDeclareTransactionV2 { - sender_address, - compiled_class_hash, - max_fee, - signature, - nonce, - contract_class, - is_query: _, - }) => { - let casm_contract_class = flattened_sierra_to_casm_contract_class(&contract_class) - .map_err(|_| BroadcastedTransactionConversionError::SierraCompilationFailed)?; - - // ensure that the user has sign the correct class hash - if get_casm_contract_class_hash(&casm_contract_class) != compiled_class_hash { - return Err(BroadcastedTransactionConversionError::InvalidCompiledClassHash); - } - let blockifier_contract_class = ContractClass::V1( - ContractClassV1::try_from(casm_contract_class) - .map_err(|_| BroadcastedTransactionConversionError::CasmContractClassConversionFailed)?, - ); - - let declare_tx = stx::DeclareTransaction::V2(stx::DeclareTransactionV2 { - max_fee: stx::Fee( - u128::try_from(Felt252Wrapper::from(max_fee)) - .map_err(|_| BroadcastedTransactionConversionError::MaxFeeTooBig) - .unwrap(), - ), - signature: stx::TransactionSignature( - signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), - ), - nonce: Felt252Wrapper::from(nonce).into(), - class_hash: Felt252Wrapper::from(contract_class.class_hash()).into(), - sender_address: Felt252Wrapper::from(sender_address).into(), - compiled_class_hash: Felt252Wrapper::from(compiled_class_hash).into(), - }); - - // TODO: use real chain id - let tx_hash = declare_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); - let class_info = ClassInfo::new( - &blockifier_contract_class, - contract_class.sierra_program.len(), - contract_class.abi.len(), - ) - .unwrap(); - - let tx = btx::DeclareTransaction::new(declare_tx, tx_hash, class_info).unwrap(); - - UserTransaction::Declare(tx) + let blockifier_contract_class = ContractClass::V1( + ContractClassV1::try_from(casm_contract_class) + .map_err(|_| BroadcastedTransactionConversionError::CasmContractClassConversionFailed)?, + ); + + let declare_tx = stx::DeclareTransaction::V2(stx::DeclareTransactionV2 { + max_fee: stx::Fee( + u128::try_from(Felt252Wrapper::from(max_fee)) + .map_err(|_| BroadcastedTransactionConversionError::MaxFeeTooBig) + .unwrap(), + ), + signature: stx::TransactionSignature( + signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + nonce: Felt252Wrapper::from(nonce).into(), + class_hash: Felt252Wrapper::from(contract_class.class_hash()).into(), + sender_address: Felt252Wrapper::from(sender_address).into(), + compiled_class_hash: Felt252Wrapper::from(compiled_class_hash).into(), + }); + + // TODO: use real chain id + let tx_hash = declare_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); + let class_info = ClassInfo::new( + &blockifier_contract_class, + contract_class.sierra_program.len(), + contract_class.abi.len(), + ) + .unwrap(); + + let tx = btx::DeclareTransaction::new(declare_tx, tx_hash, class_info).unwrap(); + + AccountTransaction::Declare(tx) + } + BroadcastedDeclareTransaction::V3(BroadcastedDeclareTransactionV3 { + sender_address, + compiled_class_hash, + signature, + nonce, + contract_class, + resource_bounds, + tip, + paymaster_data, + account_deployment_data, + nonce_data_availability_mode, + fee_data_availability_mode, + is_query: _, + }) => { + let casm_contract_class = flattened_sierra_to_casm_contract_class(&contract_class) + .map_err(|_| BroadcastedTransactionConversionError::SierraCompilationFailed)?; + + // ensure that the user has sign the correct class hash + if get_casm_contract_class_hash(&casm_contract_class) != compiled_class_hash { + return Err(BroadcastedTransactionConversionError::InvalidCompiledClassHash); } - BroadcastedDeclareTransaction::V3(BroadcastedDeclareTransactionV3 { - sender_address, - compiled_class_hash, - signature, - nonce, - contract_class, - resource_bounds, - tip, - paymaster_data, - account_deployment_data, - nonce_data_availability_mode, - fee_data_availability_mode, - is_query: _, - }) => { - let casm_contract_class = flattened_sierra_to_casm_contract_class(&contract_class) - .map_err(|_| BroadcastedTransactionConversionError::SierraCompilationFailed)?; - - // ensure that the user has sign the correct class hash - if get_casm_contract_class_hash(&casm_contract_class) != compiled_class_hash { - return Err(BroadcastedTransactionConversionError::InvalidCompiledClassHash); - } - let blockifier_contract_class = ContractClass::V1( - ContractClassV1::try_from(casm_contract_class) - .map_err(|_| BroadcastedTransactionConversionError::CasmContractClassConversionFailed)?, - ); - - let class_hash = contract_class.clone().class_hash(); - let class_hash = Felt252Wrapper::from(class_hash).into(); - - let declare_tx = stx::DeclareTransaction::V3(stx::DeclareTransactionV3 { - signature: stx::TransactionSignature( - signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), - ), - nonce: Felt252Wrapper::from(nonce).into(), - sender_address: Felt252Wrapper::from(sender_address).into(), - class_hash, - compiled_class_hash: Felt252Wrapper::from(compiled_class_hash).into(), - resource_bounds: core_resources_to_api_resources(resource_bounds), - tip: stx::Tip(tip), - paymaster_data: stx::PaymasterData( - paymaster_data.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), - ), - account_deployment_data: stx::AccountDeploymentData( - account_deployment_data - .iter() - .map(|x| Felt252Wrapper::from(*x).into()) - .collect::>(), - ), - nonce_data_availability_mode: core_da_to_api_da(nonce_data_availability_mode), - fee_data_availability_mode: core_da_to_api_da(fee_data_availability_mode), - }); - - // TODO: use real chain id - let tx_hash = declare_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); - let class_info = ClassInfo::new( - &blockifier_contract_class, - contract_class.sierra_program.len(), - contract_class.abi.len(), - ) - .unwrap(); - - let tx = btx::DeclareTransaction::new(declare_tx, tx_hash, class_info).unwrap(); - - UserTransaction::Declare(tx) - } - }; + let blockifier_contract_class = ContractClass::V1( + ContractClassV1::try_from(casm_contract_class) + .map_err(|_| BroadcastedTransactionConversionError::CasmContractClassConversionFailed)?, + ); - Ok(user_tx) - } + let class_hash = contract_class.clone().class_hash(); + let class_hash = Felt252Wrapper::from(class_hash).into(); + + let declare_tx = stx::DeclareTransaction::V3(stx::DeclareTransactionV3 { + signature: stx::TransactionSignature( + signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + nonce: Felt252Wrapper::from(nonce).into(), + sender_address: Felt252Wrapper::from(sender_address).into(), + class_hash, + compiled_class_hash: Felt252Wrapper::from(compiled_class_hash).into(), + resource_bounds: core_resources_to_api_resources(resource_bounds), + tip: stx::Tip(tip), + paymaster_data: stx::PaymasterData( + paymaster_data.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + account_deployment_data: stx::AccountDeploymentData( + account_deployment_data.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + nonce_data_availability_mode: core_da_to_api_da(nonce_data_availability_mode), + fee_data_availability_mode: core_da_to_api_da(fee_data_availability_mode), + }); + + // TODO: use real chain id + let tx_hash = declare_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); + let class_info = ClassInfo::new( + &blockifier_contract_class, + contract_class.sierra_program.len(), + contract_class.abi.len(), + ) + .unwrap(); + + let tx = btx::DeclareTransaction::new(declare_tx, tx_hash, class_info).unwrap(); + + AccountTransaction::Declare(tx) + } + }; + + Ok(user_tx) } -impl TryFrom for UserTransaction { - type Error = BroadcastedTransactionConversionError; - - fn try_from(value: BroadcastedInvokeTransaction) -> Result { - let user_tx = match value { - BroadcastedInvokeTransaction::V1(BroadcastedInvokeTransactionV1 { - sender_address, - calldata, - max_fee, - signature, - nonce, - is_query: _, - .. - }) => { - let invoke_tx = stx::InvokeTransaction::V1(stx::InvokeTransactionV1 { - max_fee: stx::Fee( - u128::try_from(Felt252Wrapper::from(max_fee)) - .map_err(|_| BroadcastedTransactionConversionError::MaxFeeTooBig) - .unwrap(), - ), - signature: stx::TransactionSignature( - signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), - ), - nonce: Felt252Wrapper::from(nonce).into(), - sender_address: Felt252Wrapper::from(sender_address).into(), - calldata: stx::Calldata( - calldata.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>().into(), - ), - }); - - let tx_hash = invoke_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); - - let tx = btx::InvokeTransaction::new(invoke_tx, tx_hash); - - UserTransaction::Invoke(tx) - } - BroadcastedInvokeTransaction::V3(BroadcastedInvokeTransactionV3 { - sender_address, - calldata, - signature, - nonce, - resource_bounds, - tip, - paymaster_data, - account_deployment_data, - nonce_data_availability_mode, - fee_data_availability_mode, - is_query: _, - }) => { - let invoke_tx = stx::InvokeTransaction::V3(stx::InvokeTransactionV3 { - signature: stx::TransactionSignature( - signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), - ), - nonce: Felt252Wrapper::from(nonce).into(), - sender_address: Felt252Wrapper::from(sender_address).into(), - calldata: stx::Calldata( - calldata.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>().into(), - ), - resource_bounds: core_resources_to_api_resources(resource_bounds), - tip: stx::Tip(tip), - paymaster_data: stx::PaymasterData( - paymaster_data.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), - ), - account_deployment_data: stx::AccountDeploymentData( - account_deployment_data - .iter() - .map(|x| Felt252Wrapper::from(*x).into()) - .collect::>(), - ), - nonce_data_availability_mode: core_da_to_api_da(nonce_data_availability_mode), - fee_data_availability_mode: core_da_to_api_da(fee_data_availability_mode), - }); - - let tx_hash = invoke_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); - - let tx = btx::InvokeTransaction::new(invoke_tx, tx_hash); - - UserTransaction::Invoke(tx) - } - }; - Ok(user_tx) - } +fn invoke_to_account_transaction( + value: BroadcastedInvokeTransaction, +) -> Result { + let user_tx = match value { + BroadcastedInvokeTransaction::V1(BroadcastedInvokeTransactionV1 { + sender_address, + calldata, + max_fee, + signature, + nonce, + is_query: _, + .. + }) => { + let invoke_tx = stx::InvokeTransaction::V1(stx::InvokeTransactionV1 { + max_fee: stx::Fee( + u128::try_from(Felt252Wrapper::from(max_fee)) + .map_err(|_| BroadcastedTransactionConversionError::MaxFeeTooBig) + .unwrap(), + ), + signature: stx::TransactionSignature( + signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + nonce: Felt252Wrapper::from(nonce).into(), + sender_address: Felt252Wrapper::from(sender_address).into(), + calldata: stx::Calldata( + calldata.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>().into(), + ), + }); + + let tx_hash = invoke_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); + + let tx = btx::InvokeTransaction::new(invoke_tx, tx_hash); + + AccountTransaction::Invoke(tx) + } + BroadcastedInvokeTransaction::V3(BroadcastedInvokeTransactionV3 { + sender_address, + calldata, + signature, + nonce, + resource_bounds, + tip, + paymaster_data, + account_deployment_data, + nonce_data_availability_mode, + fee_data_availability_mode, + is_query: _, + }) => { + let invoke_tx = stx::InvokeTransaction::V3(stx::InvokeTransactionV3 { + signature: stx::TransactionSignature( + signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + nonce: Felt252Wrapper::from(nonce).into(), + sender_address: Felt252Wrapper::from(sender_address).into(), + calldata: stx::Calldata( + calldata.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>().into(), + ), + resource_bounds: core_resources_to_api_resources(resource_bounds), + tip: stx::Tip(tip), + paymaster_data: stx::PaymasterData( + paymaster_data.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + account_deployment_data: stx::AccountDeploymentData( + account_deployment_data.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + nonce_data_availability_mode: core_da_to_api_da(nonce_data_availability_mode), + fee_data_availability_mode: core_da_to_api_da(fee_data_availability_mode), + }); + + let tx_hash = invoke_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); + + let tx = btx::InvokeTransaction::new(invoke_tx, tx_hash); + + AccountTransaction::Invoke(tx) + } + }; + Ok(user_tx) } -impl TryFrom for UserTransaction { - type Error = BroadcastedTransactionConversionError; - - fn try_from(tx: BroadcastedDeployAccountTransaction) -> Result { - let user_tx = match tx { - BroadcastedDeployAccountTransaction::V1(BroadcastedDeployAccountTransactionV1 { - max_fee, - signature, - nonce, - contract_address_salt, - constructor_calldata, - class_hash, - is_query: _, - }) => { - let deploy_account_tx = stx::DeployAccountTransaction::V1(stx::DeployAccountTransactionV1 { - max_fee: stx::Fee( - u128::try_from(Felt252Wrapper::from(max_fee)) - .map_err(|_| BroadcastedTransactionConversionError::MaxFeeTooBig) - .unwrap(), - ), - signature: stx::TransactionSignature( - signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), - ), - nonce: Felt252Wrapper::from(nonce).into(), - contract_address_salt: Felt252Wrapper::from(contract_address_salt).into(), - constructor_calldata: stx::Calldata( - constructor_calldata - .iter() - .map(|x| Felt252Wrapper::from(*x).into()) - .collect::>() - .into(), - ), - class_hash: Felt252Wrapper::from(class_hash).into(), - }); - - let tx_hash = deploy_account_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); - - let contract_address = calculate_contract_address( - Felt252Wrapper::from(contract_address_salt).into(), - Felt252Wrapper::from(class_hash).into(), - &deploy_account_tx.constructor_calldata(), - Default::default(), - ) - .unwrap(); - - let tx = btx::DeployAccountTransaction::new(deploy_account_tx, tx_hash, contract_address); - - UserTransaction::DeployAccount(tx) - } - BroadcastedDeployAccountTransaction::V3(BroadcastedDeployAccountTransactionV3 { - signature, - nonce, - contract_address_salt, - constructor_calldata, - class_hash, - resource_bounds, - tip, - paymaster_data, - nonce_data_availability_mode, - fee_data_availability_mode, - is_query: _, - }) => { - let deploy_account_tx = stx::DeployAccountTransaction::V3(stx::DeployAccountTransactionV3 { - signature: stx::TransactionSignature( - signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), - ), - nonce: Felt252Wrapper::from(nonce).into(), - contract_address_salt: Felt252Wrapper::from(contract_address_salt).into(), - constructor_calldata: stx::Calldata( - constructor_calldata - .iter() - .map(|x| Felt252Wrapper::from(*x).into()) - .collect::>() - .into(), - ), - class_hash: Felt252Wrapper::from(class_hash).into(), - resource_bounds: core_resources_to_api_resources(resource_bounds), - tip: stx::Tip(tip), - paymaster_data: stx::PaymasterData( - paymaster_data.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), - ), - nonce_data_availability_mode: core_da_to_api_da(nonce_data_availability_mode), - fee_data_availability_mode: core_da_to_api_da(fee_data_availability_mode), - }); - - let tx_hash = deploy_account_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); - - let contract_address = calculate_contract_address( - Felt252Wrapper::from(contract_address_salt).into(), - Felt252Wrapper::from(class_hash).into(), - &deploy_account_tx.constructor_calldata(), - Default::default(), - ) - .unwrap(); - - let tx = btx::DeployAccountTransaction::new(deploy_account_tx, tx_hash, contract_address); - - UserTransaction::DeployAccount(tx) - } - }; - Ok(user_tx) - } +fn deploy_account_to_account_transaction( + tx: BroadcastedDeployAccountTransaction, +) -> Result { + let user_tx = match tx { + BroadcastedDeployAccountTransaction::V1(BroadcastedDeployAccountTransactionV1 { + max_fee, + signature, + nonce, + contract_address_salt, + constructor_calldata, + class_hash, + is_query: _, + }) => { + let deploy_account_tx = stx::DeployAccountTransaction::V1(stx::DeployAccountTransactionV1 { + max_fee: stx::Fee( + u128::try_from(Felt252Wrapper::from(max_fee)) + .map_err(|_| BroadcastedTransactionConversionError::MaxFeeTooBig) + .unwrap(), + ), + signature: stx::TransactionSignature( + signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + nonce: Felt252Wrapper::from(nonce).into(), + contract_address_salt: Felt252Wrapper::from(contract_address_salt).into(), + constructor_calldata: stx::Calldata( + constructor_calldata + .iter() + .map(|x| Felt252Wrapper::from(*x).into()) + .collect::>() + .into(), + ), + class_hash: Felt252Wrapper::from(class_hash).into(), + }); + + let tx_hash = deploy_account_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); + + let contract_address = calculate_contract_address( + Felt252Wrapper::from(contract_address_salt).into(), + Felt252Wrapper::from(class_hash).into(), + &deploy_account_tx.constructor_calldata(), + Default::default(), + ) + .unwrap(); + + let tx = btx::DeployAccountTransaction::new(deploy_account_tx, tx_hash, contract_address); + + AccountTransaction::DeployAccount(tx) + } + BroadcastedDeployAccountTransaction::V3(BroadcastedDeployAccountTransactionV3 { + signature, + nonce, + contract_address_salt, + constructor_calldata, + class_hash, + resource_bounds, + tip, + paymaster_data, + nonce_data_availability_mode, + fee_data_availability_mode, + is_query: _, + }) => { + let deploy_account_tx = stx::DeployAccountTransaction::V3(stx::DeployAccountTransactionV3 { + signature: stx::TransactionSignature( + signature.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + nonce: Felt252Wrapper::from(nonce).into(), + contract_address_salt: Felt252Wrapper::from(contract_address_salt).into(), + constructor_calldata: stx::Calldata( + constructor_calldata + .iter() + .map(|x| Felt252Wrapper::from(*x).into()) + .collect::>() + .into(), + ), + class_hash: Felt252Wrapper::from(class_hash).into(), + resource_bounds: core_resources_to_api_resources(resource_bounds), + tip: stx::Tip(tip), + paymaster_data: stx::PaymasterData( + paymaster_data.iter().map(|x| Felt252Wrapper::from(*x).into()).collect::>(), + ), + nonce_data_availability_mode: core_da_to_api_da(nonce_data_availability_mode), + fee_data_availability_mode: core_da_to_api_da(fee_data_availability_mode), + }); + + let tx_hash = deploy_account_tx.compute_hash::(Felt252Wrapper::ZERO, false, None); + + let contract_address = calculate_contract_address( + Felt252Wrapper::from(contract_address_salt).into(), + Felt252Wrapper::from(class_hash).into(), + &deploy_account_tx.constructor_calldata(), + Default::default(), + ) + .unwrap(); + + let tx = btx::DeployAccountTransaction::new(deploy_account_tx, tx_hash, contract_address); + + AccountTransaction::DeployAccount(tx) + } + }; + Ok(user_tx) } fn cast_vec_of_field_elements(data: Vec) -> Vec { diff --git a/crates/primitives/transactions/src/getters.rs b/crates/primitives/transactions/src/getters.rs index 595f081f9..e013a9c84 100644 --- a/crates/primitives/transactions/src/getters.rs +++ b/crates/primitives/transactions/src/getters.rs @@ -1,4 +1,5 @@ use blockifier::transaction::account_transaction::AccountTransaction; +use blockifier::transaction::transaction_execution::Transaction; use mp_felt::Felt252Wrapper; use starknet_api::transaction::{ DeclareTransaction, DeclareTransactionV0V1, DeclareTransactionV2, DeclareTransactionV3, DeployAccountTransaction, @@ -6,173 +7,204 @@ use starknet_api::transaction::{ TransactionHash, }; -use crate::{TxType, UserOrL1HandlerTransaction, UserTransaction}; +use crate::TxType; -impl UserTransaction { - pub fn sender_address(&self) -> Felt252Wrapper { +pub trait Getters { + fn sender_address(&self) -> Felt252Wrapper; + fn signature(&self) -> Vec; + fn calldata(&self) -> Option>; + fn nonce(&self) -> Option; + fn tx_type(&self) -> TxType; +} + +pub trait Hash { + fn tx_hash(&self) -> Option; +} + +impl Getters for AccountTransaction { + fn sender_address(&self) -> Felt252Wrapper { match self { - UserTransaction::Declare(tx) => tx.tx.sender_address().into(), - UserTransaction::DeployAccount(tx) => tx.tx.contract_address_salt().into(), - UserTransaction::Invoke(tx) => tx.tx.sender_address().into(), + AccountTransaction::Declare(tx) => tx.tx.sender_address().into(), + AccountTransaction::DeployAccount(tx) => tx.tx.contract_address_salt().into(), + AccountTransaction::Invoke(tx) => tx.tx.sender_address().into(), } } - pub fn signature(&self) -> Vec { + fn signature(&self) -> Vec { match self { - UserTransaction::Declare(tx) => { + AccountTransaction::Declare(tx) => { tx.tx.signature().0.iter().map(|x| Felt252Wrapper::from(*x).into()).collect() } - UserTransaction::DeployAccount(tx) => { + AccountTransaction::DeployAccount(tx) => { tx.tx.signature().0.iter().map(|x| Felt252Wrapper::from(*x).into()).collect() } - UserTransaction::Invoke(tx) => { + AccountTransaction::Invoke(tx) => { tx.tx.signature().0.iter().map(|x| Felt252Wrapper::from(*x).into()).collect() } } } - pub fn calldata(&self) -> Option> { + fn calldata(&self) -> Option> { match self { - UserTransaction::Declare(..) => None, - UserTransaction::DeployAccount(tx) => { + AccountTransaction::Declare(..) => None, + AccountTransaction::DeployAccount(tx) => { Some(tx.tx.constructor_calldata().0.iter().map(|x| Felt252Wrapper::from(*x).into()).collect()) } - UserTransaction::Invoke(tx) => { + AccountTransaction::Invoke(tx) => { Some(tx.tx.calldata().0.iter().map(|x| Felt252Wrapper::from(*x).into()).collect()) } } } - pub fn nonce(&self) -> Option { + fn nonce(&self) -> Option { match self { - UserTransaction::Declare(tx) => Some(tx.tx.nonce().0.into()), - UserTransaction::DeployAccount(tx) => Some(tx.tx.nonce().0.into()), - UserTransaction::Invoke(tx) => Some(tx.tx.nonce().0.into()), + AccountTransaction::Declare(tx) => Some(tx.tx.nonce().0.into()), + AccountTransaction::DeployAccount(tx) => Some(tx.tx.nonce().0.into()), + AccountTransaction::Invoke(tx) => Some(tx.tx.nonce().0.into()), } } - pub fn tx_type(&self) -> TxType { + fn tx_type(&self) -> TxType { match self { - UserTransaction::Declare(..) => TxType::Declare, - UserTransaction::DeployAccount(..) => TxType::DeployAccount, - UserTransaction::Invoke(..) => TxType::Invoke, + AccountTransaction::Declare(..) => TxType::Declare, + AccountTransaction::DeployAccount(..) => TxType::DeployAccount, + AccountTransaction::Invoke(..) => TxType::Invoke, } } } -impl UserOrL1HandlerTransaction { - pub fn tx_type(&self) -> TxType { - match self { - UserOrL1HandlerTransaction::User(user_tx) => match user_tx { - AccountTransaction::Declare(_) => TxType::Declare, - AccountTransaction::DeployAccount(_) => TxType::DeployAccount, - AccountTransaction::Invoke(_) => TxType::Invoke, - }, - UserOrL1HandlerTransaction::L1Handler(_) => TxType::L1Handler, - } - } - - pub fn tx_hash(&self) -> Option { +impl Hash for Transaction { + fn tx_hash(&self) -> Option { match self { - UserOrL1HandlerTransaction::User(user_tx) => match user_tx { - AccountTransaction::Declare(declare_transaction) => Some(declare_transaction.tx_hash), - AccountTransaction::DeployAccount(deploy_account_transaction) => { - Some(deploy_account_transaction.tx_hash) - } - AccountTransaction::Invoke(invoke_transaction) => Some(invoke_transaction.tx_hash), - }, - UserOrL1HandlerTransaction::L1Handler(l1_handler_transaction) => Some(l1_handler_transaction.tx_hash), + Transaction::AccountTransaction(tx) => tx.tx_hash(), + Transaction::L1HandlerTransaction(tx) => Some(tx.tx_hash), } } } -pub trait TransactionVersion { - fn version(&self) -> u8; -} - -impl TransactionVersion for InvokeTransaction { - #[inline(always)] - fn version(&self) -> u8 { +impl Hash for AccountTransaction { + fn tx_hash(&self) -> Option { match self { - InvokeTransaction::V0(tx) => tx.version(), - InvokeTransaction::V1(tx) => tx.version(), - InvokeTransaction::V3(tx) => tx.version(), + AccountTransaction::Declare(tx) => Some(tx.tx_hash), + AccountTransaction::DeployAccount(tx) => Some(tx.tx_hash), + AccountTransaction::Invoke(tx) => Some(tx.tx_hash), } } } -impl TransactionVersion for InvokeTransactionV0 { - #[inline(always)] - fn version(&self) -> u8 { - 0 - } -} +// impl UserOrL1HandlerTransaction { +// pub fn tx_type(&self) -> TxType { +// match self { +// UserOrL1HandlerTransaction::User(user_tx) => match user_tx { +// AccountTransaction::Declare(_) => TxType::Declare, +// AccountTransaction::DeployAccount(_) => TxType::DeployAccount, +// AccountTransaction::Invoke(_) => TxType::Invoke, +// }, +// UserOrL1HandlerTransaction::L1Handler(_) => TxType::L1Handler, +// } +// } -impl TransactionVersion for InvokeTransactionV1 { - #[inline(always)] - fn version(&self) -> u8 { - 1 - } -} +// pub fn tx_hash(&self) -> Option { +// match self { +// UserOrL1HandlerTransaction::User(user_tx) => match user_tx { +// AccountTransaction::Declare(declare_transaction) => +// Some(declare_transaction.tx_hash), +// AccountTransaction::DeployAccount(deploy_account_transaction) => { +// Some(deploy_account_transaction.tx_hash) } +// AccountTransaction::Invoke(invoke_transaction) => +// Some(invoke_transaction.tx_hash), }, +// UserOrL1HandlerTransaction::L1Handler(l1_handler_transaction) => +// Some(l1_handler_transaction.tx_hash), } +// } +// } -impl TransactionVersion for InvokeTransactionV3 { - #[inline(always)] - fn version(&self) -> u8 { - 3 - } -} +// pub trait TransactionVersion { +// fn version(&self) -> u8; +// } -impl TransactionVersion for DeclareTransaction { - #[inline(always)] - fn version(&self) -> u8 { - match self { - DeclareTransaction::V0(tx) => tx.version(), - DeclareTransaction::V1(tx) => tx.version(), - DeclareTransaction::V2(tx) => tx.version(), - DeclareTransaction::V3(tx) => tx.version(), - } - } -} +// impl TransactionVersion for InvokeTransaction { +// #[inline(always)] +// fn version(&self) -> u8 { +// match self { +// InvokeTransaction::V0(tx) => tx.version(), +// InvokeTransaction::V1(tx) => tx.version(), +// InvokeTransaction::V3(tx) => tx.version(), +// } +// } +// } -impl TransactionVersion for DeclareTransactionV0V1 { - #[inline(always)] - fn version(&self) -> u8 { - 0 - } -} +// impl TransactionVersion for InvokeTransactionV0 { +// #[inline(always)] +// fn version(&self) -> u8 { +// 0 +// } +// } -// TODO: what should we do here? -// impl TransactionVersion for DeclareTransactionV1 { +// impl TransactionVersion for InvokeTransactionV1 { // #[inline(always)] // fn version(&self) -> u8 { // 1 // } // } -impl TransactionVersion for DeclareTransactionV2 { - #[inline(always)] - fn version(&self) -> u8 { - 2 - } -} +// impl TransactionVersion for InvokeTransactionV3 { +// #[inline(always)] +// fn version(&self) -> u8 { +// 3 +// } +// } -impl TransactionVersion for DeclareTransactionV3 { - #[inline(always)] - fn version(&self) -> u8 { - 3 - } -} +// impl TransactionVersion for DeclareTransaction { +// #[inline(always)] +// fn version(&self) -> u8 { +// match self { +// DeclareTransaction::V0(tx) => tx.version(), +// DeclareTransaction::V1(tx) => tx.version(), +// DeclareTransaction::V2(tx) => tx.version(), +// DeclareTransaction::V3(tx) => tx.version(), +// } +// } +// } -impl TransactionVersion for DeployAccountTransaction { - #[inline(always)] - fn version(&self) -> u8 { - 1 - } -} +// impl TransactionVersion for DeclareTransactionV0V1 { +// #[inline(always)] +// fn version(&self) -> u8 { +// 0 +// } +// } -impl TransactionVersion for L1HandlerTransaction { - #[inline(always)] - fn version(&self) -> u8 { - 0 - } -} +// // TODO: what should we do here? +// // impl TransactionVersion for DeclareTransactionV1 { +// // #[inline(always)] +// // fn version(&self) -> u8 { +// // 1 +// // } +// // } + +// impl TransactionVersion for DeclareTransactionV2 { +// #[inline(always)] +// fn version(&self) -> u8 { +// 2 +// } +// } + +// impl TransactionVersion for DeclareTransactionV3 { +// #[inline(always)] +// fn version(&self) -> u8 { +// 3 +// } +// } + +// impl TransactionVersion for DeployAccountTransaction { +// #[inline(always)] +// fn version(&self) -> u8 { +// 1 +// } +// } + +// impl TransactionVersion for L1HandlerTransaction { +// #[inline(always)] +// fn version(&self) -> u8 { +// 0 +// } +// } diff --git a/crates/primitives/transactions/src/lib.rs b/crates/primitives/transactions/src/lib.rs index 3c27cd514..f2132e4b9 100644 --- a/crates/primitives/transactions/src/lib.rs +++ b/crates/primitives/transactions/src/lib.rs @@ -61,6 +61,25 @@ impl From for TransactionType { } } +impl From<&Transaction> for TxType { + fn from(value: &Transaction) -> Self { + match value { + Transaction::AccountTransaction(tx) => tx.into(), + Transaction::L1HandlerTransaction(_) => TxType::L1Handler, + } + } +} + +impl From<&AccountTransaction> for TxType { + fn from(value: &AccountTransaction) -> Self { + match value { + AccountTransaction::Declare(_) => TxType::Declare, + AccountTransaction::DeployAccount(_) => TxType::DeployAccount, + AccountTransaction::Invoke(_) => TxType::Invoke, + } + } +} + // impl From<&UserTransaction> for TxType { // fn from(value: &UserTransaction) -> Self { // match value { @@ -80,14 +99,14 @@ impl From for TransactionType { // } // } -#[derive(Clone, Debug, Eq, PartialEq, From)] -#[cfg_attr(feature = "parity-scale-codec", derive(parity_scale_codec::Encode, parity_scale_codec::Decode))] -#[cfg_attr(feature = "scale-info", derive(scale_info::TypeInfo))] -pub enum UserTransaction { - Declare(DeclareTransaction), - DeployAccount(DeployAccountTransaction), - Invoke(InvokeTransaction), -} +// #[derive(Clone, Debug, Eq, PartialEq, From)] +// #[cfg_attr(feature = "parity-scale-codec", derive(parity_scale_codec::Encode, +// parity_scale_codec::Decode))] #[cfg_attr(feature = "scale-info", derive(scale_info::TypeInfo))] +// pub enum UserTransaction { +// Declare(DeclareTransaction), +// DeployAccount(DeployAccountTransaction), +// Invoke(InvokeTransaction), +// } // #[derive(Clone, Debug, Eq, PartialEq, From, PartialOrd, Ord)] // #[cfg_attr(feature = "parity-scale-codec", derive(parity_scale_codec::Encode, @@ -100,13 +119,13 @@ pub enum UserTransaction { // L1Handler(HandleL1MessageTransaction), // } -#[derive(Clone, Debug, Eq, PartialEq, From)] -#[cfg_attr(feature = "parity-scale-codec", derive(parity_scale_codec::Encode, parity_scale_codec::Decode))] -#[cfg_attr(feature = "scale-info", derive(scale_info::TypeInfo))] -pub enum UserOrL1HandlerTransaction { - User(AccountTransaction), - L1Handler(L1HandlerTransaction), -} +// #[derive(Clone, Debug, Eq, PartialEq, From)] +// #[cfg_attr(feature = "parity-scale-codec", derive(parity_scale_codec::Encode, +// parity_scale_codec::Decode))] #[cfg_attr(feature = "scale-info", derive(scale_info::TypeInfo))] +// pub enum UserOrL1HandlerTransaction { +// User(AccountTransaction), +// L1Handler(L1HandlerTransaction), +// } // #[derive(Debug, Clone, Eq, PartialEq, From, PartialOrd, Ord)] // #[cfg_attr(feature = "parity-scale-codec", derive(parity_scale_codec::Encode, @@ -247,48 +266,48 @@ pub enum UserOrL1HandlerTransaction { // pub calldata: Vec, // } -impl From for AccountTransaction { - fn from(user_transaction: UserTransaction) -> Self { - match user_transaction { - UserTransaction::Declare(declare_tx) => AccountTransaction::Declare(declare_tx), - UserTransaction::DeployAccount(deploy_account_tx) => AccountTransaction::DeployAccount(deploy_account_tx), - UserTransaction::Invoke(invoke_tx) => AccountTransaction::Invoke(invoke_tx), - } - } -} +// impl From for AccountTransaction { +// fn from(user_transaction: UserTransaction) -> Self { +// match user_transaction { +// UserTransaction::Declare(declare_tx) => AccountTransaction::Declare(declare_tx), +// UserTransaction::DeployAccount(deploy_account_tx) => +// AccountTransaction::DeployAccount(deploy_account_tx), +// UserTransaction::Invoke(invoke_tx) => AccountTransaction::Invoke(invoke_tx), } +// } +// } -impl From for UserTransaction { - fn from(account_transaction: AccountTransaction) -> Self { - match account_transaction { - AccountTransaction::Declare(declare_tx) => UserTransaction::Declare(declare_tx), - AccountTransaction::DeployAccount(deploy_account_tx) => UserTransaction::DeployAccount(deploy_account_tx), - AccountTransaction::Invoke(invoke_tx) => UserTransaction::Invoke(invoke_tx), - } - } -} +// impl From for UserTransaction { +// fn from(account_transaction: AccountTransaction) -> Self { +// match account_transaction { +// AccountTransaction::Declare(declare_tx) => UserTransaction::Declare(declare_tx), +// AccountTransaction::DeployAccount(deploy_account_tx) => +// UserTransaction::DeployAccount(deploy_account_tx), +// AccountTransaction::Invoke(invoke_tx) => UserTransaction::Invoke(invoke_tx), } +// } +// } -impl From for Transaction { - fn from(item: UserOrL1HandlerTransaction) -> Self { - match item { - UserOrL1HandlerTransaction::User(tx) => Transaction::AccountTransaction(tx), - UserOrL1HandlerTransaction::L1Handler(tx) => Transaction::L1HandlerTransaction(tx), - } - } -} +// impl From for Transaction { +// fn from(item: UserOrL1HandlerTransaction) -> Self { +// match item { +// UserOrL1HandlerTransaction::User(tx) => Transaction::AccountTransaction(tx), +// UserOrL1HandlerTransaction::L1Handler(tx) => Transaction::L1HandlerTransaction(tx), +// } +// } +// } -impl From for UserOrL1HandlerTransaction { - fn from(item: Transaction) -> Self { - match item { - Transaction::AccountTransaction(tx) => UserOrL1HandlerTransaction::User(tx), - Transaction::L1HandlerTransaction(tx) => UserOrL1HandlerTransaction::L1Handler(tx), - } - } -} +// impl From for UserOrL1HandlerTransaction { +// fn from(item: Transaction) -> Self { +// match item { +// Transaction::AccountTransaction(tx) => UserOrL1HandlerTransaction::User(tx), +// Transaction::L1HandlerTransaction(tx) => UserOrL1HandlerTransaction::L1Handler(tx), +// } +// } +// } -pub fn user_or_l1_into_tx_vec(user_or_l1_transactions: Vec) -> Vec { - user_or_l1_transactions.into_iter().map(|tx| tx.into()).collect() -} +// pub fn user_or_l1_into_tx_vec(user_or_l1_transactions: Vec) -> +// Vec { user_or_l1_transactions.into_iter().map(|tx| tx.into()).collect() +// } -pub fn tx_into_user_or_l1_vec(transactions: Vec) -> Vec { - transactions.into_iter().map(|tx| tx.into()).collect() -} +// pub fn tx_into_user_or_l1_vec(transactions: Vec) -> Vec +// { transactions.into_iter().map(|tx| tx.into()).collect() +// } diff --git a/crates/runtime/src/lib.rs b/crates/runtime/src/lib.rs index f2471d788..f6197b554 100644 --- a/crates/runtime/src/lib.rs +++ b/crates/runtime/src/lib.rs @@ -38,7 +38,6 @@ use mp_simulations::{ PlaceHolderErrorTypeForFailedStarknetExecution, SimulationFlagForEstimateFee, SimulationFlags, TransactionSimulationResult, }; -use mp_transactions::{UserOrL1HandlerTransaction, UserTransaction}; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; /// Import the Starknet pallet. pub use pallet_starknet; @@ -291,11 +290,11 @@ impl_runtime_apis! { Starknet::is_transaction_fee_disabled() } - fn estimate_fee(transactions: Vec, simulation_flags: Vec) -> Result, DispatchError> { + fn estimate_fee(transactions: Vec, simulation_flags: Vec) -> Result, DispatchError> { Starknet::estimate_fee(transactions, &simulation_flags) } - fn re_execute_transactions(transactions_before: Vec, transactions_to_trace: Vec, block_context: &BlockContext) -> Result, PlaceHolderErrorTypeForFailedStarknetExecution>, DispatchError> { + fn re_execute_transactions(transactions_before: Vec, transactions_to_trace: Vec, block_context: &BlockContext) -> Result, PlaceHolderErrorTypeForFailedStarknetExecution>, DispatchError> { Starknet::re_execute_transactions(transactions_before, transactions_to_trace, block_context) } @@ -303,7 +302,7 @@ impl_runtime_apis! { Starknet::estimate_message_fee(message) } - fn simulate_transactions(transactions: Vec, simulation_flags: SimulationFlags) -> Result>, DispatchError> { + fn simulate_transactions(transactions: Vec, simulation_flags: SimulationFlags) -> Result>, DispatchError> { Starknet::simulate_transactions(transactions, &simulation_flags) }