From 6097782afb58b1cdb33176264151e9c4dec54e5e Mon Sep 17 00:00:00 2001 From: jb caron Date: Tue, 5 Mar 2024 11:50:22 +0100 Subject: [PATCH 1/3] feat: :sparkles: add sepolia testnet Removing hardcoded mainnet specific variables by using a lazy static to store the configuration, refactoring of the lazy statics --- crates/client/deoxys/src/l1.rs | 16 ++--- crates/client/deoxys/src/l2.rs | 79 +++++++++++------------ crates/client/deoxys/src/utils/convert.rs | 9 ++- crates/client/deoxys/src/utils/utility.rs | 51 +++++++-------- crates/client/rpc/src/lib.rs | 37 +++++++---- crates/node/src/commands/run.rs | 37 +++++++++-- crates/primitives/chain-id/src/lib.rs | 8 +++ crates/primitives/chain-id/src/tests.rs | 6 ++ 8 files changed, 144 insertions(+), 99 deletions(-) diff --git a/crates/client/deoxys/src/l1.rs b/crates/client/deoxys/src/l1.rs index 5ac38c556..b60ea24e5 100644 --- a/crates/client/deoxys/src/l1.rs +++ b/crates/client/deoxys/src/l1.rs @@ -1,6 +1,5 @@ //! Contains the necessaries to perform an L1 verification of the state -use std::str::FromStr; use std::sync::{Arc, Mutex}; use anyhow::Result; @@ -19,8 +18,8 @@ use serde_json::Value; use starknet_api::hash::StarkHash; use crate::l2::STARKNET_STATE_UPDATE; -use crate::utility::{event_to_l1_state_update, get_state_update_at}; -use crate::utils::constant::{starknet_core_address, LOG_STATE_UPDTATE_TOPIC}; +use crate::utility::{event_to_l1_state_update, get_config, get_state_update_at}; +use crate::utils::constant::LOG_STATE_UPDTATE_TOPIC; lazy_static! { /// Shared latest L2 state update verified on L1 @@ -83,8 +82,7 @@ impl EthereumClient { /// Get the block number of the last occurrence of a given event. pub async fn get_last_event_block_number(&self) -> Result> { let topic = H256::from_slice(&hex::decode(&LOG_STATE_UPDTATE_TOPIC[2..])?); - let address = - Address::from_str(starknet_core_address::MAINNET).map_err(|e| format!("Failed to parse address: {}", e))?; + let address = get_config()?.l1_core_address; let latest_block = self.get_latest_block_number().await.expect("Failed to retrieve latest block number"); // Assuming an avg Block time of 15sec we check for a LogStateUpdate occurence in the last ~24h @@ -107,7 +105,7 @@ impl EthereumClient { /// Get the last Starknet block number verified on L1 pub async fn get_last_block_number(&self) -> Result { let data = decode("35befa5d")?; - let to: Address = starknet_core_address::MAINNET.parse()?; + let to: Address = get_config().expect("Failed to get config").l1_core_address; let tx_request = TransactionRequest::new().to(to).data(data); let tx = TypedTransaction::Legacy(tx_request); let result = self.provider.call(&tx, None).await.expect("Failed to get last block number"); @@ -121,7 +119,7 @@ impl EthereumClient { /// Get the last Starknet state root verified on L1 pub async fn get_last_state_root(&self) -> Result { let data = decode("9588eca2")?; - let to: Address = starknet_core_address::MAINNET.parse()?; + let to: Address = get_config().expect("Failed to get config").l1_core_address; let tx_request = TransactionRequest::new().to(to).data(data); let tx = TypedTransaction::Legacy(tx_request); let result = self.provider.call(&tx, None).await.expect("Failed to get last state root"); @@ -131,7 +129,7 @@ impl EthereumClient { /// Get the last Starknet block hash verified on L1 pub async fn get_last_block_hash(&self) -> Result { let data = decode("0x382d83e3")?; - let to: Address = starknet_core_address::MAINNET.parse()?; + let to: Address = get_config().expect("Failed to get config").l1_core_address; let tx_request = TransactionRequest::new().to(to).data(data); let tx = TypedTransaction::Legacy(tx_request); let result = self.provider.call(&tx, None).await.expect("Failed to get last block hash"); @@ -160,7 +158,7 @@ impl EthereumClient { /// verified state pub async fn listen_and_update_state(&self, start_block: u64) -> Result<(), Box> { let client = self.provider.clone(); - let address: Address = starknet_core_address::MAINNET.parse().expect("Failed to parse Starknet core address"); + let address: Address = get_config().expect("Failed to get config").l1_core_address; abigen!( StarknetCore, "crates/client/deoxys/src/utils/abis/starknet_core.json", diff --git a/crates/client/deoxys/src/l2.rs b/crates/client/deoxys/src/l2.rs index a5a01f8a5..97b521391 100644 --- a/crates/client/deoxys/src/l2.rs +++ b/crates/client/deoxys/src/l2.rs @@ -1,9 +1,10 @@ //! Contains the code required to fetch data from the feeder efficiently. use std::str::FromStr; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; use std::time::Duration; use itertools::Itertools; +use lazy_static::lazy_static; use mc_db::BonsaiDbs; use mc_storage::OverrideHandle; use mp_block::state_update::StateUpdateWrapper; @@ -12,7 +13,7 @@ use mp_felt::Felt252Wrapper; use mp_storage::StarknetStorageSchemaVersion; use reqwest::Url; use serde::Deserialize; -use sp_core::H256; +use sp_core::{H160, H256}; use sp_runtime::generic::{Block, Header}; use sp_runtime::traits::{BlakeTwo256, Block as BlockT}; use sp_runtime::OpaqueExtrinsic; @@ -27,7 +28,7 @@ use tokio::sync::mpsc::Sender; use tokio::task::JoinSet; use crate::commitments::lib::{build_commitment_state_diff, update_state_root}; -use crate::utility::{get_block_hash_by_number, update_highest_block_hash_and_number}; +use crate::utility::get_block_hash_by_number; use crate::CommandSink; /// Contains the Starknet verified state on L2 @@ -40,24 +41,16 @@ pub struct L2StateUpdate { lazy_static! { /// Shared latest L2 state update verified on L2 - pub static ref STARKNET_STATE_UPDATE: Arc> = Arc::new(Mutex::new(L2StateUpdate { + pub static ref STARKNET_STATE_UPDATE: Mutex = Mutex::new(L2StateUpdate { block_number: u64::default(), global_root: StarkHash::default(), block_hash: StarkHash::default(), - })); -} - -use lazy_static::lazy_static; - -// TODO: find a better place to store this -lazy_static! { - /// Store the configuration globally - static ref CONFIG: Arc> = Arc::new(Mutex::new(FetchConfig::default())); + }); } lazy_static! { - /// Shared latest block number and hash of chain - pub static ref STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER: Arc> = Arc::new(Mutex::new((FieldElement::default(), 0))); + /// Shared latest block number and hash of chain, using a RwLock to allow for concurrent reads and exclusive writes + static ref STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER: RwLock<(FieldElement, u64)> = RwLock::new((FieldElement::default(), 0)); } /// The configuration of the worker responsible for fetching new blocks and state updates from the @@ -74,19 +67,8 @@ pub struct FetchConfig { pub workers: u32, /// Whether to play a sound when a new block is fetched. pub sound: bool, -} - -impl Default for FetchConfig { - fn default() -> Self { - FetchConfig { - // Provide default values for each field of FetchConfig - gateway: Url::parse("http://default-gateway-url.com").unwrap(), - feeder_gateway: Url::parse("http://default-feeder-gateway-url.com").unwrap(), - chain_id: starknet_ff::FieldElement::default(), // Adjust as necessary - workers: 4, - sound: false, - } - } + /// The L1 contract core address + pub l1_core_address: H160, } /// The configuration of the senders responsible for sending blocks and state @@ -141,7 +123,6 @@ pub async fn sync( rpc_port: u16, backend: Arc>, ) { - update_config(&config); let SenderConfig { block_sender, state_update_sender, class_sender, command_sink, overrides } = &mut sender_config; let client = SequencerGatewayProvider::new(config.gateway.clone(), config.feeder_gateway.clone(), config.chain_id); let bonsai_dbs = BonsaiDbs { @@ -150,6 +131,7 @@ pub async fn sync( storage: Arc::clone(backend.bonsai_storage()), }; let mut current_block_number = start_at; + current_block_number = 600_000; let mut last_block_hash = None; let mut got_block = false; let mut got_state_update = false; @@ -440,9 +422,9 @@ async fn create_block(cmds: &mut CommandSink, parent_hash: &mut Option) -> /// Update the L2 state with the latest data pub fn update_l2(state_update: L2StateUpdate) { { - let last_state_update = STARKNET_STATE_UPDATE.clone(); - let mut new_state_update = last_state_update.lock().unwrap(); - *new_state_update = state_update.clone(); + let mut last_state_update = + STARKNET_STATE_UPDATE.lock().expect("Failed to acquire lock on STARKNET_STATE_UPDATE"); + *last_state_update = state_update.clone(); } } @@ -471,16 +453,31 @@ pub async fn verify_l2( Ok(()) } -pub fn get_highest_block_hash_and_number() -> (FieldElement, u64) { - STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER.lock().unwrap().clone() -} +async fn update_highest_block_hash_and_number(client: &SequencerGatewayProvider) -> Result<(), String> { + let block = client.get_block(BlockId::Latest).await.map_err(|e| format!("failed to get block: {e}"))?; + + let hash = block + .block_hash + .ok_or("block hash not found")? + .try_into() + .map_err(|e| format!("failed to convert block hash: {e}"))?; + let number = block + .block_number + .ok_or("block number not found")? + .try_into() + .map_err(|e| format!("failed to convert block number: {e}"))?; + + let mut highest_block_hash_and_number = STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER + .write() + .expect("Failed to acquire write lock on STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER"); + *highest_block_hash_and_number = (hash, number); -fn update_config(config: &FetchConfig) { - let last_config = CONFIG.clone(); - let mut new_config = last_config.lock().unwrap(); - *new_config = config.clone(); + Ok(()) } -pub fn get_config() -> FetchConfig { - CONFIG.lock().unwrap().clone() +pub fn get_highest_block_hash_and_number() -> (FieldElement, u64) { + STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER + .read() + .expect("Failed to acquire read lock on STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER") + .clone() } diff --git a/crates/client/deoxys/src/utils/convert.rs b/crates/client/deoxys/src/utils/convert.rs index f0c920937..facaa4361 100644 --- a/crates/client/deoxys/src/utils/convert.rs +++ b/crates/client/deoxys/src/utils/convert.rs @@ -7,6 +7,7 @@ use starknet_ff::FieldElement; use starknet_providers::sequencer::models as p; use crate::commitments::lib::calculate_commitments; +use crate::utility::get_config; pub async fn block(block: p::Block) -> mp_block::Block { // converts starknet_provider transactions and events to mp_transactions and starknet_api events @@ -210,7 +211,13 @@ async fn commitments( } fn chain_id() -> mp_felt::Felt252Wrapper { - starknet_ff::FieldElement::from_byte_slice_be(b"SN_MAIN").unwrap().into() + match get_config() { + Ok(config) => config.chain_id.into(), + Err(e) => { + log::error!("Failed to get chain id: {}", e); + FieldElement::from_byte_slice_be(b"").unwrap().into() + } + } } fn felt(field_element: starknet_ff::FieldElement) -> starknet_api::hash::StarkFelt { diff --git a/crates/client/deoxys/src/utils/utility.rs b/crates/client/deoxys/src/utils/utility.rs index 7b5248565..8393bd52e 100644 --- a/crates/client/deoxys/src/utils/utility.rs +++ b/crates/client/deoxys/src/utils/utility.rs @@ -1,21 +1,39 @@ //! Utility functions for Deoxys. use std::error::Error; +use std::sync::RwLock; use std::thread::sleep; use std::time::Duration; use ethers::types::I256; +use lazy_static::lazy_static; use rand::seq::SliceRandom; use rand::thread_rng; use reqwest::header; use serde_json::{json, Value}; use starknet_api::hash::StarkFelt; -use starknet_ff::FieldElement; -use starknet_providers::sequencer::models::BlockId; -use starknet_providers::SequencerGatewayProvider; use crate::l1::{L1StateUpdate, LogStateUpdate}; -use crate::l2::{L2StateUpdate, STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER}; +use crate::l2::{FetchConfig, L2StateUpdate}; + +// TODO: find a better place to store this +lazy_static! { + /// Store the configuration globally, using a RwLock to allow for concurrent reads and exclusive writes + static ref CONFIG: RwLock> = RwLock::new(None); +} + +pub fn update_config(config: &FetchConfig) { + let mut new_config = CONFIG.write().expect("Failed to acquire write lock on CONFIG"); + *new_config = Some(config.clone()); +} + +pub fn get_config() -> Result { + let config_guard = CONFIG.read().expect("Failed to acquire read lock on CONFIG"); + match &*config_guard { + Some(config) => Ok(config.clone()), + None => Err("Configuration not set yet"), + } +} // TODO: secure the auto calls here @@ -135,31 +153,6 @@ pub async fn get_state_update_at(rpc_port: u16, block_number: u64) -> Result Result<(), String> { - let block = client.get_block(BlockId::Latest).await.map_err(|e| format!("failed to get block: {e}"))?; - - let hash = block - .block_hash - .ok_or("block hash not found")? - .try_into() - .map_err(|e| format!("failed to convert block hash: {e}"))?; - let number = block - .block_number - .ok_or("block number not found")? - .try_into() - .map_err(|e| format!("failed to convert block number: {e}"))?; - - let last_highest_block_hash_and_number = STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER.clone(); - let mut new_highest_block_hash_and_number = last_highest_block_hash_and_number.lock().unwrap(); - *new_highest_block_hash_and_number = (hash, number); - - Ok(()) -} - -pub fn get_highest_block_hash_and_number() -> (FieldElement, u64) { - STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER.lock().unwrap().clone() -} - /// Returns a random Pokémon name. pub async fn get_random_pokemon_name() -> Result> { let res = reqwest::get("https://pokeapi.co/api/v2/pokemon/?limit=1000").await?; diff --git a/crates/client/rpc/src/lib.rs b/crates/client/rpc/src/lib.rs index 5f14fa691..a7feead33 100644 --- a/crates/client/rpc/src/lib.rs +++ b/crates/client/rpc/src/lib.rs @@ -14,21 +14,18 @@ use std::marker::PhantomData; use std::sync::Arc; use blockifier::execution::contract_class::{ContractClass as ContractClassBf, ContractClassV1 as ContractClassV1Bf}; -use blockifier::execution::entry_point::CallInfo; use errors::StarknetRpcApiError; use jsonrpsee::core::{async_trait, RpcResult}; use jsonrpsee::types::error::CallError; use log::error; -use mc_deoxys::commitments::transactions; -use mc_deoxys::l2::get_config; -use mc_deoxys::utility::get_highest_block_hash_and_number; +use mc_deoxys::l2::get_highest_block_hash_and_number; +use mc_deoxys::utility::get_config; use mc_genesis_data_provider::GenesisProvider; pub use mc_rpc_core::utils::*; pub use mc_rpc_core::{Felt, StarknetReadRpcApiServer, StarknetTraceRpcApiServer, StarknetWriteRpcApiServer}; use mc_storage::OverrideHandle; use mp_block::BlockStatus; use mp_contract::class::ContractClassWrapper; -use mp_convert::contract::flattened_sierra_to_sierra_contract_class; use mp_felt::{Felt252Wrapper, Felt252WrapperError}; use mp_hashers::HasherT; use mp_transactions::compute_hash::ComputeTransactionHash; @@ -58,11 +55,11 @@ use starknet_core::types::{ BlockHashAndNumber, BlockId, BlockTag, BlockWithTxHashes, BlockWithTxs, BroadcastedDeclareTransaction, BroadcastedDeployAccountTransaction, BroadcastedInvokeTransaction, BroadcastedTransaction, ContractClass, DeclareTransactionReceipt, DeclareTransactionResult, DeployAccountTransactionReceipt, - DeployAccountTransactionResult, DeployTransactionReceipt, Event, EventFilterWithPage, EventsPage, - ExecutionResources, ExecutionResult, FeeEstimate, FieldElement, FunctionCall, Hash256, InvokeTransactionReceipt, + DeployAccountTransactionResult, DeployTransactionReceipt, EventFilterWithPage, EventsPage, ExecutionResources, + ExecutionResult, FeeEstimate, FieldElement, FunctionCall, Hash256, InvokeTransactionReceipt, InvokeTransactionResult, L1HandlerTransactionReceipt, MaybePendingBlockWithTxHashes, MaybePendingBlockWithTxs, - MaybePendingTransactionReceipt, MsgFromL1, MsgToL1, StateDiff, StateUpdate, SyncStatus, SyncStatusType, - Transaction, TransactionExecutionStatus, TransactionFinalityStatus, TransactionReceipt, + MaybePendingTransactionReceipt, MsgFromL1, StateDiff, StateUpdate, SyncStatus, SyncStatusType, Transaction, + TransactionExecutionStatus, TransactionFinalityStatus, TransactionReceipt, }; use starknet_providers::{Provider, ProviderError, SequencerGatewayProvider}; @@ -294,7 +291,10 @@ where &self, declare_transaction: BroadcastedDeclareTransaction, ) -> RpcResult { - let config = get_config(); + let config = get_config().map_err(|e| { + error!("Failed to get config: {e}"); + StarknetRpcApiError::InternalServerError + })?; let sequencer = SequencerGatewayProvider::new(config.feeder_gateway, config.gateway, config.chain_id); let sequencer_response = match sequencer.add_declare_transaction(declare_transaction).await { @@ -324,7 +324,10 @@ where &self, invoke_transaction: BroadcastedInvokeTransaction, ) -> RpcResult { - let config = get_config(); + let config = get_config().map_err(|e| { + error!("Failed to get config: {e}"); + StarknetRpcApiError::InternalServerError + })?; let sequencer = SequencerGatewayProvider::new(config.feeder_gateway, config.gateway, config.chain_id); let sequencer_response = match sequencer.add_invoke_transaction(invoke_transaction).await { @@ -355,7 +358,10 @@ where &self, deploy_account_transaction: BroadcastedDeployAccountTransaction, ) -> RpcResult { - let config = get_config(); + let config = get_config().map_err(|e| { + error!("Failed to get config: {e}"); + StarknetRpcApiError::InternalServerError + })?; let sequencer = SequencerGatewayProvider::new(config.feeder_gateway, config.gateway, config.chain_id); let sequencer_response = match sequencer.add_deploy_account_transaction(deploy_account_transaction).await { @@ -968,7 +974,12 @@ where /// defined by the Starknet protocol, indicating the particular network. fn chain_id(&self) -> RpcResult { let best_block_hash = self.client.info().best_hash; - let chain_id = get_config().chain_id; + let chain_id = get_config() + .map_err(|e| { + error!("Failed to get config: {e}"); + StarknetRpcApiError::InternalServerError + })? + .chain_id; Ok(Felt(chain_id)) } diff --git a/crates/node/src/commands/run.rs b/crates/node/src/commands/run.rs index 26475c855..b05ffc3ea 100644 --- a/crates/node/src/commands/run.rs +++ b/crates/node/src/commands/run.rs @@ -1,11 +1,15 @@ use std::path::PathBuf; use std::result::Result as StdResult; +use log; use madara_runtime::SealingMode; use mc_deoxys::l2::fetch_genesis_block; +use mc_deoxys::utility::update_config; +use mc_deoxys::utils::constant::starknet_core_address; use reqwest::Url; use sc_cli::{Result, RpcMethods, RunCmd, SubstrateCli}; use serde::{Deserialize, Serialize}; +use sp_core::H160; use crate::cli::Cli; use crate::service; @@ -80,11 +84,14 @@ pub enum NetworkType { Integration, } +/// Test network is on Sepolia, +/// Goerli is the deprecated test network for StarkNet and it is not supported after the 11th of +/// april 2024. impl NetworkType { pub fn uri(&self) -> &'static str { match self { NetworkType::Main => "https://alpha-mainnet.starknet.io", - NetworkType::Test => "https://alpha4.starknet.io", + NetworkType::Test => "https://alpha-sepolia.starknet.io", NetworkType::Integration => "https://external.integration.starknet.io", } } @@ -92,19 +99,28 @@ impl NetworkType { pub fn chain_id(&self) -> starknet_core::types::FieldElement { match self { NetworkType::Main => starknet_core::types::FieldElement::from_byte_slice_be(b"SN_MAIN").unwrap(), - NetworkType::Test => starknet_core::types::FieldElement::from_byte_slice_be(b"SN_TEST").unwrap(), + NetworkType::Test => starknet_core::types::FieldElement::from_byte_slice_be(b"SN_SEPOLIA").unwrap(), NetworkType::Integration => starknet_core::types::FieldElement::from_byte_slice_be(b"SN_INTE").unwrap(), } } + pub fn l1_core_address(&self) -> H160 { + match self { + NetworkType::Main => starknet_core_address::MAINNET.parse().unwrap(), + NetworkType::Test => starknet_core_address::SEPOLIA_TESTNET.parse().unwrap(), + NetworkType::Integration => starknet_core_address::SEPOLIA_INTEGRATION.parse().unwrap(), + } + } + pub fn block_fetch_config(&self) -> mc_deoxys::FetchConfig { let uri = self.uri(); let chain_id = self.chain_id(); let gateway = format!("{uri}/gateway").parse().unwrap(); let feeder_gateway = format!("{uri}/feeder_gateway").parse().unwrap(); + let l1_core_address = self.l1_core_address(); - mc_deoxys::FetchConfig { gateway, feeder_gateway, chain_id, workers: 5, sound: false } + mc_deoxys::FetchConfig { gateway, feeder_gateway, chain_id, workers: 5, sound: false, l1_core_address } } } @@ -173,6 +189,9 @@ pub fn run_node(mut cli: Cli) -> Result<()> { let genesis_block = fetch_genesis_block(fetch_block_config.clone()).await.unwrap(); fetch_block_config.sound = cli.run.sound; + update_config(&fetch_block_config); + log::debug!("Using fetch block config: {:?}", fetch_block_config); + service::new_full( config, sealing, @@ -205,11 +224,17 @@ fn override_dev_environment(cmd: &mut ExtendedRunCmd) { fn deoxys_environment(cmd: &mut ExtendedRunCmd) { // Set the blockchain network to 'starknet' cmd.base.shared_params.chain = Some("starknet".to_string()); - cmd.base.shared_params.base_path = Some(PathBuf::from("/tmp/deoxys")); + cmd.base.shared_params.base_path = Some(PathBuf::from("../db_deoxys")); // Assign a random pokemon name at each startup - cmd.base.name = - Some(tokio::runtime::Runtime::new().unwrap().block_on(mc_deoxys::utility::get_random_pokemon_name()).unwrap()); + cmd.base.name = Some( + tokio::runtime::Runtime::new().unwrap().block_on(mc_deoxys::utility::get_random_pokemon_name()).unwrap_or_else( + |e| { + log::warn!("Failed to get random pokemon name: {}", e); + "gimmighoul".to_string() + }, + ), + ); // Define telemetry endpoints at deoxys.kasar.io cmd.base.telemetry_params.telemetry_endpoints = vec![("wss://deoxys.kasar.io/submit/".to_string(), 0)]; diff --git a/crates/primitives/chain-id/src/lib.rs b/crates/primitives/chain-id/src/lib.rs index 9404bf13c..f4dfb00d6 100644 --- a/crates/primitives/chain-id/src/lib.rs +++ b/crates/primitives/chain-id/src/lib.rs @@ -11,6 +11,14 @@ pub const SN_GOERLI_CHAIN_ID: Felt252Wrapper = Felt252Wrapper(starknet_ff::Field 398700013197595345, ])); +/// ChainId for Starknet Goerli testnet +pub const SN_SEPOLIA_CHAIN_ID: Felt252Wrapper = Felt252Wrapper(starknet_ff::FieldElement::from_mont([ + 1555806712078248243, + 18446744073708869172, + 18446744073709551615, + 507980251676163170, +])); + /// ChainId for Starknet Mainnet pub const SN_MAIN_CHAIN_ID: Felt252Wrapper = Felt252Wrapper(starknet_ff::FieldElement::from_mont([ 17696389056366564951, diff --git a/crates/primitives/chain-id/src/tests.rs b/crates/primitives/chain-id/src/tests.rs index 5886a6fde..fadfc708f 100644 --- a/crates/primitives/chain-id/src/tests.rs +++ b/crates/primitives/chain-id/src/tests.rs @@ -8,6 +8,12 @@ fn test_sn_goerli_chain_id() { assert_eq!(SN_GOERLI_CHAIN_ID, expected_value, "SN_GOERLI_CHAIN_ID does not match the expected value."); } +#[test] +fn test_sn_sepolia_chain_id() { + let expected_value = Felt252Wrapper(FieldElement::from_byte_slice_be(b"SN_SEPOLIA").unwrap()); + assert_eq!(SN_SEPOLIA_CHAIN_ID, expected_value, "SN_SEPOLIA_CHAIN_ID does not match the expected value."); +} + #[test] fn test_sn_main_chain_id() { let expected_value = Felt252Wrapper(FieldElement::from_byte_slice_be(b"SN_MAIN").unwrap()); From 2e8c913775dd61123b573b8c9d616ce08a70e0e6 Mon Sep 17 00:00:00 2001 From: jb caron Date: Wed, 6 Mar 2024 11:21:58 +0100 Subject: [PATCH 2/3] chore: :twisted_rightwards_arrows: change folder deoxys to sync to prepare merge --- crates/client/{deoxys => sync}/Cargo.toml | 0 crates/client/{deoxys => sync}/src/commitments/classes.rs | 0 crates/client/{deoxys => sync}/src/commitments/contracts.rs | 0 crates/client/{deoxys => sync}/src/commitments/events.rs | 0 crates/client/{deoxys => sync}/src/commitments/lib.rs | 0 crates/client/{deoxys => sync}/src/commitments/mod.rs | 0 crates/client/{deoxys => sync}/src/commitments/transactions.rs | 0 crates/client/{deoxys => sync}/src/l1.rs | 0 crates/client/{deoxys => sync}/src/l2.rs | 0 crates/client/{deoxys => sync}/src/lib.rs | 0 crates/client/{deoxys => sync}/src/tests/utils/mod.rs | 0 crates/client/{deoxys => sync}/src/tests/utils/read_resource.rs | 0 crates/client/{deoxys => sync}/src/tests/utils/retry.rs | 0 crates/client/{deoxys => sync}/src/types/mod.rs | 0 crates/client/{deoxys => sync}/src/utils/abis/starknet_core.json | 0 crates/client/{deoxys => sync}/src/utils/abis/usdc.json | 0 crates/client/{deoxys => sync}/src/utils/constant.rs | 0 crates/client/{deoxys => sync}/src/utils/convert.rs | 0 crates/client/{deoxys => sync}/src/utils/m.rs | 0 crates/client/{deoxys => sync}/src/utils/mod.rs | 0 crates/client/{deoxys => sync}/src/utils/utility.rs | 0 21 files changed, 0 insertions(+), 0 deletions(-) rename crates/client/{deoxys => sync}/Cargo.toml (100%) rename crates/client/{deoxys => sync}/src/commitments/classes.rs (100%) rename crates/client/{deoxys => sync}/src/commitments/contracts.rs (100%) rename crates/client/{deoxys => sync}/src/commitments/events.rs (100%) rename crates/client/{deoxys => sync}/src/commitments/lib.rs (100%) rename crates/client/{deoxys => sync}/src/commitments/mod.rs (100%) rename crates/client/{deoxys => sync}/src/commitments/transactions.rs (100%) rename crates/client/{deoxys => sync}/src/l1.rs (100%) rename crates/client/{deoxys => sync}/src/l2.rs (100%) rename crates/client/{deoxys => sync}/src/lib.rs (100%) rename crates/client/{deoxys => sync}/src/tests/utils/mod.rs (100%) rename crates/client/{deoxys => sync}/src/tests/utils/read_resource.rs (100%) rename crates/client/{deoxys => sync}/src/tests/utils/retry.rs (100%) rename crates/client/{deoxys => sync}/src/types/mod.rs (100%) rename crates/client/{deoxys => sync}/src/utils/abis/starknet_core.json (100%) rename crates/client/{deoxys => sync}/src/utils/abis/usdc.json (100%) rename crates/client/{deoxys => sync}/src/utils/constant.rs (100%) rename crates/client/{deoxys => sync}/src/utils/convert.rs (100%) rename crates/client/{deoxys => sync}/src/utils/m.rs (100%) rename crates/client/{deoxys => sync}/src/utils/mod.rs (100%) rename crates/client/{deoxys => sync}/src/utils/utility.rs (100%) diff --git a/crates/client/deoxys/Cargo.toml b/crates/client/sync/Cargo.toml similarity index 100% rename from crates/client/deoxys/Cargo.toml rename to crates/client/sync/Cargo.toml diff --git a/crates/client/deoxys/src/commitments/classes.rs b/crates/client/sync/src/commitments/classes.rs similarity index 100% rename from crates/client/deoxys/src/commitments/classes.rs rename to crates/client/sync/src/commitments/classes.rs diff --git a/crates/client/deoxys/src/commitments/contracts.rs b/crates/client/sync/src/commitments/contracts.rs similarity index 100% rename from crates/client/deoxys/src/commitments/contracts.rs rename to crates/client/sync/src/commitments/contracts.rs diff --git a/crates/client/deoxys/src/commitments/events.rs b/crates/client/sync/src/commitments/events.rs similarity index 100% rename from crates/client/deoxys/src/commitments/events.rs rename to crates/client/sync/src/commitments/events.rs diff --git a/crates/client/deoxys/src/commitments/lib.rs b/crates/client/sync/src/commitments/lib.rs similarity index 100% rename from crates/client/deoxys/src/commitments/lib.rs rename to crates/client/sync/src/commitments/lib.rs diff --git a/crates/client/deoxys/src/commitments/mod.rs b/crates/client/sync/src/commitments/mod.rs similarity index 100% rename from crates/client/deoxys/src/commitments/mod.rs rename to crates/client/sync/src/commitments/mod.rs diff --git a/crates/client/deoxys/src/commitments/transactions.rs b/crates/client/sync/src/commitments/transactions.rs similarity index 100% rename from crates/client/deoxys/src/commitments/transactions.rs rename to crates/client/sync/src/commitments/transactions.rs diff --git a/crates/client/deoxys/src/l1.rs b/crates/client/sync/src/l1.rs similarity index 100% rename from crates/client/deoxys/src/l1.rs rename to crates/client/sync/src/l1.rs diff --git a/crates/client/deoxys/src/l2.rs b/crates/client/sync/src/l2.rs similarity index 100% rename from crates/client/deoxys/src/l2.rs rename to crates/client/sync/src/l2.rs diff --git a/crates/client/deoxys/src/lib.rs b/crates/client/sync/src/lib.rs similarity index 100% rename from crates/client/deoxys/src/lib.rs rename to crates/client/sync/src/lib.rs diff --git a/crates/client/deoxys/src/tests/utils/mod.rs b/crates/client/sync/src/tests/utils/mod.rs similarity index 100% rename from crates/client/deoxys/src/tests/utils/mod.rs rename to crates/client/sync/src/tests/utils/mod.rs diff --git a/crates/client/deoxys/src/tests/utils/read_resource.rs b/crates/client/sync/src/tests/utils/read_resource.rs similarity index 100% rename from crates/client/deoxys/src/tests/utils/read_resource.rs rename to crates/client/sync/src/tests/utils/read_resource.rs diff --git a/crates/client/deoxys/src/tests/utils/retry.rs b/crates/client/sync/src/tests/utils/retry.rs similarity index 100% rename from crates/client/deoxys/src/tests/utils/retry.rs rename to crates/client/sync/src/tests/utils/retry.rs diff --git a/crates/client/deoxys/src/types/mod.rs b/crates/client/sync/src/types/mod.rs similarity index 100% rename from crates/client/deoxys/src/types/mod.rs rename to crates/client/sync/src/types/mod.rs diff --git a/crates/client/deoxys/src/utils/abis/starknet_core.json b/crates/client/sync/src/utils/abis/starknet_core.json similarity index 100% rename from crates/client/deoxys/src/utils/abis/starknet_core.json rename to crates/client/sync/src/utils/abis/starknet_core.json diff --git a/crates/client/deoxys/src/utils/abis/usdc.json b/crates/client/sync/src/utils/abis/usdc.json similarity index 100% rename from crates/client/deoxys/src/utils/abis/usdc.json rename to crates/client/sync/src/utils/abis/usdc.json diff --git a/crates/client/deoxys/src/utils/constant.rs b/crates/client/sync/src/utils/constant.rs similarity index 100% rename from crates/client/deoxys/src/utils/constant.rs rename to crates/client/sync/src/utils/constant.rs diff --git a/crates/client/deoxys/src/utils/convert.rs b/crates/client/sync/src/utils/convert.rs similarity index 100% rename from crates/client/deoxys/src/utils/convert.rs rename to crates/client/sync/src/utils/convert.rs diff --git a/crates/client/deoxys/src/utils/m.rs b/crates/client/sync/src/utils/m.rs similarity index 100% rename from crates/client/deoxys/src/utils/m.rs rename to crates/client/sync/src/utils/m.rs diff --git a/crates/client/deoxys/src/utils/mod.rs b/crates/client/sync/src/utils/mod.rs similarity index 100% rename from crates/client/deoxys/src/utils/mod.rs rename to crates/client/sync/src/utils/mod.rs diff --git a/crates/client/deoxys/src/utils/utility.rs b/crates/client/sync/src/utils/utility.rs similarity index 100% rename from crates/client/deoxys/src/utils/utility.rs rename to crates/client/sync/src/utils/utility.rs From b79401e7664dc4407c843b224b561f89d9b1d8a9 Mon Sep 17 00:00:00 2001 From: jb caron Date: Wed, 6 Mar 2024 11:50:05 +0100 Subject: [PATCH 3/3] feat: :sparkles: Removal of the hardcoded mainnet configuration use the lazy_static CONFIG --- CHANGELOG.md | 1 + crates/client/rpc/src/lib.rs | 4 ++-- crates/client/sync/src/commitments/events.rs | 4 ++-- crates/client/sync/src/l2.rs | 17 +++-------------- crates/client/sync/src/utils/utility.rs | 18 +----------------- crates/node/src/commands/run.rs | 1 - 6 files changed, 9 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 784aecd80..23ff22964 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ git # Deoxys Changelog ## Next release +- feat: Removal of the hardcoded mainnet configuration - refactor: pass new CI - fix(workflows): Fix deoxys CI - feat(rpc): add_invoke_tx, add_deploy_account_tx, add_declare_tx diff --git a/crates/client/rpc/src/lib.rs b/crates/client/rpc/src/lib.rs index c939cb0f8..71a1d37a5 100644 --- a/crates/client/rpc/src/lib.rs +++ b/crates/client/rpc/src/lib.rs @@ -22,8 +22,8 @@ use mc_genesis_data_provider::GenesisProvider; pub use mc_rpc_core::utils::*; pub use mc_rpc_core::{Felt, StarknetReadRpcApiServer, StarknetTraceRpcApiServer, StarknetWriteRpcApiServer}; use mc_storage::OverrideHandle; -use mc_sync::l2::get_config; -use mc_sync::utility::get_highest_block_hash_and_number; +use mc_sync::l2::get_highest_block_hash_and_number; +use mc_sync::utility::get_config; use mp_block::BlockStatus; use mp_contract::class::ContractClassWrapper; use mp_felt::{Felt252Wrapper, Felt252WrapperError}; diff --git a/crates/client/sync/src/commitments/events.rs b/crates/client/sync/src/commitments/events.rs index dc3ba11e2..95793e411 100644 --- a/crates/client/sync/src/commitments/events.rs +++ b/crates/client/sync/src/commitments/events.rs @@ -81,10 +81,10 @@ pub fn event_commitment(events: &[Event], bonsai_db: &Arc } let id = id_builder.new_id(); - bonsai_storage.commit(id).map_err(|_| format!("Failed to commit to bonsai storage"))?; + bonsai_storage.commit(id).map_err(|_| "Failed to commit to bonsai storage")?; // restores the Bonsai Trie to it's previous state - let root_hash = bonsai_storage.root_hash().map_err(|_| format!("Failed to get root hash"))?; + let root_hash = bonsai_storage.root_hash().map_err(|_| "Failed to get root hash")?; bonsai_storage.revert_to(zero).unwrap(); Ok(Felt252Wrapper::from(root_hash)) diff --git a/crates/client/sync/src/l2.rs b/crates/client/sync/src/l2.rs index 86384d423..d5da4cf9d 100644 --- a/crates/client/sync/src/l2.rs +++ b/crates/client/sync/src/l2.rs @@ -41,7 +41,6 @@ pub struct L2StateUpdate { lazy_static! { /// Shared latest L2 state update verified on L2 - pub static ref STARKNET_STATE_UPDATE: Mutex = Mutex::new(L2StateUpdate { pub static ref STARKNET_STATE_UPDATE: Mutex = Mutex::new(L2StateUpdate { block_number: u64::default(), global_root: StarkHash::default(), @@ -132,7 +131,6 @@ pub async fn sync( storage: Arc::clone(backend.bonsai_storage()), }; let mut current_block_number = start_at; - current_block_number = 600_000; let mut last_block_hash = None; let mut got_block = false; let mut got_state_update = false; @@ -453,16 +451,8 @@ pub async fn verify_l2( async fn update_highest_block_hash_and_number(client: &SequencerGatewayProvider) -> Result<(), String> { let block = client.get_block(BlockId::Latest).await.map_err(|e| format!("failed to get block: {e}"))?; - let hash = block - .block_hash - .ok_or("block hash not found")? - .try_into() - .map_err(|e| format!("failed to convert block hash: {e}"))?; - let number = block - .block_number - .ok_or("block number not found")? - .try_into() - .map_err(|e| format!("failed to convert block number: {e}"))?; + let hash = block.block_hash.ok_or("block hash not found")?; + let number = block.block_number.ok_or("block number not found")?; let mut highest_block_hash_and_number = STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER .write() @@ -473,8 +463,7 @@ async fn update_highest_block_hash_and_number(client: &SequencerGatewayProvider) } pub fn get_highest_block_hash_and_number() -> (FieldElement, u64) { - STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER + *STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER .read() .expect("Failed to acquire read lock on STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER") - .clone() } diff --git a/crates/client/sync/src/utils/utility.rs b/crates/client/sync/src/utils/utility.rs index e3be086f9..6116aa29c 100644 --- a/crates/client/sync/src/utils/utility.rs +++ b/crates/client/sync/src/utils/utility.rs @@ -22,6 +22,7 @@ lazy_static! { static ref CONFIG: RwLock> = RwLock::new(None); } +/// this function needs to be called only once at the start of the program pub fn update_config(config: &FetchConfig) { let mut new_config = CONFIG.write().expect("Failed to acquire write lock on CONFIG"); *new_config = Some(config.clone()); @@ -150,23 +151,6 @@ pub async fn get_state_update_at(rpc_port: u16, block_number: u64) -> Result Result<(), String> { - let block = client.get_block(BlockId::Latest).await.map_err(|e| format!("failed to get block: {e}"))?; - - let hash = block.block_hash.ok_or("block hash not found")?; - let number = block.block_number.ok_or("block number not found")?; - - let last_highest_block_hash_and_number = STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER.clone(); - let mut new_highest_block_hash_and_number = last_highest_block_hash_and_number.lock().unwrap(); - *new_highest_block_hash_and_number = (hash, number); - - Ok(()) -} - -pub fn get_highest_block_hash_and_number() -> (FieldElement, u64) { - *STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER.lock().expect("failed to lock STARKNET_HIGHEST_BLOCK_HASH_AND_NUMBER") -} - /// Returns a random Pokémon name. pub async fn get_random_pokemon_name() -> Result> { let res = reqwest::get("https://pokeapi.co/api/v2/pokemon/?limit=1000").await?; diff --git a/crates/node/src/commands/run.rs b/crates/node/src/commands/run.rs index ef042ea1a..6460d75d8 100644 --- a/crates/node/src/commands/run.rs +++ b/crates/node/src/commands/run.rs @@ -1,7 +1,6 @@ use std::path::PathBuf; use std::result::Result as StdResult; -use log; use madara_runtime::SealingMode; use mc_sync::l2::fetch_genesis_block; use mc_sync::utility::update_config;