diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b670e912..a82d95250 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Next release +- refactor: replace starknet-rs BlockId with types-rs BlockId and remove redundant mp_block::BlockId - feat(fgw): added `add_transaction` for gateway client - fix(fgw): include `l1_to_l2_consumed_message` in L1 handler receipt - build: up starknet-rs, starknet-types, blockifier(v0.8.0), cairo diff --git a/Cargo.lock b/Cargo.lock index b6e69d68b..19fefba59 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5607,6 +5607,7 @@ dependencies = [ "starknet", "starknet-core", "starknet-providers", + "starknet-types-core", "tempfile", "tokio", "tracing", @@ -6133,6 +6134,7 @@ dependencies = [ "serde_yaml", "starknet-core", "starknet-crypto 0.7.2", + "starknet-types-core", "tokio", "tracing", "tracing-core", diff --git a/crates/client/block_import/src/lib.rs b/crates/client/block_import/src/lib.rs index 303299c3c..fe2e5d617 100644 --- a/crates/client/block_import/src/lib.rs +++ b/crates/client/block_import/src/lib.rs @@ -42,7 +42,7 @@ use anyhow::Context; use mc_db::{MadaraBackend, MadaraStorageError}; use metrics::BlockMetrics; use mp_class::{class_hash::ComputeClassHashError, compile::ClassCompilationError}; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; use std::{borrow::Cow, sync::Arc}; mod metrics; diff --git a/crates/client/block_import/src/pre_validate.rs b/crates/client/block_import/src/pre_validate.rs index ef6657476..cbbd4f756 100644 --- a/crates/client/block_import/src/pre_validate.rs +++ b/crates/client/block_import/src/pre_validate.rs @@ -11,7 +11,7 @@ use mp_transactions::Transaction; use rayon::iter::{IntoParallelIterator, IntoParallelRefIterator}; use rayon::prelude::*; use starknet_api::core::ChainId; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; use starknet_types_core::hash::{Pedersen, Poseidon, StarkHash}; use std::mem; use std::sync::Arc; diff --git a/crates/client/block_import/src/tests/block_import_utils.rs b/crates/client/block_import/src/tests/block_import_utils.rs index d1e2a1794..07d28dbd3 100644 --- a/crates/client/block_import/src/tests/block_import_utils.rs +++ b/crates/client/block_import/src/tests/block_import_utils.rs @@ -2,7 +2,7 @@ use mp_block::header::{GasPrices, L1DataAvailabilityMode}; use mp_block::Header; use mp_chain_config::StarknetVersion; use mp_state_update::StateDiff; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; use crate::{ BlockValidationContext, PreValidatedBlock, PreValidatedPendingBlock, UnverifiedCommitments, UnverifiedFullBlock, diff --git a/crates/client/block_import/src/types.rs b/crates/client/block_import/src/types.rs index 30ca85750..3e0419a57 100644 --- a/crates/client/block_import/src/types.rs +++ b/crates/client/block_import/src/types.rs @@ -15,7 +15,7 @@ use mp_state_update::StateDiff; use mp_transactions::Transaction; use serde::{Deserialize, Serialize}; use starknet_api::core::ChainId; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; #[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)] pub struct UnverifiedHeader { diff --git a/crates/client/block_import/src/verify_apply.rs b/crates/client/block_import/src/verify_apply.rs index abad5fc4c..9113b88ac 100644 --- a/crates/client/block_import/src/verify_apply.rs +++ b/crates/client/block_import/src/verify_apply.rs @@ -4,13 +4,14 @@ use crate::{ }; use itertools::Itertools; use mc_db::{MadaraBackend, MadaraStorageError}; +use mp_block::BlockTag; use mp_block::{ - header::PendingHeader, BlockId, BlockTag, Header, MadaraBlockInfo, MadaraBlockInner, MadaraMaybePendingBlock, + header::PendingHeader, BlockId, Header, MadaraBlockInfo, MadaraBlockInner, MadaraMaybePendingBlock, MadaraMaybePendingBlockInfo, MadaraPendingBlockInfo, }; use mp_convert::{FeltHexDisplay, ToFelt}; use starknet_api::core::ChainId; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; use starknet_types_core::hash::{Poseidon, StarkHash}; use std::{borrow::Cow, sync::Arc}; diff --git a/crates/client/db/src/contract_db.rs b/crates/client/db/src/contract_db.rs index 200d817b1..70666b463 100644 --- a/crates/client/db/src/contract_db.rs +++ b/crates/client/db/src/contract_db.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use rayon::{iter::ParallelIterator, slice::ParallelSlice}; use rocksdb::{BoundColumnFamily, IteratorMode, ReadOptions, WriteOptions}; use serde::Serialize; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; use crate::{ db_block_id::{DbBlockId, DbBlockIdResolvable}, diff --git a/crates/client/db/src/db_block_id.rs b/crates/client/db/src/db_block_id.rs index 75471719b..548422c56 100644 --- a/crates/client/db/src/db_block_id.rs +++ b/crates/client/db/src/db_block_id.rs @@ -26,12 +26,6 @@ impl DbBlockIdResolvable for BlockId { } } -impl DbBlockIdResolvable for starknet_core::types::BlockId { - fn resolve_db_block_id(&self, backend: &MadaraBackend) -> Result, MadaraStorageError> { - backend.id_to_storage_type(&(*self).into()) - } -} - impl DbBlockIdResolvable for DbBlockId { fn resolve_db_block_id(&self, _backend: &MadaraBackend) -> Result, MadaraStorageError> { Ok(Some(*self)) diff --git a/crates/client/db/src/devnet_db.rs b/crates/client/db/src/devnet_db.rs index b3971d1f5..d4354aa38 100644 --- a/crates/client/db/src/devnet_db.rs +++ b/crates/client/db/src/devnet_db.rs @@ -2,7 +2,7 @@ use crate::DatabaseExt; use crate::{Column, MadaraBackend, MadaraStorageError}; use rocksdb::WriteOptions; use serde::{Deserialize, Serialize}; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; pub const DEVNET_KEYS: &[u8] = b"DEVNET_KEYS"; diff --git a/crates/client/db/src/tests/test_block.rs b/crates/client/db/src/tests/test_block.rs index f9531b401..a9e043c06 100644 --- a/crates/client/db/src/tests/test_block.rs +++ b/crates/client/db/src/tests/test_block.rs @@ -4,8 +4,7 @@ mod block_tests { use super::super::common::*; use crate::db_block_id::DbBlockIdResolvable; use crate::{block_db::TxIndex, db_block_id::DbBlockId}; - use mp_block::BlockId; - use mp_block::Header; + use mp_block::{BlockId, Header}; use mp_chain_config::ChainConfig; use starknet_api::felt; diff --git a/crates/client/devnet/src/predeployed_contracts.rs b/crates/client/devnet/src/predeployed_contracts.rs index 4a8e0f633..b53e94fc8 100644 --- a/crates/client/devnet/src/predeployed_contracts.rs +++ b/crates/client/devnet/src/predeployed_contracts.rs @@ -3,8 +3,8 @@ use blockifier::abi::{abi_utils::get_fee_token_var_address, sierra_types::next_s use core::fmt; use mc_db::MadaraBackend; use mp_block::{BlockId, BlockTag}; -use starknet_core::types::Felt; use starknet_signers::SigningKey; +use starknet_types_core::felt::Felt; use crate::{ ContractFeeTokensBalance, ERC20_ETH_CONTRACT_ADDRESS, ERC20_STRK_CONTRACT_ADDRESS, ETH_WEI_DECIMALS, diff --git a/crates/client/gateway/client/src/methods.rs b/crates/client/gateway/client/src/methods.rs index 525644786..639e47fce 100644 --- a/crates/client/gateway/client/src/methods.rs +++ b/crates/client/gateway/client/src/methods.rs @@ -27,7 +27,7 @@ impl GatewayProvider { let request = RequestBuilder::new(&self.client, self.feeder_gateway_url.clone(), self.headers.clone()) .add_uri_segment("get_block") .expect("Failed to add URI segment. This should not fail in prod.") - .with_block_id(block_id); + .with_block_id(&block_id); match block_id { BlockId::Tag(BlockTag::Pending) => { @@ -41,7 +41,7 @@ impl GatewayProvider { let request = RequestBuilder::new(&self.client, self.feeder_gateway_url.clone(), self.headers.clone()) .add_uri_segment("get_state_update") .expect("Failed to add URI segment. This should not fail in prod") - .with_block_id(block_id); + .with_block_id(&block_id); match block_id { BlockId::Tag(BlockTag::Pending) => { @@ -58,7 +58,7 @@ impl GatewayProvider { let request = RequestBuilder::new(&self.client, self.feeder_gateway_url.clone(), self.headers.clone()) .add_uri_segment("get_state_update") .expect("Failed to add URI segment. This should not fail in prod") - .with_block_id(block_id) + .with_block_id(&block_id) .add_param(Cow::from("includeBlock"), "true"); match block_id { @@ -79,7 +79,7 @@ impl GatewayProvider { let request = RequestBuilder::new(&self.client, self.feeder_gateway_url.clone(), self.headers.clone()) .add_uri_segment("get_signature") .expect("Failed to add URI segment. This should not fail in prod") - .with_block_id(block_id); + .with_block_id(&block_id); request.send_get::().await } @@ -92,7 +92,7 @@ impl GatewayProvider { let request = RequestBuilder::new(&self.client, self.feeder_gateway_url.clone(), self.headers.clone()) .add_uri_segment("get_class_by_hash") .expect("Failed to add URI segment. This should not fail in prod.") - .with_block_id(block_id) + .with_block_id(&block_id) .with_class_hash(class_hash); let value = request.send_get::().await?; @@ -149,12 +149,11 @@ mod tests { bufread::{GzDecoder, GzEncoder}, Compression, }; - use mp_block::BlockTag; use mp_class::CompressedLegacyContractClass; use mp_gateway::error::{SequencerError, StarknetError, StarknetErrorCode}; use rstest::*; use serde::de::DeserializeOwned; - use starknet_core::types::Felt; + use starknet_types_core::felt::Felt; use std::fs::{remove_file, File}; use std::io::{BufReader, BufWriter, Read, Write}; use std::ops::Drop; diff --git a/crates/client/gateway/client/src/request_builder.rs b/crates/client/gateway/client/src/request_builder.rs index 26f48a4f2..ca7d56e26 100644 --- a/crates/client/gateway/client/src/request_builder.rs +++ b/crates/client/gateway/client/src/request_builder.rs @@ -45,7 +45,7 @@ impl<'a> RequestBuilder<'a> { self } - pub fn with_block_id(mut self, block_id: BlockId) -> Self { + pub fn with_block_id(mut self, block_id: &BlockId) -> Self { match block_id { BlockId::Hash(hash) => { self = self.add_param(Cow::from("blockHash"), &format!("0x{hash:x}")); diff --git a/crates/client/gateway/server/src/handler.rs b/crates/client/gateway/server/src/handler.rs index ccdaf44a3..236c3f977 100644 --- a/crates/client/gateway/server/src/handler.rs +++ b/crates/client/gateway/server/src/handler.rs @@ -46,12 +46,12 @@ pub async fn handle_get_block( let block_info = backend .get_block_info(&block_id) - .or_internal_server_error(format!("Retrieving block {block_id}"))? + .or_internal_server_error(format!("Retrieving block {block_id:?}"))? .ok_or(StarknetError::block_not_found())?; match block_info { MadaraMaybePendingBlockInfo::Pending(_) => Err(GatewayError::InternalServerError(format!( - "Retrieved pending block info from db for non-pending block {block_id}" + "Retrieved pending block info from db for non-pending block {block_id:?}" ))), MadaraMaybePendingBlockInfo::NotPending(block_info) => { let body = json!({ @@ -64,7 +64,7 @@ pub async fn handle_get_block( } else { let block = backend .get_block(&block_id) - .or_internal_server_error(format!("Retrieving block {block_id}"))? + .or_internal_server_error(format!("Retrieving block {block_id:?}"))? .ok_or(StarknetError::block_not_found())?; if let Ok(block) = MadaraBlock::try_from(block.clone()) { @@ -101,12 +101,12 @@ pub async fn handle_get_signature( let block_info = backend .get_block_info(&block_id) - .or_internal_server_error(format!("Retrieving block info for block {block_id}"))? + .or_internal_server_error(format!("Retrieving block info for block {block_id:?}"))? .ok_or(StarknetError::block_not_found())?; match block_info { MadaraMaybePendingBlockInfo::Pending(_) => Err(GatewayError::InternalServerError(format!( - "Retrieved pending block info from db for non-pending block {block_id}" + "Retrieved pending block info from db for non-pending block {block_id:?}" ))), MadaraMaybePendingBlockInfo::NotPending(block_info) => { let private_key = &backend.chain_config().private_key; @@ -238,8 +238,7 @@ pub async fn handle_get_block_traces( traces: Vec, } - let traces = - v0_7_1_trace_block_transactions(&Starknet::new(backend, add_transaction_provider), block_id.into()).await?; + let traces = v0_7_1_trace_block_transactions(&Starknet::new(backend, add_transaction_provider), block_id).await?; let block_traces = BlockTraces { traces }; Ok(create_json_response(hyper::StatusCode::OK, &block_traces)) diff --git a/crates/client/mempool/src/block_production.rs b/crates/client/mempool/src/block_production.rs index 11949f392..c29994399 100644 --- a/crates/client/mempool/src/block_production.rs +++ b/crates/client/mempool/src/block_production.rs @@ -578,7 +578,7 @@ mod test { core::{ClassHash, ContractAddress, PatriciaKey}, felt, patricia_key, }; - use starknet_core::types::Felt; + use starknet_types_core::felt::Felt; #[test] fn state_map_to_state_diff() { diff --git a/crates/client/mempool/src/lib.rs b/crates/client/mempool/src/lib.rs index 27f2edc43..28445193e 100644 --- a/crates/client/mempool/src/lib.rs +++ b/crates/client/mempool/src/lib.rs @@ -1,19 +1,16 @@ use blockifier::blockifier::stateful_validator::StatefulValidatorError; use blockifier::transaction::account_transaction::AccountTransaction; use blockifier::transaction::transaction_execution::Transaction; -use blockifier::transaction::transactions::DeployAccountTransaction; -use blockifier::transaction::transactions::InvokeTransaction; -use blockifier::transaction::transactions::{DeclareTransaction, L1HandlerTransaction}; +use blockifier::transaction::transactions::{ + DeclareTransaction, DeployAccountTransaction, InvokeTransaction, L1HandlerTransaction, +}; use header::make_pending_header; use inner::MempoolInner; use mc_db::db_block_id::DbBlockId; -use mc_db::MadaraBackend; -use mc_db::MadaraStorageError; +use mc_db::{MadaraBackend, MadaraStorageError}; use mc_exec::ExecutionContext; use metrics::MempoolMetrics; -use mp_block::BlockId; -use mp_block::BlockTag; -use mp_block::MadaraPendingBlockInfo; +use mp_block::{BlockId, BlockTag, MadaraPendingBlockInfo}; use mp_class::ConvertedClass; use mp_convert::ToFelt; use mp_transactions::{ @@ -22,16 +19,12 @@ use mp_transactions::{ use mp_transactions::{BroadcastedToBlockifierError, L1HandlerTransactionResult}; use starknet_api::core::{ContractAddress, Nonce}; use starknet_api::transaction::TransactionHash; -use starknet_core::types::BroadcastedDeclareTransaction; -use starknet_core::types::BroadcastedDeployAccountTransaction; -use starknet_core::types::BroadcastedInvokeTransaction; -use starknet_core::types::BroadcastedTransaction; -use starknet_core::types::DeclareTransactionResult; -use starknet_core::types::DeployAccountTransactionResult; -use starknet_core::types::InvokeTransactionResult; +use starknet_core::types::{ + BroadcastedDeclareTransaction, BroadcastedDeployAccountTransaction, BroadcastedInvokeTransaction, + BroadcastedTransaction, DeclareTransactionResult, DeployAccountTransactionResult, InvokeTransactionResult, +}; use starknet_types_core::felt::Felt; -use std::sync::Arc; -use std::sync::RwLock; +use std::sync::{Arc, RwLock}; pub use inner::TxInsersionError; pub use inner::{ArrivedAtTimestamp, MempoolTransaction}; @@ -359,7 +352,7 @@ pub(crate) fn clone_transaction(tx: &Transaction) -> Transaction { mod test { use std::sync::Arc; - use starknet_core::types::Felt; + use starknet_types_core::felt::Felt; use crate::MockL1DataProvider; diff --git a/crates/client/rpc/src/lib.rs b/crates/client/rpc/src/lib.rs index 77bf5860d..c173d8745 100644 --- a/crates/client/rpc/src/lib.rs +++ b/crates/client/rpc/src/lib.rs @@ -17,7 +17,7 @@ use std::sync::Arc; use mc_db::db_block_id::DbBlockIdResolvable; use mc_db::MadaraBackend; -use mp_block::{MadaraMaybePendingBlock, MadaraMaybePendingBlockInfo}; +use mp_block::{BlockId, BlockTag, MadaraMaybePendingBlock, MadaraMaybePendingBlockInfo}; use mp_chain_config::{ChainConfig, RpcVersion}; use mp_convert::ToFelt; @@ -74,7 +74,7 @@ impl Starknet { } pub fn current_block_number(&self) -> StarknetRpcResult { - self.get_block_n(&mp_block::BlockId::Tag(mp_block::BlockTag::Latest)) + self.get_block_n(&BlockId::Tag(BlockTag::Latest)) } pub fn current_spec_version(&self) -> RpcVersion { diff --git a/crates/client/rpc/src/test_utils.rs b/crates/client/rpc/src/test_utils.rs index def5ef190..1f5939e9b 100644 --- a/crates/client/rpc/src/test_utils.rs +++ b/crates/client/rpc/src/test_utils.rs @@ -17,8 +17,9 @@ use mp_transactions::{BroadcastedDeclareTransactionV0, InvokeTransaction, Invoke use rstest::fixture; use starknet_core::types::{ BroadcastedDeclareTransaction, BroadcastedDeployAccountTransaction, BroadcastedInvokeTransaction, - DeclareTransactionResult, DeployAccountTransactionResult, Felt, InvokeTransactionResult, + DeclareTransactionResult, DeployAccountTransactionResult, InvokeTransactionResult, }; +use starknet_types_core::felt::Felt; use std::sync::Arc; use crate::{providers::AddTransactionProvider, Starknet}; diff --git a/crates/client/rpc/src/versions/v0_7_1/api.rs b/crates/client/rpc/src/versions/v0_7_1/api.rs index a9ffdd30c..50fdb5972 100644 --- a/crates/client/rpc/src/versions/v0_7_1/api.rs +++ b/crates/client/rpc/src/versions/v0_7_1/api.rs @@ -1,6 +1,9 @@ use jsonrpsee::core::RpcResult; +use m_proc_macros::versioned_rpc; +use mp_block::BlockId; +use mp_transactions::BroadcastedDeclareTransactionV0; use starknet_core::types::{ - BlockHashAndNumber, BlockId, BroadcastedDeclareTransaction, BroadcastedDeployAccountTransaction, + BlockHashAndNumber, BroadcastedDeclareTransaction, BroadcastedDeployAccountTransaction, BroadcastedInvokeTransaction, BroadcastedTransaction, ContractClass, DeclareTransactionResult, DeployAccountTransactionResult, EventFilterWithPage, EventsPage, FeeEstimate, FunctionCall, InvokeTransactionResult, MaybePendingBlockWithReceipts, MaybePendingBlockWithTxHashes, MaybePendingBlockWithTxs, @@ -9,8 +12,6 @@ use starknet_core::types::{ }; use starknet_types_core::felt::Felt; -use m_proc_macros::versioned_rpc; -use mp_transactions::BroadcastedDeclareTransactionV0; // Starknet RPC API trait and types // // Starkware maintains [a description of the Starknet API](https://github.com/starkware-libs/starknet-specs/blob/master/api/starknet_api_openrpc.json) diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/block_hash_and_number.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/block_hash_and_number.rs index b616c40f1..85a639241 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/block_hash_and_number.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/block_hash_and_number.rs @@ -34,7 +34,7 @@ mod tests { }; use mp_state_update::StateDiff; use rstest::rstest; - use starknet_core::types::Felt; + use starknet_types_core::felt::Felt; #[rstest] fn test_block_hash_and_number(rpc_test_setup: (Arc, Starknet)) { diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/call.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/call.rs index 553b21d36..c438ce29d 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/call.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/call.rs @@ -1,9 +1,9 @@ use std::sync::Arc; -use starknet_core::types::{BlockId, FunctionCall}; -use starknet_types_core::felt::Felt; - use mc_exec::ExecutionContext; +use mp_block::BlockId; +use starknet_core::types::FunctionCall; +use starknet_types_core::felt::Felt; use crate::errors::StarknetRpcApiError; use crate::errors::StarknetRpcResult; diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/estimate_fee.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/estimate_fee.rs index c981e283b..a28f5bcea 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/estimate_fee.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/estimate_fee.rs @@ -1,8 +1,9 @@ use std::sync::Arc; -use starknet_core::types::{BlockId, BroadcastedTransaction, FeeEstimate, SimulationFlagForEstimateFee}; +use starknet_core::types::{BroadcastedTransaction, FeeEstimate, SimulationFlagForEstimateFee}; use mc_exec::ExecutionContext; +use mp_block::BlockId; use mp_transactions::broadcasted_to_blockifier; use crate::errors::StarknetRpcApiError; diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/estimate_message_fee.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/estimate_message_fee.rs index c5a208a2e..b34fe5ed1 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/estimate_message_fee.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/estimate_message_fee.rs @@ -1,11 +1,11 @@ use std::sync::Arc; -use starknet_api::transaction::{Fee, TransactionHash}; -use starknet_core::types::{BlockId, FeeEstimate, MsgFromL1}; -use starknet_types_core::felt::Felt; - use mc_exec::ExecutionContext; +use mp_block::BlockId; use mp_transactions::L1HandlerTransaction; +use starknet_api::transaction::{Fee, TransactionHash}; +use starknet_core::types::{FeeEstimate, MsgFromL1}; +use starknet_types_core::felt::Felt; use crate::errors::StarknetRpcApiError; use crate::errors::StarknetRpcResult; diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_transaction_count.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_transaction_count.rs index acbaa9ea8..b441151f8 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_transaction_count.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_transaction_count.rs @@ -1,5 +1,4 @@ -use mp_block::MadaraMaybePendingBlockInfo; -use starknet_core::types::BlockId; +use mp_block::{BlockId, MadaraMaybePendingBlockInfo}; use crate::{errors::StarknetRpcResult, Starknet}; @@ -36,8 +35,9 @@ mod tests { errors::StarknetRpcApiError, test_utils::{sample_chain_for_block_getters, SampleChainForBlockGetters}, }; + use mp_block::BlockTag; use rstest::rstest; - use starknet_core::types::{BlockTag, Felt}; + use starknet_types_core::felt::Felt; #[rstest] fn test_get_block_transaction_count(sample_chain_for_block_getters: (SampleChainForBlockGetters, Starknet)) { diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_receipts.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_receipts.rs index dd7bb76a8..17a20f4f9 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_receipts.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_receipts.rs @@ -1,7 +1,7 @@ -use mp_block::MadaraMaybePendingBlockInfo; +use mp_block::{BlockId, MadaraMaybePendingBlockInfo}; use starknet_core::types::{ - BlockId, BlockStatus, BlockWithReceipts, MaybePendingBlockWithReceipts, PendingBlockWithReceipts, - TransactionFinalityStatus, TransactionWithReceipt, + BlockStatus, BlockWithReceipts, MaybePendingBlockWithReceipts, PendingBlockWithReceipts, TransactionFinalityStatus, + TransactionWithReceipt, }; use crate::errors::StarknetRpcResult; @@ -73,7 +73,7 @@ mod tests { test_utils::{rpc_test_setup, sample_chain_for_block_getters, SampleChainForBlockGetters}, }; use mc_db::MadaraBackend; - use mp_block::{header::GasPrices, Header, MadaraBlockInfo, MadaraBlockInner, MadaraMaybePendingBlock}; + use mp_block::{header::GasPrices, BlockTag, Header, MadaraBlockInfo, MadaraBlockInner, MadaraMaybePendingBlock}; use mp_chain_config::StarknetVersion; use mp_receipt::{ ExecutionResources, ExecutionResult, FeePayment, InvokeTransactionReceipt, PriceUnit, TransactionReceipt, @@ -81,7 +81,8 @@ mod tests { use mp_state_update::StateDiff; use mp_transactions::{InvokeTransaction, InvokeTransactionV0, Transaction}; use rstest::rstest; - use starknet_core::types::{BlockTag, Felt, L1DataAvailabilityMode, ResourcePrice}; + use starknet_core::types::{L1DataAvailabilityMode, ResourcePrice}; + use starknet_types_core::felt::Felt; use std::sync::Arc; #[rstest] diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_tx_hashes.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_tx_hashes.rs index 59505bd63..a61550823 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_tx_hashes.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_tx_hashes.rs @@ -1,9 +1,7 @@ -use starknet_core::types::{BlockId, MaybePendingBlockWithTxHashes}; +use mp_block::{BlockId, MadaraMaybePendingBlockInfo}; +use starknet_core::types::{BlockStatus, BlockWithTxHashes, MaybePendingBlockWithTxHashes, PendingBlockWithTxHashes}; use crate::errors::StarknetRpcResult; -use mp_block::MadaraMaybePendingBlockInfo; -use starknet_core::types::{BlockStatus, BlockWithTxHashes, PendingBlockWithTxHashes}; - use crate::Starknet; /// Get block information with transaction hashes given the block id. @@ -71,8 +69,10 @@ mod tests { errors::StarknetRpcApiError, test_utils::{sample_chain_for_block_getters, SampleChainForBlockGetters}, }; + use mp_block::BlockTag; use rstest::rstest; - use starknet_core::types::{BlockTag, Felt, L1DataAvailabilityMode, ResourcePrice}; + use starknet_core::types::{L1DataAvailabilityMode, ResourcePrice}; + use starknet_types_core::felt::Felt; #[rstest] fn test_get_block_with_tx_hashes(sample_chain_for_block_getters: (SampleChainForBlockGetters, Starknet)) { diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_txs.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_txs.rs index dcd279919..40c2d6c3c 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_txs.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_block_with_txs.rs @@ -1,8 +1,6 @@ -use starknet_core::types::{BlockId, MaybePendingBlockWithTxs}; - use jsonrpsee::core::RpcResult; -use mp_block::MadaraMaybePendingBlockInfo; -use starknet_core::types::{BlockStatus, BlockWithTxs, PendingBlockWithTxs}; +use mp_block::{BlockId, MadaraMaybePendingBlockInfo}; +use starknet_core::types::{BlockStatus, BlockWithTxs, MaybePendingBlockWithTxs, PendingBlockWithTxs}; use crate::Starknet; @@ -75,8 +73,10 @@ mod tests { errors::StarknetRpcApiError, test_utils::{sample_chain_for_block_getters, SampleChainForBlockGetters}, }; + use mp_block::BlockTag; use rstest::rstest; - use starknet_core::types::{BlockTag, Felt, L1DataAvailabilityMode, ResourcePrice}; + use starknet_core::types::{L1DataAvailabilityMode, ResourcePrice}; + use starknet_types_core::felt::Felt; #[rstest] fn test_get_block_with_txs(sample_chain_for_block_getters: (SampleChainForBlockGetters, Starknet)) { diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class.rs index f7f3d5aac..5e04829d2 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class.rs @@ -1,4 +1,6 @@ -use starknet_core::types::{BlockId, ContractClass, Felt}; +use mp_block::BlockId; +use starknet_core::types::ContractClass; +use starknet_types_core::felt::Felt; use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; use crate::utils::ResultExt; diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class_at.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class_at.rs index 6d47b0a8f..1dbd3f27a 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class_at.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class_at.rs @@ -1,4 +1,6 @@ -use starknet_core::types::{BlockId, ContractClass, Felt}; +use mp_block::BlockId; +use starknet_core::types::ContractClass; +use starknet_types_core::felt::Felt; use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; use crate::utils::{OptionExt, ResultExt}; diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class_hash_at.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class_hash_at.rs index 72ee3fbc4..c0fcc6c8a 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class_hash_at.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_class_hash_at.rs @@ -1,4 +1,4 @@ -use starknet_core::types::BlockId; +use mp_block::BlockId; use starknet_types_core::felt::Felt; use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; @@ -38,8 +38,8 @@ pub fn get_class_hash_at(starknet: &Starknet, block_id: BlockId, contract_addres mod tests { use super::*; use crate::test_utils::{sample_chain_for_state_updates, SampleChainForStateUpdates}; + use mp_block::BlockTag; use rstest::rstest; - use starknet_core::types::BlockTag; #[rstest] fn test_get_class_hash_at(sample_chain_for_state_updates: (SampleChainForStateUpdates, Starknet)) { @@ -47,26 +47,26 @@ mod tests { // Block 0 let block_n = BlockId::Number(0); - assert_eq!(get_class_hash_at(&rpc, block_n, contracts[0]).unwrap(), class_hashes[0]); - assert_eq!(get_class_hash_at(&rpc, block_n, contracts[1]), Err(StarknetRpcApiError::ContractNotFound)); + assert_eq!(get_class_hash_at(&rpc, block_n.clone(), contracts[0]).unwrap(), class_hashes[0]); + assert_eq!(get_class_hash_at(&rpc, block_n.clone(), contracts[1]), Err(StarknetRpcApiError::ContractNotFound)); assert_eq!(get_class_hash_at(&rpc, block_n, contracts[2]), Err(StarknetRpcApiError::ContractNotFound)); // Block 1 let block_n = BlockId::Number(1); - assert_eq!(get_class_hash_at(&rpc, block_n, contracts[0]).unwrap(), class_hashes[0]); - assert_eq!(get_class_hash_at(&rpc, block_n, contracts[1]).unwrap(), class_hashes[1]); + assert_eq!(get_class_hash_at(&rpc, block_n.clone(), contracts[0]).unwrap(), class_hashes[0]); + assert_eq!(get_class_hash_at(&rpc, block_n.clone(), contracts[1]).unwrap(), class_hashes[1]); assert_eq!(get_class_hash_at(&rpc, block_n, contracts[2]).unwrap(), class_hashes[0]); // Block 2 let block_n = BlockId::Number(2); - assert_eq!(get_class_hash_at(&rpc, block_n, contracts[0]).unwrap(), class_hashes[0]); - assert_eq!(get_class_hash_at(&rpc, block_n, contracts[1]).unwrap(), class_hashes[1]); + assert_eq!(get_class_hash_at(&rpc, block_n.clone(), contracts[0]).unwrap(), class_hashes[0]); + assert_eq!(get_class_hash_at(&rpc, block_n.clone(), contracts[1]).unwrap(), class_hashes[1]); assert_eq!(get_class_hash_at(&rpc, block_n, contracts[2]).unwrap(), class_hashes[0]); // Pending let block_n = BlockId::Tag(BlockTag::Pending); - assert_eq!(get_class_hash_at(&rpc, block_n, contracts[0]).unwrap(), class_hashes[2]); - assert_eq!(get_class_hash_at(&rpc, block_n, contracts[1]).unwrap(), class_hashes[1]); + assert_eq!(get_class_hash_at(&rpc, block_n.clone(), contracts[0]).unwrap(), class_hashes[2]); + assert_eq!(get_class_hash_at(&rpc, block_n.clone(), contracts[1]).unwrap(), class_hashes[1]); assert_eq!(get_class_hash_at(&rpc, block_n, contracts[2]).unwrap(), class_hashes[0]); } @@ -78,7 +78,7 @@ mod tests { let block_n = BlockId::Number(3); assert_eq!(get_class_hash_at(&rpc, block_n, contracts[0]), Err(StarknetRpcApiError::BlockNotFound)); let block_n = BlockId::Number(0); - assert_eq!(get_class_hash_at(&rpc, block_n, contracts[1]), Err(StarknetRpcApiError::ContractNotFound)); + assert_eq!(get_class_hash_at(&rpc, block_n.clone(), contracts[1]), Err(StarknetRpcApiError::ContractNotFound)); let does_not_exist = Felt::from_hex_unchecked("0x7128638126378"); assert_eq!(get_class_hash_at(&rpc, block_n, does_not_exist), Err(StarknetRpcApiError::ContractNotFound)); } diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_events.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_events.rs index 4c12b75f2..81dd2175a 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_events.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_events.rs @@ -1,5 +1,6 @@ -use mp_block::{MadaraMaybePendingBlock, MadaraMaybePendingBlockInfo}; -use starknet_core::types::{BlockId, BlockTag, EmittedEvent, EventFilterWithPage, EventsPage, Felt}; +use mp_block::{BlockId, BlockTag, MadaraMaybePendingBlock, MadaraMaybePendingBlockInfo}; +use starknet_core::types::{EmittedEvent, EventFilterWithPage, EventsPage}; +use starknet_types_core::felt::Felt; use crate::constants::{MAX_EVENTS_CHUNK_SIZE, MAX_EVENTS_KEYS}; use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; @@ -105,23 +106,35 @@ fn event_match_filter(event: &EmittedEvent, address: Option, keys: &[Vec, - to_block: Option, + from_block: Option, + to_block: Option, ) -> StarknetRpcResult<(u64, u64, u64)> { let latest_block_n = starknet.get_block_n(&BlockId::Tag(BlockTag::Latest))?; let from_block_n = match from_block { - Some(BlockId::Tag(BlockTag::Pending)) => latest_block_n + 1, - Some(block_id) => starknet.get_block_n(&block_id)?, + Some(starknet_core::types::BlockId::Tag(starknet_core::types::BlockTag::Pending)) => latest_block_n + 1, + Some(block_id) => starknet.get_block_n(&to_block_id(block_id))?, None => 0, }; let to_block_n = match to_block { - Some(BlockId::Tag(BlockTag::Pending)) => latest_block_n + 1, - Some(block_id) => starknet.get_block_n(&block_id)?, + Some(starknet_core::types::BlockId::Tag(starknet_core::types::BlockTag::Pending)) => latest_block_n + 1, + Some(block_id) => starknet.get_block_n(&to_block_id(block_id))?, None => latest_block_n, }; Ok((from_block_n, to_block_n, latest_block_n)) } +// TODO: this is a temporary solution until we use all types of starknet_types_rpc +fn to_block_id(block_id: starknet_core::types::BlockId) -> BlockId { + match block_id { + starknet_core::types::BlockId::Hash(hash) => BlockId::Hash(hash), + starknet_core::types::BlockId::Number(number) => BlockId::Number(number), + starknet_core::types::BlockId::Tag(tag) => BlockId::Tag(match tag { + starknet_core::types::BlockTag::Latest => BlockTag::Latest, + starknet_core::types::BlockTag::Pending => BlockTag::Pending, + }), + } +} + fn get_block_events(_starknet: &Starknet, block: &MadaraMaybePendingBlock) -> Vec { let (block_hash, block_number) = match &block.info { MadaraMaybePendingBlockInfo::Pending(_) => (None, None), diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_nonce.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_nonce.rs index c4ea2b728..6d1bf7dd4 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_nonce.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_nonce.rs @@ -1,4 +1,4 @@ -use starknet_core::types::BlockId; +use mp_block::BlockId; use starknet_types_core::felt::Felt; use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; @@ -51,8 +51,8 @@ pub fn get_nonce(starknet: &Starknet, block_id: BlockId, contract_address: Felt) mod tests { use super::*; use crate::test_utils::{sample_chain_for_state_updates, SampleChainForStateUpdates}; + use mp_block::BlockTag; use rstest::rstest; - use starknet_core::types::BlockTag; #[rstest] fn test_get_nonce(sample_chain_for_state_updates: (SampleChainForStateUpdates, Starknet)) { @@ -60,26 +60,26 @@ mod tests { // Block 0 let block_n = BlockId::Number(0); - assert_eq!(get_nonce(&rpc, block_n, contracts[0]).unwrap(), 0.into()); - assert_eq!(get_nonce(&rpc, block_n, contracts[1]), Err(StarknetRpcApiError::ContractNotFound)); + assert_eq!(get_nonce(&rpc, block_n.clone(), contracts[0]).unwrap(), 0.into()); + assert_eq!(get_nonce(&rpc, block_n.clone(), contracts[1]), Err(StarknetRpcApiError::ContractNotFound)); assert_eq!(get_nonce(&rpc, block_n, contracts[2]), Err(StarknetRpcApiError::ContractNotFound)); // Block 1 let block_n = BlockId::Number(1); - assert_eq!(get_nonce(&rpc, block_n, contracts[0]).unwrap(), 1.into()); - assert_eq!(get_nonce(&rpc, block_n, contracts[1]).unwrap(), 0.into()); + assert_eq!(get_nonce(&rpc, block_n.clone(), contracts[0]).unwrap(), 1.into()); + assert_eq!(get_nonce(&rpc, block_n.clone(), contracts[1]).unwrap(), 0.into()); assert_eq!(get_nonce(&rpc, block_n, contracts[2]).unwrap(), 2.into()); // Block 2 let block_n = BlockId::Number(2); - assert_eq!(get_nonce(&rpc, block_n, contracts[0]).unwrap(), 1.into()); - assert_eq!(get_nonce(&rpc, block_n, contracts[1]).unwrap(), 0.into()); + assert_eq!(get_nonce(&rpc, block_n.clone(), contracts[0]).unwrap(), 1.into()); + assert_eq!(get_nonce(&rpc, block_n.clone(), contracts[1]).unwrap(), 0.into()); assert_eq!(get_nonce(&rpc, block_n, contracts[2]).unwrap(), 2.into()); // Pending let block_n = BlockId::Tag(BlockTag::Pending); - assert_eq!(get_nonce(&rpc, block_n, contracts[0]).unwrap(), 3.into()); - assert_eq!(get_nonce(&rpc, block_n, contracts[1]).unwrap(), 2.into()); + assert_eq!(get_nonce(&rpc, block_n.clone(), contracts[0]).unwrap(), 3.into()); + assert_eq!(get_nonce(&rpc, block_n.clone(), contracts[1]).unwrap(), 2.into()); assert_eq!(get_nonce(&rpc, block_n, contracts[2]).unwrap(), 2.into()); } @@ -91,7 +91,7 @@ mod tests { let block_n = BlockId::Number(3); assert_eq!(get_nonce(&rpc, block_n, contracts[0]), Err(StarknetRpcApiError::BlockNotFound)); let block_n = BlockId::Number(0); - assert_eq!(get_nonce(&rpc, block_n, contracts[1]), Err(StarknetRpcApiError::ContractNotFound)); + assert_eq!(get_nonce(&rpc, block_n.clone(), contracts[1]), Err(StarknetRpcApiError::ContractNotFound)); let does_not_exist = Felt::from_hex_unchecked("0x7128638126378"); assert_eq!(get_nonce(&rpc, block_n, does_not_exist), Err(StarknetRpcApiError::ContractNotFound)); } diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_state_update.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_state_update.rs index 3786fc765..d2b3b8cfe 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_state_update.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_state_update.rs @@ -1,4 +1,6 @@ -use starknet_core::types::{BlockId, BlockTag, Felt, MaybePendingStateUpdate, PendingStateUpdate, StateUpdate}; +use mp_block::{BlockId, BlockTag}; +use starknet_core::types::{MaybePendingStateUpdate, PendingStateUpdate, StateUpdate}; +use starknet_types_core::felt::Felt; use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; use crate::utils::OptionExt; diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_storage_at.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_storage_at.rs index b2d2f2813..a2217ad0d 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_storage_at.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_storage_at.rs @@ -1,9 +1,10 @@ +use mc_db::db_block_id::{DbBlockId, DbBlockIdResolvable}; +use mp_block::BlockId; +use starknet_types_core::felt::Felt; + use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; use crate::utils::ResultExt; use crate::Starknet; -use mc_db::db_block_id::{DbBlockId, DbBlockIdResolvable}; -use starknet_core::types::BlockId; -use starknet_types_core::felt::Felt; /// Get the value of the storage at the given address and key. /// @@ -47,6 +48,8 @@ pub fn get_storage_at( let block_number = block_id.resolve_db_block_id(&starknet.backend)?; + // Felt::ONE is a special contract address that is a mapping of the block number to the block hash. + // no contract is deployed at this address, so we skip the contract check. let skip_contract_check = matches!( block_number, Some(DbBlockId::Number(num)) if num >= 10 && contract_address == Felt::ONE @@ -73,20 +76,20 @@ pub fn get_storage_at( mod tests { use super::*; use crate::test_utils::{sample_chain_for_state_updates, SampleChainForStateUpdates}; + use mp_block::BlockTag; use rstest::rstest; - use starknet_core::types::BlockTag; #[rstest] fn test_get_storage_at(sample_chain_for_state_updates: (SampleChainForStateUpdates, Starknet)) { let (SampleChainForStateUpdates { keys, values, contracts, .. }, rpc) = sample_chain_for_state_updates; // Expected values are in the format `values[contract][key] = value`. - let check_contract_key_value = |block_n, contracts_kv: [Option<[Felt; 3]>; 3]| { + let check_contract_key_value = |block_n: BlockId, contracts_kv: [Option<[Felt; 3]>; 3]| { for (contract_i, contract_values) in contracts_kv.into_iter().enumerate() { if let Some(contract_values) = contract_values { for (key_i, value) in contract_values.into_iter().enumerate() { assert_eq!( - get_storage_at(&rpc, contracts[contract_i], keys[key_i], block_n).unwrap(), + get_storage_at(&rpc, contracts[contract_i], keys[key_i], block_n.clone()).unwrap(), value, "get storage at blockid {block_n:?}, contract #{contract_i}, key #{key_i}" ); @@ -95,7 +98,7 @@ mod tests { // contract not found for (key_i, _) in keys.iter().enumerate() { assert_eq!( - get_storage_at(&rpc, contracts[contract_i], keys[key_i], block_n), + get_storage_at(&rpc, contracts[contract_i], keys[key_i], block_n.clone()), Err(StarknetRpcApiError::ContractNotFound), "get storage at blockid {block_n:?}, contract #{contract_i}, key #{key_i} should not found" ); @@ -145,9 +148,15 @@ mod tests { let block_n = BlockId::Number(3); assert_eq!(get_storage_at(&rpc, contracts[0], keys[0], block_n), Err(StarknetRpcApiError::BlockNotFound)); let block_n = BlockId::Number(0); - assert_eq!(get_storage_at(&rpc, contracts[1], keys[0], block_n), Err(StarknetRpcApiError::ContractNotFound)); + assert_eq!( + get_storage_at(&rpc, contracts[1], keys[0], block_n.clone()), + Err(StarknetRpcApiError::ContractNotFound) + ); let does_not_exist = Felt::from_hex_unchecked("0x7128638126378"); - assert_eq!(get_storage_at(&rpc, does_not_exist, keys[0], block_n), Err(StarknetRpcApiError::ContractNotFound)); + assert_eq!( + get_storage_at(&rpc, does_not_exist, keys[0], block_n.clone()), + Err(StarknetRpcApiError::ContractNotFound) + ); assert_eq!( get_storage_at(&rpc, contracts[0], keys[1], block_n), Ok(Felt::ZERO) // return ZERO when key not found diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_by_block_id_and_index.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_by_block_id_and_index.rs index aa1abf834..4c0c2df8b 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_by_block_id_and_index.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_by_block_id_and_index.rs @@ -1,4 +1,5 @@ -use starknet_core::types::{BlockId, Transaction}; +use mp_block::BlockId; +use starknet_core::types::Transaction; use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; use crate::Starknet; @@ -39,8 +40,8 @@ pub fn get_transaction_by_block_id_and_index( mod tests { use super::*; use crate::test_utils::{sample_chain_for_block_getters, SampleChainForBlockGetters}; + use mp_block::BlockTag; use rstest::rstest; - use starknet_core::types::BlockTag; #[rstest] fn test_get_transaction_by_block_id_and_index( diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_by_hash.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_by_hash.rs index fa0cbefc7..65aae0b1a 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_by_hash.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_by_hash.rs @@ -1,4 +1,5 @@ -use starknet_core::types::{Felt, Transaction}; +use starknet_core::types::Transaction; +use starknet_types_core::felt::Felt; use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; use crate::utils::{OptionExt, ResultExt}; diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_receipt.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_receipt.rs index 08f996ea8..1d8579a97 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_receipt.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/get_transaction_receipt.rs @@ -1,5 +1,6 @@ use mp_block::MadaraMaybePendingBlockInfo; -use starknet_core::types::{Felt, TransactionFinalityStatus, TransactionReceiptWithBlockInfo}; +use starknet_core::types::{TransactionFinalityStatus, TransactionReceiptWithBlockInfo}; +use starknet_types_core::felt::Felt; use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/read/lib.rs b/crates/client/rpc/src/versions/v0_7_1/methods/read/lib.rs index 344d053c9..9c4e7e87d 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/read/lib.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/read/lib.rs @@ -1,7 +1,8 @@ use jsonrpsee::core::{async_trait, RpcResult}; +use mp_block::BlockId; use mp_chain_config::RpcVersion; use starknet_core::types::{ - BlockHashAndNumber, BlockId, BroadcastedTransaction, ContractClass, EventFilterWithPage, EventsPage, FeeEstimate, + BlockHashAndNumber, BroadcastedTransaction, ContractClass, EventFilterWithPage, EventsPage, FeeEstimate, FunctionCall, MaybePendingBlockWithReceipts, MaybePendingBlockWithTxHashes, MaybePendingBlockWithTxs, MaybePendingStateUpdate, MsgFromL1, SimulationFlagForEstimateFee, SyncStatusType, Transaction, TransactionReceiptWithBlockInfo, TransactionStatus, diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/trace/mod.rs b/crates/client/rpc/src/versions/v0_7_1/methods/trace/mod.rs index 1c29ac72f..19a84c267 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/trace/mod.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/trace/mod.rs @@ -3,11 +3,10 @@ pub mod trace_block_transactions; pub(crate) mod trace_transaction; use jsonrpsee::core::{async_trait, RpcResult}; -use starknet_core::types::{ - BlockId, BroadcastedTransaction, Felt, SimulatedTransaction, SimulationFlag, TransactionTraceWithHash, -}; - +use mp_block::BlockId; use simulate_transactions::simulate_transactions; +use starknet_core::types::{BroadcastedTransaction, SimulatedTransaction, SimulationFlag, TransactionTraceWithHash}; +use starknet_types_core::felt::Felt; use trace_block_transactions::trace_block_transactions; use trace_transaction::trace_transaction; diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/trace/simulate_transactions.rs b/crates/client/rpc/src/versions/v0_7_1/methods/trace/simulate_transactions.rs index eef9af8b0..3c8a9785e 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/trace/simulate_transactions.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/trace/simulate_transactions.rs @@ -3,8 +3,9 @@ use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; use crate::utils::ResultExt; use crate::Starknet; use mc_exec::{execution_result_to_tx_trace, ExecutionContext}; +use mp_block::BlockId; use mp_transactions::broadcasted_to_blockifier; -use starknet_core::types::{BlockId, BroadcastedTransaction, SimulatedTransaction, SimulationFlag}; +use starknet_core::types::{BroadcastedTransaction, SimulatedTransaction, SimulationFlag}; use std::sync::Arc; pub async fn simulate_transactions( diff --git a/crates/client/rpc/src/versions/v0_7_1/methods/trace/trace_block_transactions.rs b/crates/client/rpc/src/versions/v0_7_1/methods/trace/trace_block_transactions.rs index 8dfd90d5c..cae8bc41a 100644 --- a/crates/client/rpc/src/versions/v0_7_1/methods/trace/trace_block_transactions.rs +++ b/crates/client/rpc/src/versions/v0_7_1/methods/trace/trace_block_transactions.rs @@ -4,9 +4,10 @@ use crate::utils::transaction::to_blockifier_transactions; use crate::utils::ResultExt; use crate::Starknet; use mc_exec::{execution_result_to_tx_trace, ExecutionContext}; +use mp_block::BlockId; use mp_convert::ToFelt; use starknet_api::transaction::TransactionHash; -use starknet_core::types::{BlockId, TransactionTraceWithHash}; +use starknet_core::types::TransactionTraceWithHash; use std::sync::Arc; pub async fn trace_block_transactions( @@ -27,7 +28,7 @@ pub async fn trace_block_transactions( .into_iter() .zip(block.info.tx_hashes()) .map(|(tx, hash)| { - to_blockifier_transactions(starknet.clone_backend(), block_id.into(), tx, &TransactionHash(*hash)) + to_blockifier_transactions(starknet.clone_backend(), block_id.clone(), tx, &TransactionHash(*hash)) }) .collect::>()?; diff --git a/crates/client/rpc/src/versions/v0_8_0/api.rs b/crates/client/rpc/src/versions/v0_8_0/api.rs index 008ddb08b..40f87b90a 100644 --- a/crates/client/rpc/src/versions/v0_8_0/api.rs +++ b/crates/client/rpc/src/versions/v0_8_0/api.rs @@ -1,5 +1,6 @@ use jsonrpsee::core::RpcResult; use m_proc_macros::versioned_rpc; +use mp_block::BlockId; use starknet_types_core::felt::Felt; pub(crate) type NewHead = starknet_types_rpc::BlockHeader; @@ -7,8 +8,7 @@ pub(crate) type NewHead = starknet_types_rpc::BlockHeader; #[versioned_rpc("V0_8_0", "starknet")] pub trait StarknetWsRpcApi { #[subscription(name = "subscribeNewHeads", unsubscribe = "unsubscribe", item = NewHead, param_kind = map)] - async fn subscribe_new_heads(&self, block_id: starknet_core::types::BlockId) - -> jsonrpsee::core::SubscriptionResult; + async fn subscribe_new_heads(&self, block_id: BlockId) -> jsonrpsee::core::SubscriptionResult; } #[versioned_rpc("V0_8_0", "starknet")] diff --git a/crates/client/rpc/src/versions/v0_8_0/methods/read/get_compiled_casm.rs b/crates/client/rpc/src/versions/v0_8_0/methods/read/get_compiled_casm.rs index 511619a33..17ff609fa 100644 --- a/crates/client/rpc/src/versions/v0_8_0/methods/read/get_compiled_casm.rs +++ b/crates/client/rpc/src/versions/v0_8_0/methods/read/get_compiled_casm.rs @@ -1,6 +1,7 @@ use std::str::FromStr; -use starknet_core::types::{BlockId, BlockTag, Felt}; +use mp_block::{BlockId, BlockTag}; +use starknet_types_core::felt::Felt; use crate::errors::{StarknetRpcApiError, StarknetRpcResult}; use crate::utils::ResultExt; diff --git a/crates/client/rpc/src/versions/v0_8_0/methods/ws/lib.rs b/crates/client/rpc/src/versions/v0_8_0/methods/ws/lib.rs index a8ead391d..6f0d609b8 100644 --- a/crates/client/rpc/src/versions/v0_8_0/methods/ws/lib.rs +++ b/crates/client/rpc/src/versions/v0_8_0/methods/ws/lib.rs @@ -1,3 +1,5 @@ +use mp_block::{BlockId, BlockTag}; + use crate::{ errors::{ErrorExtWs, OptionExtWs, StarknetWsApiError}, versions::v0_8_0::StarknetWsRpcApiV0_8_0Server, @@ -10,17 +12,17 @@ impl StarknetWsRpcApiV0_8_0Server for crate::Starknet { async fn subscribe_new_heads( &self, subscription_sink: jsonrpsee::PendingSubscriptionSink, - block_id: starknet_core::types::BlockId, + block_id: BlockId, ) -> jsonrpsee::core::SubscriptionResult { let sink = subscription_sink.accept().await.or_internal_server_error("Failed to establish websocket connection")?; let mut block_n = match block_id { - starknet_core::types::BlockId::Number(block_n) => { + BlockId::Number(block_n) => { let err = || format!("Failed to retrieve block info for block {block_n}"); let block_latest = self .backend - .get_block_n(&mp_block::BlockId::Tag(mp_block::BlockTag::Latest)) + .get_block_n(&BlockId::Tag(BlockTag::Latest)) .or_else_internal_server_error(err)? .ok_or(StarknetWsApiError::NoBlocks)?; @@ -30,11 +32,11 @@ impl StarknetWsRpcApiV0_8_0Server for crate::Starknet { block_n } - starknet_core::types::BlockId::Hash(block_hash) => { + BlockId::Hash(block_hash) => { let err = || format!("Failed to retrieve block info at hash {block_hash:#x}"); let block_latest = self .backend - .get_block_n(&mp_block::BlockId::Tag(mp_block::BlockTag::Latest)) + .get_block_n(&BlockId::Tag(BlockTag::Latest)) .or_else_internal_server_error(err)? .ok_or(StarknetWsApiError::NoBlocks)?; @@ -50,12 +52,12 @@ impl StarknetWsRpcApiV0_8_0Server for crate::Starknet { block_n } - starknet_core::types::BlockId::Tag(starknet_core::types::BlockTag::Latest) => self + BlockId::Tag(BlockTag::Latest) => self .backend .get_latest_block_n() .or_internal_server_error("Failed to retrieve block info for latest block")? .ok_or(StarknetWsApiError::NoBlocks)?, - starknet_core::types::BlockId::Tag(starknet_core::types::BlockTag::Pending) => { + BlockId::Tag(BlockTag::Pending) => { return Err(StarknetWsApiError::Pending.into()); } }; @@ -66,7 +68,7 @@ impl StarknetWsRpcApiV0_8_0Server for crate::Starknet { return Ok(()); } - let block_info = match self.backend.get_block_info(&mp_block::BlockId::Number(n)) { + let block_info = match self.backend.get_block_info(&BlockId::Number(n)) { Ok(Some(block_info)) => { let err = || format!("Failed to retrieve block info for block {n}"); block_info.as_nonpending_owned().ok_or_else_internal_server_error(err)? @@ -138,14 +140,14 @@ async fn send_block_header<'a>( #[cfg(test)] mod test { + use super::*; + use jsonrpsee::ws_client::WsClientBuilder; - use starknet_core::types::Felt; + use starknet_types_core::felt::Felt; use crate::{ test_utils::rpc_test_setup, - versions::v0_8_0::{ - methods::ws::BLOCK_PAST_LIMIT, NewHead, StarknetWsRpcApiV0_8_0Client, StarknetWsRpcApiV0_8_0Server, - }, + versions::v0_8_0::{NewHead, StarknetWsRpcApiV0_8_0Client}, Starknet, }; @@ -171,7 +173,7 @@ mod test { .expect("Storing block"); let block_info = backend - .get_block_info(&mp_block::BlockId::Number(n)) + .get_block_info(&BlockId::Number(n)) .expect("Retrieving block info") .expect("Retrieving block info") .as_nonpending_owned() @@ -194,10 +196,8 @@ mod test { let mut generator = block_generator(&backend); let expected = generator.next().expect("Retrieving block from backend"); - let mut sub = client - .subscribe_new_heads(starknet_core::types::BlockId::Tag(starknet_core::types::BlockTag::Latest)) - .await - .expect("starknet_subscribeNewHeads"); + let mut sub = + client.subscribe_new_heads(BlockId::Tag(BlockTag::Latest)).await.expect("starknet_subscribeNewHeads"); let next = sub.next().await; let header = next.expect("Waiting for block header").expect("Waiting for block header"); @@ -224,10 +224,7 @@ mod test { let generator = block_generator(&backend); let expected: Vec<_> = generator.take(BLOCK_PAST_LIMIT as usize).collect(); - let mut sub = client - .subscribe_new_heads(starknet_core::types::BlockId::Number(0)) - .await - .expect("starknet_subscribeNewHeads"); + let mut sub = client.subscribe_new_heads(BlockId::Number(0)).await.expect("starknet_subscribeNewHeads"); for e in expected { let next = sub.next().await; @@ -256,10 +253,7 @@ mod test { let mut generator = block_generator(&backend); let expected = generator.next().expect("Retrieving block from backend"); - let mut sub = client - .subscribe_new_heads(starknet_core::types::BlockId::Number(0)) - .await - .expect("starknet_subscribeNewHeads"); + let mut sub = client.subscribe_new_heads(BlockId::Number(0)).await.expect("starknet_subscribeNewHeads"); let next = sub.next().await; let header = next.expect("Waiting for block header").expect("Waiting for block header"); @@ -289,10 +283,7 @@ mod test { let mut generator = block_generator(&backend); let _block_0 = generator.next().expect("Retrieving block from backend"); - let mut sub = client - .subscribe_new_heads(starknet_core::types::BlockId::Number(1)) - .await - .expect("starknet_subscribeNewHeads"); + let mut sub = client.subscribe_new_heads(BlockId::Number(1)).await.expect("starknet_subscribeNewHeads"); let block_1 = generator.next().expect("Retrieving block from backend"); @@ -327,10 +318,7 @@ mod test { let generator = block_generator(&backend); let _expected: Vec<_> = generator.take(BLOCK_PAST_LIMIT as usize + 2).collect(); - let mut sub = client - .subscribe_new_heads(starknet_core::types::BlockId::Number(0)) - .await - .expect("starknet_subscribeNewHeads"); + let mut sub = client.subscribe_new_heads(BlockId::Number(0)).await.expect("starknet_subscribeNewHeads"); // Jsonrsee seems to just close the connection and not return the error // to the client so this is the best we can do :/ @@ -354,10 +342,8 @@ mod test { let generator = block_generator(&backend); let _expected: Vec<_> = generator.take(BLOCK_PAST_LIMIT as usize + 2).collect(); - let mut sub = client - .subscribe_new_heads(starknet_core::types::BlockId::Hash(Felt::from(0))) - .await - .expect("starknet_subscribeNewHeads"); + let mut sub = + client.subscribe_new_heads(BlockId::Hash(Felt::from(0))).await.expect("starknet_subscribeNewHeads"); // Jsonrsee seems to just close the connection and not return the error // to the client so this is the best we can do :/ @@ -378,10 +364,8 @@ mod test { let generator = block_generator(&backend); let _expected: Vec<_> = generator.take(BLOCK_PAST_LIMIT as usize + 2).collect(); - let mut sub = client - .subscribe_new_heads(starknet_core::types::BlockId::Tag(starknet_core::types::BlockTag::Pending)) - .await - .expect("starknet_subscribeNewHeads"); + let mut sub = + client.subscribe_new_heads(BlockId::Tag(BlockTag::Pending)).await.expect("starknet_subscribeNewHeads"); // Jsonrsee seems to just close the connection and not return the error // to the client so this is the best we can do :/ diff --git a/crates/client/sync/src/fetch/fetchers.rs b/crates/client/sync/src/fetch/fetchers.rs index a793ff6bc..4cb8e2daf 100644 --- a/crates/client/sync/src/fetch/fetchers.rs +++ b/crates/client/sync/src/fetch/fetchers.rs @@ -2,19 +2,17 @@ use super::FetchError; use crate::l2::L2SyncError; use anyhow::Context; -use core::fmt; use core::time::Duration; use futures::FutureExt; use mc_block_import::{UnverifiedCommitments, UnverifiedFullBlock, UnverifiedPendingFullBlock}; use mc_gateway_client::GatewayProvider; +use mp_block::{BlockId, BlockTag}; use mp_class::class_update::{ClassUpdate, LegacyClassUpdate, SierraClassUpdate}; use mp_class::{ContractClass, MISSED_CLASS_HASHES}; -use mp_convert::ToFelt; use mp_gateway::block::{ProviderBlock, ProviderBlockPending}; use mp_gateway::error::{SequencerError, StarknetError, StarknetErrorCode}; use mp_gateway::state_update::ProviderStateUpdateWithBlockPendingMaybe::{self}; use mp_gateway::state_update::{ProviderStateUpdate, ProviderStateUpdatePending, StateDiff}; -use mp_transactions::MAIN_CHAIN_ID; use mp_utils::{stopwatch_end, wait_or_graceful_shutdown, PerfStopwatch}; use starknet_api::core::ChainId; use starknet_types_core::felt::Felt; @@ -44,57 +42,16 @@ pub struct FetchConfig { pub n_blocks_to_sync: Option, } -#[derive(Clone, Copy, PartialEq, Eq)] -pub enum FetchBlockId { - BlockN(u64), - Pending, -} - -impl FetchBlockId { - pub fn block_n(self) -> Option { - match self { - FetchBlockId::BlockN(block_n) => Some(block_n), - FetchBlockId::Pending => None, - } - } -} - -impl fmt::Debug for FetchBlockId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::BlockN(block) => write!(f, "#{}", block), - Self::Pending => write!(f, ""), - } - } -} - -impl From for mp_block::BlockId { - fn from(value: FetchBlockId) -> Self { - match value { - FetchBlockId::BlockN(block_n) => mp_block::BlockId::Number(block_n), - FetchBlockId::Pending => mp_block::BlockId::Tag(mp_block::BlockTag::Pending), - } - } -} -impl From for starknet_core::types::BlockId { - fn from(value: FetchBlockId) -> Self { - match value { - FetchBlockId::BlockN(block_n) => starknet_core::types::BlockId::Number(block_n), - FetchBlockId::Pending => starknet_core::types::BlockId::Tag(starknet_core::types::BlockTag::Pending), - } - } -} - pub async fn fetch_pending_block_and_updates( parent_block_hash: Felt, chain_id: &ChainId, provider: &GatewayProvider, ) -> Result, FetchError> { - let block_id = FetchBlockId::Pending; + let block_id = BlockId::Tag(BlockTag::Pending); let sw = PerfStopwatch::new(); let block = retry( || async { - match provider.get_state_update_with_block(block_id.into()).await { + match provider.get_state_update_with_block(block_id.clone()).await { Ok(block) => Ok(Some(block)), // Ignore (this is the case where we returned a closed block when we asked for a pending one) // When the FGW does not have a pending block, it can return the latest block instead @@ -125,7 +82,7 @@ pub async fn fetch_pending_block_and_updates( ); return Ok(None); } - let class_update = fetch_class_updates(chain_id, &state_update.state_diff, block_id, provider).await?; + let class_update = fetch_class_updates(chain_id, &state_update.state_diff, block_id.clone(), provider).await?; stopwatch_end!(sw, "fetching {:?}: {:?}", block_id); @@ -140,13 +97,13 @@ pub async fn fetch_block_and_updates( block_n: u64, provider: &GatewayProvider, ) -> Result { - let block_id = FetchBlockId::BlockN(block_n); + let block_id = BlockId::Number(block_n); let sw = PerfStopwatch::new(); let (state_update, block) = retry( || async { provider - .get_state_update_with_block(block_id.into()) + .get_state_update_with_block(block_id.clone()) .await .map(ProviderStateUpdateWithBlockPendingMaybe::as_update_and_block) }, @@ -204,18 +161,16 @@ where async fn fetch_class_updates( chain_id: &ChainId, state_diff: &StateDiff, - block_id: FetchBlockId, + block_id: BlockId, provider: &GatewayProvider, ) -> anyhow::Result> { - let chain_id: Felt = chain_id.to_felt(); - // for blocks before 2597 on mainnet new classes are not declared in the state update // https://github.com/madara-alliance/madara/issues/233 - let legacy_classes: Vec<_> = if chain_id == MAIN_CHAIN_ID && block_id.block_n().is_some_and(|id| id < 2597) { - let block_number = block_id.block_n().unwrap(); // Safe to unwrap because of the condition above - MISSED_CLASS_HASHES.get(&block_number).cloned().unwrap_or_default() - } else { - state_diff.old_declared_contracts.clone() + let legacy_classes: Vec<_> = match (chain_id, &block_id) { + (ChainId::Mainnet, &BlockId::Number(block_n)) if block_n < 2597 => { + MISSED_CLASS_HASHES.get(&block_n).cloned().unwrap_or_default() + } + _ => state_diff.old_declared_contracts.clone(), }; let sierra_classes: Vec<_> = state_diff @@ -225,9 +180,10 @@ async fn fetch_class_updates( .collect(); let legacy_class_futures = legacy_classes.into_iter().map(|class_hash| { + let block_id = block_id.clone(); async move { let (class_hash, contract_class) = - retry(|| fetch_class(class_hash, block_id, provider), MAX_RETRY, BASE_DELAY).await?; + retry(|| fetch_class(class_hash, block_id.clone(), provider), MAX_RETRY, BASE_DELAY).await?; let ContractClass::Legacy(contract_class) = contract_class else { return Err(L2SyncError::UnexpectedClassType { class_hash }); @@ -241,9 +197,10 @@ async fn fetch_class_updates( }); let sierra_class_futures = sierra_classes.into_iter().map(|(class_hash, &compiled_class_hash)| { + let block_id = block_id.clone(); async move { let (class_hash, contract_class) = - retry(|| fetch_class(class_hash, block_id, provider), MAX_RETRY, BASE_DELAY).await?; + retry(|| fetch_class(class_hash, block_id.clone(), provider), MAX_RETRY, BASE_DELAY).await?; let ContractClass::Sierra(contract_class) = contract_class else { return Err(L2SyncError::UnexpectedClassType { class_hash }); @@ -267,10 +224,10 @@ async fn fetch_class_updates( /// of the current type hell we decided to deal with raw JSON data instead of starknet-providers `DeployedContract`. async fn fetch_class( class_hash: Felt, - block_id: FetchBlockId, + block_id: BlockId, provider: &GatewayProvider, ) -> Result<(Felt, ContractClass), SequencerError> { - let contract_class = provider.get_class_by_hash(class_hash, block_id.into()).await?; + let contract_class = provider.get_class_by_hash(class_hash, block_id).await?; tracing::debug!("Got the contract class {:?}", class_hash); Ok((class_hash, contract_class)) } @@ -484,7 +441,7 @@ mod test_l2_fetchers { let (state_update, block) = ctx .provider - .get_state_update_with_block(FetchBlockId::Pending.into()) + .get_state_update_with_block(BlockId::Tag(BlockTag::Pending)) .await .expect("Failed to fetch state update with block on tag pending") .as_update_and_block(); @@ -600,7 +557,7 @@ mod test_l2_fetchers { // Mock a "block not found" scenario ctx.mock_block_not_found(5); - let result = ctx.provider.get_state_update_with_block(FetchBlockId::BlockN(5).into()).await; + let result = ctx.provider.get_state_update_with_block(BlockId::Number(5)).await; assert!( matches!( @@ -626,7 +583,7 @@ mod test_l2_fetchers { ctx.mock_block_partial_data(5); ctx.mock_class_hash(m_cairo_test_contracts::TEST_CONTRACT_SIERRA); - let result = ctx.provider.get_state_update_with_block(FetchBlockId::BlockN(5).into()).await; + let result = ctx.provider.get_state_update_with_block(BlockId::Number(5)).await; assert!( matches!(result, Err(SequencerError::DeserializeBody { .. })), @@ -653,20 +610,16 @@ mod test_l2_fetchers { // block, DO NOT call `get_state_update` on it! let state_update = ctx .provider - .get_state_update_with_block(FetchBlockId::BlockN(5).into()) + .get_state_update_with_block(BlockId::Number(5)) .await .expect("Failed to fetch state update at block number 5") .state_update(); let state_diff = state_update.state_diff(); - let class_updates = fetch_class_updates( - &ctx.backend.chain_config().chain_id, - state_diff, - FetchBlockId::BlockN(5), - &ctx.provider, - ) - .await - .expect("Failed to fetch class updates"); + let class_updates = + fetch_class_updates(&ctx.backend.chain_config().chain_id, state_diff, BlockId::Number(5), &ctx.provider) + .await + .expect("Failed to fetch class updates"); assert!(!class_updates.is_empty(), "Should have fetched at least one class update"); @@ -688,20 +641,16 @@ mod test_l2_fetchers { ctx.mock_block(5); let state_update = ctx .provider - .get_state_update_with_block(FetchBlockId::BlockN(5).into()) + .get_state_update_with_block(BlockId::Number(5)) .await .expect("Failed to fetch state update at block number 5") .state_update(); let state_diff = state_update.state_diff(); ctx.mock_class_hash_not_found("0x40fe2533528521fc49a8ad8440f8a1780c50337a94d0fce43756015fa816a8a".to_string()); - let result = fetch_class_updates( - &ctx.backend.chain_config().chain_id, - state_diff, - FetchBlockId::BlockN(5), - &ctx.provider, - ) - .await; + let result = + fetch_class_updates(&ctx.backend.chain_config().chain_id, state_diff, BlockId::Number(5), &ctx.provider) + .await; assert!(matches!( result, @@ -726,7 +675,7 @@ mod test_l2_fetchers { ctx.mock_class_hash(m_cairo_test_contracts::TEST_CONTRACT_SIERRA); let (fetched_hash, _contract_class) = - fetch_class(class_hash, FetchBlockId::BlockN(5), &ctx.provider).await.expect("Failed to fetch class"); + fetch_class(class_hash, BlockId::Number(5), &ctx.provider).await.expect("Failed to fetch class"); assert_eq!(fetched_hash, class_hash, "Fetched class hash should match the requested one"); } @@ -744,7 +693,7 @@ mod test_l2_fetchers { let class_hash = felt!("0x1234"); ctx.mock_class_hash_not_found("0x1234".to_string()); - let result = fetch_class(class_hash, FetchBlockId::BlockN(5), &ctx.provider).await; + let result = fetch_class(class_hash, BlockId::Number(5), &ctx.provider).await; assert!( matches!( @@ -766,7 +715,7 @@ mod test_l2_fetchers { let (state_update, block) = ctx .provider - .get_state_update_with_block(FetchBlockId::BlockN(5).into()) + .get_state_update_with_block(BlockId::Number(5)) .await .expect("Failed to fetch state update with block at block number 5") .as_update_and_block(); diff --git a/crates/client/sync/src/lib.rs b/crates/client/sync/src/lib.rs index 221731e64..8437c8a32 100644 --- a/crates/client/sync/src/lib.rs +++ b/crates/client/sync/src/lib.rs @@ -6,6 +6,7 @@ use mc_block_import::BlockImporter; use mc_db::MadaraBackend; use mc_gateway_client::GatewayProvider; use mc_telemetry::TelemetryHandle; +use mp_block::{BlockId, BlockTag}; use std::{sync::Arc, time::Duration}; pub mod fetch; @@ -32,7 +33,7 @@ pub async fn sync( } else { ( backend - .get_block_n(&mp_block::BlockId::Tag(mp_block::BlockTag::Latest)) + .get_block_n(&BlockId::Tag(BlockTag::Latest)) .context("getting sync tip")? .map(|block_id| block_id + 1) // next block after the tip .unwrap_or_default() as _, // or genesis diff --git a/crates/primitives/block/src/lib.rs b/crates/primitives/block/src/lib.rs index 354109bab..4cca7ef65 100644 --- a/crates/primitives/block/src/lib.rs +++ b/crates/primitives/block/src/lib.rs @@ -2,8 +2,6 @@ pub mod header; -use std::fmt::Display; - pub use header::Header; use header::{L1DataAvailabilityMode, PendingHeader}; use mp_chain_config::StarknetVersion; @@ -14,6 +12,9 @@ use starknet_types_core::felt::Felt; use crate::header::GasPrices; +pub type BlockId = starknet_types_rpc::BlockId; +pub type BlockTag = starknet_types_rpc::BlockTag; + #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[allow(clippy::large_enum_variant)] pub enum MadaraMaybePendingBlockInfo { @@ -130,74 +131,6 @@ impl From for starknet_types_rpc::BlockHeader { } } -/// Block tag. -/// -/// A tag specifying a dynamic reference to a block. -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, serde::Serialize)] -#[serde(rename_all = "lowercase")] -pub enum BlockTag { - Latest, - Pending, -} - -impl From for BlockTag { - fn from(value: starknet_core::types::BlockTag) -> Self { - match value { - starknet_core::types::BlockTag::Latest => BlockTag::Latest, - starknet_core::types::BlockTag::Pending => BlockTag::Pending, - } - } -} - -impl From for starknet_core::types::BlockTag { - fn from(value: BlockTag) -> Self { - match value { - BlockTag::Latest => starknet_core::types::BlockTag::Latest, - BlockTag::Pending => starknet_core::types::BlockTag::Pending, - } - } -} - -/// Block Id -/// Block hash, number or tag -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum BlockId { - Hash(Felt), - Number(u64), - Tag(BlockTag), -} - -impl From for BlockId { - fn from(value: starknet_core::types::BlockId) -> Self { - match value { - starknet_core::types::BlockId::Hash(felt) => BlockId::Hash(Felt::from_bytes_be(&felt.to_bytes_be())), - starknet_core::types::BlockId::Number(number) => BlockId::Number(number), - starknet_core::types::BlockId::Tag(tag) => BlockId::Tag(tag.into()), - } - } -} -impl From for starknet_core::types::BlockId { - fn from(value: BlockId) -> Self { - match value { - BlockId::Hash(felt) => starknet_core::types::BlockId::Hash(felt), - BlockId::Number(number) => starknet_core::types::BlockId::Number(number), - BlockId::Tag(tag) => starknet_core::types::BlockId::Tag(tag.into()), - } - } -} -impl Display for BlockId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - BlockId::Hash(hash) => write!(f, "0x{hash:x}"), - BlockId::Number(number) => write!(f, "{number}"), - BlockId::Tag(blocktag) => match blocktag { - BlockTag::Latest => write!(f, "latest"), - BlockTag::Pending => write!(f, "pending"), - }, - } - } -} - // Light version of the block with block_hash #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct MadaraPendingBlockInfo { @@ -376,40 +309,4 @@ mod tests { assert!(MadaraBlock::try_from(maybe_pending.clone()).is_err()); assert!(MadaraPendingBlock::try_from(maybe_pending.clone()).is_ok()); } - - #[test] - fn test_block_tag() { - let tag = BlockTag::Latest; - let tag_converted: starknet_core::types::BlockTag = tag.into(); - assert_eq!(tag_converted, starknet_core::types::BlockTag::Latest); - let tag_back: BlockTag = tag_converted.into(); - assert_eq!(tag_back, tag); - - let tag = BlockTag::Pending; - let tag_converted: starknet_core::types::BlockTag = tag.into(); - assert_eq!(tag_converted, starknet_core::types::BlockTag::Pending); - let tag_back: BlockTag = tag_converted.into(); - assert_eq!(tag_back, tag); - } - - #[test] - fn test_block_id() { - let hash = Felt::from(1); - let hash_converted: starknet_core::types::BlockId = BlockId::Hash(hash).into(); - assert_eq!(hash_converted, starknet_core::types::BlockId::Hash(hash)); - let hash_back: BlockId = hash_converted.into(); - assert_eq!(hash_back, BlockId::Hash(hash)); - - let number = 1; - let number_converted: starknet_core::types::BlockId = BlockId::Number(number).into(); - assert_eq!(number_converted, starknet_core::types::BlockId::Number(number)); - let number_back: BlockId = number_converted.into(); - assert_eq!(number_back, BlockId::Number(number)); - - let tag = BlockTag::Latest; - let tag_converted: starknet_core::types::BlockId = BlockId::Tag(tag).into(); - assert_eq!(tag_converted, starknet_core::types::BlockId::Tag(starknet_core::types::BlockTag::Latest)); - let tag_back: BlockId = tag_converted.into(); - assert_eq!(tag_back, BlockId::Tag(BlockTag::Latest)); - } } diff --git a/crates/primitives/class/src/class_hash.rs b/crates/primitives/class/src/class_hash.rs index 674547ff1..c46839a4d 100644 --- a/crates/primitives/class/src/class_hash.rs +++ b/crates/primitives/class/src/class_hash.rs @@ -72,8 +72,8 @@ impl CompressedLegacyContractClass { mod tests { use starknet_core::types::BlockId; use starknet_core::types::BlockTag; - use starknet_core::types::Felt; use starknet_providers::{Provider, SequencerGatewayProvider}; + use starknet_types_core::felt::Felt; use crate::ContractClass; diff --git a/crates/primitives/gateway/src/error.rs b/crates/primitives/gateway/src/error.rs index 06ccfbffd..7b38a84c5 100644 --- a/crates/primitives/gateway/src/error.rs +++ b/crates/primitives/gateway/src/error.rs @@ -1,6 +1,6 @@ use hyper::StatusCode; use serde::{Deserialize, Serialize}; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; use starknet_types_core::felt::FromStrError; #[derive(Debug, thiserror::Error)] diff --git a/crates/primitives/utils/Cargo.toml b/crates/primitives/utils/Cargo.toml index 9e0f73f5a..7772292ab 100644 --- a/crates/primitives/utils/Cargo.toml +++ b/crates/primitives/utils/Cargo.toml @@ -19,6 +19,7 @@ targets = ["x86_64-unknown-linux-gnu"] # Starknet starknet-core.workspace = true starknet-crypto.workspace = true +starknet-types-core.workspace = true # Other anyhow.workspace = true diff --git a/crates/primitives/utils/src/crypto.rs b/crates/primitives/utils/src/crypto.rs index f82b9ba7c..17681d2c4 100644 --- a/crates/primitives/utils/src/crypto.rs +++ b/crates/primitives/utils/src/crypto.rs @@ -1,6 +1,6 @@ use crypto_bigint::{Encoding, NonZero, U256}; use rand::{rngs::StdRng, Rng, SeedableRng}; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; /// A private key store with zeroing safeguards #[derive(serde::Serialize, serde::Deserialize)] diff --git a/crates/primitives/utils/src/parsers.rs b/crates/primitives/utils/src/parsers.rs index 10890ffd9..244b403ff 100644 --- a/crates/primitives/utils/src/parsers.rs +++ b/crates/primitives/utils/src/parsers.rs @@ -1,6 +1,6 @@ use anyhow::{anyhow, bail, ensure, Context}; use serde_yaml::Value; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; use std::time::Duration; diff --git a/crates/primitives/utils/src/serde.rs b/crates/primitives/utils/src/serde.rs index e9134adb8..aea7816bb 100644 --- a/crates/primitives/utils/src/serde.rs +++ b/crates/primitives/utils/src/serde.rs @@ -1,7 +1,7 @@ use std::time::Duration; use serde::{Deserialize, Deserializer}; -use starknet_core::types::Felt; +use starknet_types_core::felt::Felt; use crate::{crypto::ZeroingPrivateKey, parsers::parse_duration}; diff --git a/crates/tests/Cargo.toml b/crates/tests/Cargo.toml index 40f677a38..1254ffd7b 100644 --- a/crates/tests/Cargo.toml +++ b/crates/tests/Cargo.toml @@ -23,6 +23,7 @@ serde_json = { workspace = true } starknet = { workspace = true } starknet-core.workspace = true starknet-providers.workspace = true +starknet-types-core.workspace = true tempfile.workspace = true tokio = { workspace = true, features = ["rt", "macros"] } tracing-subscriber.workspace = true diff --git a/crates/tests/src/lib.rs b/crates/tests/src/lib.rs index 027569715..f024f59b2 100644 --- a/crates/tests/src/lib.rs +++ b/crates/tests/src/lib.rs @@ -222,7 +222,8 @@ fn madara_help_shows() { #[rstest] #[tokio::test] async fn madara_can_sync_a_few_blocks() { - use starknet_core::types::{BlockHashAndNumber, Felt}; + use starknet_core::types::BlockHashAndNumber; + use starknet_types_core::felt::Felt; let _ = tracing_subscriber::fmt().with_test_writer().try_init();