Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: move rpc state reader to state reader crate #492

Open
wants to merge 1 commit into
base: pr/Itay-Tsabary-Starkware/tsabary/state_reader_client/53ab0222
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion crates/gateway/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ hyper.workspace = true
mempool_test_utils = { path = "../mempool_test_utils", version = "0.0" }
num-traits.workspace = true
papyrus_config.workspace = true
papyrus_rpc.workspace = true
reqwest.workspace = true
serde.workspace = true
serde_json.workspace = true
Expand Down
27 changes: 0 additions & 27 deletions crates/gateway/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,33 +147,6 @@ impl SerializeConfig for StatelessTransactionValidatorConfig {
}
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, Validate, PartialEq)]
pub struct RpcStateReaderConfig {
pub url: String,
pub json_rpc_version: String,
}

#[cfg(any(feature = "testing", test))]
impl RpcStateReaderConfig {
pub fn create_for_testing() -> Self {
Self { url: "http://localhost:8080".to_string(), json_rpc_version: "2.0".to_string() }
}
}

impl SerializeConfig for RpcStateReaderConfig {
fn dump(&self) -> BTreeMap<ParamPath, SerializedParam> {
BTreeMap::from_iter([
ser_param("url", &self.url, "The url of the rpc server.", ParamPrivacyInput::Public),
ser_param(
"json_rpc_version",
&self.json_rpc_version,
"The json rpc version.",
ParamPrivacyInput::Public,
),
])
}
}

// TODO(Arni): Remove this struct once Chain info supports Papyrus serialization.
#[derive(Clone, Debug, Serialize, Deserialize, Validate, PartialEq)]
pub struct ChainInfoConfig {
Expand Down
23 changes: 1 addition & 22 deletions crates/gateway/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use blockifier::execution::errors::ContractClassError;
use blockifier::state::errors::StateError;
use blockifier::transaction::errors::TransactionExecutionError;
use cairo_vm::types::errors::program_errors::ProgramError;
use serde_json::{Error as SerdeError, Value};
use serde_json::Value;
use starknet_api::block::{BlockNumber, GasPrice};
use starknet_api::core::CompiledClassHash;
use starknet_api::transaction::{Resource, ResourceBounds};
Expand Down Expand Up @@ -134,24 +134,3 @@ pub enum RPCStateReaderError {
#[error("Unexpected error code: {0}")]
UnexpectedErrorCode(u16),
}

pub type RPCStateReaderResult<T> = Result<T, RPCStateReaderError>;

impl From<RPCStateReaderError> for StateError {
fn from(err: RPCStateReaderError) -> Self {
match err {
RPCStateReaderError::ClassHashNotFound(request) => {
match serde_json::from_value(request["params"]["class_hash"].clone()) {
Ok(class_hash) => StateError::UndeclaredClassHash(class_hash),
Err(e) => serde_err_to_state_err(e),
}
}
_ => StateError::StateReadError(err.to_string()),
}
}
}

// Converts a serde error to the error type of the state reader.
pub fn serde_err_to_state_err(err: SerdeError) -> StateError {
StateError::StateReadError(format!("Failed to parse rpc result {:?}", err.to_string()))
}
5 changes: 3 additions & 2 deletions crates/gateway/src/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ use starknet_api::transaction::TransactionHash;
use starknet_mempool_infra::component_runner::{ComponentStartError, ComponentStarter};
use starknet_mempool_types::communication::SharedMempoolClient;
use starknet_mempool_types::mempool_types::{Account, MempoolInput};
use starknet_state_reader::config::RpcStateReaderConfig;
use starknet_state_reader::rpc_state_reader::RpcStateReaderFactory;
use starknet_state_reader::state_reader::StateReaderFactory;
use tracing::{info, instrument};

use crate::compilation::GatewayCompiler;
use crate::config::{GatewayConfig, GatewayNetworkConfig, RpcStateReaderConfig};
use crate::config::{GatewayConfig, GatewayNetworkConfig};
use crate::errors::{GatewayError, GatewayResult, GatewayRunError};
use crate::rpc_state_reader::RpcStateReaderFactory;
use crate::stateful_transaction_validator::StatefulTransactionValidator;
use crate::stateless_transaction_validator::StatelessTransactionValidator;
use crate::utils::{external_tx_to_thin_tx, get_sender_address};
Expand Down
4 changes: 0 additions & 4 deletions crates/gateway/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@ mod compiler_version;
pub mod config;
pub mod errors;
pub mod gateway;
mod rpc_objects;
mod rpc_state_reader;
#[cfg(test)]
mod rpc_state_reader_test;

mod stateful_transaction_validator;
mod stateless_transaction_validator;
Expand Down
3 changes: 2 additions & 1 deletion crates/mempool_node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ starknet_gateway = { path = "../gateway", version = "0.0" }
starknet_mempool = { path = "../mempool", version = "0.0" }
starknet_mempool_infra = { path = "../mempool_infra", version = "0.0" }
starknet_mempool_types = { path = "../mempool_types", version = "0.0" }
starknet_state_reader = { path = "../state_reader", version = "0.0" }
tokio.workspace = true
tracing.workspace = true
validator.workspace = true
Expand All @@ -27,6 +28,6 @@ validator.workspace = true
assert-json-diff.workspace = true
assert_matches.workspace = true
colored.workspace = true
mempool_test_utils = { path = "../mempool_test_utils" }
pretty_assertions.workspace = true
serde_json.workspace = true
mempool_test_utils = { path = "../mempool_test_utils" }
3 changes: 2 additions & 1 deletion crates/mempool_node/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ use papyrus_config::dumping::{append_sub_config_name, ser_param, SerializeConfig
use papyrus_config::loading::load_and_process_config;
use papyrus_config::{ConfigError, ParamPath, ParamPrivacyInput, SerializedParam};
use serde::{Deserialize, Serialize};
use starknet_gateway::config::{GatewayConfig, RpcStateReaderConfig};
use starknet_gateway::config::GatewayConfig;
use starknet_state_reader::config::RpcStateReaderConfig;
use validator::{Validate, ValidationError};

use crate::version::VERSION_FULL;
Expand Down
13 changes: 13 additions & 0 deletions crates/state_reader/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,20 @@ workspace = true
testing = []

[dependencies]
axum.workspace = true
blockifier = { workspace = true, features = ["testing"] }
cairo-lang-starknet-classes.workspace = true
mempool_test_utils = { path = "../mempool_test_utils", version = "0.0" }
papyrus_config.workspace = true
papyrus_rpc.workspace = true
reqwest.workspace = true
serde.workspace = true
serde_json.workspace = true
starknet-types-core.workspace = true
starknet_api.workspace = true
thiserror.workspace = true
tokio.workspace = true
validator.workspace = true

[dev-dependencies]
mockito.workspace = true
33 changes: 33 additions & 0 deletions crates/state_reader/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use std::collections::BTreeMap;

use papyrus_config::dumping::{ser_param, SerializeConfig};
use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam};
use serde::{Deserialize, Serialize};
use validator::Validate;

#[derive(Clone, Debug, Default, Serialize, Deserialize, Validate, PartialEq)]
pub struct RpcStateReaderConfig {
pub url: String,
pub json_rpc_version: String,
}

#[cfg(any(feature = "testing", test))]
impl RpcStateReaderConfig {
pub fn create_for_testing() -> Self {
Self { url: "http://localhost:8080".to_string(), json_rpc_version: "2.0".to_string() }
}
}

impl SerializeConfig for RpcStateReaderConfig {
fn dump(&self) -> BTreeMap<ParamPath, SerializedParam> {
BTreeMap::from_iter([
ser_param("url", &self.url, "The url of the rpc server.", ParamPrivacyInput::Public),
ser_param(
"json_rpc_version",
&self.json_rpc_version,
"The json rpc version.",
ParamPrivacyInput::Public,
),
])
}
}
44 changes: 44 additions & 0 deletions crates/state_reader/src/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use axum::http::StatusCode;
use blockifier::state::errors::StateError;
use serde_json::{Error as SerdeError, Value};
use starknet_api::block::GasPrice;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum RPCStateReaderError {
#[error("Block not found for request {0}")]
BlockNotFound(Value),
#[error("Class hash not found for request {0}")]
ClassHashNotFound(Value),
#[error("Failed to parse gas price {:?}", 0)]
GasPriceParsingFailure(GasPrice),
#[error("Contract address not found for request {0}")]
ContractAddressNotFound(Value),
#[error(transparent)]
ReqwestError(#[from] reqwest::Error),
#[error("RPC error: {0}")]
RPCError(StatusCode),
#[error("Unexpected error code: {0}")]
UnexpectedErrorCode(u16),
}

pub type RPCStateReaderResult<T> = Result<T, RPCStateReaderError>;

impl From<RPCStateReaderError> for StateError {
fn from(err: RPCStateReaderError) -> Self {
match err {
RPCStateReaderError::ClassHashNotFound(request) => {
match serde_json::from_value(request["params"]["class_hash"].clone()) {
Ok(class_hash) => StateError::UndeclaredClassHash(class_hash),
Err(e) => serde_err_to_state_err(e),
}
}
_ => StateError::StateReadError(err.to_string()),
}
}
}

// Converts a serde error to the error type of the state reader.
pub fn serde_err_to_state_err(err: SerdeError) -> StateError {
StateError::StateReadError(format!("Failed to parse rpc result {:?}", err.to_string()))
}
5 changes: 4 additions & 1 deletion crates/state_reader/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
pub mod config;
pub mod errors;
mod rpc_objects;
pub mod rpc_state_reader;
pub mod state_reader;

#[cfg(any(feature = "testing", test))]
pub mod state_reader_test_utils;
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
#[cfg(test)]
#[path = "rpc_state_reader_test.rs"]
mod rpc_state_reader_test;

use blockifier::blockifier::block::BlockInfo;
use blockifier::execution::contract_class::{ContractClass, ContractClassV0, ContractClassV1};
use blockifier::state::errors::StateError;
Expand All @@ -9,7 +13,6 @@ use serde_json::{json, Value};
use starknet_api::block::BlockNumber;
use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce};
use starknet_api::state::StorageKey;
use starknet_state_reader::state_reader::{MempoolStateReader, StateReaderFactory};
use starknet_types_core::felt::Felt;

use crate::config::RpcStateReaderConfig;
Expand All @@ -19,6 +22,7 @@ use crate::rpc_objects::{
GetCompiledContractClassParams, GetNonceParams, GetStorageAtParams, RpcResponse,
RPC_CLASS_HASH_NOT_FOUND, RPC_ERROR_BLOCK_NOT_FOUND, RPC_ERROR_CONTRACT_ADDRESS_NOT_FOUND,
};
use crate::state_reader::{MempoolStateReader, StateReaderFactory};

pub struct RpcStateReader {
pub config: RpcStateReaderConfig,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use serde_json::json;
use starknet_api::block::{BlockNumber, GasPrice};
use starknet_api::core::{ClassHash, ContractAddress, Nonce, PatriciaKey};
use starknet_api::{class_hash, contract_address, felt, patricia_key};
use starknet_state_reader::state_reader::MempoolStateReader;

use crate::config::RpcStateReaderConfig;
use crate::rpc_objects::{
Expand All @@ -16,6 +15,7 @@ use crate::rpc_objects::{
RpcSuccessResponse,
};
use crate::rpc_state_reader::RpcStateReader;
use crate::state_reader::MempoolStateReader;

async fn run_rpc_server() -> mockito::ServerGuard {
mockito::Server::new_async().await
Expand Down
1 change: 1 addition & 0 deletions crates/tests-integration/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ starknet_gateway = { path = "../gateway", version = "0.0", features = ["testing"
starknet_mempool_infra = { path = "../mempool_infra", version = "0.0" }
starknet_mempool_node = { path = "../mempool_node", version = "0.0" }
starknet_mempool_types = { path = "../mempool_types", version = "0.0" }
starknet_state_reader = { path = "../state_reader", version = "0.0" }
starknet_task_executor = { path = "../task_executor", version = "0.0" }
strum.workspace = true
tempfile.workspace = true
Expand Down
3 changes: 2 additions & 1 deletion crates/tests-integration/src/integration_test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ use reqwest::{Client, Response};
use starknet_api::rpc_transaction::RPCTransaction;
use starknet_api::transaction::TransactionHash;
use starknet_gateway::config::{
GatewayConfig, GatewayNetworkConfig, RpcStateReaderConfig, StatefulTransactionValidatorConfig,
GatewayConfig, GatewayNetworkConfig, StatefulTransactionValidatorConfig,
StatelessTransactionValidatorConfig,
};
use starknet_gateway::errors::GatewayError;
use starknet_mempool_node::config::MempoolNodeConfig;
use starknet_state_reader::config::RpcStateReaderConfig;
use tokio::net::TcpListener;

use crate::integration_test_setup::IntegrationTestSetup;
Expand Down
Loading