diff --git a/chains/era/ZkStack.yaml b/chains/era/ZkStack.yaml index 306473ba93a8..4347d62c4f14 100644 --- a/chains/era/ZkStack.yaml +++ b/chains/era/ZkStack.yaml @@ -12,3 +12,4 @@ base_token: nominator: 1 denominator: 1 wallet_creation: Localhost +evm_emulator: false diff --git a/core/Cargo.lock b/core/Cargo.lock index 144145f638dc..6ff139a1a688 100644 --- a/core/Cargo.lock +++ b/core/Cargo.lock @@ -11711,6 +11711,20 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "zksync_gateway_migrator" +version = "26.5.0-non-semver-compat" +dependencies = [ + "anyhow", + "async-trait", + "tokio", + "tracing", + "zksync_basic_types", + "zksync_config", + "zksync_contracts", + "zksync_eth_client", +] + [[package]] name = "zksync_health_check" version = "26.5.0-non-semver-compat" @@ -11872,20 +11886,6 @@ dependencies = [ "zksync_crypto_primitives", ] -[[package]] -name = "zksync_multilayer_client" -version = "26.5.0-non-semver-compat" -dependencies = [ - "anyhow", - "async-trait", - "tokio", - "tracing", - "zksync_basic_types", - "zksync_config", - "zksync_contracts", - "zksync_eth_client", -] - [[package]] name = "zksync_multivm" version = "26.5.0-non-semver-compat" @@ -12092,12 +12092,12 @@ dependencies = [ "zksync_eth_watch", "zksync_external_price_api", "zksync_external_proof_integration_api", + "zksync_gateway_migrator", "zksync_health_check", "zksync_house_keeper", "zksync_logs_bloom_backfill", "zksync_metadata_calculator", "zksync_mini_merkle_tree", - "zksync_multilayer_client", "zksync_node_api_server", "zksync_node_consensus", "zksync_node_db_pruner", diff --git a/core/Cargo.toml b/core/Cargo.toml index 18210d7beabf..7bf0cff08360 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -78,7 +78,7 @@ members = [ "lib/external_price_api", "lib/task_management", "lib/test_contracts", - "lib/multilayer_client", + "lib/gateway_migrator", "lib/zk_os_merkle_tree", # Test infrastructure "tests/loadnext", @@ -334,4 +334,4 @@ zksync_contract_verification_server = { version = "26.5.0-non-semver-compat", pa zksync_node_api_server = { version = "26.5.0-non-semver-compat", path = "node/api_server" } zksync_base_token_adjuster = { version = "26.5.0-non-semver-compat", path = "node/base_token_adjuster" } zksync_logs_bloom_backfill = { version = "26.5.0-non-semver-compat", path = "node/logs_bloom_backfill" } -zksync_multilayer_client = { version = "26.5.0-non-semver-compat", path = "lib/multilayer_client" } +zksync_gateway_migrator = { version = "26.5.0-non-semver-compat", path = "lib/gateway_migrator" } diff --git a/core/bin/block_reverter/src/main.rs b/core/bin/block_reverter/src/main.rs index eb06357c1968..fdacd9d60b74 100644 --- a/core/bin/block_reverter/src/main.rs +++ b/core/bin/block_reverter/src/main.rs @@ -16,17 +16,16 @@ use zksync_block_reverter::{ use zksync_config::{ configs::{ chain::NetworkConfig, wallets::Wallets, BasicWitnessInputProducerConfig, DatabaseSecrets, - GatewayChainConfig, GeneralConfig, L1Secrets, ObservabilityConfig, - ProtectiveReadsWriterConfig, + GeneralConfig, L1Secrets, ObservabilityConfig, ProtectiveReadsWriterConfig, }, - ContractsConfig, DBConfig, EthConfig, GenesisConfig, PostgresConfig, + ContractsConfig, DBConfig, EthConfig, GenesisConfig, PostgresConfig, SettlementLayerContracts, }; use zksync_core_leftovers::temp_config_store::read_yaml_repr; use zksync_dal::{ConnectionPool, Core}; use zksync_env_config::{object_store::SnapshotsObjectStoreConfig, FromEnv}; use zksync_object_store::ObjectStoreFactory; use zksync_protobuf_config::proto; -use zksync_types::{Address, L1BatchNumber}; +use zksync_types::{settlement::SettlementMode, Address, L1BatchNumber}; #[derive(Debug, Parser)] #[command(author = "Matter Labs", version, about = "Block revert utility", long_about = None)] @@ -203,7 +202,6 @@ async fn main() -> anyhow::Result<()> { let gas_adjuster = eth_sender.gas_adjuster.context("gas_adjuster")?; let default_priority_fee_per_gas = gas_adjuster.default_priority_fee_per_gas; - let settlement_mode = gas_adjuster.settlement_mode; let database_secrets = match &secrets_config { Some(secrets_config) => secrets_config @@ -235,33 +233,30 @@ async fn main() -> anyhow::Result<()> { } }; - let (sl_rpc_url, sl_diamond_proxy, sl_validator_timelock) = if settlement_mode.is_gateway() { - // Gateway config is required to be provided by file for now. - let gateway_chain_config: GatewayChainConfig = - read_yaml_repr::( - &opts - .gateway_chain_path - .context("Genesis config path not provided")?, - ) - .context("failed decoding genesis YAML config")?; - - let gateway_url = l1_secrets - .gateway_rpc_url - .context("Gateway URL not found")?; + let contracts = SettlementLayerContracts::new(&contracts, None); + // TODO think more about it + let (sl_rpc_url, settlement_mode) = if opts.gateway_chain_path.is_some() { ( - gateway_url, - gateway_chain_config.diamond_proxy_addr, - gateway_chain_config.validator_timelock_addr, + l1_secrets + .gateway_rpc_url + .context("Gateway URL not found")?, + SettlementMode::Gateway, ) } else { - ( - l1_secrets.l1_rpc_url, - contracts.diamond_proxy_addr, - contracts.validator_timelock_addr, - ) + (l1_secrets.l1_rpc_url, SettlementMode::SettlesToL1) }; + let sl_diamond_proxy = contracts + .current_contracts() + .chain_contracts_config + .diamond_proxy_addr; + let sl_validator_timelock = contracts + .current_contracts() + .ecosystem_contracts + .validator_timelock_addr + .expect("Should be presented"); + let config = BlockReverterEthConfig::new( ð_sender, sl_diamond_proxy, @@ -302,7 +297,8 @@ async fn main() -> anyhow::Result<()> { priority_fee_per_gas, nonce, } => { - let sl_client = Client::http(sl_rpc_url).context("Ethereum client")?.build(); + let sl_client: Client = + Client::http(sl_rpc_url).context("Ethereum client")?.build(); let reverter_private_key = if let Some(wallets_config) = wallets_config { wallets_config .eth_sender diff --git a/core/bin/external_node/src/config/mod.rs b/core/bin/external_node/src/config/mod.rs index 0ed7fedfd76f..9e42154674b6 100644 --- a/core/bin/external_node/src/config/mod.rs +++ b/core/bin/external_node/src/config/mod.rs @@ -13,6 +13,11 @@ use zksync_config::{ configs::{ api::{MaxResponseSize, MaxResponseSizeOverrides}, consensus::{ConsensusConfig, ConsensusSecrets}, + contracts::{ + chain::{ChainContracts, L2Contracts}, + ecosystem::{EcosystemCommonContracts, L1SpecificContracts}, + ChainSpecificContracts, + }, en_config::ENConfig, DataAvailabilitySecrets, GeneralConfig, Secrets, }, @@ -27,7 +32,7 @@ use zksync_env_config::da_client::{da_client_config_from_env, da_client_secrets_ use zksync_metadata_calculator::MetadataCalculatorRecoveryConfig; use zksync_node_api_server::{ tx_sender::{TimestampAsserterParams, TxSenderConfig}, - web3::{state::InternalApiConfig, Namespace}, + web3::{state::InternalApiConfigBuilder, Namespace}, }; use zksync_protobuf_config::proto; use zksync_snapshots_applier::SnapshotsApplierConfig; @@ -131,7 +136,7 @@ pub(crate) struct RemoteENConfig { pub l2_timestamp_asserter_addr: Option
, pub l1_wrapped_base_token_store: Option
, pub l1_server_notifier_addr: Option
, - pub base_token_addr: Address, + pub base_token_addr: Option
, pub l1_batch_commit_data_generator_mode: L1BatchCommitmentMode, pub dummy_verifier: bool, } @@ -191,10 +196,10 @@ impl RemoteENConfig { l1_bridgehub_proxy_addr: ecosystem_contracts.as_ref().map(|a| a.bridgehub_proxy_addr), l1_state_transition_proxy_addr: ecosystem_contracts .as_ref() - .map(|a| a.state_transition_proxy_addr), + .and_then(|a| a.state_transition_proxy_addr), l1_transparent_proxy_admin_addr: ecosystem_contracts .as_ref() - .map(|a| a.transparent_proxy_admin_addr), + .and_then(|a| a.transparent_proxy_admin_addr), l1_bytecodes_supplier_addr: ecosystem_contracts .as_ref() .and_then(|a| a.l1_bytecodes_supplier_addr), @@ -213,7 +218,7 @@ impl RemoteENConfig { l2_legacy_shared_bridge_addr: bridges.l2_legacy_shared_bridge, l1_weth_bridge_addr: bridges.l1_weth_bridge, l2_weth_bridge_addr: bridges.l2_weth_bridge, - base_token_addr, + base_token_addr: Some(base_token_addr), l1_batch_commit_data_generator_mode: genesis .as_ref() .map(|a| a.l1_batch_commit_data_generator_mode) @@ -238,7 +243,7 @@ impl RemoteENConfig { l2_erc20_bridge_addr: Some(Address::repeat_byte(3)), l2_weth_bridge_addr: None, l2_testnet_paymaster_addr: None, - base_token_addr: Address::repeat_byte(4), + base_token_addr: Some(Address::repeat_byte(4)), l1_shared_bridge_proxy_addr: Some(Address::repeat_byte(5)), l1_weth_bridge_addr: None, l2_shared_bridge_addr: Some(Address::repeat_byte(6)), @@ -1479,18 +1484,18 @@ impl ExternalNodeConfig { } } -impl From<&ExternalNodeConfig> for InternalApiConfig { +impl From<&ExternalNodeConfig> for InternalApiConfigBuilder { fn from(config: &ExternalNodeConfig) -> Self { Self { l1_chain_id: config.required.l1_chain_id, l2_chain_id: config.required.l2_chain_id, - max_tx_size: config.optional.max_tx_size_bytes, - estimate_gas_scale_factor: config.optional.estimate_gas_scale_factor, - estimate_gas_acceptable_overestimation: config - .optional - .estimate_gas_acceptable_overestimation, - estimate_gas_optimize_search: config.optional.estimate_gas_optimize_search, - bridge_addresses: BridgeAddresses { + max_tx_size: Some(config.optional.max_tx_size_bytes), + estimate_gas_scale_factor: Some(config.optional.estimate_gas_scale_factor), + estimate_gas_acceptable_overestimation: Some( + config.optional.estimate_gas_acceptable_overestimation, + ), + estimate_gas_optimize_search: Some(config.optional.estimate_gas_optimize_search), + bridge_addresses: Some(BridgeAddresses { l1_erc20_default_bridge: config.remote.l1_erc20_bridge_proxy_addr, l2_erc20_default_bridge: config.remote.l2_erc20_bridge_addr, l1_shared_default_bridge: config.remote.l1_shared_bridge_proxy_addr, @@ -1498,18 +1503,18 @@ impl From<&ExternalNodeConfig> for InternalApiConfig { l2_legacy_shared_bridge: config.remote.l2_legacy_shared_bridge_addr, l1_weth_bridge: config.remote.l1_weth_bridge_addr, l2_weth_bridge: config.remote.l2_weth_bridge_addr, - }, + }), l1_bytecodes_supplier_addr: config.remote.l1_bytecodes_supplier_addr, l1_wrapped_base_token_store: config.remote.l1_wrapped_base_token_store, l1_bridgehub_proxy_addr: config.remote.l1_bridgehub_proxy_addr, l1_state_transition_proxy_addr: config.remote.l1_state_transition_proxy_addr, l1_transparent_proxy_admin_addr: config.remote.l1_transparent_proxy_admin_addr, - l1_diamond_proxy_addr: config.l1_diamond_proxy_address(), + l1_diamond_proxy_addr: Some(config.l1_diamond_proxy_address()), l2_testnet_paymaster_addr: config.remote.l2_testnet_paymaster_addr, - req_entities_limit: config.optional.req_entities_limit, - fee_history_limit: config.optional.fee_history_limit, - base_token_address: Some(config.remote.base_token_addr), - filters_disabled: config.optional.filters_disabled, + req_entities_limit: Some(config.optional.req_entities_limit), + fee_history_limit: Some(config.optional.fee_history_limit), + base_token_address: config.remote.base_token_addr, + filters_disabled: Some(config.optional.filters_disabled), dummy_verifier: config.remote.dummy_verifier, l1_batch_commit_data_generator_mode: config.remote.l1_batch_commit_data_generator_mode, timestamp_asserter_address: config.remote.l2_timestamp_asserter_addr, @@ -1536,17 +1541,55 @@ impl From<&ExternalNodeConfig> for TxSenderConfig { chain_id: config.required.l2_chain_id, // Does not matter for EN. whitelisted_tokens_for_aa: Default::default(), - timestamp_asserter_params: config.remote.l2_timestamp_asserter_addr.map(|address| { + timestamp_asserter_params: config.remote.l2_timestamp_asserter_addr.map(|addr| { TimestampAsserterParams { - address, + address: addr, min_time_till_end: Duration::from_secs( - config - .optional - .timestamp_asserter_min_time_till_end_sec - .into(), + config.optional.timestamp_asserter_min_time_till_end_sec as u64, ), } }), } } } + +impl From<&ExternalNodeConfig> for L1SpecificContracts { + fn from(config: &ExternalNodeConfig) -> Self { + L1SpecificContracts { + bytecodes_supplier_addr: config.remote.l1_bytecodes_supplier_addr, + wrapped_base_token_store: config.remote.l1_wrapped_base_token_store, + bridge_hub: config.remote.l1_bridgehub_proxy_addr, + shared_bridge: config.remote.l1_shared_bridge_proxy_addr, + erc_20_bridge: config.remote.l1_erc20_bridge_proxy_addr, + base_token_address: config.remote.base_token_addr, + l1_diamond_proxy: config.l1_diamond_proxy_address(), + } + } +} + +impl From<&ExternalNodeConfig> for ChainSpecificContracts { + fn from(config: &ExternalNodeConfig) -> Self { + ChainSpecificContracts { + ecosystem_contracts: EcosystemCommonContracts { + bridgehub_proxy_addr: config.remote.l1_bridgehub_proxy_addr, + state_transition_proxy_addr: config.remote.l1_state_transition_proxy_addr, + server_notifier_addr: config.remote.l1_server_notifier_addr, + multicall3: None, + validator_timelock_addr: None, + no_da_validium_l1_validator_addr: None, + }, + chain_contracts_config: ChainContracts { + diamond_proxy_addr: config.remote.l1_diamond_proxy_addr, + chain_admin: None, + }, + l2_contracts: L2Contracts { + erc20_default_bridge: config.remote.l2_erc20_bridge_addr, + shared_bridge_addr: config.remote.l2_shared_bridge_addr, + legacy_shared_bridge_addr: config.remote.l2_legacy_shared_bridge_addr, + timestamp_asserter_addr: config.remote.l2_timestamp_asserter_addr, + da_validator_addr: None, + testnet_paymaster_addr: config.remote.l2_testnet_paymaster_addr, + }, + } + } +} diff --git a/core/bin/external_node/src/node_builder.rs b/core/bin/external_node/src/node_builder.rs index aeeeab8f01d6..610c0318d192 100644 --- a/core/bin/external_node/src/node_builder.rs +++ b/core/bin/external_node/src/node_builder.rs @@ -6,6 +6,7 @@ use zksync_block_reverter::NodeRole; use zksync_config::{ configs::{ api::{HealthCheckConfig, MerkleTreeApiConfig}, + chain::TimestampAsserterConfig, database::MerkleTreeMode, DataAvailabilitySecrets, DatabaseSecrets, }, @@ -14,7 +15,7 @@ use zksync_config::{ use zksync_metadata_calculator::{ MerkleTreeReaderConfig, MetadataCalculatorConfig, MetadataCalculatorRecoveryConfig, }; -use zksync_node_api_server::web3::Namespace; +use zksync_node_api_server::web3::{state::InternalApiConfigBuilder, Namespace}; use zksync_node_framework::{ implementations::layers::{ batch_status_updater::BatchStatusUpdaterLayer, @@ -27,6 +28,7 @@ use zksync_node_framework::{ no_da::NoDAClientWiringLayer, object_store::ObjectStorageClientWiringLayer, }, data_availability_fetcher::DataAvailabilityFetcherLayer, + gateway_client::GatewayClientLayer, healtcheck_server::HealthCheckLayer, l1_batch_commitment_mode_validation::L1BatchCommitmentModeValidationLayer, logs_bloom_backfill::LogsBloomBackfillLayer, @@ -43,6 +45,7 @@ use zksync_node_framework::{ pruning::PruningLayer, query_eth_client::QueryEthClientLayer, reorg_detector::ReorgDetectorLayer, + settlement_layer_data_en::SettlementLayerDataEn, sigint::SigintHandlerLayer, state_keeper::{ external_io::ExternalIOLayer, main_batch_executor::MainBatchExecutorLayer, @@ -62,7 +65,6 @@ use zksync_node_framework::{ service::{ZkStackService, ZkStackServiceBuilder}, }; use zksync_state::RocksdbStorageOptions; -use zksync_types::L2_ASSET_ROUTER_ADDRESS; use crate::{config::ExternalNodeConfig, metrics::framework::ExternalNodeMetricsLayer, Component}; @@ -149,6 +151,23 @@ impl ExternalNodeBuilder { Ok(self) } + fn add_settlement_layer_data(mut self) -> anyhow::Result { + self.node.add_layer(SettlementLayerDataEn::new( + (&self.config).into(), + (&self.config).into(), + )); + Ok(self) + } + + fn add_gateway_client_layer(mut self) -> anyhow::Result { + let query_eth_client_layer = GatewayClientLayer::new( + self.config.required.eth_client_url.clone(), + self.config.optional.gateway_url.clone(), + ); + self.node.add_layer(query_eth_client_layer); + Ok(self) + } + fn add_main_node_client_layer(mut self) -> anyhow::Result { let layer = MainNodeClientLayer::new( self.config.required.main_node_url.clone(), @@ -204,27 +223,12 @@ impl ExternalNodeBuilder { // compression. const OPTIONAL_BYTECODE_COMPRESSION: bool = true; - let l2_shared_bridge_addr = self - .config - .remote - .l2_shared_bridge_addr - .context("Missing `l2_shared_bridge_addr`")?; - let l2_legacy_shared_bridge_addr = if l2_shared_bridge_addr == L2_ASSET_ROUTER_ADDRESS { - // System has migrated to `L2_ASSET_ROUTER_ADDRESS`, use legacy shared bridge address from main node. - self.config.remote.l2_legacy_shared_bridge_addr - } else { - // System hasn't migrated on `L2_ASSET_ROUTER_ADDRESS`, we can safely use `l2_shared_bridge_addr`. - Some(l2_shared_bridge_addr) - }; - - let persistence_layer = OutputHandlerLayer::new( - l2_legacy_shared_bridge_addr, - self.config.optional.l2_block_seal_queue_capacity, - ) - .with_pre_insert_txs(true) // EN requires txs to be pre-inserted. - .with_protective_reads_persistence_enabled( - self.config.optional.protective_reads_persistence_enabled, - ); + let persistence_layer = + OutputHandlerLayer::new(self.config.optional.l2_block_seal_queue_capacity) + .with_pre_insert_txs(true) // EN requires txs to be pre-inserted. + .with_protective_reads_persistence_enabled( + self.config.optional.protective_reads_persistence_enabled, + ); let io_layer = ExternalIOLayer::new(self.config.required.l2_chain_id); @@ -286,7 +290,6 @@ impl ExternalNodeBuilder { fn add_l1_batch_commitment_mode_validation_layer(mut self) -> anyhow::Result { let layer = L1BatchCommitmentModeValidationLayer::new( - self.config.l1_diamond_proxy_address(), self.config.optional.l1_batch_commit_data_generator_mode, ); self.node.add_layer(layer); @@ -306,10 +309,8 @@ impl ExternalNodeBuilder { fn add_consistency_checker_layer(mut self) -> anyhow::Result { let max_batches_to_recheck = 10; // TODO (BFT-97): Make it a part of a proper EN config let layer = ConsistencyCheckerLayer::new( - self.config.l1_diamond_proxy_address(), max_batches_to_recheck, self.config.optional.l1_batch_commit_data_generator_mode, - self.config.required.l2_chain_id, ); self.node.add_layer(layer); Ok(self) @@ -334,11 +335,7 @@ impl ExternalNodeBuilder { } fn add_tree_data_fetcher_layer(mut self) -> anyhow::Result { - let layer = TreeDataFetcherLayer::new( - self.config.l1_diamond_proxy_address(), - self.config.required.l2_chain_id, - ); - self.node.add_layer(layer); + self.node.add_layer(TreeDataFetcherLayer); Ok(self) } @@ -478,9 +475,15 @@ impl ExternalNodeBuilder { }; let max_vm_concurrency = self.config.optional.vm_concurrency_limit; let tx_sender_layer = TxSenderLayer::new( - (&self.config).into(), postgres_storage_config, max_vm_concurrency, + (&self.config).into(), + Some(TimestampAsserterConfig { + min_time_till_end_sec: self + .config + .optional + .timestamp_asserter_min_time_till_end_sec, + }), ) .with_whitelisted_tokens_for_aa_cache(true); @@ -539,9 +542,11 @@ impl ExternalNodeBuilder { fn add_http_web3_api_layer(mut self) -> anyhow::Result { let optional_config = self.web3_api_optional_config(); + let internal_api_config_builder: InternalApiConfigBuilder = (&self.config).into(); + self.node.add_layer(Web3ServerLayer::http( self.config.required.http_port, - (&self.config).into(), + internal_api_config_builder, optional_config, )); @@ -551,9 +556,11 @@ impl ExternalNodeBuilder { fn add_ws_web3_api_layer(mut self) -> anyhow::Result { // TODO: Support websocket requests per minute limit let optional_config = self.web3_api_optional_config(); + let internal_api_config_builder: InternalApiConfigBuilder = (&self.config).into(); + self.node.add_layer(Web3ServerLayer::ws( self.config.required.ws_port, - (&self.config).into(), + internal_api_config_builder, optional_config, )); @@ -628,6 +635,8 @@ impl ExternalNodeBuilder { .add_pools_layer()? .add_main_node_client_layer()? .add_query_eth_client_layer()? + .add_settlement_layer_data()? + .add_gateway_client_layer()? .add_reorg_detector_layer()?; // Add layers that must run only on a single component. @@ -647,8 +656,8 @@ impl ExternalNodeBuilder { // Add preconditions for all the components. self = self - .add_l1_batch_commitment_mode_validation_layer()? - .add_validate_chain_ids_layer()? + // .add_l1_batch_commitment_mode_validation_layer()? + // .add_validate_chain_ids_layer()? .add_storage_initialization_layer(LayerKind::Precondition)?; // Sort the components, so that the components they may depend on each other are added in the correct order. @@ -711,7 +720,7 @@ impl ExternalNodeBuilder { .add_state_keeper_layer()? .add_consensus_layer()? .add_pruning_layer()? - .add_consistency_checker_layer()? + // .add_consistency_checker_layer()? .add_commitment_generator_layer()? .add_batch_status_updater_layer()? .add_logs_bloom_backfill_layer()?; diff --git a/core/bin/genesis_generator/src/main.rs b/core/bin/genesis_generator/src/main.rs index 2a96cdc6c6cc..d48f05f1b6e5 100644 --- a/core/bin/genesis_generator/src/main.rs +++ b/core/bin/genesis_generator/src/main.rs @@ -22,7 +22,7 @@ use zksync_types::{ protocol_version::ProtocolSemanticVersion, url::SensitiveUrl, ProtocolVersionId, }; -const DEFAULT_GENESIS_FILE_PATH: &str = "./etc/env/file_based/genesis.yaml"; +const DEFAULT_GENESIS_FILE_PATH: &str = "../etc/env/file_based/genesis.yaml"; #[derive(Debug, Parser)] #[command(author = "Matter Labs", version, about = "Genesis config generator", long_about = None)] diff --git a/core/bin/zksync_server/src/main.rs b/core/bin/zksync_server/src/main.rs index e424f606e441..b299b96cd108 100644 --- a/core/bin/zksync_server/src/main.rs +++ b/core/bin/zksync_server/src/main.rs @@ -9,18 +9,19 @@ use zksync_config::{ CircuitBreakerConfig, MempoolConfig, NetworkConfig, OperationsManagerConfig, StateKeeperConfig, TimestampAsserterConfig, }, + contracts::ecosystem::L1SpecificContracts, fri_prover_group::FriProverGroupConfig, house_keeper::HouseKeeperConfig, - BasicWitnessInputProducerConfig, ContractVerifierSecrets, ContractsConfig, - DataAvailabilitySecrets, DatabaseSecrets, ExperimentalVmConfig, - ExternalPriceApiClientConfig, FriProofCompressorConfig, FriProverConfig, - FriProverGatewayConfig, FriWitnessGeneratorConfig, FriWitnessVectorGeneratorConfig, - L1Secrets, ObservabilityConfig, PrometheusConfig, ProofDataHandlerConfig, - ProtectiveReadsWriterConfig, Secrets, + BasicWitnessInputProducerConfig, ContractVerifierSecrets, DataAvailabilitySecrets, + DatabaseSecrets, ExperimentalVmConfig, ExternalPriceApiClientConfig, + FriProofCompressorConfig, FriProverConfig, FriProverGatewayConfig, + FriWitnessGeneratorConfig, FriWitnessVectorGeneratorConfig, L1Secrets, ObservabilityConfig, + PrometheusConfig, ProofDataHandlerConfig, ProtectiveReadsWriterConfig, Secrets, }, - ApiConfig, BaseTokenAdjusterConfig, ContractVerifierConfig, DAClientConfig, DADispatcherConfig, - DBConfig, EthConfig, EthWatchConfig, ExternalProofIntegrationApiConfig, GasAdjusterConfig, - GenesisConfig, ObjectStoreConfig, PostgresConfig, SnapshotsCreatorConfig, + ApiConfig, BaseTokenAdjusterConfig, ContractVerifierConfig, ContractsConfig, DAClientConfig, + DADispatcherConfig, DBConfig, EthConfig, EthWatchConfig, ExternalProofIntegrationApiConfig, + GasAdjusterConfig, GenesisConfig, ObjectStoreConfig, PostgresConfig, SettlementLayerContracts, + SnapshotsCreatorConfig, }; use zksync_core_leftovers::{ temp_config_store::{read_yaml_repr, TempConfigStore}, @@ -157,13 +158,17 @@ fn main() -> anyhow::Result<()> { .clone() .context("observability config")?; + let l1_specific_contracts = L1SpecificContracts::new(&contracts_config); + let contracts = + SettlementLayerContracts::new(&contracts_config, gateway_contracts_config.as_ref()); + let node = MainNodeBuilder::new( configs, wallets, genesis, - contracts_config, - gateway_contracts_config, secrets, + contracts, + l1_specific_contracts, )?; let observability_guard = { @@ -188,23 +193,18 @@ fn main() -> anyhow::Result<()> { } fn find_gateway_update_error(zkstack_result: &Result<(), ZkStackServiceError>) -> bool { - if let Err(zkstack_err) = zkstack_result { - match &zkstack_err { - ZkStackServiceError::Task(tasks) => { - for task in &tasks.0 { - if let TaskError::TaskFailed(task, err) = task { - if task.contains("gateway_migrator") - && err.to_string().contains("Settlement layer changed") - { - return true; - } - } + if let Err(ZkStackServiceError::Task(tasks)) = zkstack_result { + for task in &tasks.0 { + if let TaskError::TaskFailed(task, err) = task { + if task.contains("gateway_migrator") + && err.to_string().contains("Settlement layer changed") + { + return true; } } - _ => {} } } - return false; + false } fn load_env_config() -> anyhow::Result { diff --git a/core/bin/zksync_server/src/node_builder.rs b/core/bin/zksync_server/src/node_builder.rs index 9d5ba82c6959..8d1d225e5fc2 100644 --- a/core/bin/zksync_server/src/node_builder.rs +++ b/core/bin/zksync_server/src/node_builder.rs @@ -1,21 +1,19 @@ //! This module provides a "builder" for the main node, //! as well as an interface to run the node with the specified components. -use std::time::Duration; - use anyhow::{bail, Context}; use zksync_config::{ configs::{ - da_client::DAClientConfig, gateway::GatewayChainConfig, secrets::DataAvailabilitySecrets, - wallets::Wallets, GeneralConfig, Secrets, + contracts::ecosystem::L1SpecificContracts, da_client::DAClientConfig, + secrets::DataAvailabilitySecrets, wallets::Wallets, GeneralConfig, Secrets, }, - ContractsConfig, GenesisConfig, + GenesisConfig, SettlementLayerContracts, }; use zksync_core_leftovers::Component; use zksync_metadata_calculator::MetadataCalculatorConfig; use zksync_node_api_server::{ - tx_sender::{TimestampAsserterParams, TxSenderConfig}, - web3::{state::InternalApiConfig, Namespace}, + tx_sender::TxSenderConfig, + web3::{state::InternalApiConfigBuilder, Namespace}, }; use zksync_node_framework::{ implementations::layers::{ @@ -36,6 +34,7 @@ use zksync_node_framework::{ eth_watch::EthWatchLayer, external_proof_integration_api::ExternalProofIntegrationApiLayer, gas_adjuster::GasAdjusterLayer, + gateway_client::GatewayClientLayer, gateway_migrator_layer::GatewayMigratorLayer, healtcheck_server::HealthCheckLayer, house_keeper::HouseKeeperLayer, @@ -53,6 +52,7 @@ use zksync_node_framework::{ prometheus_exporter::PrometheusExporterLayer, proof_data_handler::ProofDataHandlerLayer, query_eth_client::QueryEthClientLayer, + settlement_layer_data::SettlementLayerData, sigint::SigintHandlerLayer, state_keeper::{ main_batch_executor::MainBatchExecutorLayer, mempool_io::MempoolIOLayer, @@ -92,9 +92,9 @@ pub struct MainNodeBuilder { configs: GeneralConfig, wallets: Wallets, genesis_config: GenesisConfig, - contracts_config: ContractsConfig, - gateway_chain_config: Option, secrets: Secrets, + contracts: SettlementLayerContracts, + l1_specific_contracts: L1SpecificContracts, } impl MainNodeBuilder { @@ -102,18 +102,18 @@ impl MainNodeBuilder { configs: GeneralConfig, wallets: Wallets, genesis_config: GenesisConfig, - contracts_config: ContractsConfig, - gateway_chain_config: Option, secrets: Secrets, + contracts: SettlementLayerContracts, + l1_specific_contracts: L1SpecificContracts, ) -> anyhow::Result { Ok(Self { node: ZkStackServiceBuilder::new().context("Cannot create ZkStackServiceBuilder")?, configs, wallets, genesis_config, - contracts_config, - gateway_chain_config, secrets, + contracts, + l1_specific_contracts, }) } @@ -170,12 +170,8 @@ impl MainNodeBuilder { fn add_pk_signing_client_layer(mut self) -> anyhow::Result { let eth_config = try_load_config!(self.configs.eth); let wallets = try_load_config!(self.wallets.eth_sender); - self.node.add_layer(PKSigningEthClientLayer::new( - eth_config, - self.contracts_config.clone(), - self.gateway_chain_config.clone(), - wallets, - )); + self.node + .add_layer(PKSigningEthClientLayer::new(eth_config, wallets)); Ok(self) } @@ -185,15 +181,22 @@ impl MainNodeBuilder { let query_eth_client_layer = QueryEthClientLayer::new( genesis.l1_chain_id, eth_config.l1_rpc_url, - self.gateway_chain_config - .as_ref() - .map(|c| c.gateway_chain_id), + // TODO query from the server + None, eth_config.gateway_rpc_url, ); self.node.add_layer(query_eth_client_layer); Ok(self) } + fn add_gateway_client_layer(mut self) -> anyhow::Result { + let eth_config = try_load_config!(self.secrets.l1); + let query_eth_client_layer = + GatewayClientLayer::new(eth_config.l1_rpc_url, eth_config.gateway_rpc_url); + self.node.add_layer(query_eth_client_layer); + Ok(self) + } + fn add_gas_adjuster_layer(mut self) -> anyhow::Result { let gas_adjuster_config = try_load_config!(self.configs.eth) .gas_adjuster @@ -210,7 +213,8 @@ impl MainNodeBuilder { fn add_l1_gas_layer(mut self) -> anyhow::Result { // Ensure the BaseTokenRatioProviderResource is inserted if the base token is not ETH. - if self.contracts_config.base_token_addr != Some(SHARED_BRIDGE_ETHER_TOKEN_ADDRESS) { + if self.l1_specific_contracts.base_token_address != Some(SHARED_BRIDGE_ETHER_TOKEN_ADDRESS) + { let base_token_adjuster_config = try_load_config!(self.configs.base_token_adjuster); self.node .add_layer(BaseTokenRatioProviderLayer::new(base_token_adjuster_config)); @@ -230,7 +234,6 @@ impl MainNodeBuilder { fn add_l1_batch_commitment_mode_validation_layer(mut self) -> anyhow::Result { let layer = L1BatchCommitmentModeValidationLayer::new( - self.contracts_config.diamond_proxy_addr, self.genesis_config.l1_batch_commit_data_generator_mode, ); self.node.add_layer(layer); @@ -262,17 +265,15 @@ impl MainNodeBuilder { let wallets = self.wallets.clone(); let sk_config = try_load_config!(self.configs.state_keeper_config); - let persistence_layer = OutputHandlerLayer::new( - self.contracts_config.l2_legacy_shared_bridge_addr, - sk_config.l2_block_seal_queue_capacity, - ) - .with_protective_reads_persistence_enabled(sk_config.protective_reads_persistence_enabled); + let persistence_layer = OutputHandlerLayer::new(sk_config.l2_block_seal_queue_capacity) + .with_protective_reads_persistence_enabled( + sk_config.protective_reads_persistence_enabled, + ); let mempool_io_layer = MempoolIOLayer::new( self.genesis_config.l2_chain_id, sk_config.clone(), try_load_config!(self.configs.mempool_config), try_load_config!(wallets.state_keeper), - self.contracts_config.l2_da_validator_addr, self.get_pubdata_type()?, ); let db_config = try_load_config!(self.configs.db_config); @@ -305,21 +306,24 @@ impl MainNodeBuilder { let eth_config = try_load_config!(self.configs.eth); self.node.add_layer(EthWatchLayer::new( try_load_config!(eth_config.watcher), - self.contracts_config.clone(), - self.gateway_chain_config.clone(), self.genesis_config.l2_chain_id, )); Ok(self) } - fn add_gateway_migrator_layer(mut self) -> anyhow::Result { - self.node.add_layer(GatewayMigratorLayer::new( - self.contracts_config.clone(), - self.gateway_chain_config.clone(), + fn add_settlement_mode_data(mut self) -> anyhow::Result { + self.node.add_layer(SettlementLayerData::new( + self.contracts.clone(), + self.l1_specific_contracts.clone(), )); Ok(self) } + fn add_gateway_migrator_layer(mut self) -> anyhow::Result { + self.node.add_layer(GatewayMigratorLayer); + Ok(self) + } + fn add_proof_data_handler_layer(mut self) -> anyhow::Result { self.node.add_layer(ProofDataHandlerLayer::new( try_load_config!(self.configs.proof_data_handler_config), @@ -339,19 +343,6 @@ impl MainNodeBuilder { let sk_config = try_load_config!(self.configs.state_keeper_config); let rpc_config = try_load_config!(self.configs.api_config).web3_json_rpc; - let timestamp_asserter_params = match self.contracts_config.l2_timestamp_asserter_addr { - Some(address) => { - let timestamp_asserter_config = - try_load_config!(self.configs.timestamp_asserter_config); - Some(TimestampAsserterParams { - address, - min_time_till_end: Duration::from_secs( - timestamp_asserter_config.min_time_till_end_sec.into(), - ), - }) - } - None => None, - }; let postgres_storage_caches_config = PostgresStorageCachesConfig { factory_deps_cache_size: rpc_config.factory_deps_cache_size() as u64, initial_writes_cache_size: rpc_config.initial_writes_cache_size() as u64, @@ -368,6 +359,8 @@ impl MainNodeBuilder { self.node.add_layer(MasterPoolSinkLayer); let layer = TxSenderLayer::new( + postgres_storage_caches_config, + rpc_config.vm_concurrency_limit(), TxSenderConfig::new( &sk_config, &rpc_config, @@ -375,10 +368,8 @@ impl MainNodeBuilder { .fee_account .address(), self.genesis_config.l2_chain_id, - timestamp_asserter_params, ), - postgres_storage_caches_config, - rpc_config.vm_concurrency_limit(), + self.configs.timestamp_asserter_config.clone(), ); let layer = layer.with_vm_mode(vm_config.api_fast_vm_mode); self.node.add_layer(layer); @@ -428,9 +419,12 @@ impl MainNodeBuilder { with_extended_tracing: rpc_config.extended_api_tracing, ..Default::default() }; + let http_port = rpc_config.http_port; + let internal_config_builder = InternalApiConfigBuilder::from_genesis(&self.genesis_config) + .with_web3_config(rpc_config); self.node.add_layer(Web3ServerLayer::http( - rpc_config.http_port, - InternalApiConfig::new(&rpc_config, &self.contracts_config, &self.genesis_config), + http_port, + internal_config_builder, optional_config, )); @@ -469,9 +463,13 @@ impl MainNodeBuilder { with_extended_tracing: rpc_config.extended_api_tracing, ..Default::default() }; + let ws_port = rpc_config.ws_port; + let internal_config_builder = InternalApiConfigBuilder::from_genesis(&self.genesis_config) + .with_web3_config(rpc_config); + self.node.add_layer(Web3ServerLayer::ws( - rpc_config.ws_port, - InternalApiConfig::new(&rpc_config, &self.contracts_config, &self.genesis_config), + ws_port, + internal_config_builder, optional_config, )); @@ -491,8 +489,6 @@ impl MainNodeBuilder { let eth_sender_config = try_load_config!(self.configs.eth); self.node.add_layer(EthTxAggregatorLayer::new( eth_sender_config, - self.contracts_config.clone(), - self.gateway_chain_config.clone(), self.genesis_config.l2_chain_id, self.genesis_config.l1_batch_commit_data_generator_mode, )); @@ -611,7 +607,6 @@ impl MainNodeBuilder { self.node.add_layer(DataAvailabilityDispatcherLayer::new( state_keeper_config, da_config, - self.contracts_config.clone(), )); Ok(self) @@ -662,12 +657,10 @@ impl MainNodeBuilder { fn add_base_token_ratio_persister_layer(mut self) -> anyhow::Result { let config = try_load_config!(self.configs.base_token_adjuster); - let contracts_config = self.contracts_config.clone(); let wallets = self.wallets.clone(); let l1_chain_id = self.genesis_config.l1_chain_id; self.node.add_layer(BaseTokenRatioPersisterLayer::new( config, - contracts_config, wallets, l1_chain_id, )); @@ -705,7 +698,6 @@ impl MainNodeBuilder { fn add_storage_initialization_layer(mut self, kind: LayerKind) -> anyhow::Result { self.node.add_layer(MainNodeInitStrategyLayer { genesis: self.genesis_config.clone(), - contracts: self.contracts_config.clone(), }); let mut layer = NodeStorageInitializerLayer::new(); if matches!(kind, LayerKind::Precondition) { @@ -720,6 +712,8 @@ impl MainNodeBuilder { self = self .add_pools_layer()? .add_query_eth_client_layer()? + .add_settlement_mode_data()? + .add_gateway_client_layer()? .add_storage_initialization_layer(LayerKind::Task)?; Ok(self.node.build()) @@ -736,6 +730,8 @@ impl MainNodeBuilder { .add_healthcheck_layer()? .add_prometheus_exporter_layer()? .add_query_eth_client_layer()? + .add_settlement_mode_data()? + .add_gateway_client_layer()? .add_gateway_migrator_layer()? .add_gas_adjuster_layer()?; diff --git a/core/lib/config/src/configs/contracts.rs b/core/lib/config/src/configs/contracts/chain.rs similarity index 69% rename from core/lib/config/src/configs/contracts.rs rename to core/lib/config/src/configs/contracts/chain.rs index 418c45ccdcb8..58c41e8417db 100644 --- a/core/lib/config/src/configs/contracts.rs +++ b/core/lib/config/src/configs/contracts/chain.rs @@ -1,37 +1,11 @@ -// External uses -use serde::{Deserialize, Serialize}; -// Workspace uses +use serde::Deserialize; use zksync_basic_types::{Address, H256}; -#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] -pub struct EcosystemContracts { - pub bridgehub_proxy_addr: Address, - pub state_transition_proxy_addr: Address, - pub transparent_proxy_admin_addr: Address, - pub l1_bytecodes_supplier_addr: Option
, - // Note that on the contract side of things this contract is called `L2WrappedBaseTokenStore`, - // while on the server side for consistency with the conventions, where the prefix denotes - // the location of the contracts we call it `l1_wrapped_base_token_store` - pub l1_wrapped_base_token_store: Option
, - pub server_notifier_addr: Option
, -} - -impl EcosystemContracts { - fn for_tests() -> Self { - Self { - bridgehub_proxy_addr: Address::repeat_byte(0x14), - state_transition_proxy_addr: Address::repeat_byte(0x15), - transparent_proxy_admin_addr: Address::repeat_byte(0x15), - l1_bytecodes_supplier_addr: Some(Address::repeat_byte(0x16)), - l1_wrapped_base_token_store: Some(Address::repeat_byte(0x17)), - server_notifier_addr: Some(Address::repeat_byte(0x18)), - } - } -} +use crate::configs::contracts::ecosystem::EcosystemContracts; -/// Data about deployed contracts. +/// Data about deployed contracts unified l1/l2 contracts and bridges. To Be Deleted #[derive(Debug, Deserialize, Clone, PartialEq)] -pub struct ContractsConfig { +pub struct AllContractsConfig { pub governance_addr: Address, pub verifier_addr: Address, pub default_upgrade_addr: Address, @@ -62,7 +36,7 @@ pub struct ContractsConfig { pub no_da_validium_l1_validator_addr: Option
, } -impl ContractsConfig { +impl AllContractsConfig { pub fn for_tests() -> Self { Self { verifier_addr: Address::repeat_byte(0x06), @@ -89,3 +63,21 @@ impl ContractsConfig { } } } + +// Contracts specific for the chain. Should be deployed to all Settlement Layers +#[derive(Debug, Clone)] +pub struct ChainContracts { + pub diamond_proxy_addr: Address, + pub chain_admin: Option
, +} + +// Contracts deployed to the l2 +#[derive(Debug, Clone)] +pub struct L2Contracts { + pub erc20_default_bridge: Option
, + pub shared_bridge_addr: Option
, + pub legacy_shared_bridge_addr: Option
, + pub timestamp_asserter_addr: Option
, + pub da_validator_addr: Option
, + pub testnet_paymaster_addr: Option
, +} diff --git a/core/lib/config/src/configs/contracts/ecosystem.rs b/core/lib/config/src/configs/contracts/ecosystem.rs new file mode 100644 index 000000000000..f1ad7551b26b --- /dev/null +++ b/core/lib/config/src/configs/contracts/ecosystem.rs @@ -0,0 +1,74 @@ +// External uses +use serde::{Deserialize, Serialize}; +use zksync_basic_types::Address; + +// Workspace uses +use crate::configs::AllContractsConfig; + +// Unified ecosystem contracts. To be deleted, after contracts config migration +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] +pub struct EcosystemContracts { + pub bridgehub_proxy_addr: Address, + pub state_transition_proxy_addr: Option
, + pub transparent_proxy_admin_addr: Option
, + pub l1_bytecodes_supplier_addr: Option
, + // Note that on the contract side of things this contract is called `L2WrappedBaseTokenStore`, + // while on the server side for consistency with the conventions, where the prefix denotes + // the location of the contracts we call it `l1_wrapped_base_token_store` + pub l1_wrapped_base_token_store: Option
, + pub server_notifier_addr: Option
, +} + +impl EcosystemContracts { + pub(crate) fn for_tests() -> Self { + Self { + bridgehub_proxy_addr: Address::repeat_byte(0x14), + state_transition_proxy_addr: Some(Address::repeat_byte(0x15)), + transparent_proxy_admin_addr: Some(Address::repeat_byte(0x15)), + l1_bytecodes_supplier_addr: Some(Address::repeat_byte(0x16)), + l1_wrapped_base_token_store: Some(Address::repeat_byte(0x17)), + server_notifier_addr: Some(Address::repeat_byte(0x18)), + } + } +} + +// Ecosystem contracts that are specific only for L1 +#[derive(Debug, Clone)] +pub struct L1SpecificContracts { + pub bytecodes_supplier_addr: Option
, + // Note that on the contract side of things this contract is called `L2WrappedBaseTokenStore`, + // while on the server side for consistency with the conventions, where the prefix denotes + // the location of the contracts we call it `l1_wrapped_base_token_store` + pub wrapped_base_token_store: Option
, + pub bridge_hub: Option
, + pub shared_bridge: Option
, + pub erc_20_bridge: Option
, + pub base_token_address: Option
, + pub l1_diamond_proxy: Address, +} + +// Ecosystem contracts that are presented on all Settlement Layers +#[derive(Debug, Clone)] +pub struct EcosystemCommonContracts { + pub bridgehub_proxy_addr: Option
, + pub state_transition_proxy_addr: Option
, + pub server_notifier_addr: Option
, + pub multicall3: Option
, + pub validator_timelock_addr: Option
, + pub no_da_validium_l1_validator_addr: Option
, +} + +impl L1SpecificContracts { + pub fn new(contracts_config: &AllContractsConfig) -> Self { + let ecosystem = contracts_config.ecosystem_contracts.as_ref().unwrap(); + Self { + bytecodes_supplier_addr: ecosystem.l1_bytecodes_supplier_addr, + wrapped_base_token_store: ecosystem.l1_wrapped_base_token_store, + l1_diamond_proxy: contracts_config.diamond_proxy_addr, + bridge_hub: Some(ecosystem.bridgehub_proxy_addr), + shared_bridge: contracts_config.l1_shared_bridge_proxy_addr, + erc_20_bridge: contracts_config.l1_erc20_bridge_proxy_addr, + base_token_address: contracts_config.base_token_addr, + } + } +} diff --git a/core/lib/config/src/configs/gateway.rs b/core/lib/config/src/configs/contracts/gateway.rs similarity index 75% rename from core/lib/config/src/configs/gateway.rs rename to core/lib/config/src/configs/contracts/gateway.rs index 9981a30d1278..5bf28f8a82b8 100644 --- a/core/lib/config/src/configs/gateway.rs +++ b/core/lib/config/src/configs/contracts/gateway.rs @@ -1,6 +1,6 @@ use zksync_basic_types::{web3::Bytes, Address, SLChainId}; -use super::ContractsConfig; +use super::chain::AllContractsConfig; /// Config that is only stored for the gateway chain. #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)] @@ -24,12 +24,13 @@ pub struct GatewayConfig { #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)] pub struct GatewayChainConfig { - pub state_transition_proxy_addr: Address, - pub validator_timelock_addr: Address, + pub state_transition_proxy_addr: Option
, + pub validator_timelock_addr: Option
, pub multicall3_addr: Address, pub diamond_proxy_addr: Address, pub chain_admin_addr: Address, pub gateway_chain_id: SLChainId, + pub server_notifier: Option
, } impl GatewayChainConfig { @@ -40,29 +41,30 @@ impl GatewayChainConfig { gateway_chain_id: SLChainId, ) -> Self { Self { - state_transition_proxy_addr: gateway_config.state_transition_proxy_addr, - validator_timelock_addr: gateway_config.validator_timelock_addr, + state_transition_proxy_addr: Some(gateway_config.state_transition_proxy_addr), + validator_timelock_addr: Some(gateway_config.validator_timelock_addr), multicall3_addr: gateway_config.multicall3_addr, diamond_proxy_addr, chain_admin_addr: l2_chain_admin_addr, gateway_chain_id, + server_notifier: None, } } pub fn from_contracts_and_chain_id( - contracts: ContractsConfig, + contracts: AllContractsConfig, gateway_chain_id: SLChainId, ) -> Self { Self { state_transition_proxy_addr: contracts .ecosystem_contracts - .unwrap() - .state_transition_proxy_addr, - validator_timelock_addr: contracts.validator_timelock_addr, + .and_then(|a| a.state_transition_proxy_addr), + validator_timelock_addr: Some(contracts.validator_timelock_addr), multicall3_addr: contracts.l1_multicall3_addr, diamond_proxy_addr: contracts.diamond_proxy_addr, chain_admin_addr: contracts.chain_admin_addr, gateway_chain_id, + server_notifier: None, } } } diff --git a/core/lib/config/src/configs/contracts/mod.rs b/core/lib/config/src/configs/contracts/mod.rs new file mode 100644 index 000000000000..22d9939de8de --- /dev/null +++ b/core/lib/config/src/configs/contracts/mod.rs @@ -0,0 +1,132 @@ +use zksync_basic_types::{settlement::SettlementMode, Address, SLChainId, H160}; + +use crate::configs::{ + contracts::{ + chain::{AllContractsConfig, ChainContracts, L2Contracts}, + ecosystem::EcosystemCommonContracts, + }, + gateway::GatewayChainConfig, +}; + +pub mod chain; +pub mod ecosystem; +pub mod gateway; + +pub const L2_BRIDGEHUB_ADDRESS: Address = H160([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x02, +]); + +#[derive(Debug, Clone)] +pub struct ChainSpecificContracts { + pub ecosystem_contracts: EcosystemCommonContracts, + pub chain_contracts_config: ChainContracts, + pub l2_contracts: L2Contracts, +} + +#[derive(Debug, Clone)] +pub struct SettlementLayerContracts { + l1_contracts: ChainSpecificContracts, + gateway_contracts: Option, + sl_mode: SettlementMode, + gateway_chain_id: Option, +} + +impl SettlementLayerContracts { + pub fn current_contracts(&self) -> &ChainSpecificContracts { + match self.sl_mode { + SettlementMode::SettlesToL1 => &self.l1_contracts, + SettlementMode::Gateway => self.gateway_contracts.as_ref().expect("Settles to Gateway"), + } + } + + pub fn l1_contracts(&self) -> &ChainSpecificContracts { + &self.l1_contracts + } + + pub fn gateway(&self) -> Option<&ChainSpecificContracts> { + self.gateway_contracts.as_ref() + } + pub fn set_settlement_mode(&mut self, settlement_mode: SettlementMode) { + self.sl_mode = settlement_mode; + } + pub fn settlement_mode(&self) -> SettlementMode { + self.sl_mode + } +} + +impl SettlementLayerContracts { + pub fn new_raw( + l1_contracts: ChainSpecificContracts, + gateway_contracts: Option, + sl_mode: SettlementMode, + ) -> Self { + Self { + l1_contracts, + gateway_contracts, + sl_mode, + gateway_chain_id: None, + } + } + + pub fn new( + contracts_config: &AllContractsConfig, + gateway_chain_config: Option<&GatewayChainConfig>, + ) -> Self { + let ecosystem = contracts_config.ecosystem_contracts.as_ref().unwrap(); + Self { + l1_contracts: ChainSpecificContracts { + ecosystem_contracts: EcosystemCommonContracts { + bridgehub_proxy_addr: Some(ecosystem.bridgehub_proxy_addr), + state_transition_proxy_addr: ecosystem.state_transition_proxy_addr, + server_notifier_addr: ecosystem.server_notifier_addr, + multicall3: Some(contracts_config.l1_multicall3_addr), + validator_timelock_addr: Some(contracts_config.validator_timelock_addr), + no_da_validium_l1_validator_addr: contracts_config + .no_da_validium_l1_validator_addr, + }, + chain_contracts_config: ChainContracts { + diamond_proxy_addr: contracts_config.diamond_proxy_addr, + chain_admin: Some(contracts_config.chain_admin_addr), + }, + l2_contracts: L2Contracts { + erc20_default_bridge: contracts_config.l2_erc20_bridge_addr, + shared_bridge_addr: contracts_config.l2_shared_bridge_addr, + legacy_shared_bridge_addr: contracts_config.l2_legacy_shared_bridge_addr, + timestamp_asserter_addr: contracts_config.l2_timestamp_asserter_addr, + da_validator_addr: contracts_config.l2_da_validator_addr, + testnet_paymaster_addr: contracts_config.l2_testnet_paymaster_addr, + }, + }, + gateway_chain_id: gateway_chain_config.as_ref().map(|a| a.gateway_chain_id), + gateway_contracts: gateway_chain_config.map(|gateway| ChainSpecificContracts { + ecosystem_contracts: EcosystemCommonContracts { + bridgehub_proxy_addr: Some(L2_BRIDGEHUB_ADDRESS), + state_transition_proxy_addr: gateway.state_transition_proxy_addr, + server_notifier_addr: gateway.server_notifier, + multicall3: Some(gateway.multicall3_addr), + validator_timelock_addr: gateway.validator_timelock_addr, + // TODO set it properly + no_da_validium_l1_validator_addr: None, + }, + chain_contracts_config: ChainContracts { + diamond_proxy_addr: gateway.diamond_proxy_addr, + chain_admin: Some(gateway.chain_admin_addr), + }, + l2_contracts: L2Contracts { + erc20_default_bridge: contracts_config.l2_erc20_bridge_addr, + shared_bridge_addr: contracts_config.l2_shared_bridge_addr, + legacy_shared_bridge_addr: contracts_config.l2_legacy_shared_bridge_addr, + timestamp_asserter_addr: contracts_config.l2_timestamp_asserter_addr, + da_validator_addr: contracts_config.l2_da_validator_addr, + testnet_paymaster_addr: contracts_config.l2_testnet_paymaster_addr, + }, + }), + sl_mode: Default::default(), + } + } + + pub fn gateway_chain_id(&self) -> Option { + self.gateway_chain_id + } +} diff --git a/core/lib/config/src/configs/eth_sender.rs b/core/lib/config/src/configs/eth_sender.rs index 04c37dd8f8ab..22f8ffdb1831 100644 --- a/core/lib/config/src/configs/eth_sender.rs +++ b/core/lib/config/src/configs/eth_sender.rs @@ -2,7 +2,7 @@ use std::time::Duration; use anyhow::Context as _; use serde::Deserialize; -use zksync_basic_types::{pubdata_da::PubdataSendingMode, settlement::SettlementMode, H256}; +use zksync_basic_types::{pubdata_da::PubdataSendingMode, H256}; use zksync_crypto_primitives::K256PrivateKey; use crate::EthWatchConfig; @@ -57,7 +57,6 @@ impl EthConfig { num_samples_for_blob_base_fee_estimate: 10, internal_pubdata_pricing_multiplier: 1.0, max_blob_base_fee: None, - settlement_mode: Default::default(), }), watcher: Some(EthWatchConfig { confirmations_for_eth_event: None, @@ -206,10 +205,6 @@ pub struct GasAdjusterConfig { pub internal_pubdata_pricing_multiplier: f64, /// Max blob base fee that is allowed to be used. pub max_blob_base_fee: Option, - /// Whether the gas adjuster should require that the L2 node is used as a settlement layer. - /// It offers a runtime check for correctly provided values. - #[serde(default)] - pub settlement_mode: SettlementMode, } impl GasAdjusterConfig { diff --git a/core/lib/config/src/configs/mod.rs b/core/lib/config/src/configs/mod.rs index 1063ef809f27..a02172ef1057 100644 --- a/core/lib/config/src/configs/mod.rs +++ b/core/lib/config/src/configs/mod.rs @@ -4,7 +4,7 @@ pub use self::{ base_token_adjuster::BaseTokenAdjusterConfig, commitment_generator::CommitmentGeneratorConfig, contract_verifier::ContractVerifierConfig, - contracts::{ContractsConfig, EcosystemContracts}, + contracts::{chain::AllContractsConfig, ecosystem::EcosystemContracts, gateway}, da_client::{avail::AvailConfig, celestia::CelestiaConfig, eigen::EigenConfig, DAClientConfig}, da_dispatcher::DADispatcherConfig, database::{DBConfig, PostgresConfig}, @@ -18,7 +18,6 @@ pub use self::{ fri_prover_gateway::FriProverGatewayConfig, fri_witness_generator::FriWitnessGeneratorConfig, fri_witness_vector_generator::FriWitnessVectorGeneratorConfig, - gateway::{GatewayChainConfig, GatewayConfig}, general::GeneralConfig, genesis::GenesisConfig, object_store::ObjectStoreConfig, @@ -57,7 +56,6 @@ pub mod fri_prover_gateway; pub mod fri_prover_group; pub mod fri_witness_generator; pub mod fri_witness_vector_generator; -pub mod gateway; mod general; pub mod genesis; pub mod house_keeper; diff --git a/core/lib/config/src/lib.rs b/core/lib/config/src/lib.rs index f77a8ceb39ad..50876145d222 100644 --- a/core/lib/config/src/lib.rs +++ b/core/lib/config/src/lib.rs @@ -1,10 +1,11 @@ #![allow(clippy::upper_case_acronyms, clippy::derive_partial_eq_without_eq)] pub use crate::configs::{ + contracts::{chain::AllContractsConfig as ContractsConfig, SettlementLayerContracts}, ApiConfig, AvailConfig, BaseTokenAdjusterConfig, CelestiaConfig, ContractVerifierConfig, - ContractsConfig, DAClientConfig, DADispatcherConfig, DBConfig, EigenConfig, EthConfig, - EthWatchConfig, ExternalProofIntegrationApiConfig, GasAdjusterConfig, GenesisConfig, - ObjectStoreConfig, PostgresConfig, SnapshotsCreatorConfig, + DAClientConfig, DADispatcherConfig, DBConfig, EigenConfig, EthConfig, EthWatchConfig, + ExternalProofIntegrationApiConfig, GasAdjusterConfig, GenesisConfig, ObjectStoreConfig, + PostgresConfig, SnapshotsCreatorConfig, }; pub mod configs; diff --git a/core/lib/config/src/testonly.rs b/core/lib/config/src/testonly.rs index 8719cc8d94ad..7a3aa68bd8f3 100644 --- a/core/lib/config/src/testonly.rs +++ b/core/lib/config/src/testonly.rs @@ -247,9 +247,9 @@ impl Distribution for EncodeDist { } } -impl Distribution for EncodeDist { - fn sample(&self, rng: &mut R) -> configs::ContractsConfig { - configs::ContractsConfig { +impl Distribution for EncodeDist { + fn sample(&self, rng: &mut R) -> configs::AllContractsConfig { + configs::AllContractsConfig { governance_addr: rng.gen(), verifier_addr: rng.gen(), default_upgrade_addr: rng.gen(), @@ -440,8 +440,6 @@ impl Distribution for EncodeDist { num_samples_for_blob_base_fee_estimate: self.sample(rng), internal_pubdata_pricing_multiplier: self.sample(rng), max_blob_base_fee: self.sample(rng), - // TODO(EVM-676): generate it randomly once this value is used - settlement_mode: Default::default(), } } } diff --git a/core/lib/env_config/src/contracts.rs b/core/lib/env_config/src/contracts.rs index 4c0bafed85bb..f07389bb2238 100644 --- a/core/lib/env_config/src/contracts.rs +++ b/core/lib/env_config/src/contracts.rs @@ -7,9 +7,11 @@ impl FromEnv for EcosystemContracts { Ok(Self { bridgehub_proxy_addr: std::env::var("CONTRACTS_BRIDGEHUB_PROXY_ADDR")?.parse()?, state_transition_proxy_addr: std::env::var("CONTRACTS_STATE_TRANSITION_PROXY_ADDR")? - .parse()?, + .parse() + .ok(), transparent_proxy_admin_addr: std::env::var("CONTRACTS_TRANSPARENT_PROXY_ADMIN_ADDR")? - .parse()?, + .parse() + .ok(), l1_bytecodes_supplier_addr: std::env::var("CONTRACTS_L1_BYTECODE_SUPPLIER_ADDR")? .parse() .ok(), @@ -82,15 +84,19 @@ mod tests { l1_multicall3_addr: addr("0xcA11bde05977b3631167028862bE2a173976CA11"), ecosystem_contracts: Some(EcosystemContracts { bridgehub_proxy_addr: addr("0x35ea7f92f4c5f433efe15284e99c040110cf6297"), - state_transition_proxy_addr: addr("0xd90f1c081c6117241624e97cb6147257c3cb2097"), - transparent_proxy_admin_addr: addr("0xdd6fa5c14e7550b4caf2aa2818d24c69cbc347e5"), + state_transition_proxy_addr: Some(addr( + "0xd90f1c081c6117241624e97cb6147257c3cb2097", + )), + transparent_proxy_admin_addr: Some(addr( + "0xdd6fa5c14e7550b4caf2aa2818d24c69cbc347e5", + )), l1_bytecodes_supplier_addr: Some(addr( "0x36ea7f92f4c5f433efe15284e99c040110cf6297", )), l1_wrapped_base_token_store: Some(addr( "0x36ea7f92f4c5f433efe15284e99c040110cf6298", )), - server_notifier_addr: Some(addr("0x36ea7f92f4c5f433efe15284e99c040110cf6298")), + server_notifier_addr: Some(addr("0xbe8381498ED34E9c2EdB51Ecd778d71B225E26fb")), }), base_token_addr: Some(SHARED_BRIDGE_ETHER_TOKEN_ADDRESS), l1_base_token_asset_id: Some( @@ -99,7 +105,7 @@ mod tests { ) .unwrap(), ), - chain_admin_addr: Some(addr("0xdd6fa5c14e7550b4caf2aa2818d24c69cbc347ff")), + chain_admin_addr: addr("0xdd6fa5c14e7550b4caf2aa2818d24c69cbc347ff"), l2_da_validator_addr: Some(addr("0xed6fa5c14e7550b4caf2aa2818d24c69cbc347ff")), l2_timestamp_asserter_addr: Some(addr("0x0000000000000000000000000000000000000002")), no_da_validium_l1_validator_addr: Some(addr( @@ -140,6 +146,7 @@ CONTRACTS_CHAIN_ADMIN_ADDR="0xdd6fa5c14e7550b4caf2aa2818d24c69cbc347ff" CONTRACTS_L2_DA_VALIDATOR_ADDR="0xed6fa5c14e7550b4caf2aa2818d24c69cbc347ff" CONTRACTS_L2_TIMESTAMP_ASSERTER_ADDR="0x0000000000000000000000000000000000000002" CONTRACTS_NO_DA_VALIDIUM_L1_VALIDATOR_ADDR="0xbe8381498ED34E9c2EdB51Ecd778d71B225E26fb" +CONTRACTS_SERVER_NOTIFIER_ADDR="0xbe8381498ED34E9c2EdB51Ecd778d71B225E26fb" "#; lock.set_env(config); diff --git a/core/lib/env_config/src/eth_sender.rs b/core/lib/env_config/src/eth_sender.rs index 3030d4206812..4739939560b4 100644 --- a/core/lib/env_config/src/eth_sender.rs +++ b/core/lib/env_config/src/eth_sender.rs @@ -90,7 +90,6 @@ mod tests { num_samples_for_blob_base_fee_estimate: 10, internal_pubdata_pricing_multiplier: 1.0, max_blob_base_fee: None, - settlement_mode: Default::default(), }), watcher: Some(EthWatchConfig { confirmations_for_eth_event: Some(0), diff --git a/core/lib/eth_client/src/clients/http/signing.rs b/core/lib/eth_client/src/clients/http/signing.rs index e602f98a35e9..917cf28331a9 100644 --- a/core/lib/eth_client/src/clients/http/signing.rs +++ b/core/lib/eth_client/src/clients/http/signing.rs @@ -6,7 +6,7 @@ use zksync_eth_signer::{EthereumSigner, PrivateKeySigner, TransactionParameters} use zksync_types::{ ethabi, web3, Address, K256PrivateKey, SLChainId, EIP_4844_TX_TYPE, H160, U256, }; -use zksync_web3_decl::client::{DynClient, L1}; +use zksync_web3_decl::client::{DynClient, Network}; use super::{Method, LATENCIES}; use crate::{ @@ -15,15 +15,15 @@ use crate::{ }; /// HTTP-based Ethereum client, backed by a private key to sign transactions. -pub type PKSigningClient = SigningClient; +pub type PKSigningClient = SigningClient; -impl PKSigningClient { +impl PKSigningClient { pub fn new_raw( operator_private_key: K256PrivateKey, diamond_proxy_addr: Address, default_priority_fee_per_gas: u64, chain_id: SLChainId, - query_client: Box>, + query_client: Box>, ) -> Self { let operator_address = operator_private_key.address(); let signer = PrivateKeySigner::new(operator_private_key); @@ -48,9 +48,9 @@ const FALLBACK_GAS_LIMIT: u64 = 3_000_000; /// HTTP-based client, instantiated for a certain account. This client is capable of signing transactions. #[derive(Clone)] -pub struct SigningClient { +pub struct SigningClient { inner: Arc>, - query_client: Box>, + query_client: Box>, } struct EthDirectClientInner { @@ -62,11 +62,11 @@ struct EthDirectClientInner { default_priority_fee_per_gas: U256, } -impl fmt::Debug for SigningClient { +impl fmt::Debug for SigningClient { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // We do not want to have a private key in the debug representation. - f.debug_struct("ETHDirectClient") + f.debug_struct("SigningClient") .field("sender_account", &self.inner.sender_account) .field("contract_addr", &self.inner.contract_addr) .field("chain_id", &self.inner.chain_id) @@ -74,14 +74,14 @@ impl fmt::Debug for SigningClient { } } -impl AsRef for SigningClient { +impl AsRef for SigningClient { fn as_ref(&self) -> &(dyn EthInterface + 'static) { &self.query_client } } #[async_trait] -impl BoundEthInterface for SigningClient { +impl BoundEthInterface for SigningClient { fn clone_boxed(&self) -> Box { Box::new(self.clone()) } @@ -209,9 +209,9 @@ impl BoundEthInterface for SigningClient { } } -impl SigningClient { +impl SigningClient { pub fn new( - query_client: Box>, + query_client: Box>, contract: ethabi::Contract, operator_eth_addr: H160, eth_signer: S, diff --git a/core/lib/multilayer_client/Cargo.toml b/core/lib/gateway_migrator/Cargo.toml similarity index 93% rename from core/lib/multilayer_client/Cargo.toml rename to core/lib/gateway_migrator/Cargo.toml index f57559f66ccd..7f46d2f2bc41 100644 --- a/core/lib/multilayer_client/Cargo.toml +++ b/core/lib/gateway_migrator/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "zksync_multilayer_client" +name = "zksync_gateway_migrator" version.workspace = true edition.workspace = true authors.workspace = true diff --git a/core/lib/multilayer_client/src/lib.rs b/core/lib/gateway_migrator/src/lib.rs similarity index 69% rename from core/lib/multilayer_client/src/lib.rs rename to core/lib/gateway_migrator/src/lib.rs index 65c267bc52d3..80334cb646b0 100644 --- a/core/lib/multilayer_client/src/lib.rs +++ b/core/lib/gateway_migrator/src/lib.rs @@ -4,29 +4,27 @@ use anyhow::bail; use tokio::sync::watch; use zksync_basic_types::{ethabi::Contract, settlement::SettlementMode, Address}; use zksync_contracts::getters_facet_contract; -use zksync_eth_client::{ - clients::{DynClient, L1}, - CallFunctionArgs, EthInterface, -}; +use zksync_eth_client::{CallFunctionArgs, EthInterface}; #[derive(Debug)] pub struct GatewayMigrator { - eth_client: Box>, + sl_client: Box, diamond_proxy_addr: Address, settlement_mode: SettlementMode, abi: Contract, } impl GatewayMigrator { - pub async fn new(eth_client: Box>, diamond_proxy_addr: Address) -> Self { + pub fn new( + sl_client: Box, + diamond_proxy_addr: Address, + initial_settlement_mode: SettlementMode, + ) -> Self { let abi = getters_facet_contract(); - let settlement_mode = get_settlement_layer(ð_client, diamond_proxy_addr, &abi) - .await - .unwrap(); Self { - eth_client, + sl_client, diamond_proxy_addr, - settlement_mode, + settlement_mode: initial_settlement_mode, abi, } } @@ -42,18 +40,13 @@ impl GatewayMigrator { return Ok(()); } let settlement_mode = - get_settlement_layer(&self.eth_client, self.diamond_proxy_addr, &self.abi) + get_settlement_layer(self.sl_client.as_ref(), self.diamond_proxy_addr, &self.abi) .await .unwrap(); - dbg!(settlement_mode); if settlement_mode != self.settlement_mode { bail!("Settlement layer changed") } - // if attempts == 10 { - // bail!("Settlement layer changed") - // } - // attempts += 1; tokio::time::sleep(Duration::from_secs(1)).await; } } @@ -65,7 +58,7 @@ pub async fn get_settlement_layer( abi: &Contract, ) -> anyhow::Result { let settlement_layer: Address = CallFunctionArgs::new("getSettlementLayer", ()) - .for_contract(diamond_proxy_addr, &abi) + .for_contract(diamond_proxy_addr, abi) .call(eth_client) .await?; diff --git a/core/lib/protobuf_config/src/contracts.rs b/core/lib/protobuf_config/src/contracts.rs index 25f5123712d9..ba5deb91ed23 100644 --- a/core/lib/protobuf_config/src/contracts.rs +++ b/core/lib/protobuf_config/src/contracts.rs @@ -1,5 +1,7 @@ use anyhow::Context as _; -use zksync_config::configs::{ContractsConfig, EcosystemContracts}; +use zksync_config::configs::contracts::{ + chain::AllContractsConfig as ContractsConfig, ecosystem::EcosystemContracts, +}; use zksync_protobuf::{repr::ProtoRepr, required}; use crate::{parse_h160, parse_h256, proto::contracts as proto}; @@ -20,16 +22,18 @@ impl ProtoRepr for proto::Contracts { bridgehub_proxy_addr: required(&ecosystem_contracts.bridgehub_proxy_addr) .and_then(|x| parse_h160(x)) .context("bridgehub_proxy_addr")?, - state_transition_proxy_addr: required( - &ecosystem_contracts.state_transition_proxy_addr, - ) - .and_then(|x| parse_h160(x)) - .context("state_transition_proxy_addr")?, - transparent_proxy_admin_addr: required( - &ecosystem_contracts.transparent_proxy_admin_addr, - ) - .and_then(|x| parse_h160(x)) - .context("transparent_proxy_admin_addr")?, + state_transition_proxy_addr: ecosystem_contracts + .state_transition_proxy_addr + .as_ref() + .map(|x| parse_h160(x)) + .transpose() + .context("state_transition_proxy_addr")?, + transparent_proxy_admin_addr: ecosystem_contracts + .transparent_proxy_admin_addr + .as_ref() + .map(|x| parse_h160(x)) + .transpose() + .context("transparent_proxy_admin_addr")?, l1_bytecodes_supplier_addr: ecosystem_contracts .l1_bytecodes_supplier_addr .as_ref() diff --git a/core/lib/protobuf_config/src/eth.rs b/core/lib/protobuf_config/src/eth.rs index 55982a667a16..8293cc6f2ccc 100644 --- a/core/lib/protobuf_config/src/eth.rs +++ b/core/lib/protobuf_config/src/eth.rs @@ -1,7 +1,7 @@ use anyhow::Context as _; use zksync_config::configs::{self}; use zksync_protobuf::{required, ProtoRepr}; -use zksync_types::{pubdata_da::PubdataSendingMode, settlement::SettlementMode}; +use zksync_types::pubdata_da::PubdataSendingMode; use crate::{proto::eth as proto, read_optional_repr}; @@ -45,24 +45,6 @@ impl proto::PubdataSendingMode { } } -impl proto::SettlementMode { - fn new(x: &SettlementMode) -> Self { - use SettlementMode as From; - match x { - From::SettlesToL1 => Self::SettlesToL1, - From::Gateway => Self::Gateway, - } - } - - fn parse(&self) -> SettlementMode { - use SettlementMode as To; - match self { - Self::SettlesToL1 => To::SettlesToL1, - Self::Gateway => To::Gateway, - } - } -} - impl ProtoRepr for proto::Eth { type Type = configs::eth_sender::EthConfig; @@ -191,12 +173,6 @@ impl ProtoRepr for proto::GasAdjuster { ) .context("internal_pubdata_pricing_multiplier")?, max_blob_base_fee: self.max_blob_base_fee, - settlement_mode: self - .settlement_mode - .map(proto::SettlementMode::try_from) - .transpose()? - .map(|x| x.parse()) - .unwrap_or_default(), }) } @@ -218,7 +194,7 @@ impl ProtoRepr for proto::GasAdjuster { ), internal_pubdata_pricing_multiplier: Some(this.internal_pubdata_pricing_multiplier), max_blob_base_fee: this.max_blob_base_fee, - settlement_mode: Some(proto::SettlementMode::new(&this.settlement_mode).into()), + settlement_mode: None, } } } diff --git a/core/lib/protobuf_config/src/gateway.rs b/core/lib/protobuf_config/src/gateway.rs index dbbc935dd3e5..96828479d721 100644 --- a/core/lib/protobuf_config/src/gateway.rs +++ b/core/lib/protobuf_config/src/gateway.rs @@ -10,12 +10,18 @@ impl ProtoRepr for proto::GatewayChainConfig { fn read(&self) -> anyhow::Result { Ok(Self::Type { - state_transition_proxy_addr: required(&self.state_transition_proxy_addr) - .and_then(|x| parse_h160(x)) + state_transition_proxy_addr: self + .state_transition_proxy_addr + .as_ref() + .map(|x| parse_h160(x)) + .transpose() .context("state_transition_proxy_addr")?, - validator_timelock_addr: required(&self.validator_timelock_addr) - .and_then(|x| parse_h160(x)) + validator_timelock_addr: self + .validator_timelock_addr + .as_ref() + .map(|x| parse_h160(x)) + .transpose() .context("validator_timelock_addr")?, multicall3_addr: required(&self.multicall3_addr) @@ -33,6 +39,7 @@ impl ProtoRepr for proto::GatewayChainConfig { gateway_chain_id: required(&self.gateway_chain_id) .map(|x| SLChainId(*x)) .context("gateway_chain_id")?, + server_notifier: None, }) } diff --git a/core/node/api_server/src/tx_sender/mod.rs b/core/node/api_server/src/tx_sender/mod.rs index be2b823393aa..f9aaeab85e06 100644 --- a/core/node/api_server/src/tx_sender/mod.rs +++ b/core/node/api_server/src/tx_sender/mod.rs @@ -258,7 +258,6 @@ impl TxSenderConfig { web3_json_config: &Web3JsonRpcConfig, fee_account_addr: Address, chain_id: L2ChainId, - timestamp_asserter_params: Option, ) -> Self { Self { fee_account_addr, @@ -270,9 +269,17 @@ impl TxSenderConfig { .validation_computational_gas_limit, chain_id, whitelisted_tokens_for_aa: web3_json_config.whitelisted_tokens_for_aa.clone(), - timestamp_asserter_params, + timestamp_asserter_params: None, } } + + pub fn with_timestamp_asserter_params( + mut self, + timestamp_asserter_params: TimestampAsserterParams, + ) -> Self { + self.timestamp_asserter_params = Some(timestamp_asserter_params); + self + } } pub struct TxSenderInner { diff --git a/core/node/api_server/src/web3/metrics.rs b/core/node/api_server/src/web3/metrics.rs index 9d8cbf813b03..6a6dd755bec8 100644 --- a/core/node/api_server/src/web3/metrics.rs +++ b/core/node/api_server/src/web3/metrics.rs @@ -374,6 +374,7 @@ impl ApiMetrics { }, }; if self.web3_rpc_errors[&labels].inc() == 0 || FILTER.should_report() { + dbg!(raw_params); let ProtocolErrorLabels { method, error_code, diff --git a/core/node/api_server/src/web3/namespaces/en.rs b/core/node/api_server/src/web3/namespaces/en.rs index 5bc7533044a9..2698aca2ff00 100644 --- a/core/node/api_server/src/web3/namespaces/en.rs +++ b/core/node/api_server/src/web3/namespaces/en.rs @@ -154,16 +154,8 @@ impl EnNamespace { .l1_bridgehub_proxy_addr .map(|bridgehub_proxy_addr| EcosystemContracts { bridgehub_proxy_addr, - state_transition_proxy_addr: self - .state - .api_config - .l1_state_transition_proxy_addr - .unwrap(), - transparent_proxy_admin_addr: self - .state - .api_config - .l1_transparent_proxy_admin_addr - .unwrap(), + state_transition_proxy_addr: self.state.api_config.l1_state_transition_proxy_addr, + transparent_proxy_admin_addr: self.state.api_config.l1_transparent_proxy_admin_addr, l1_bytecodes_supplier_addr: self.state.api_config.l1_bytecodes_supplier_addr, l1_wrapped_base_token_store: self.state.api_config.l1_wrapped_base_token_store, server_notifier_addr: self.state.api_config.l1_server_notifier_addr, diff --git a/core/node/api_server/src/web3/state.rs b/core/node/api_server/src/web3/state.rs index 90299b2df3d7..4d913a040b70 100644 --- a/core/node/api_server/src/web3/state.rs +++ b/core/node/api_server/src/web3/state.rs @@ -13,15 +13,20 @@ use lru::LruCache; use tokio::sync::{Mutex, RwLock}; use vise::GaugeGuard; use zksync_config::{ - configs::{api::Web3JsonRpcConfig, ContractsConfig}, + configs::{ + api::Web3JsonRpcConfig, + contracts::{ecosystem::L1SpecificContracts, ChainSpecificContracts}, + }, GenesisConfig, }; use zksync_dal::{Connection, ConnectionPool, Core, CoreDal, DalError}; use zksync_metadata_calculator::api_server::TreeApiClient; use zksync_node_sync::SyncState; +use zksync_system_constants::ETHEREUM_ADDRESS; use zksync_types::{ - api, commitment::L1BatchCommitmentMode, l2::L2Tx, transaction_request::CallRequest, Address, - L1BatchNumber, L1ChainId, L2BlockNumber, L2ChainId, H256, U256, U64, + api, api::BridgeAddresses, commitment::L1BatchCommitmentMode, l2::L2Tx, + transaction_request::CallRequest, Address, L1BatchNumber, L1ChainId, L2BlockNumber, L2ChainId, + H256, U256, U64, }; use zksync_web3_decl::{ client::{DynClient, L2}, @@ -93,6 +98,139 @@ impl BlockStartInfo { } } +/// Configuration values for the API. +/// This structure is detached from `ZkSyncConfig`, since different node types (main, external, etc.) +/// may require different configuration layouts. +/// The intention is to only keep the actually used information here. +#[derive(Debug, Clone)] +pub struct InternalApiConfigBuilder { + /// Chain ID of the L1 network. Note, that it may be different from the chain id of the settlement layer. + pub l1_chain_id: L1ChainId, + pub l2_chain_id: L2ChainId, + pub dummy_verifier: bool, + pub l1_batch_commit_data_generator_mode: L1BatchCommitmentMode, + pub max_tx_size: Option, + pub estimate_gas_scale_factor: Option, + pub estimate_gas_acceptable_overestimation: Option, + pub estimate_gas_optimize_search: Option, + pub bridge_addresses: Option, + pub l1_bytecodes_supplier_addr: Option
, + pub l1_wrapped_base_token_store: Option
, + pub l1_bridgehub_proxy_addr: Option
, + pub l1_state_transition_proxy_addr: Option
, + pub l1_transparent_proxy_admin_addr: Option
, + pub l1_diamond_proxy_addr: Option
, + pub l2_testnet_paymaster_addr: Option
, + pub base_token_address: Option
, + pub timestamp_asserter_address: Option
, + pub l1_server_notifier_addr: Option
, + pub req_entities_limit: Option, + pub fee_history_limit: Option, + pub filters_disabled: Option, +} + +impl InternalApiConfigBuilder { + pub fn from_genesis(genesis: &GenesisConfig) -> Self { + Self { + l1_chain_id: genesis.l1_chain_id, + l2_chain_id: genesis.l2_chain_id, + dummy_verifier: genesis.dummy_verifier, + l1_batch_commit_data_generator_mode: genesis.l1_batch_commit_data_generator_mode, + max_tx_size: None, + estimate_gas_scale_factor: None, + estimate_gas_acceptable_overestimation: None, + estimate_gas_optimize_search: None, + bridge_addresses: None, + l1_bytecodes_supplier_addr: None, + l1_wrapped_base_token_store: None, + l1_bridgehub_proxy_addr: None, + l1_state_transition_proxy_addr: None, + l1_transparent_proxy_admin_addr: None, + l1_diamond_proxy_addr: None, + l2_testnet_paymaster_addr: None, + req_entities_limit: None, + fee_history_limit: None, + base_token_address: None, + filters_disabled: None, + timestamp_asserter_address: None, + l1_server_notifier_addr: None, + } + } + + pub fn with_web3_config(mut self, web3_config: Web3JsonRpcConfig) -> Self { + self.max_tx_size = Some(web3_config.max_tx_size); + self.estimate_gas_scale_factor = Some(web3_config.estimate_gas_scale_factor); + self.estimate_gas_acceptable_overestimation = + Some(web3_config.estimate_gas_acceptable_overestimation); + self.estimate_gas_optimize_search = Some(web3_config.estimate_gas_optimize_search); + self.req_entities_limit = Some(web3_config.req_entities_limit()); + self.fee_history_limit = Some(web3_config.fee_history_limit()); + self.filters_disabled = Some(web3_config.filters_disabled); + self + } + + pub fn with_contracts( + mut self, + contracts_config: ChainSpecificContracts, + l1_ecosystem_contracts: L1SpecificContracts, + ) -> Self { + InternalApiConfigBuilder { + bridge_addresses: Some(BridgeAddresses { + l1_erc20_default_bridge: l1_ecosystem_contracts.erc_20_bridge, + l2_erc20_default_bridge: contracts_config.l2_contracts.erc20_default_bridge, + l1_shared_default_bridge: l1_ecosystem_contracts.shared_bridge, + l2_shared_default_bridge: contracts_config.l2_contracts.shared_bridge_addr, + // WETH bridge is not available + l1_weth_bridge: None, + l2_weth_bridge: None, + l2_legacy_shared_bridge: contracts_config.l2_contracts.legacy_shared_bridge_addr, + }), + l1_bytecodes_supplier_addr: l1_ecosystem_contracts.bytecodes_supplier_addr, + l1_wrapped_base_token_store: l1_ecosystem_contracts.wrapped_base_token_store, + l1_bridgehub_proxy_addr: l1_ecosystem_contracts.bridge_hub, + l1_state_transition_proxy_addr: contracts_config + .ecosystem_contracts + .state_transition_proxy_addr, + l1_transparent_proxy_admin_addr: contracts_config.chain_contracts_config.chain_admin, + l1_diamond_proxy_addr: Some(l1_ecosystem_contracts.l1_diamond_proxy), + l2_testnet_paymaster_addr: contracts_config.l2_contracts.testnet_paymaster_addr, + base_token_address: l1_ecosystem_contracts.base_token_address, + timestamp_asserter_address: contracts_config.l2_contracts.timestamp_asserter_addr, + l1_server_notifier_addr: contracts_config.ecosystem_contracts.server_notifier_addr, + ..self + } + } + + pub fn build(self) -> InternalApiConfig { + InternalApiConfig { + l1_chain_id: self.l1_chain_id, + l2_chain_id: self.l2_chain_id, + max_tx_size: self.max_tx_size.unwrap(), + estimate_gas_scale_factor: self.estimate_gas_scale_factor.unwrap(), + estimate_gas_acceptable_overestimation: self + .estimate_gas_acceptable_overestimation + .unwrap(), + estimate_gas_optimize_search: self.estimate_gas_optimize_search.unwrap(), + bridge_addresses: self.bridge_addresses.unwrap(), + l1_bytecodes_supplier_addr: self.l1_bytecodes_supplier_addr, + l1_wrapped_base_token_store: self.l1_wrapped_base_token_store, + l1_bridgehub_proxy_addr: self.l1_bridgehub_proxy_addr, + l1_state_transition_proxy_addr: self.l1_state_transition_proxy_addr, + l1_transparent_proxy_admin_addr: self.l1_transparent_proxy_admin_addr, + l2_testnet_paymaster_addr: self.l2_testnet_paymaster_addr, + base_token_address: self.base_token_address, + l1_diamond_proxy_addr: self.l1_diamond_proxy_addr.unwrap(), + req_entities_limit: self.req_entities_limit.unwrap(), + fee_history_limit: self.fee_history_limit.unwrap(), + filters_disabled: self.filters_disabled.unwrap(), + dummy_verifier: self.dummy_verifier, + l1_batch_commit_data_generator_mode: self.l1_batch_commit_data_generator_mode, + timestamp_asserter_address: self.timestamp_asserter_address, + l1_server_notifier_addr: self.l1_server_notifier_addr, + } + } +} + /// Configuration values for the API. /// This structure is detached from `ZkSyncConfig`, since different node types (main, external, etc.) /// may require different configuration layouts. @@ -127,7 +265,8 @@ pub struct InternalApiConfig { impl InternalApiConfig { pub fn new( web3_config: &Web3JsonRpcConfig, - contracts_config: &ContractsConfig, + contracts_config: &ChainSpecificContracts, + l1_ecosystem_contracts: &L1SpecificContracts, genesis_config: &GenesisConfig, ) -> Self { Self { @@ -139,55 +278,36 @@ impl InternalApiConfig { .estimate_gas_acceptable_overestimation, estimate_gas_optimize_search: web3_config.estimate_gas_optimize_search, bridge_addresses: api::BridgeAddresses { - l1_erc20_default_bridge: contracts_config.l1_erc20_bridge_proxy_addr, - l2_erc20_default_bridge: contracts_config.l2_erc20_bridge_addr, - l1_shared_default_bridge: contracts_config.l1_shared_bridge_proxy_addr, - l2_shared_default_bridge: contracts_config.l2_shared_bridge_addr, - l1_weth_bridge: Some( - contracts_config - .l1_weth_bridge_proxy_addr - .unwrap_or_default(), - ), - l2_weth_bridge: Some( - contracts_config - .l1_weth_bridge_proxy_addr - .unwrap_or_default(), - ), - l2_legacy_shared_bridge: contracts_config.l2_legacy_shared_bridge_addr, + l1_erc20_default_bridge: l1_ecosystem_contracts.erc_20_bridge, + l2_erc20_default_bridge: contracts_config.l2_contracts.erc20_default_bridge, + l1_shared_default_bridge: l1_ecosystem_contracts.shared_bridge, + l2_shared_default_bridge: contracts_config.l2_contracts.shared_bridge_addr, + // WETH bridge is not available + l1_weth_bridge: None, + l2_weth_bridge: None, + l2_legacy_shared_bridge: contracts_config.l2_contracts.legacy_shared_bridge_addr, }, - l1_bridgehub_proxy_addr: contracts_config - .ecosystem_contracts - .as_ref() - .map(|a| a.bridgehub_proxy_addr), + l1_bridgehub_proxy_addr: l1_ecosystem_contracts.bridge_hub, l1_state_transition_proxy_addr: contracts_config .ecosystem_contracts - .as_ref() - .map(|a| a.state_transition_proxy_addr), - l1_transparent_proxy_admin_addr: contracts_config - .ecosystem_contracts - .as_ref() - .map(|a| a.transparent_proxy_admin_addr), - l1_bytecodes_supplier_addr: contracts_config - .ecosystem_contracts - .as_ref() - .and_then(|a| a.l1_bytecodes_supplier_addr), - l1_wrapped_base_token_store: contracts_config - .ecosystem_contracts - .as_ref() - .and_then(|a| a.l1_wrapped_base_token_store), - l1_diamond_proxy_addr: contracts_config.diamond_proxy_addr, - l2_testnet_paymaster_addr: contracts_config.l2_testnet_paymaster_addr, + .state_transition_proxy_addr, + l1_transparent_proxy_admin_addr: None, + l1_bytecodes_supplier_addr: l1_ecosystem_contracts.bytecodes_supplier_addr, + l1_wrapped_base_token_store: l1_ecosystem_contracts.wrapped_base_token_store, + l1_diamond_proxy_addr: l1_ecosystem_contracts.l1_diamond_proxy, + l2_testnet_paymaster_addr: contracts_config.l2_contracts.testnet_paymaster_addr, req_entities_limit: web3_config.req_entities_limit(), fee_history_limit: web3_config.fee_history_limit(), - base_token_address: contracts_config.base_token_addr, + base_token_address: Some( + l1_ecosystem_contracts + .base_token_address + .unwrap_or(ETHEREUM_ADDRESS), + ), filters_disabled: web3_config.filters_disabled, dummy_verifier: genesis_config.dummy_verifier, l1_batch_commit_data_generator_mode: genesis_config.l1_batch_commit_data_generator_mode, - timestamp_asserter_address: contracts_config.l2_timestamp_asserter_addr, - l1_server_notifier_addr: contracts_config - .ecosystem_contracts - .as_ref() - .and_then(|a| a.server_notifier_addr), + timestamp_asserter_address: contracts_config.l2_contracts.timestamp_asserter_addr, + l1_server_notifier_addr: contracts_config.ecosystem_contracts.server_notifier_addr, } } } diff --git a/core/node/api_server/src/web3/testonly.rs b/core/node/api_server/src/web3/testonly.rs index 540ea085711b..2d642b9a04b8 100644 --- a/core/node/api_server/src/web3/testonly.rs +++ b/core/node/api_server/src/web3/testonly.rs @@ -34,7 +34,6 @@ pub(crate) async fn create_test_tx_sender( &web3_config, wallets.state_keeper.unwrap().fee_account.address(), l2_chain_id, - None, ); let storage_caches = PostgresStorageCaches::new(1, 1); diff --git a/core/node/api_server/src/web3/tests/mod.rs b/core/node/api_server/src/web3/tests/mod.rs index 93854f99ef79..723556845244 100644 --- a/core/node/api_server/src/web3/tests/mod.rs +++ b/core/node/api_server/src/web3/tests/mod.rs @@ -12,9 +12,10 @@ use zksync_config::{ configs::{ api::Web3JsonRpcConfig, chain::{NetworkConfig, StateKeeperConfig}, - ContractsConfig, + contracts::ecosystem::L1SpecificContracts, + AllContractsConfig as ContractsConfig, }, - GenesisConfig, + GenesisConfig, SettlementLayerContracts, }; use zksync_contracts::BaseSystemContracts; use zksync_dal::{Connection, ConnectionPool, CoreDal}; @@ -285,7 +286,12 @@ async fn test_http_server(test: impl HttpTest) { let contracts_config = ContractsConfig::for_tests(); let web3_config = Web3JsonRpcConfig::for_tests(); let genesis = GenesisConfig::for_tests(); - let mut api_config = InternalApiConfig::new(&web3_config, &contracts_config, &genesis); + let mut api_config = InternalApiConfig::new( + &web3_config, + SettlementLayerContracts::new(&contracts_config, None).current_contracts(), + &L1SpecificContracts::new(&contracts_config), + &genesis, + ); api_config.filters_disabled = test.filters_disabled(); let mut server_builder = TestServerBuilder::new(pool.clone(), api_config) .with_tx_executor(test.transaction_executor()) diff --git a/core/node/api_server/src/web3/tests/ws.rs b/core/node/api_server/src/web3/tests/ws.rs index 7720d6763056..d6efd1c0276c 100644 --- a/core/node/api_server/src/web3/tests/ws.rs +++ b/core/node/api_server/src/web3/tests/ws.rs @@ -6,7 +6,10 @@ use assert_matches::assert_matches; use async_trait::async_trait; use http::StatusCode; use tokio::sync::watch; -use zksync_config::configs::chain::NetworkConfig; +use zksync_config::{ + configs::{chain::NetworkConfig, contracts::ecosystem::L1SpecificContracts}, + SettlementLayerContracts, +}; use zksync_dal::ConnectionPool; use zksync_types::{api, Address, Bloom, L1BatchNumber, H160, H256, U64}; use zksync_web3_decl::{ @@ -168,7 +171,10 @@ async fn test_ws_server(test: impl WsTest) { let contracts_config = ContractsConfig::for_tests(); let web3_config = Web3JsonRpcConfig::for_tests(); let genesis_config = GenesisConfig::for_tests(); - let api_config = InternalApiConfig::new(&web3_config, &contracts_config, &genesis_config); + let sl_layer_contracts = SettlementLayerContracts::new(&contracts_config, None); + let contracts = sl_layer_contracts.current_contracts(); + let l1_specific = L1SpecificContracts::new(&contracts_config); + let api_config = InternalApiConfig::new(&web3_config, contracts, &l1_specific, &genesis_config); let mut storage = pool.connection().await.unwrap(); test.storage_initialization() .prepare_storage(&network_config, &mut storage) diff --git a/core/node/commitment_generator/src/validation_task.rs b/core/node/commitment_generator/src/validation_task.rs index 60c678873718..853f794d22a6 100644 --- a/core/node/commitment_generator/src/validation_task.rs +++ b/core/node/commitment_generator/src/validation_task.rs @@ -1,10 +1,7 @@ use std::time::Duration; use tokio::sync::watch; -use zksync_eth_client::{ - clients::{DynClient, L1}, - CallFunctionArgs, ClientError, ContractCallError, EthInterface, -}; +use zksync_eth_client::{CallFunctionArgs, ClientError, ContractCallError, EthInterface}; use zksync_types::{commitment::L1BatchCommitmentMode, Address}; /// Managed task that asynchronously validates that the commitment mode (rollup or validium) from the node config @@ -13,7 +10,7 @@ use zksync_types::{commitment::L1BatchCommitmentMode, Address}; pub struct L1BatchCommitmentModeValidationTask { diamond_proxy_address: Address, expected_mode: L1BatchCommitmentMode, - eth_client: Box>, + eth_client: Box, retry_interval: Duration, exit_on_success: bool, } @@ -25,12 +22,12 @@ impl L1BatchCommitmentModeValidationTask { pub fn new( diamond_proxy_address: Address, expected_mode: L1BatchCommitmentMode, - eth_client: Box>, + eth_client: Box, ) -> Self { Self { diamond_proxy_address, expected_mode, - eth_client: eth_client.for_component("commitment_mode_validation"), + eth_client, retry_interval: Self::DEFAULT_RETRY_INTERVAL, exit_on_success: false, } @@ -48,7 +45,8 @@ impl L1BatchCommitmentModeValidationTask { let diamond_proxy_address = self.diamond_proxy_address; loop { let result = - Self::get_pubdata_pricing_mode(diamond_proxy_address, &self.eth_client).await; + Self::get_pubdata_pricing_mode(diamond_proxy_address, self.eth_client.as_ref()) + .await; match result { Ok(mode) => { anyhow::ensure!( @@ -127,7 +125,7 @@ mod tests { use zksync_eth_client::clients::MockSettlementLayer; use zksync_types::{ethabi, U256}; use zksync_web3_decl::{ - client::MockClient, + client::{MockClient, L1}, jsonrpsee::{core::BoxError, types::ErrorObject}, }; diff --git a/core/node/consensus/src/testonly.rs b/core/node/consensus/src/testonly.rs index 1a4da71f85a0..979fd61c2c49 100644 --- a/core/node/consensus/src/testonly.rs +++ b/core/node/consensus/src/testonly.rs @@ -9,6 +9,7 @@ use zksync_config::{ configs::{ chain::{OperationsManagerConfig, StateKeeperConfig}, consensus as config, + contracts::ecosystem::L1SpecificContracts, database::{MerkleTreeConfig, MerkleTreeMode}, }, }; @@ -602,7 +603,12 @@ impl StateKeeperRunner { // Spawn HTTP server. let cfg = InternalApiConfig::new( &configs::api::Web3JsonRpcConfig::for_tests(), - &configs::contracts::ContractsConfig::for_tests(), + configs::contracts::SettlementLayerContracts::new( + &configs::AllContractsConfig::for_tests(), + None, + ) + .current_contracts(), + &L1SpecificContracts::new(&configs::AllContractsConfig::for_tests()), &configs::GenesisConfig::for_tests(), ); let mut server = TestServerBuilder::new(self.pool.0.clone(), cfg) @@ -681,9 +687,16 @@ impl StateKeeperRunner { }); s.spawn_bg(async { // Spawn HTTP server. + let sl_contracts = &configs::contracts::SettlementLayerContracts::new( + &configs::AllContractsConfig::for_tests(), + None, + ); + let l1_specific = + L1SpecificContracts::new(&configs::AllContractsConfig::for_tests()); let cfg = InternalApiConfig::new( &configs::api::Web3JsonRpcConfig::for_tests(), - &configs::contracts::ContractsConfig::for_tests(), + sl_contracts.current_contracts(), + &l1_specific, &configs::GenesisConfig::for_tests(), ); let mut server = TestServerBuilder::new(self.pool.0.clone(), cfg) diff --git a/core/node/consistency_checker/src/lib.rs b/core/node/consistency_checker/src/lib.rs index c1735a54fd7f..8532616e6b76 100644 --- a/core/node/consistency_checker/src/lib.rs +++ b/core/node/consistency_checker/src/lib.rs @@ -4,14 +4,10 @@ use anyhow::Context as _; use serde::Serialize; use tokio::sync::watch; use zksync_contracts::{ - bridgehub_contract, POST_BOOJUM_COMMIT_FUNCTION, POST_SHARED_BRIDGE_COMMIT_FUNCTION, - PRE_BOOJUM_COMMIT_FUNCTION, + POST_BOOJUM_COMMIT_FUNCTION, POST_SHARED_BRIDGE_COMMIT_FUNCTION, PRE_BOOJUM_COMMIT_FUNCTION, }; use zksync_dal::{Connection, ConnectionPool, Core, CoreDal}; -use zksync_eth_client::{ - clients::{DynClient, L1}, - CallFunctionArgs, ContractCallError, EnrichedClientError, EthInterface, -}; +use zksync_eth_client::{CallFunctionArgs, ContractCallError, EnrichedClientError, EthInterface}; use zksync_health_check::{Health, HealthStatus, HealthUpdater, ReactiveHealthCheck}; use zksync_l1_contract_interface::{ i_executor::structures::{ @@ -26,8 +22,7 @@ use zksync_types::{ ethabi, ethabi::{ParamType, Token}, pubdata_da::PubdataSendingMode, - Address, L1BatchNumber, L2ChainId, ProtocolVersionId, SLChainId, H256, L2_BRIDGEHUB_ADDRESS, - U256, + Address, L1BatchNumber, ProtocolVersionId, SLChainId, H256, U256, }; #[cfg(test)] @@ -355,7 +350,7 @@ pub fn detect_da( #[derive(Debug)] pub struct SLChainAccess { - client: Box>, + client: Box, chain_id: SLChainId, diamond_proxy_addr: Option
, } @@ -367,8 +362,8 @@ pub struct ConsistencyChecker { /// How many past batches to check when starting max_batches_to_recheck: u32, sleep_interval: Duration, - l1_chain_data: SLChainAccess, - gateway_chain_data: Option, + chain_data: SLChainAccess, + // gateway_chain_data: Option, event_handler: Box, l1_data_mismatch_behavior: L1DataMismatchBehavior, pool: ConnectionPool, @@ -380,42 +375,39 @@ impl ConsistencyChecker { const DEFAULT_SLEEP_INTERVAL: Duration = Duration::from_secs(5); pub async fn new( - l1_client: Box>, - gateway_client: Option>>, + gateway_client: Box, max_batches_to_recheck: u32, pool: ConnectionPool, commitment_mode: L1BatchCommitmentMode, - l2_chain_id: L2ChainId, ) -> anyhow::Result { let (health_check, health_updater) = ConsistencyCheckerHealthUpdater::new(); - let l1_chain_id = l1_client.fetch_chain_id().await?; - let l1_chain_data = SLChainAccess { - client: l1_client.for_component("consistency_checker"), + let l1_chain_id = gateway_client.fetch_chain_id().await?; + let chain_data = SLChainAccess { + client: gateway_client, chain_id: l1_chain_id, diamond_proxy_addr: None, }; - let gateway_chain_data = if let Some(client) = gateway_client { - let gateway_diamond_proxy = - CallFunctionArgs::new("getZKChain", Token::Uint(l2_chain_id.as_u64().into())) - .for_contract(L2_BRIDGEHUB_ADDRESS, &bridgehub_contract()) - .call(&client) - .await?; - let chain_id = client.fetch_chain_id().await?; - Some(SLChainAccess { - client: client.for_component("consistency_checker"), - chain_id, - diamond_proxy_addr: Some(gateway_diamond_proxy), - }) - } else { - None - }; + // let gateway_chain_data = if let Some(client) = gateway_client { + // let gateway_diamond_proxy = + // CallFunctionArgs::new("getZKChain", Token::Uint(l2_chain_id.as_u64().into())) + // .for_contract(L2_BRIDGEHUB_ADDRESS, &bridgehub_contract()) + // .call(&client) + // .await?; + // let chain_id = client.fetch_chain_id().await?; + // Some(SLChainAccess { + // client: client.for_component("consistency_checker"), + // chain_id, + // diamond_proxy_addr: Some(gateway_diamond_proxy), + // }) + // } else { + // None + // }; Ok(Self { contract: zksync_contracts::hyperchain_contract(), max_batches_to_recheck, sleep_interval: Self::DEFAULT_SLEEP_INTERVAL, - l1_chain_data, - gateway_chain_data, + chain_data, event_handler: Box::new(health_updater), l1_data_mismatch_behavior: L1DataMismatchBehavior::Log, pool, @@ -425,7 +417,7 @@ impl ConsistencyChecker { } pub fn with_l1_diamond_proxy_addr(mut self, address: Address) -> Self { - self.l1_chain_data.diamond_proxy_addr = Some(address); + self.chain_data.diamond_proxy_addr = Some(address); self } @@ -442,34 +434,15 @@ impl ConsistencyChecker { let commit_tx_hash = local.commit_tx_hash; tracing::info!("Checking commit tx {commit_tx_hash} for L1 batch #{batch_number}"); - let sl_chain_id = self - .pool - .connection_tagged("consistency_checker") - .await - .map_err(|err| CheckError::Internal(err.into()))? - .eth_sender_dal() - .get_batch_commit_chain_id(batch_number) - .await - .map_err(|err| CheckError::Internal(err.into()))?; - let chain_data = match sl_chain_id { - Some(chain_id) => { - let Some(chain_data) = self.chain_data_by_id(chain_id) else { - return Err(CheckError::Validation(anyhow::anyhow!( - "failed to find client for chain id {chain_id}" - ))); - }; - chain_data - } - None => &self.l1_chain_data, - }; - let commit_tx_status = chain_data + let commit_tx_status = self + .chain_data .client .get_tx_status(commit_tx_hash) .await? .with_context(|| { format!( "receipt for tx {commit_tx_hash:?} not found on target chain with id {}", - chain_data.chain_id + self.chain_data.chain_id ) }) .map_err(CheckError::Validation)?; @@ -479,14 +452,15 @@ impl ConsistencyChecker { } // We can't get tx calldata from the DB because it can be fake. - let commit_tx = chain_data + let commit_tx = self + .chain_data .client .get_tx(commit_tx_hash) .await? .with_context(|| format!("commit transaction {commit_tx_hash:?} not found on L1")) .map_err(CheckError::Internal)?; // we've got a transaction receipt previously, thus an internal error - if let Some(diamond_proxy_addr) = chain_data.diamond_proxy_addr { + if let Some(diamond_proxy_addr) = self.chain_data.diamond_proxy_addr { let event = self .contract .event("BlockCommit") @@ -550,7 +524,9 @@ impl ConsistencyChecker { }) .map_err(CheckError::Validation)?; - let is_gateway = chain_data.chain_id != self.l1_chain_data.chain_id; + // TODO set properly + // let is_gateway = self.chain_data.chain_id != self.l1_chain_data.chain_id; + let is_gateway = false; local .verify_commitment(&commitment, is_gateway) .map_err(CheckError::Validation) @@ -657,31 +633,29 @@ impl ConsistencyChecker { } async fn sanity_check_diamond_proxy_addr(&self) -> Result<(), CheckError> { - for client_data in std::iter::once(&self.l1_chain_data).chain(&self.gateway_chain_data) { - let Some(address) = client_data.diamond_proxy_addr else { - continue; - }; - let chain_id = client_data.chain_id; - tracing::debug!("Performing sanity checks for chain id {chain_id}, diamond proxy contract {address:?}"); + let Some(address) = self.chain_data.diamond_proxy_addr else { + return Ok(()); + }; + let chain_id = self.chain_data.chain_id; + tracing::debug!( + "Performing sanity checks for chain id {chain_id}, diamond proxy contract {address:?}" + ); - let version: U256 = CallFunctionArgs::new("getProtocolVersion", ()) - .for_contract(address, &self.contract) - .call(&client_data.client) - .await?; - tracing::info!("Checked chain id {chain_id}, diamond proxy {address:?} (protocol version: {version})"); - } + let version: U256 = CallFunctionArgs::new("getProtocolVersion", ()) + .for_contract(address, &self.contract) + .call(self.chain_data.client.as_ref()) + .await?; + tracing::info!( + "Checked chain id {chain_id}, diamond proxy {address:?} (protocol version: {version})" + ); Ok(()) } pub async fn run(mut self, mut stop_receiver: watch::Receiver) -> anyhow::Result<()> { tracing::info!( - "Starting consistency checker with l1 diamond proxy contract: {:?}, \ - gateway diamond proxy contract: {:?}, \ + "Starting consistency checker with diamond proxy contract: {:?}, \ sleep interval: {:?}, max historic L1 batches to check: {}", - self.l1_chain_data.diamond_proxy_addr, - self.gateway_chain_data - .as_ref() - .map(|d| d.diamond_proxy_addr), + self.chain_data.diamond_proxy_addr, self.sleep_interval, self.max_batches_to_recheck ); @@ -812,15 +786,15 @@ impl ConsistencyChecker { Ok(()) } - fn chain_data_by_id(&self, searched_chain_id: SLChainId) -> Option<&SLChainAccess> { - if searched_chain_id == self.l1_chain_data.chain_id { - Some(&self.l1_chain_data) - } else if Some(searched_chain_id) == self.gateway_chain_data.as_ref().map(|d| d.chain_id) { - self.gateway_chain_data.as_ref() - } else { - None - } - } + // fn chain_data_by_id(&self, searched_chain_id: SLChainId) -> Option<&SLChainAccess> { + // if searched_chain_id == self.l1_chain_data.chain_id { + // Some(&self.l1_chain_data) + // } else if Some(searched_chain_id) == self.gateway_chain_data.as_ref().map(|d| d.chain_id) { + // self.gateway_chain_data.as_ref() + // } else { + // None + // } + // } } /// Repeatedly polls the DB until there is an L1 batch with metadata. We may not have such a batch initially diff --git a/core/node/consistency_checker/src/tests/mod.rs b/core/node/consistency_checker/src/tests/mod.rs index 57511fbb69c7..26b263d8fb97 100644 --- a/core/node/consistency_checker/src/tests/mod.rs +++ b/core/node/consistency_checker/src/tests/mod.rs @@ -16,6 +16,7 @@ use zksync_node_test_utils::{ use zksync_types::{ aggregated_operations::AggregatedActionType, commitment::L1BatchWithMetadata, protocol_version::ProtocolSemanticVersion, web3::Log, ProtocolVersion, ProtocolVersionId, H256, + L2_BRIDGEHUB_ADDRESS, }; use super::*; @@ -98,7 +99,7 @@ pub(crate) async fn create_mock_checker( let (health_check, health_updater) = ConsistencyCheckerHealthUpdater::new(); let client = client.into_client(); let chain_id = client.fetch_chain_id().await.unwrap(); - let l1_chain_data = SLChainAccess { + let chain_data = SLChainAccess { client: Box::new(client), chain_id, diamond_proxy_addr: Some(L1_DIAMOND_PROXY_ADDR), @@ -107,8 +108,7 @@ pub(crate) async fn create_mock_checker( contract: zksync_contracts::hyperchain_contract(), max_batches_to_recheck: 100, sleep_interval: Duration::from_millis(10), - l1_chain_data, - gateway_chain_data: None, + chain_data, event_handler: Box::new(health_updater), l1_data_mismatch_behavior: L1DataMismatchBehavior::Bail, pool, @@ -564,11 +564,9 @@ async fn checker_works_with_different_settlement_layers() { let (l1_batch_updates_sender, mut l1_batch_updates_receiver) = mpsc::unbounded_channel(); let mut checker = ConsistencyChecker::new( Box::new(clients[0].clone().into_client()), - Some(Box::new(clients[1].clone().into_client())), 100, pool.clone(), commitment_mode, - L2ChainId::new(ERA_CHAIN_ID).unwrap(), ) .await .unwrap(); diff --git a/core/node/da_dispatcher/src/da_dispatcher.rs b/core/node/da_dispatcher/src/da_dispatcher.rs index 4344788c7799..8adc100c94b8 100644 --- a/core/node/da_dispatcher/src/da_dispatcher.rs +++ b/core/node/da_dispatcher/src/da_dispatcher.rs @@ -4,7 +4,7 @@ use anyhow::Context; use chrono::Utc; use rand::Rng; use tokio::sync::watch::Receiver; -use zksync_config::{ContractsConfig, DADispatcherConfig}; +use zksync_config::{configs::contracts::ChainSpecificContracts, DADispatcherConfig}; use zksync_da_client::{ types::{DAError, InclusionData}, DataAvailabilityClient, @@ -26,7 +26,7 @@ pub struct DataAvailabilityDispatcher { client: Box, pool: ConnectionPool, config: DADispatcherConfig, - contracts_config: ContractsConfig, + contracts_config: ChainSpecificContracts, settlement_layer_client: Box>, transitional_l2_da_validator_address: Option
, // set only if inclusion_verification_transition_enabled is true @@ -37,7 +37,7 @@ impl DataAvailabilityDispatcher { pool: ConnectionPool, config: DADispatcherConfig, client: Box, - contracts_config: ContractsConfig, + contracts_config: ChainSpecificContracts, settlement_layer_client: Box>, ) -> Self { Self { @@ -268,7 +268,11 @@ impl DataAvailabilityDispatcher { } async fn check_for_misconfiguration(&mut self) -> anyhow::Result<()> { - if let Some(no_da_validator) = self.contracts_config.no_da_validium_l1_validator_addr { + if let Some(no_da_validator) = self + .contracts_config + .ecosystem_contracts + .no_da_validium_l1_validator_addr + { if self.config.use_dummy_inclusion_data() { let l1_da_validator_address = self.fetch_l1_da_validator_address().await?; @@ -284,14 +288,14 @@ impl DataAvailabilityDispatcher { if self.config.inclusion_verification_transition_enabled() { self.transitional_l2_da_validator_address = Some( self.contracts_config - .l2_da_validator_addr + .l2_contracts + .da_validator_addr .context("L2 DA validator address is not set")?, ); } Ok(()) } - async fn fetch_l1_da_validator_address(&self) -> anyhow::Result
{ let signature = ethabi::short_signature("getDAValidatorPair", &[]); let response = self @@ -299,7 +303,11 @@ impl DataAvailabilityDispatcher { .call_contract_function( CallRequest { data: Some(signature.into()), - to: Some(self.contracts_config.diamond_proxy_addr), + to: Some( + self.contracts_config + .chain_contracts_config + .diamond_proxy_addr, + ), ..CallRequest::default() }, None, diff --git a/core/node/eth_sender/src/eth_tx_aggregator.rs b/core/node/eth_sender/src/eth_tx_aggregator.rs index d9b1c6248148..65ba355d5d13 100644 --- a/core/node/eth_sender/src/eth_tx_aggregator.rs +++ b/core/node/eth_sender/src/eth_tx_aggregator.rs @@ -937,7 +937,7 @@ async fn gateway_status( .unwrap() .signature(); - let topics = vec![to_gateway.clone(), from_gateway.clone()]; + let topics = vec![to_gateway, from_gateway]; let notifications = storage .server_notifications_dal() diff --git a/core/node/eth_sender/src/eth_tx_manager.rs b/core/node/eth_sender/src/eth_tx_manager.rs index 17f71b69303a..64b19bd81a6c 100644 --- a/core/node/eth_sender/src/eth_tx_manager.rs +++ b/core/node/eth_sender/src/eth_tx_manager.rs @@ -12,7 +12,9 @@ use zksync_eth_client::{ use zksync_health_check::{Health, HealthStatus, HealthUpdater, ReactiveHealthCheck}; use zksync_node_fee_model::l1_gas_price::TxParamsProvider; use zksync_shared_metrics::BlockL1Stage; -use zksync_types::{eth_sender::EthTx, Address, L1BlockNumber, H256, U256}; +use zksync_types::{ + eth_sender::EthTx, settlement::SettlementMode, Address, L1BlockNumber, H256, U256, +}; use super::{metrics::METRICS, EthSenderError}; use crate::{ @@ -36,6 +38,7 @@ pub struct EthTxManager { fees_oracle: Box, pool: ConnectionPool, health_updater: HealthUpdater, + sl_mode: SettlementMode, } impl EthTxManager { @@ -46,6 +49,7 @@ impl EthTxManager { ethereum_gateway: Option>, ethereum_gateway_blobs: Option>, l2_gateway: Option>, + sl_mode: SettlementMode, ) -> Self { let ethereum_gateway = ethereum_gateway.map(|eth| eth.for_component("eth_tx_manager")); let ethereum_gateway_blobs = @@ -71,6 +75,7 @@ impl EthTxManager { fees_oracle: Box::new(fees_oracle), pool, health_updater: ReactiveHealthCheck::new("eth_tx_manager").1, + sl_mode, } } @@ -645,11 +650,7 @@ impl EthTxManager { &mut self, storage: &mut Connection<'_, Core>, ) { - if !self - .l1_interface - .supported_operator_types() - .contains(&OperatorType::Gateway) - { + if !self.sl_mode.is_gateway() { return; } diff --git a/core/node/eth_sender/src/tester.rs b/core/node/eth_sender/src/tester.rs index b62ccceac586..8a4fa5bfb43f 100644 --- a/core/node/eth_sender/src/tester.rs +++ b/core/node/eth_sender/src/tester.rs @@ -5,7 +5,10 @@ use zksync_config::{ ContractsConfig, EthConfig, GasAdjusterConfig, }; use zksync_dal::{Connection, ConnectionPool, Core, CoreDal}; -use zksync_eth_client::{clients::MockSettlementLayer, BaseFees, BoundEthInterface}; +use zksync_eth_client::{ + clients::{DynClient, MockSettlementLayer, L1}, + BaseFees, BoundEthInterface, +}; use zksync_l1_contract_interface::i_executor::methods::{ExecuteBatches, ProveBatches}; use zksync_node_fee_model::l1_gas_price::{GasAdjuster, GasAdjusterClient}; use zksync_node_test_utils::{create_l1_batch, l1_batch_metadata_to_commitment_artifacts}; @@ -220,9 +223,10 @@ impl EthSenderTester { gateway_blobs.advance_block_number(Self::WAIT_CONFIRMATIONS); let gateway_blobs = Box::new(gateway_blobs); + let client: Box> = Box::new(gateway.clone().into_client()); let gas_adjuster = Arc::new( GasAdjuster::new( - GasAdjusterClient::from_l1(Box::new(gateway.clone().into_client())), + GasAdjusterClient::from(client), GasAdjusterConfig { max_base_fee_samples: Self::MAX_BASE_FEE_SAMPLES, pricing_formula_parameter_a: 3.0, @@ -284,6 +288,7 @@ impl EthSenderTester { Some(gateway.clone()), Some(gateway_blobs.clone()), None, + SettlementMode::SettlesToL1, ); let connection_pool_clone = connection_pool.clone(); @@ -320,6 +325,7 @@ impl EthSenderTester { None, None, Some(self.l2_gateway.clone()), + SettlementMode::Gateway, ); self.is_l2 = true; tracing::info!("Switched eth-sender tester to use Gateway!"); diff --git a/core/node/eth_watch/src/lib.rs b/core/node/eth_watch/src/lib.rs index 1967fedda9c4..f37d5ad1b3b9 100644 --- a/core/node/eth_watch/src/lib.rs +++ b/core/node/eth_watch/src/lib.rs @@ -14,7 +14,7 @@ use zksync_types::{ web3::BlockNumber as Web3BlockNumber, L1BatchNumber, L2ChainId, PriorityOpId, }; -pub use self::client::{EthClient, EthHttpQueryClient, ZkSyncExtentionEthClient}; +pub use self::client::{EthClient, EthHttpQueryClient, GetLogsClient, ZkSyncExtentionEthClient}; use self::{ client::RETRY_LIMIT, event_processors::{EventProcessor, EventProcessorError, PriorityOpsEventProcessor}, diff --git a/core/node/eth_watch/src/tests/client.rs b/core/node/eth_watch/src/tests/client.rs index 56d578c08f89..490b4b319813 100644 --- a/core/node/eth_watch/src/tests/client.rs +++ b/core/node/eth_watch/src/tests/client.rs @@ -328,6 +328,10 @@ impl EthClient for MockEthClient { ) -> Result, ContractCallError> { Ok(Some(H256::zero())) } + + async fn get_settlement_layer(&self) -> Result { + Ok(Address::default()) + } } #[async_trait::async_trait] diff --git a/core/node/eth_watch/src/tests/mod.rs b/core/node/eth_watch/src/tests/mod.rs index 87249100b033..87303601a041 100644 --- a/core/node/eth_watch/src/tests/mod.rs +++ b/core/node/eth_watch/src/tests/mod.rs @@ -1,6 +1,5 @@ use std::convert::TryInto; -use zksync_contracts::{chain_admin_contract, gateway_migration_contract}; use zksync_dal::{Connection, ConnectionPool, Core, CoreDal}; use zksync_types::{ abi, diff --git a/core/node/fee_model/src/l1_gas_price/gas_adjuster/mod.rs b/core/node/fee_model/src/l1_gas_price/gas_adjuster/mod.rs index 6fce46f77225..b35f32a4e743 100644 --- a/core/node/fee_model/src/l1_gas_price/gas_adjuster/mod.rs +++ b/core/node/fee_model/src/l1_gas_price/gas_adjuster/mod.rs @@ -23,35 +23,22 @@ mod tests; #[derive(Debug)] pub struct GasAdjusterClient { - gateway_mode: bool, inner: Box, } -impl GasAdjusterClient { - pub fn from_l1(inner: Box>) -> Self { - Self { - inner: Box::new(inner.for_component("gas_adjuster")), - gateway_mode: false, - } - } - - pub fn from_l2(inner: Box>) -> Self { +impl From>> for GasAdjusterClient { + fn from(inner: Box>) -> Self { Self { inner: Box::new(inner.for_component("gas_adjuster")), - gateway_mode: true, } } } -impl From>> for GasAdjusterClient { - fn from(inner: Box>) -> Self { - Self::from_l1(inner) - } -} - impl From>> for GasAdjusterClient { fn from(inner: Box>) -> Self { - Self::from_l2(inner) + Self { + inner: Box::new(inner.for_component("gas_adjuster")), + } } } @@ -84,21 +71,21 @@ impl GasAdjuster { commitment_mode: L1BatchCommitmentMode, ) -> anyhow::Result { // A runtime check to ensure consistent config. - if config.settlement_mode.is_gateway() { - anyhow::ensure!(client.gateway_mode, "Must be L2 client in L2 mode"); - - anyhow::ensure!( - matches!(pubdata_sending_mode, PubdataSendingMode::RelayedL2Calldata | PubdataSendingMode::Custom), - "Only relayed L2 calldata or Custom is available for L2 mode, got: {pubdata_sending_mode:?}" - ); - } else { - anyhow::ensure!(!client.gateway_mode, "Must be L1 client in L1 mode"); - - anyhow::ensure!( - !matches!(pubdata_sending_mode, PubdataSendingMode::RelayedL2Calldata), - "Relayed L2 calldata is only available in L2 mode" - ); - } + // if config.settlement_mode.is_gateway() { + // anyhow::ensure!(client.gateway_mode, "Must be L2 client in L2 mode"); + // + // anyhow::ensure!( + // matches!(pubdata_sending_mode, PubdataSendingMode::RelayedL2Calldata | PubdataSendingMode::Custom), + // "Only relayed L2 calldata or Custom is available for L2 mode, got: {pubdata_sending_mode:?}" + // ); + // } else { + // anyhow::ensure!(!client.gateway_mode, "Must be L1 client in L1 mode"); + // + // anyhow::ensure!( + // !matches!(pubdata_sending_mode, PubdataSendingMode::RelayedL2Calldata), + // "Relayed L2 calldata is only available in L2 mode" + // ); + // } // Subtracting 1 from the "latest" block number to prevent errors in case // the info about the latest block is not yet present on the node. diff --git a/core/node/fee_model/src/l1_gas_price/gas_adjuster/tests.rs b/core/node/fee_model/src/l1_gas_price/gas_adjuster/tests.rs index ab649e2d7c90..31a56bcb5168 100644 --- a/core/node/fee_model/src/l1_gas_price/gas_adjuster/tests.rs +++ b/core/node/fee_model/src/l1_gas_price/gas_adjuster/tests.rs @@ -6,7 +6,7 @@ use zksync_eth_client::{clients::MockSettlementLayer, BaseFees}; use zksync_types::{ commitment::L1BatchCommitmentMode, pubdata_da::PubdataSendingMode, settlement::SettlementMode, }; -use zksync_web3_decl::client::L2; +use zksync_web3_decl::client::{DynClient, L2}; use super::{GasAdjuster, GasStatistics, GasStatisticsInner}; use crate::l1_gas_price::GasAdjusterClient; @@ -72,7 +72,6 @@ fn test_config(settlement_mode: SettlementMode) -> GasAdjusterConfig { num_samples_for_blob_base_fee_estimate: 3, internal_pubdata_pricing_multiplier: 1.0, max_blob_base_fee: None, - settlement_mode, } } @@ -102,8 +101,9 @@ async fn kept_updated(commitment_mode: L1BatchCommitmentMode) { eth_client.advance_block_number(6); let config = test_config(SettlementMode::SettlesToL1); + let client: Box> = Box::new(eth_client.clone().into_client()); let adjuster = GasAdjuster::new( - GasAdjusterClient::from_l1(Box::new(eth_client.clone().into_client())), + GasAdjusterClient::from(client), config, PubdataSendingMode::Calldata, commitment_mode, @@ -166,8 +166,10 @@ async fn kept_updated_l2(commitment_mode: L1BatchCommitmentMode) { eth_client.advance_block_number(6); let config = test_config(SettlementMode::Gateway); + let client: Box> = Box::new(eth_client.clone().into_client()); + let adjuster = GasAdjuster::new( - GasAdjusterClient::from_l2(Box::new(eth_client.clone().into_client())), + GasAdjusterClient::from(client), config, PubdataSendingMode::RelayedL2Calldata, commitment_mode, diff --git a/core/node/fee_model/src/lib.rs b/core/node/fee_model/src/lib.rs index a66d05f7cb2e..b810b63b45b8 100644 --- a/core/node/fee_model/src/lib.rs +++ b/core/node/fee_model/src/lib.rs @@ -181,6 +181,7 @@ mod tests { pubdata_da::PubdataSendingMode, U256, }; + use zksync_web3_decl::client::{DynClient, L2}; use super::*; @@ -383,8 +384,10 @@ mod tests { ..Default::default() }; + let client: Box> = Box::new(mock.clone().into_client()); + GasAdjuster::new( - GasAdjusterClient::from_l1(Box::new(mock.into_client())), + GasAdjusterClient::from(client), gas_adjuster_config, PubdataSendingMode::Blobs, L1BatchCommitmentMode::Rollup, diff --git a/core/node/node_framework/Cargo.toml b/core/node/node_framework/Cargo.toml index 23fce3b1a6ef..4f5030034a15 100644 --- a/core/node/node_framework/Cargo.toml +++ b/core/node/node_framework/Cargo.toml @@ -56,7 +56,7 @@ zksync_external_price_api.workspace = true zksync_external_proof_integration_api.workspace = true zksync_logs_bloom_backfill.workspace = true zksync_shared_metrics.workspace = true -zksync_multilayer_client.workspace = true +zksync_gateway_migrator.workspace = true pin-project-lite.workspace = true tracing.workspace = true diff --git a/core/node/node_framework/src/implementations/layers/base_token/base_token_ratio_persister.rs b/core/node/node_framework/src/implementations/layers/base_token/base_token_ratio_persister.rs index 26b24d2f8662..5e453cb59080 100644 --- a/core/node/node_framework/src/implementations/layers/base_token/base_token_ratio_persister.rs +++ b/core/node/node_framework/src/implementations/layers/base_token/base_token_ratio_persister.rs @@ -1,14 +1,15 @@ use zksync_base_token_adjuster::{BaseTokenL1Behaviour, BaseTokenRatioPersister, UpdateOnL1Params}; -use zksync_config::{ - configs::{base_token_adjuster::BaseTokenAdjusterConfig, wallets::Wallets}, - ContractsConfig, -}; +use zksync_config::configs::{base_token_adjuster::BaseTokenAdjusterConfig, wallets::Wallets}; use zksync_contracts::{chain_admin_contract, getters_facet_contract}; use zksync_eth_client::clients::PKSigningClient; use zksync_types::L1ChainId; use crate::{ implementations::resources::{ + contracts::{ + L1ChainContractsResource, L1EcosystemContractsResource, + SettlementLayerContractsResource, + }, eth_interface::EthInterfaceResource, l1_tx_params::TxParamsResource, pools::{MasterPool, PoolResource}, @@ -27,7 +28,6 @@ use crate::{ #[derive(Debug)] pub struct BaseTokenRatioPersisterLayer { config: BaseTokenAdjusterConfig, - contracts_config: ContractsConfig, wallets_config: Wallets, l1_chain_id: L1ChainId, } @@ -40,6 +40,8 @@ pub struct Input { pub price_api_client: PriceAPIClientResource, pub eth_client: EthInterfaceResource, pub tx_params: TxParamsResource, + pub contracts_resource: L1ChainContractsResource, + pub l1ecosystem_contracts_resource: L1EcosystemContractsResource, } #[derive(Debug, IntoContext)] @@ -52,13 +54,11 @@ pub struct Output { impl BaseTokenRatioPersisterLayer { pub fn new( config: BaseTokenAdjusterConfig, - contracts_config: ContractsConfig, wallets_config: Wallets, l1_chain_id: L1ChainId, ) -> Self { Self { config, - contracts_config, wallets_config, l1_chain_id, } @@ -78,9 +78,10 @@ impl WiringLayer for BaseTokenRatioPersisterLayer { let master_pool = input.master_pool.get().await?; let price_api_client = input.price_api_client; - let base_token_addr = self - .contracts_config - .base_token_addr + let base_token_addr = input + .l1ecosystem_contracts_resource + .0 + .base_token_address .expect("base token address is not set"); let l1_behaviour = self @@ -93,7 +94,11 @@ impl WiringLayer for BaseTokenRatioPersisterLayer { let signing_client = PKSigningClient::new_raw( tms_private_key.clone(), - self.contracts_config.diamond_proxy_addr, + input + .contracts_resource + .0 + .chain_contracts_config + .diamond_proxy_addr, self.config.default_priority_fee_per_gas, #[allow(clippy::useless_conversion)] self.l1_chain_id.into(), @@ -106,8 +111,19 @@ impl WiringLayer for BaseTokenRatioPersisterLayer { token_multiplier_setter_account_address: tms_address, chain_admin_contract: chain_admin_contract(), getters_facet_contract: getters_facet_contract(), - diamond_proxy_contract_address: self.contracts_config.diamond_proxy_addr, - chain_admin_contract_address: Some(self.contracts_config.chain_admin_addr), + diamond_proxy_contract_address: input + .contracts_resource + .0 + .chain_contracts_config + .diamond_proxy_addr, + chain_admin_contract_address: Some( + input + .contracts_resource + .0 + .chain_contracts_config + .chain_admin + .expect("Should be presented"), + ), config: self.config.clone(), }, last_persisted_l1_ratio: None, diff --git a/core/node/node_framework/src/implementations/layers/consistency_checker.rs b/core/node/node_framework/src/implementations/layers/consistency_checker.rs index a76b358b53b4..b93542946f6f 100644 --- a/core/node/node_framework/src/implementations/layers/consistency_checker.rs +++ b/core/node/node_framework/src/implementations/layers/consistency_checker.rs @@ -1,9 +1,10 @@ use zksync_consistency_checker::ConsistencyChecker; -use zksync_types::{commitment::L1BatchCommitmentMode, Address, L2ChainId}; +use zksync_types::commitment::L1BatchCommitmentMode; use crate::{ implementations::resources::{ - eth_interface::{EthInterfaceResource, GatewayEthInterfaceResource}, + contracts::SettlementLayerContractsResource, + eth_interface::UniversalClientResource, healthcheck::AppHealthCheckResource, pools::{MasterPool, PoolResource}, }, @@ -16,17 +17,15 @@ use crate::{ /// Wiring layer for the `ConsistencyChecker` (used by the external node). #[derive(Debug)] pub struct ConsistencyCheckerLayer { - l1_diamond_proxy_addr: Address, max_batches_to_recheck: u32, commitment_mode: L1BatchCommitmentMode, - l2_chain_id: L2ChainId, } #[derive(Debug, FromContext)] #[context(crate = crate)] pub struct Input { - pub l1_client: EthInterfaceResource, - pub gateway_client: Option, + pub gateway_client: UniversalClientResource, + pub sl_chain_contracts: SettlementLayerContractsResource, pub master_pool: PoolResource, #[context(default)] pub app_health: AppHealthCheckResource, @@ -41,16 +40,12 @@ pub struct Output { impl ConsistencyCheckerLayer { pub fn new( - l1_diamond_proxy_addr: Address, max_batches_to_recheck: u32, commitment_mode: L1BatchCommitmentMode, - l2_chain_id: L2ChainId, ) -> ConsistencyCheckerLayer { Self { - l1_diamond_proxy_addr, max_batches_to_recheck, commitment_mode, - l2_chain_id, } } } @@ -65,23 +60,25 @@ impl WiringLayer for ConsistencyCheckerLayer { } async fn wire(self, input: Self::Input) -> Result { - // Get resources. - let l1_client = input.l1_client.0; - let gateway_client = input.gateway_client.map(|c| c.0); + let gateway_client = input.gateway_client.0; let singleton_pool = input.master_pool.get_singleton().await?; let consistency_checker = ConsistencyChecker::new( - l1_client, - gateway_client, + gateway_client.into(), self.max_batches_to_recheck, singleton_pool, self.commitment_mode, - self.l2_chain_id, ) .await .map_err(WiringError::Internal)? - .with_l1_diamond_proxy_addr(self.l1_diamond_proxy_addr); + .with_l1_diamond_proxy_addr( + input + .sl_chain_contracts + .0 + .chain_contracts_config + .diamond_proxy_addr, + ); input .app_health diff --git a/core/node/node_framework/src/implementations/layers/da_dispatcher.rs b/core/node/node_framework/src/implementations/layers/da_dispatcher.rs index 8ade216ccbd8..81f72e37a84c 100644 --- a/core/node/node_framework/src/implementations/layers/da_dispatcher.rs +++ b/core/node/node_framework/src/implementations/layers/da_dispatcher.rs @@ -1,11 +1,9 @@ -use zksync_config::{ - configs::{chain::StateKeeperConfig, da_dispatcher::DADispatcherConfig}, - ContractsConfig, -}; +use zksync_config::configs::{chain::StateKeeperConfig, da_dispatcher::DADispatcherConfig}; use zksync_da_dispatcher::DataAvailabilityDispatcher; use crate::{ implementations::resources::{ + contracts::SettlementLayerContractsResource, da_client::DAClientResource, eth_interface::EthInterfaceResource, pools::{MasterPool, PoolResource}, @@ -21,7 +19,6 @@ use crate::{ pub struct DataAvailabilityDispatcherLayer { state_keeper_config: StateKeeperConfig, da_config: DADispatcherConfig, - contracts_config: ContractsConfig, } #[derive(Debug, FromContext)] @@ -30,6 +27,7 @@ pub struct Input { pub master_pool: PoolResource, pub eth_client: EthInterfaceResource, pub da_client: DAClientResource, + pub contracts_resource: SettlementLayerContractsResource, } #[derive(Debug, IntoContext)] @@ -40,15 +38,10 @@ pub struct Output { } impl DataAvailabilityDispatcherLayer { - pub fn new( - state_keeper_config: StateKeeperConfig, - da_config: DADispatcherConfig, - contracts_config: ContractsConfig, - ) -> Self { + pub fn new(state_keeper_config: StateKeeperConfig, da_config: DADispatcherConfig) -> Self { Self { state_keeper_config, da_config, - contracts_config, } } } @@ -80,7 +73,7 @@ impl WiringLayer for DataAvailabilityDispatcherLayer { master_pool, self.da_config, da_client, - self.contracts_config, + input.contracts_resource.0.clone(), input.eth_client.0, ); diff --git a/core/node/node_framework/src/implementations/layers/eth_sender/aggregator.rs b/core/node/node_framework/src/implementations/layers/eth_sender/aggregator.rs index 55bb0245403c..4b292cc64fd2 100644 --- a/core/node/node_framework/src/implementations/layers/eth_sender/aggregator.rs +++ b/core/node/node_framework/src/implementations/layers/eth_sender/aggregator.rs @@ -1,6 +1,6 @@ use anyhow::Context; use zksync_circuit_breaker::l1_txs::FailedL1TransactionChecker; -use zksync_config::configs::{eth_sender::EthConfig, gateway::GatewayChainConfig, ContractsConfig}; +use zksync_config::configs::eth_sender::EthConfig; use zksync_eth_client::BoundEthInterface; use zksync_eth_sender::{Aggregator, EthTxAggregator}; use zksync_types::{commitment::L1BatchCommitmentMode, L2ChainId}; @@ -8,6 +8,7 @@ use zksync_types::{commitment::L1BatchCommitmentMode, L2ChainId}; use crate::{ implementations::resources::{ circuit_breakers::CircuitBreakersResource, + contracts::SettlementLayerContractsResource, eth_interface::{ BoundEthInterfaceForBlobsResource, BoundEthInterfaceForL2Resource, BoundEthInterfaceResource, @@ -44,8 +45,6 @@ use crate::{ #[derive(Debug)] pub struct EthTxAggregatorLayer { eth_sender_config: EthConfig, - contracts_config: ContractsConfig, - gateway_chain_config: Option, zksync_network_id: L2ChainId, l1_batch_commit_data_generator_mode: L1BatchCommitmentMode, } @@ -64,6 +63,7 @@ pub struct Input { pub circuit_breakers: CircuitBreakersResource, #[context(default)] pub app_health: AppHealthCheckResource, + pub contracts_resource: SettlementLayerContractsResource, } #[derive(Debug, IntoContext)] @@ -76,15 +76,11 @@ pub struct Output { impl EthTxAggregatorLayer { pub fn new( eth_sender_config: EthConfig, - contracts_config: ContractsConfig, - gateway_chain_config: Option, zksync_network_id: L2ChainId, l1_batch_commit_data_generator_mode: L1BatchCommitmentMode, ) -> Self { Self { eth_sender_config, - contracts_config, - gateway_chain_config, zksync_network_id, l1_batch_commit_data_generator_mode, } @@ -106,37 +102,32 @@ impl WiringLayer for EthTxAggregatorLayer { input.settlement_mode.0, input.settlement_mode.0.is_gateway() ); - tracing::info!("Contracts: {:?}", self.contracts_config); - tracing::info!("Gateway contracts: {:?}", self.gateway_chain_config); + tracing::info!("Contracts: {:?}", &input.contracts_resource.0); // Get resources. - let ( - validator_timelock_addr, - multicall3_addr, - diamond_proxy_addr, - state_transition_manager_address, - ) = if input.settlement_mode.0.is_gateway() { - let gateway_chain_config = self - .gateway_chain_config - .as_ref() - .context("gateway_chain_config")?; - ( - gateway_chain_config.validator_timelock_addr, - gateway_chain_config.multicall3_addr, - gateway_chain_config.diamond_proxy_addr, - gateway_chain_config.state_transition_proxy_addr, - ) - } else { - ( - self.contracts_config.validator_timelock_addr, - self.contracts_config.l1_multicall3_addr, - self.contracts_config.diamond_proxy_addr, - self.contracts_config - .ecosystem_contracts - .context("Missing ecosystem contracts")? - .state_transition_proxy_addr, - ) - }; + let validator_timelock_addr = input + .contracts_resource + .0 + .ecosystem_contracts + .validator_timelock_addr + .expect("Should be presented"); + let multicall3_addr = input + .contracts_resource + .0 + .ecosystem_contracts + .multicall3 + .expect("Should be presented"); + let diamond_proxy_addr = input + .contracts_resource + .0 + .chain_contracts_config + .diamond_proxy_addr; + let state_transition_manager_address = input + .contracts_resource + .0 + .ecosystem_contracts + .state_transition_proxy_addr + .expect("Should be presented"); let eth_client = if input.settlement_mode.0.is_gateway() { input diff --git a/core/node/node_framework/src/implementations/layers/eth_sender/manager.rs b/core/node/node_framework/src/implementations/layers/eth_sender/manager.rs index b8951c2a91ca..683f3eee17d5 100644 --- a/core/node/node_framework/src/implementations/layers/eth_sender/manager.rs +++ b/core/node/node_framework/src/implementations/layers/eth_sender/manager.rs @@ -13,6 +13,7 @@ use crate::{ gas_adjuster::GasAdjusterResource, healthcheck::AppHealthCheckResource, pools::{MasterPool, PoolResource, ReplicaPool}, + settlement_layer::SettlementModeResource, }, service::StopReceiver, task::{Task, TaskId}, @@ -51,6 +52,7 @@ pub struct Input { pub eth_client_blobs: Option, pub eth_client_gateway: Option, pub gas_adjuster: GasAdjusterResource, + pub sl_mode: SettlementModeResource, #[context(default)] pub circuit_breakers: CircuitBreakersResource, #[context(default)] @@ -99,6 +101,7 @@ impl WiringLayer for EthTxManagerLayer { Some(eth_client), eth_client_blobs, l2_client, + input.sl_mode.0, ); // Insert circuit breaker. diff --git a/core/node/node_framework/src/implementations/layers/eth_watch.rs b/core/node/node_framework/src/implementations/layers/eth_watch.rs index f8af0e4fc5cc..cf19ac39a4a9 100644 --- a/core/node/node_framework/src/implementations/layers/eth_watch.rs +++ b/core/node/node_framework/src/implementations/layers/eth_watch.rs @@ -1,11 +1,15 @@ -use anyhow::Context; -use zksync_config::{configs::gateway::GatewayChainConfig, ContractsConfig, EthWatchConfig}; -use zksync_eth_watch::{EthHttpQueryClient, EthWatch, ZkSyncExtentionEthClient}; +use zksync_config::EthWatchConfig; +use zksync_eth_watch::{EthHttpQueryClient, EthWatch, GetLogsClient, ZkSyncExtentionEthClient}; use zksync_types::L2ChainId; +use zksync_web3_decl::client::{DynClient, Network}; use crate::{ implementations::resources::{ - eth_interface::{EthInterfaceResource, L2InterfaceResource}, + contracts::{ + L1ChainContractsResource, L1EcosystemContractsResource, + SettlementLayerContractsResource, + }, + eth_interface::{EthInterfaceResource, UniversalClient, UniversalClientResource}, pools::{MasterPool, PoolResource}, settlement_layer::SettlementModeResource, }, @@ -22,17 +26,18 @@ use crate::{ #[derive(Debug)] pub struct EthWatchLayer { eth_watch_config: EthWatchConfig, - contracts_config: ContractsConfig, - gateway_chain_config: Option, chain_id: L2ChainId, } #[derive(Debug, FromContext)] #[context(crate = crate)] pub struct Input { + pub l1_contracts: L1ChainContractsResource, + pub contracts_resource: SettlementLayerContractsResource, + pub l1ecosystem_contracts_resource: L1EcosystemContractsResource, pub master_pool: PoolResource, pub eth_client: EthInterfaceResource, - pub gateway_client: Option, + pub client: UniversalClientResource, pub settlement_mode: SettlementModeResource, } @@ -44,19 +49,46 @@ pub struct Output { } impl EthWatchLayer { - pub fn new( - eth_watch_config: EthWatchConfig, - contracts_config: ContractsConfig, - gateway_chain_config: Option, - chain_id: L2ChainId, - ) -> Self { + pub fn new(eth_watch_config: EthWatchConfig, chain_id: L2ChainId) -> Self { Self { eth_watch_config, - contracts_config, - gateway_chain_config, chain_id, } } + fn create_client( + &self, + client: Box>, + contracts_resource: &SettlementLayerContractsResource, + l1_ecosystem_contracts_resource: &L1EcosystemContractsResource, + ) -> EthHttpQueryClient + where + Box>: GetLogsClient, + { + EthHttpQueryClient::new( + client, + contracts_resource + .0 + .chain_contracts_config + .diamond_proxy_addr, + l1_ecosystem_contracts_resource.0.bytecodes_supplier_addr, + l1_ecosystem_contracts_resource.0.wrapped_base_token_store, + l1_ecosystem_contracts_resource.0.shared_bridge, + contracts_resource + .0 + .ecosystem_contracts + .state_transition_proxy_addr, + contracts_resource + .0 + .chain_contracts_config + .diamond_proxy_addr, + contracts_resource + .0 + .ecosystem_contracts + .server_notifier_addr, + self.eth_watch_config.confirmations_for_eth_event, + self.chain_id, + ) + } } #[async_trait::async_trait] @@ -72,74 +104,63 @@ impl WiringLayer for EthWatchLayer { let main_pool = input.master_pool.get().await?; let client = input.eth_client.0; - let sl_diamond_proxy_addr = if input.settlement_mode.0.is_gateway() { - self.gateway_chain_config - .clone() - .context("Lacking `gateway_contracts_config`")? - .diamond_proxy_addr - } else { - self.contracts_config.diamond_proxy_addr - }; - tracing::info!( - "Diamond proxy address ethereum: {:#?}", - self.contracts_config.diamond_proxy_addr - ); tracing::info!( "Diamond proxy address settlement_layer: {:#?}", - sl_diamond_proxy_addr + input + .contracts_resource + .0 + .chain_contracts_config + .diamond_proxy_addr ); let l1_client = EthHttpQueryClient::new( client, - self.contracts_config.diamond_proxy_addr, - self.contracts_config + input + .l1_contracts + .0 + .chain_contracts_config + .diamond_proxy_addr, + input + .l1ecosystem_contracts_resource + .0 + .bytecodes_supplier_addr, + input + .l1ecosystem_contracts_resource + .0 + .wrapped_base_token_store, + input.l1ecosystem_contracts_resource.0.shared_bridge, + input + .l1_contracts + .0 .ecosystem_contracts - .as_ref() - .and_then(|a| a.l1_bytecodes_supplier_addr), - self.contracts_config + .state_transition_proxy_addr, + input + .l1_contracts + .0 + .chain_contracts_config + .chain_admin + .expect("Should be presented"), + input + .l1_contracts + .0 .ecosystem_contracts - .as_ref() - .and_then(|a| a.l1_wrapped_base_token_store), - self.contracts_config.l1_shared_bridge_proxy_addr, - self.contracts_config - .ecosystem_contracts - .as_ref() - .map(|a| a.state_transition_proxy_addr), - self.contracts_config.chain_admin_addr, - self.contracts_config - .ecosystem_contracts - .as_ref() - .map(|a| a.server_notifier_addr) - .flatten(), + .server_notifier_addr, self.eth_watch_config.confirmations_for_eth_event, self.chain_id, ); - let sl_l2_client: Box = - if let Some(gateway_client) = input.gateway_client { - let contracts_config = self.gateway_chain_config.unwrap(); - Box::new(EthHttpQueryClient::new( - gateway_client.0, - contracts_config.diamond_proxy_addr, - // Only present on L1. - None, - // Only present on L1. - None, - // Only present on L1. - None, - Some(contracts_config.state_transition_proxy_addr), - contracts_config.chain_admin_addr, - self.contracts_config - .ecosystem_contracts - .as_ref() - .map(|a| a.server_notifier_addr) - .flatten(), - self.eth_watch_config.confirmations_for_eth_event, - self.chain_id, - )) - } else { - Box::new(l1_client.clone()) - }; + let sl_l2_client: Box = match input.client.0 { + UniversalClient::L1(client) => Box::new(self.create_client( + client, + &input.contracts_resource, + &input.l1ecosystem_contracts_resource, + )), + UniversalClient::L2(client) => Box::new(self.create_client( + client, + &input.contracts_resource, + &input.l1ecosystem_contracts_resource, + )), + }; let eth_watch = EthWatch::new( Box::new(l1_client), diff --git a/core/node/node_framework/src/implementations/layers/gas_adjuster.rs b/core/node/node_framework/src/implementations/layers/gas_adjuster.rs index 241c4d829beb..4168cd3eb195 100644 --- a/core/node/node_framework/src/implementations/layers/gas_adjuster.rs +++ b/core/node/node_framework/src/implementations/layers/gas_adjuster.rs @@ -7,7 +7,7 @@ use zksync_types::pubdata_da::PubdataSendingMode; use crate::{ implementations::resources::{ - eth_interface::{EthInterfaceResource, L2InterfaceResource}, + eth_interface::{UniversalClient, UniversalClientResource}, gas_adjuster::GasAdjusterResource, }, service::StopReceiver, @@ -28,8 +28,7 @@ pub struct GasAdjusterLayer { #[derive(Debug, FromContext)] #[context(crate = crate)] pub struct Input { - pub eth_interface_client: EthInterfaceResource, - pub l2_inteface_client: Option, + pub client: UniversalClientResource, } #[derive(Debug, IntoContext)] @@ -65,10 +64,9 @@ impl WiringLayer for GasAdjusterLayer { } async fn wire(self, input: Self::Input) -> Result { - let client = if self.gas_adjuster_config.settlement_mode.is_gateway() { - input.l2_inteface_client.unwrap().0.into() - } else { - input.eth_interface_client.0.into() + let client = match input.client.0 { + UniversalClient::L1(client) => client.into(), + UniversalClient::L2(client) => client.into(), }; let adjuster = GasAdjuster::new( diff --git a/core/node/node_framework/src/implementations/layers/gateway_client.rs b/core/node/node_framework/src/implementations/layers/gateway_client.rs new file mode 100644 index 000000000000..8d165cb4a64d --- /dev/null +++ b/core/node/node_framework/src/implementations/layers/gateway_client.rs @@ -0,0 +1,74 @@ +use anyhow::Context; +use zksync_node_framework_derive::FromContext; +use zksync_types::{settlement::SettlementMode, url::SensitiveUrl, L2ChainId}; +use zksync_web3_decl::client::Client; + +use crate::{ + implementations::resources::{ + eth_interface::{UniversalClient, UniversalClientResource}, + settlement_layer::{SettlementModeResource, SlChainIdResource}, + }, + wiring_layer::{WiringError, WiringLayer}, + IntoContext, +}; + +/// Wiring layer for Ethereum client. +#[derive(Debug)] +pub struct GatewayClientLayer { + l1_rpc_url: SensitiveUrl, + gateway_rpc_url: Option, +} + +impl GatewayClientLayer { + pub fn new(l1_rpc_url: SensitiveUrl, gateway_rpc_url: Option) -> Self { + Self { + l1_rpc_url, + gateway_rpc_url, + } + } +} + +#[derive(Debug, FromContext)] +#[context(crate = crate)] +pub struct Input { + initial_settlement_mode: SettlementModeResource, + sl_chain_id_resource: SlChainIdResource, +} + +#[derive(Debug, IntoContext)] +#[context(crate = crate)] +pub struct Output { + query_client_gateway: UniversalClientResource, +} + +#[async_trait::async_trait] +impl WiringLayer for GatewayClientLayer { + type Input = Input; + type Output = Output; + + fn layer_name(&self) -> &'static str { + "gateway_client" + } + + async fn wire(self, input: Self::Input) -> Result { + Ok(Output { + query_client_gateway: match input.initial_settlement_mode.0 { + SettlementMode::SettlesToL1 => { + let mut builder = Client::http(self.l1_rpc_url).context("Client::new()")?; + builder = builder.for_network(input.sl_chain_id_resource.0.into()); + UniversalClientResource(UniversalClient::L1(Box::new(builder.build()))) + } + SettlementMode::Gateway => { + let mut builder = + Client::http(self.gateway_rpc_url.unwrap()).context("Client::new()")?; + builder = builder.for_network( + L2ChainId::new(input.sl_chain_id_resource.0 .0) + .unwrap() + .into(), + ); + UniversalClientResource(UniversalClient::L2(Box::new(builder.build()))) + } + }, + }) + } +} diff --git a/core/node/node_framework/src/implementations/layers/gateway_migrator_layer.rs b/core/node/node_framework/src/implementations/layers/gateway_migrator_layer.rs index f7f7a820fefb..6548a3c43b8c 100644 --- a/core/node/node_framework/src/implementations/layers/gateway_migrator_layer.rs +++ b/core/node/node_framework/src/implementations/layers/gateway_migrator_layer.rs @@ -1,46 +1,30 @@ use async_trait::async_trait; -use zksync_config::{configs::GatewayChainConfig, ContractsConfig}; -use zksync_multilayer_client::GatewayMigrator; +use zksync_gateway_migrator::GatewayMigrator; use crate::{ implementations::resources::{ - contracts::ContractsResource, eth_interface::EthInterfaceResource, + contracts::L1ChainContractsResource, eth_interface::EthInterfaceResource, settlement_layer::SettlementModeResource, }, wiring_layer::{WiringError, WiringLayer}, FromContext, IntoContext, StopReceiver, Task, TaskId, }; -/// Wiring layer for [`PKSigningClient`]. +/// Wiring layer for [`GatewayMigrator`]. #[derive(Debug)] -pub struct GatewayMigratorLayer { - contracts_config: ContractsConfig, - gateway_chain_config: Option, -} - -impl GatewayMigratorLayer { - pub fn new( - contracts_config: ContractsConfig, - gateway_chain_config: Option, - ) -> Self { - Self { - contracts_config, - gateway_chain_config, - } - } -} +pub struct GatewayMigratorLayer; #[derive(Debug, FromContext)] #[context(crate = crate)] pub struct Input { - pub eth_client: EthInterfaceResource, + eth_client: EthInterfaceResource, + contracts: L1ChainContractsResource, + settlement_mode_resource: SettlementModeResource, } #[derive(Debug, IntoContext)] #[context(crate = crate)] pub struct Output { - initial_settlement_mode: SettlementModeResource, - contracts: ContractsResource, #[context(task)] gateway_migrator: GatewayMigrator, } @@ -55,13 +39,13 @@ impl WiringLayer for GatewayMigratorLayer { } async fn wire(self, input: Self::Input) -> Result { - let migrator = - GatewayMigrator::new(input.eth_client.0, self.contracts_config.diamond_proxy_addr) - .await; + let migrator = GatewayMigrator::new( + Box::new(input.eth_client.0), + input.contracts.0.chain_contracts_config.diamond_proxy_addr, + input.settlement_mode_resource.0, + ); Ok(Output { - initial_settlement_mode: SettlementModeResource(migrator.settlement_mode()), - contracts: ContractsResource(self.gateway_chain_config.unwrap()), gateway_migrator: migrator, }) } diff --git a/core/node/node_framework/src/implementations/layers/l1_batch_commitment_mode_validation.rs b/core/node/node_framework/src/implementations/layers/l1_batch_commitment_mode_validation.rs index 1ef340e08aa7..7c22e754e743 100644 --- a/core/node/node_framework/src/implementations/layers/l1_batch_commitment_mode_validation.rs +++ b/core/node/node_framework/src/implementations/layers/l1_batch_commitment_mode_validation.rs @@ -1,8 +1,14 @@ use zksync_commitment_generator::validation_task::L1BatchCommitmentModeValidationTask; -use zksync_types::{commitment::L1BatchCommitmentMode, Address}; +use zksync_types::commitment::L1BatchCommitmentMode; use crate::{ - implementations::resources::eth_interface::EthInterfaceResource, + implementations::resources::{ + contracts::{ + GatewayChainContractsResource, L1ChainContractsResource, L1EcosystemContractsResource, + SettlementLayerContractsResource, + }, + eth_interface::{EthInterfaceResource, UniversalClient, UniversalClientResource}, + }, service::StopReceiver, task::{Task, TaskId, TaskKind}, wiring_layer::{WiringError, WiringLayer}, @@ -13,14 +19,14 @@ use crate::{ /// against L1. #[derive(Debug)] pub struct L1BatchCommitmentModeValidationLayer { - diamond_proxy_addr: Address, l1_batch_commit_data_generator_mode: L1BatchCommitmentMode, } #[derive(Debug, FromContext)] #[context(crate = crate)] pub struct Input { - pub eth_client: EthInterfaceResource, + pub contracts: L1EcosystemContractsResource, + pub client: EthInterfaceResource, } #[derive(Debug, IntoContext)] @@ -31,12 +37,8 @@ pub struct Output { } impl L1BatchCommitmentModeValidationLayer { - pub fn new( - diamond_proxy_addr: Address, - l1_batch_commit_data_generator_mode: L1BatchCommitmentMode, - ) -> Self { + pub fn new(l1_batch_commit_data_generator_mode: L1BatchCommitmentMode) -> Self { Self { - diamond_proxy_addr, l1_batch_commit_data_generator_mode, } } @@ -52,11 +54,10 @@ impl WiringLayer for L1BatchCommitmentModeValidationLayer { } async fn wire(self, input: Self::Input) -> Result { - let EthInterfaceResource(query_client) = input.eth_client; let task = L1BatchCommitmentModeValidationTask::new( - self.diamond_proxy_addr, + input.contracts.0.l1_diamond_proxy, self.l1_batch_commit_data_generator_mode, - query_client, + Box::new(input.client.0), ); Ok(Output { task }) diff --git a/core/node/node_framework/src/implementations/layers/mod.rs b/core/node/node_framework/src/implementations/layers/mod.rs index 2a6b4afb65f9..bc4ef2426fb8 100644 --- a/core/node/node_framework/src/implementations/layers/mod.rs +++ b/core/node/node_framework/src/implementations/layers/mod.rs @@ -14,6 +14,7 @@ pub mod eth_sender; pub mod eth_watch; pub mod external_proof_integration_api; pub mod gas_adjuster; +pub mod gateway_client; pub mod gateway_migrator_layer; pub mod healtcheck_server; pub mod house_keeper; @@ -33,6 +34,8 @@ pub mod proof_data_handler; pub mod pruning; pub mod query_eth_client; pub mod reorg_detector; +pub mod settlement_layer_data; +pub mod settlement_layer_data_en; pub mod sigint; pub mod state_keeper; pub mod sync_state_updater; diff --git a/core/node/node_framework/src/implementations/layers/node_storage_init/main_node_strategy.rs b/core/node/node_framework/src/implementations/layers/node_storage_init/main_node_strategy.rs index ef43aaf1aee0..6ccc92bf1954 100644 --- a/core/node/node_framework/src/implementations/layers/node_storage_init/main_node_strategy.rs +++ b/core/node/node_framework/src/implementations/layers/node_storage_init/main_node_strategy.rs @@ -1,11 +1,12 @@ use std::sync::Arc; -use zksync_config::{ContractsConfig, GenesisConfig}; +use zksync_config::GenesisConfig; use zksync_node_storage_init::{main_node::MainNodeGenesis, NodeInitializationStrategy}; use super::NodeInitializationStrategyResource; use crate::{ implementations::resources::{ + contracts::SettlementLayerContractsResource, eth_interface::EthInterfaceResource, pools::{MasterPool, PoolResource}, }, @@ -17,7 +18,6 @@ use crate::{ #[derive(Debug)] pub struct MainNodeInitStrategyLayer { pub genesis: GenesisConfig, - pub contracts: ContractsConfig, } #[derive(Debug, FromContext)] @@ -25,6 +25,7 @@ pub struct MainNodeInitStrategyLayer { pub struct Input { pub master_pool: PoolResource, pub eth_interface: EthInterfaceResource, + pub contracts_resource: SettlementLayerContractsResource, } #[derive(Debug, IntoContext)] @@ -46,7 +47,7 @@ impl WiringLayer for MainNodeInitStrategyLayer { let pool = input.master_pool.get().await?; let EthInterfaceResource(l1_client) = input.eth_interface; let genesis = Arc::new(MainNodeGenesis { - contracts: self.contracts, + contracts: input.contracts_resource.0, genesis: self.genesis, l1_client, pool, diff --git a/core/node/node_framework/src/implementations/layers/pk_signing_eth_client.rs b/core/node/node_framework/src/implementations/layers/pk_signing_eth_client.rs index bcc01c20cc42..1e9325b4f6d2 100644 --- a/core/node/node_framework/src/implementations/layers/pk_signing_eth_client.rs +++ b/core/node/node_framework/src/implementations/layers/pk_signing_eth_client.rs @@ -1,14 +1,15 @@ use anyhow::Context as _; -use zksync_config::{ - configs::{gateway::GatewayChainConfig, wallets, ContractsConfig}, - EthConfig, -}; +use zksync_config::{configs::wallets, EthConfig}; use zksync_eth_client::{clients::PKSigningClient, EthInterface}; use crate::{ - implementations::resources::eth_interface::{ - BoundEthInterfaceForBlobsResource, BoundEthInterfaceForL2Resource, - BoundEthInterfaceResource, EthInterfaceResource, GatewayEthInterfaceResource, + implementations::resources::{ + contracts::{L1ChainContractsResource, SettlementLayerContractsResource}, + eth_interface::{ + BoundEthInterfaceForBlobsResource, BoundEthInterfaceForL2Resource, + BoundEthInterfaceResource, EthInterfaceResource, UniversalClient, + UniversalClientResource, + }, }, wiring_layer::{WiringError, WiringLayer}, FromContext, IntoContext, @@ -18,8 +19,6 @@ use crate::{ #[derive(Debug)] pub struct PKSigningEthClientLayer { eth_sender_config: EthConfig, - contracts_config: ContractsConfig, - gateway_chain_config: Option, wallets: wallets::EthSender, } @@ -27,7 +26,9 @@ pub struct PKSigningEthClientLayer { #[context(crate = crate)] pub struct Input { pub eth_client: EthInterfaceResource, - pub gateway_client: Option, + pub contracts: SettlementLayerContractsResource, + pub l1_contracts: L1ChainContractsResource, + pub gateway_client: UniversalClientResource, } #[derive(Debug, IntoContext)] @@ -40,16 +41,9 @@ pub struct Output { } impl PKSigningEthClientLayer { - pub fn new( - eth_sender_config: EthConfig, - contracts_config: ContractsConfig, - gateway_chain_config: Option, - wallets: wallets::EthSender, - ) -> Self { + pub fn new(eth_sender_config: EthConfig, wallets: wallets::EthSender) -> Self { Self { eth_sender_config, - contracts_config, - gateway_chain_config, wallets, } } @@ -79,7 +73,11 @@ impl WiringLayer for PKSigningEthClientLayer { .map_err(WiringError::internal)?; let signing_client = PKSigningClient::new_raw( private_key.clone(), - self.contracts_config.diamond_proxy_addr, + input + .l1_contracts + .0 + .chain_contracts_config + .diamond_proxy_addr, gas_adjuster_config.default_priority_fee_per_gas, l1_chain_id, query_client.clone(), @@ -90,7 +88,11 @@ impl WiringLayer for PKSigningEthClientLayer { let private_key = blob_operator.private_key(); let signing_client_for_blobs = PKSigningClient::new_raw( private_key.clone(), - self.contracts_config.diamond_proxy_addr, + input + .l1_contracts + .0 + .chain_contracts_config + .diamond_proxy_addr, gas_adjuster_config.default_priority_fee_per_gas, l1_chain_id, query_client, @@ -98,33 +100,31 @@ impl WiringLayer for PKSigningEthClientLayer { BoundEthInterfaceForBlobsResource(Box::new(signing_client_for_blobs)) }); - let signing_client_for_gateway = if let (Some(client), Some(gateway_contracts)) = - (&input.gateway_client, self.gateway_chain_config.as_ref()) - { - if gateway_contracts.gateway_chain_id.0 != 0u64 { + let signing_client_for_l2_gateway = match input.gateway_client.0 { + UniversalClient::L2(gateway_client) => { let private_key = self.wallets.operator.private_key(); - let GatewayEthInterfaceResource(gateway_client) = client; + let chain_id = gateway_client + .fetch_chain_id() + .await + .map_err(WiringError::internal)?; let signing_client_for_blobs = PKSigningClient::new_raw( private_key.clone(), - gateway_contracts.diamond_proxy_addr, + input.contracts.0.chain_contracts_config.diamond_proxy_addr, gas_adjuster_config.default_priority_fee_per_gas, - gateway_contracts.gateway_chain_id, + chain_id, gateway_client.clone(), ); Some(BoundEthInterfaceForL2Resource(Box::new( signing_client_for_blobs, ))) - } else { - None } - } else { - None + UniversalClient::L1(_) => None, }; Ok(Output { signing_client, signing_client_for_blobs, - signing_client_for_gateway, + signing_client_for_gateway: signing_client_for_l2_gateway, }) } } diff --git a/core/node/node_framework/src/implementations/layers/query_eth_client.rs b/core/node/node_framework/src/implementations/layers/query_eth_client.rs index 62bbccd41e24..3eef8078aaae 100644 --- a/core/node/node_framework/src/implementations/layers/query_eth_client.rs +++ b/core/node/node_framework/src/implementations/layers/query_eth_client.rs @@ -3,9 +3,7 @@ use zksync_types::{url::SensitiveUrl, L1ChainId, L2ChainId, SLChainId}; use zksync_web3_decl::client::Client; use crate::{ - implementations::resources::eth_interface::{ - EthInterfaceResource, GatewayEthInterfaceResource, L2InterfaceResource, - }, + implementations::resources::eth_interface::{EthInterfaceResource, L2InterfaceResource}, wiring_layer::{WiringError, WiringLayer}, IntoContext, }; @@ -40,7 +38,6 @@ impl QueryEthClientLayer { pub struct Output { query_client_l1: EthInterfaceResource, query_client_l2: Option, - query_client_gateway: Option, } #[async_trait::async_trait] @@ -72,16 +69,6 @@ impl WiringLayer for QueryEthClientLayer { } else { None }, - query_client_gateway: if let Some(gateway_rpc_url) = self.gateway_rpc_url { - let mut builder = Client::http(gateway_rpc_url).context("Client::new()")?; - if let Some(gateway_chain_id) = self.gateway_chain_id { - builder = builder.for_network(gateway_chain_id.into()) - } - - Some(GatewayEthInterfaceResource(Box::new(builder.build()))) - } else { - None - }, }) } } diff --git a/core/node/node_framework/src/implementations/layers/settlement_layer_data.rs b/core/node/node_framework/src/implementations/layers/settlement_layer_data.rs new file mode 100644 index 000000000000..197d5e0000ce --- /dev/null +++ b/core/node/node_framework/src/implementations/layers/settlement_layer_data.rs @@ -0,0 +1,104 @@ +use anyhow::Context; +use zksync_config::{configs::contracts::ecosystem::L1SpecificContracts, SettlementLayerContracts}; +use zksync_contracts::getters_facet_contract; +use zksync_eth_client::EthInterface; +use zksync_gateway_migrator::get_settlement_layer; +use zksync_types::settlement::SettlementMode; + +use crate::{ + implementations::resources::{ + contracts::{ + L1ChainContractsResource, L1EcosystemContractsResource, + SettlementLayerContractsResource, + }, + eth_interface::{EthInterfaceResource, L2InterfaceResource}, + settlement_layer::{SettlementModeResource, SlChainIdResource}, + }, + wiring_layer::{WiringError, WiringLayer}, + FromContext, IntoContext, +}; + +/// Wiring layer for [`SettlementLayerData`]. +#[derive(Debug)] +pub struct SettlementLayerData { + contracts: SettlementLayerContracts, + l1_ecosystem_contracts: L1SpecificContracts, +} + +impl SettlementLayerData { + pub fn new( + contracts: SettlementLayerContracts, + l1_ecosystem_contracts: L1SpecificContracts, + ) -> Self { + Self { + contracts, + l1_ecosystem_contracts, + } + } +} + +#[derive(Debug, FromContext)] +#[context(crate = crate)] +pub struct Input { + pub eth_client: EthInterfaceResource, + pub l2_eth_client: Option, +} + +#[derive(Debug, IntoContext)] +#[context(crate = crate)] +pub struct Output { + initial_settlement_mode: SettlementModeResource, + contracts: SettlementLayerContractsResource, + l1_ecosystem_contracts: L1EcosystemContractsResource, + l1_contracts: L1ChainContractsResource, + sl_chain_id: SlChainIdResource, +} + +#[async_trait::async_trait] +impl WiringLayer for SettlementLayerData { + type Input = Input; + type Output = Output; + + fn layer_name(&self) -> &'static str { + "settlement_layer_data" + } + + async fn wire(self, input: Self::Input) -> Result { + let mut contracts = self.contracts.clone(); + let initial_sl_mode = get_settlement_layer( + &input.eth_client.0, + self.contracts + .l1_contracts() + .chain_contracts_config + .diamond_proxy_addr, + &getters_facet_contract(), + ) + .await?; + contracts.set_settlement_mode(initial_sl_mode); + let sl_chain_id = match initial_sl_mode { + SettlementMode::SettlesToL1 => input + .eth_client + .0 + .fetch_chain_id() + .await + .context("fetch_chain_id")?, + SettlementMode::Gateway => input + .l2_eth_client + .expect("Should be present for gateway settlement mode") + .0 + .fetch_chain_id() + .await + .context("fetch_chain_id")?, + }; + + Ok(Output { + initial_settlement_mode: SettlementModeResource(initial_sl_mode), + contracts: SettlementLayerContractsResource(contracts.current_contracts().clone()), + l1_ecosystem_contracts: L1EcosystemContractsResource( + self.l1_ecosystem_contracts.clone(), + ), + l1_contracts: L1ChainContractsResource(contracts.l1_contracts().clone()), + sl_chain_id: SlChainIdResource(sl_chain_id), + }) + } +} diff --git a/core/node/node_framework/src/implementations/layers/settlement_layer_data_en.rs b/core/node/node_framework/src/implementations/layers/settlement_layer_data_en.rs new file mode 100644 index 000000000000..89a33995f3d5 --- /dev/null +++ b/core/node/node_framework/src/implementations/layers/settlement_layer_data_en.rs @@ -0,0 +1,94 @@ +use zksync_config::configs::contracts::{ecosystem::L1SpecificContracts, ChainSpecificContracts}; +use zksync_contracts::getters_facet_contract; +use zksync_eth_client::EthInterface; +use zksync_gateway_migrator::get_settlement_layer; +use zksync_types::settlement::SettlementMode; + +use crate::{ + implementations::resources::{ + contracts::{ + L1ChainContractsResource, L1EcosystemContractsResource, + SettlementLayerContractsResource, + }, + eth_interface::{EthInterfaceResource, L2InterfaceResource}, + settlement_layer::{SettlementModeResource, SlChainIdResource}, + }, + wiring_layer::{WiringError, WiringLayer}, + FromContext, IntoContext, +}; + +/// Wiring layer for [`SettlementLayerData`]. +#[derive(Debug)] +pub struct SettlementLayerDataEn { + l1specific_contracts: L1SpecificContracts, + chain_specific_contracts: ChainSpecificContracts, +} + +impl SettlementLayerDataEn { + pub fn new( + l1specific_contracts: L1SpecificContracts, + chain_specific_contracts: ChainSpecificContracts, + ) -> Self { + Self { + l1specific_contracts, + chain_specific_contracts, + } + } +} + +#[derive(Debug, FromContext)] +#[context(crate = crate)] +pub struct Input { + pub eth_client: EthInterfaceResource, + pub l2_eth_client: Option, +} + +#[derive(Debug, IntoContext)] +#[context(crate = crate)] +pub struct Output { + initial_settlement_mode: SettlementModeResource, + contracts: SettlementLayerContractsResource, + l1_contracts: L1ChainContractsResource, + l1_ecosystem_contracts: L1EcosystemContractsResource, + sl_chain_id_resource: SlChainIdResource, +} + +#[async_trait::async_trait] +impl WiringLayer for SettlementLayerDataEn { + type Input = Input; + type Output = Output; + + fn layer_name(&self) -> &'static str { + "settlement_layer_en" + } + + async fn wire(self, input: Self::Input) -> Result { + let initial_sl_mode = get_settlement_layer( + &input.eth_client.0, + self.chain_specific_contracts + .chain_contracts_config + .diamond_proxy_addr, + &getters_facet_contract(), + ) + .await?; + + let chain_id = match initial_sl_mode { + SettlementMode::SettlesToL1 => input.eth_client.0.fetch_chain_id().await.unwrap(), + SettlementMode::Gateway => input + .l2_eth_client + .unwrap() + .0 + .fetch_chain_id() + .await + .unwrap(), + }; + + Ok(Output { + contracts: SettlementLayerContractsResource(self.chain_specific_contracts.clone()), + l1_contracts: L1ChainContractsResource(self.chain_specific_contracts.clone()), + l1_ecosystem_contracts: L1EcosystemContractsResource(self.l1specific_contracts.clone()), + initial_settlement_mode: SettlementModeResource(initial_sl_mode), + sl_chain_id_resource: SlChainIdResource(chain_id), + }) + } +} diff --git a/core/node/node_framework/src/implementations/layers/state_keeper/mempool_io.rs b/core/node/node_framework/src/implementations/layers/state_keeper/mempool_io.rs index 79eb233041a6..f4ab8e837aef 100644 --- a/core/node/node_framework/src/implementations/layers/state_keeper/mempool_io.rs +++ b/core/node/node_framework/src/implementations/layers/state_keeper/mempool_io.rs @@ -4,10 +4,11 @@ use zksync_config::configs::{ wallets, }; use zksync_state_keeper::{MempoolFetcher, MempoolGuard, MempoolIO, SequencerSealer}; -use zksync_types::{commitment::PubdataType, Address, L2ChainId}; +use zksync_types::{commitment::PubdataType, L2ChainId}; use crate::{ implementations::resources::{ + contracts::SettlementLayerContractsResource, fee_input::SequencerFeeInputResource, pools::{MasterPool, PoolResource}, state_keeper::{ConditionalSealerResource, StateKeeperIOResource}, @@ -39,7 +40,6 @@ pub struct MempoolIOLayer { state_keeper_config: StateKeeperConfig, mempool_config: MempoolConfig, wallets: wallets::StateKeeper, - l2_da_validator_addr: Option
, pubdata_type: PubdataType, } @@ -48,6 +48,7 @@ pub struct MempoolIOLayer { pub struct Input { pub fee_input: SequencerFeeInputResource, pub master_pool: PoolResource, + pub contracts_resource: SettlementLayerContractsResource, } #[derive(Debug, IntoContext)] @@ -65,7 +66,6 @@ impl MempoolIOLayer { state_keeper_config: StateKeeperConfig, mempool_config: MempoolConfig, wallets: wallets::StateKeeper, - l2_da_validator_addr: Option
, pubdata_type: PubdataType, ) -> Self { Self { @@ -73,7 +73,6 @@ impl MempoolIOLayer { state_keeper_config, mempool_config, wallets, - l2_da_validator_addr, pubdata_type, } } @@ -135,7 +134,7 @@ impl WiringLayer for MempoolIOLayer { self.wallets.fee_account.address(), self.mempool_config.delay_interval(), self.zksync_network_id, - self.l2_da_validator_addr, + input.contracts_resource.0.l2_contracts.da_validator_addr, self.pubdata_type, )?; diff --git a/core/node/node_framework/src/implementations/layers/state_keeper/output_handler.rs b/core/node/node_framework/src/implementations/layers/state_keeper/output_handler.rs index 1a07591c1cd9..88e2153e8e22 100644 --- a/core/node/node_framework/src/implementations/layers/state_keeper/output_handler.rs +++ b/core/node/node_framework/src/implementations/layers/state_keeper/output_handler.rs @@ -4,10 +4,10 @@ use zksync_state_keeper::{ io::seal_logic::l2_block_seal_subtasks::L2BlockSealProcess, L2BlockSealerTask, OutputHandler, StateKeeperPersistence, TreeWritesPersistence, }; -use zksync_types::Address; use crate::{ implementations::resources::{ + contracts::SettlementLayerContractsResource, pools::{MasterPool, PoolResource}, state_keeper::OutputHandlerResource, sync_state::SyncStateResource, @@ -35,7 +35,6 @@ use crate::{ /// - `L2BlockSealerTask` #[derive(Debug)] pub struct OutputHandlerLayer { - l2_legacy_shared_bridge_addr: Option
, l2_block_seal_queue_capacity: usize, /// Whether transactions should be pre-inserted to DB. /// Should be set to `true` for EN's IO as EN doesn't store transactions in DB @@ -52,6 +51,7 @@ pub struct OutputHandlerLayer { pub struct Input { pub master_pool: PoolResource, pub sync_state: Option, + pub contracts: SettlementLayerContractsResource, } #[derive(Debug, IntoContext)] @@ -63,12 +63,8 @@ pub struct Output { } impl OutputHandlerLayer { - pub fn new( - l2_legacy_shared_bridge_addr: Option
, - l2_block_seal_queue_capacity: usize, - ) -> Self { + pub fn new(l2_block_seal_queue_capacity: usize) -> Self { Self { - l2_legacy_shared_bridge_addr, l2_block_seal_queue_capacity, pre_insert_txs: false, protective_reads_persistence_enabled: false, @@ -109,7 +105,7 @@ impl WiringLayer for OutputHandlerLayer { let (mut persistence, l2_block_sealer) = StateKeeperPersistence::new( persistence_pool.clone(), - self.l2_legacy_shared_bridge_addr, + input.contracts.0.l2_contracts.legacy_shared_bridge_addr, self.l2_block_seal_queue_capacity, ) .await?; diff --git a/core/node/node_framework/src/implementations/layers/tree_data_fetcher.rs b/core/node/node_framework/src/implementations/layers/tree_data_fetcher.rs index cdf0700a0e73..710ea38063dd 100644 --- a/core/node/node_framework/src/implementations/layers/tree_data_fetcher.rs +++ b/core/node/node_framework/src/implementations/layers/tree_data_fetcher.rs @@ -1,9 +1,9 @@ use zksync_node_sync::tree_data_fetcher::TreeDataFetcher; -use zksync_types::{Address, L2ChainId}; use crate::{ implementations::resources::{ - eth_interface::{EthInterfaceResource, GatewayEthInterfaceResource}, + contracts::SettlementLayerContractsResource, + eth_interface::UniversalClientResource, healthcheck::AppHealthCheckResource, main_node_client::MainNodeClientResource, pools::{MasterPool, PoolResource}, @@ -16,18 +16,15 @@ use crate::{ /// Wiring layer for [`TreeDataFetcher`]. #[derive(Debug)] -pub struct TreeDataFetcherLayer { - l1_diamond_proxy_addr: Address, - l2_chain_id: L2ChainId, -} +pub struct TreeDataFetcherLayer; #[derive(Debug, FromContext)] #[context(crate = crate)] pub struct Input { pub master_pool: PoolResource, pub main_node_client: MainNodeClientResource, - pub l1_client: EthInterfaceResource, - pub gateway_client: Option, + pub gateway_client: UniversalClientResource, + pub settlement_layer_contracts_resource: SettlementLayerContractsResource, #[context(default)] pub app_health: AppHealthCheckResource, } @@ -39,15 +36,6 @@ pub struct Output { pub task: TreeDataFetcher, } -impl TreeDataFetcherLayer { - pub fn new(l1_diamond_proxy_addr: Address, l2_chain_id: L2ChainId) -> Self { - Self { - l1_diamond_proxy_addr, - l2_chain_id, - } - } -} - #[async_trait::async_trait] impl WiringLayer for TreeDataFetcherLayer { type Input = Input; @@ -60,8 +48,7 @@ impl WiringLayer for TreeDataFetcherLayer { async fn wire(self, input: Self::Input) -> Result { let pool = input.master_pool.get().await?; let MainNodeClientResource(client) = input.main_node_client; - let EthInterfaceResource(l1_client) = input.l1_client; - let gateway_client = input.gateway_client.map(|c| c.0); + let gateway_client = input.gateway_client.0; tracing::warn!( "Running tree data fetcher (allows a node to operate w/o a Merkle tree or w/o waiting the tree to catch up). \ @@ -69,10 +56,12 @@ impl WiringLayer for TreeDataFetcherLayer { ); let task = TreeDataFetcher::new(client, pool) .with_l1_data( - l1_client, - self.l1_diamond_proxy_addr, - gateway_client, - self.l2_chain_id, + gateway_client.into(), + input + .settlement_layer_contracts_resource + .0 + .chain_contracts_config + .diamond_proxy_addr, ) .await?; diff --git a/core/node/node_framework/src/implementations/layers/validate_chain_ids.rs b/core/node/node_framework/src/implementations/layers/validate_chain_ids.rs index 926da1fcd5eb..cc7ffb23aee5 100644 --- a/core/node/node_framework/src/implementations/layers/validate_chain_ids.rs +++ b/core/node/node_framework/src/implementations/layers/validate_chain_ids.rs @@ -3,7 +3,7 @@ use zksync_types::{L1ChainId, L2ChainId, SLChainId}; use crate::{ implementations::resources::{ - eth_interface::{EthInterfaceResource, GatewayEthInterfaceResource}, + eth_interface::{EthInterfaceResource, UniversalClientResource}, main_node_client::MainNodeClientResource, }, service::StopReceiver, @@ -35,7 +35,7 @@ pub struct ValidateChainIdsLayer { #[context(crate = crate)] pub struct Input { pub l1_client: EthInterfaceResource, - pub gateway_client: Option, + pub gateway_client: UniversalClientResource, pub main_node_client: MainNodeClientResource, } @@ -79,7 +79,7 @@ impl WiringLayer for ValidateChainIdsLayer { self.gateway_chain_id, l1_query_client, main_node_client, - input.gateway_client.map(|c| c.0), + Some(input.gateway_client.0.into()), ); Ok(Output { task }) diff --git a/core/node/node_framework/src/implementations/layers/web3_api/server/bridge_addresses.rs b/core/node/node_framework/src/implementations/layers/web3_api/server/bridge_addresses.rs index b85d74699857..8c784aef2176 100644 --- a/core/node/node_framework/src/implementations/layers/web3_api/server/bridge_addresses.rs +++ b/core/node/node_framework/src/implementations/layers/web3_api/server/bridge_addresses.rs @@ -1,10 +1,10 @@ use std::time::Duration; -use zksync_eth_client::{CallFunctionArgs, ContractCallError}; +use zksync_eth_client::{CallFunctionArgs, ContractCallError, EthInterface}; use zksync_node_api_server::web3::state::BridgeAddressesHandle; use zksync_types::{ethabi::Contract, Address, L2_ASSET_ROUTER_ADDRESS}; use zksync_web3_decl::{ - client::{DynClient, L1, L2}, + client::{DynClient, L2}, namespaces::ZksNamespaceClient, }; @@ -33,7 +33,7 @@ impl MainNodeUpdaterInner { #[derive(Debug)] pub struct L1UpdaterInner { pub bridge_address_updater: BridgeAddressesHandle, - pub l1_eth_client: Box>, + pub l1_eth_client: Box, pub bridgehub_addr: Address, pub update_interval: Option, pub bridgehub_abi: Contract, @@ -49,13 +49,13 @@ impl L1UpdaterInner { async fn get_shared_bridge_info(&self) -> Result { let l1_shared_bridge_addr: Address = CallFunctionArgs::new("sharedBridge", ()) .for_contract(self.bridgehub_addr, &self.bridgehub_abi) - .call(&self.l1_eth_client) + .call(self.l1_eth_client.as_ref()) .await?; let l1_nullifier_addr: Result = CallFunctionArgs::new("L1_NULLIFIER", ()) .for_contract(l1_shared_bridge_addr, &self.l1_asset_router_abi) - .call(&self.l1_eth_client) + .call(self.l1_eth_client.as_ref()) .await; // In case we can successfully retrieve the l1 nullifier, this is definitely the new l1 asset router. diff --git a/core/node/node_framework/src/implementations/layers/web3_api/server/mod.rs b/core/node/node_framework/src/implementations/layers/web3_api/server/mod.rs index b1d9ca79979e..680b15422408 100644 --- a/core/node/node_framework/src/implementations/layers/web3_api/server/mod.rs +++ b/core/node/node_framework/src/implementations/layers/web3_api/server/mod.rs @@ -7,7 +7,7 @@ use zksync_circuit_breaker::replication_lag::ReplicationLagChecker; use zksync_config::configs::api::MaxResponseSize; use zksync_contracts::{bridgehub_contract, l1_asset_router_contract}; use zksync_node_api_server::web3::{ - state::{BridgeAddressesHandle, InternalApiConfig, SealedL2BlockNumber}, + state::{BridgeAddressesHandle, InternalApiConfigBuilder, SealedL2BlockNumber}, ApiBuilder, ApiServer, Namespace, }; @@ -18,6 +18,7 @@ use crate::{ }, resources::{ circuit_breakers::CircuitBreakersResource, + contracts::{L1ChainContractsResource, L1EcosystemContractsResource}, eth_interface::EthInterfaceResource, healthcheck::AppHealthCheckResource, main_node_client::MainNodeClientResource, @@ -115,8 +116,8 @@ enum Transport { pub struct Web3ServerLayer { transport: Transport, port: u16, - internal_api_config: InternalApiConfig, optional_config: Web3ServerOptionalConfig, + internal_api_config_builder: InternalApiConfigBuilder, } #[derive(Debug, FromContext)] @@ -132,7 +133,9 @@ pub struct Input { #[context(default)] pub app_health: AppHealthCheckResource, pub main_node_client: Option, - pub l1_eth_client: EthInterfaceResource, + pub l1_client: EthInterfaceResource, + pub contracts_resource: L1ChainContractsResource, + pub l1_ecosystem_contracts_resource: L1EcosystemContractsResource, } #[derive(Debug, IntoContext)] @@ -151,27 +154,27 @@ pub struct Output { impl Web3ServerLayer { pub fn http( port: u16, - internal_api_config: InternalApiConfig, + internal_api_config_builder: InternalApiConfigBuilder, optional_config: Web3ServerOptionalConfig, ) -> Self { Self { transport: Transport::Http, port, - internal_api_config, optional_config, + internal_api_config_builder, } } pub fn ws( port: u16, - internal_api_config: InternalApiConfig, + internal_api_config_builder: InternalApiConfigBuilder, optional_config: Web3ServerOptionalConfig, ) -> Self { Self { transport: Transport::Ws, port, - internal_api_config, optional_config, + internal_api_config_builder, } } } @@ -198,9 +201,15 @@ impl WiringLayer for Web3ServerLayer { let sync_state = input.sync_state.map(|state| state.0); let tree_api_client = input.tree_api_client.map(|client| client.0); + let contracts = input.contracts_resource.0; + let internal_api_config = self + .internal_api_config_builder + .with_contracts(contracts, input.l1_ecosystem_contracts_resource.0) + .build(); + let sealed_l2_block_handle = SealedL2BlockNumber::default(); let bridge_addresses_handle = - BridgeAddressesHandle::new(self.internal_api_config.bridge_addresses.clone()); + BridgeAddressesHandle::new(internal_api_config.bridge_addresses.clone()); let sealed_l2_block_updater_task = SealedL2BlockUpdaterTask { number_updater: sealed_l2_block_handle.clone(), @@ -219,9 +228,8 @@ impl WiringLayer for Web3ServerLayer { } else { BridgeAddressesUpdaterTask::L1Updater(L1UpdaterInner { bridge_address_updater: bridge_addresses_handle.clone(), - l1_eth_client: input.l1_eth_client.0, - bridgehub_addr: self - .internal_api_config + l1_eth_client: Box::new(input.l1_client.0), + bridgehub_addr: internal_api_config .l1_bridgehub_proxy_addr .context("Lacking l1 bridgehub proxy address")?, update_interval: self.optional_config.bridge_addresses_refresh_interval, @@ -232,7 +240,7 @@ impl WiringLayer for Web3ServerLayer { // Build server. let mut api_builder = - ApiBuilder::jsonrpsee_backend(self.internal_api_config, replica_pool.clone()) + ApiBuilder::jsonrpsee_backend(internal_api_config, replica_pool.clone()) .with_tx_sender(tx_sender) .with_mempool_cache(mempool_cache) .with_extended_tracing(self.optional_config.with_extended_tracing) diff --git a/core/node/node_framework/src/implementations/layers/web3_api/tx_sender.rs b/core/node/node_framework/src/implementations/layers/web3_api/tx_sender.rs index 023ef1059c79..2b24cd8fc29e 100644 --- a/core/node/node_framework/src/implementations/layers/web3_api/tx_sender.rs +++ b/core/node/node_framework/src/implementations/layers/web3_api/tx_sender.rs @@ -1,9 +1,10 @@ use std::{sync::Arc, time::Duration}; use tokio::sync::RwLock; +use zksync_config::configs::chain::TimestampAsserterConfig; use zksync_node_api_server::{ execution_sandbox::{VmConcurrencyBarrier, VmConcurrencyLimiter}, - tx_sender::{SandboxExecutorOptions, TxSenderBuilder, TxSenderConfig}, + tx_sender::{SandboxExecutorOptions, TimestampAsserterParams, TxSenderBuilder, TxSenderConfig}, }; use zksync_state::{PostgresStorageCaches, PostgresStorageCachesTask}; use zksync_types::{vm::FastVmMode, AccountTreeId, Address}; @@ -15,6 +16,7 @@ use zksync_web3_decl::{ use crate::{ implementations::resources::{ + contracts::SettlementLayerContractsResource, fee_input::ApiFeeInputResource, main_node_client::MainNodeClientResource, pools::{PoolResource, ReplicaPool}, @@ -56,11 +58,12 @@ pub struct PostgresStorageCachesConfig { /// - `WhitelistedTokensForAaUpdateTask` (optional) #[derive(Debug)] pub struct TxSenderLayer { - tx_sender_config: TxSenderConfig, postgres_storage_caches_config: PostgresStorageCachesConfig, max_vm_concurrency: usize, whitelisted_tokens_for_aa_cache: bool, vm_mode: FastVmMode, + timestamp_asserter_config: Option, + tx_sender_config: TxSenderConfig, } #[derive(Debug, FromContext)] @@ -71,6 +74,7 @@ pub struct Input { pub fee_input: ApiFeeInputResource, pub main_node_client: Option, pub sealer: Option, + pub contracts_resource: SettlementLayerContractsResource, } #[derive(Debug, IntoContext)] @@ -87,16 +91,18 @@ pub struct Output { impl TxSenderLayer { pub fn new( - tx_sender_config: TxSenderConfig, postgres_storage_caches_config: PostgresStorageCachesConfig, max_vm_concurrency: usize, + tx_sender_config: TxSenderConfig, + timestamp_asserter_config: Option, ) -> Self { Self { - tx_sender_config, postgres_storage_caches_config, max_vm_concurrency, whitelisted_tokens_for_aa_cache: false, vm_mode: FastVmMode::Old, + timestamp_asserter_config, + tx_sender_config, } } @@ -132,6 +138,27 @@ impl WiringLayer for TxSenderLayer { let sealer = input.sealer.map(|s| s.0); let fee_input = input.fee_input.0; + let config = match input + .contracts_resource + .0 + .l2_contracts + .timestamp_asserter_addr + { + Some(address) => { + let timestamp_asserter_config = + self.timestamp_asserter_config.expect("Should be presented"); + + self.tx_sender_config + .with_timestamp_asserter_params(TimestampAsserterParams { + address, + min_time_till_end: Duration::from_secs( + timestamp_asserter_config.min_time_till_end_sec.into(), + ), + }) + } + None => self.tx_sender_config, + }; + // Initialize Postgres caches. let factory_deps_capacity = self.postgres_storage_caches_config.factory_deps_cache_size; let initial_writes_capacity = self @@ -158,7 +185,7 @@ impl WiringLayer for TxSenderLayer { VmConcurrencyLimiter::new(self.max_vm_concurrency); // TODO (BFT-138): Allow to dynamically reload API contracts - let config = self.tx_sender_config; + let mut executor_options = SandboxExecutorOptions::new( config.chain_id, AccountTreeId::new(config.fee_account_addr), diff --git a/core/node/node_framework/src/implementations/resources/contracts.rs b/core/node/node_framework/src/implementations/resources/contracts.rs index 67f6074c19b8..91f98c6e4177 100644 --- a/core/node/node_framework/src/implementations/resources/contracts.rs +++ b/core/node/node_framework/src/implementations/resources/contracts.rs @@ -1,12 +1,39 @@ -use zksync_config::configs::gateway::GatewayChainConfig; +use zksync_config::configs::contracts::{ecosystem::L1SpecificContracts, ChainSpecificContracts}; use crate::Resource; #[derive(Debug, Clone)] -pub struct ContractsResource(pub GatewayChainConfig); +pub struct SettlementLayerContractsResource(pub ChainSpecificContracts); -impl Resource for ContractsResource { +impl Resource for SettlementLayerContractsResource { fn name() -> String { - "common/contracts".into() + "common/sl_layer_contracts".into() + } +} + +#[derive(Debug, Clone)] +pub struct L1EcosystemContractsResource(pub L1SpecificContracts); + +impl Resource for L1EcosystemContractsResource { + fn name() -> String { + "common/l1_ecosystem_contracts".into() + } +} + +#[derive(Debug, Clone)] +pub struct L1ChainContractsResource(pub ChainSpecificContracts); + +impl Resource for L1ChainContractsResource { + fn name() -> String { + "common/l1_contracts".into() + } +} + +#[derive(Debug, Clone)] +pub struct GatewayChainContractsResource(pub ChainSpecificContracts); + +impl Resource for GatewayChainContractsResource { + fn name() -> String { + "common/gateway_chain_contracts".into() } } diff --git a/core/node/node_framework/src/implementations/resources/eth_interface.rs b/core/node/node_framework/src/implementations/resources/eth_interface.rs index f1bc17027f90..73a4a40e14b6 100644 --- a/core/node/node_framework/src/implementations/resources/eth_interface.rs +++ b/core/node/node_framework/src/implementations/resources/eth_interface.rs @@ -1,4 +1,4 @@ -use zksync_eth_client::BoundEthInterface; +use zksync_eth_client::{BoundEthInterface, EthInterface}; use zksync_web3_decl::client::{DynClient, L1, L2}; use crate::resource::Resource; @@ -14,11 +14,26 @@ impl Resource for EthInterfaceResource { } #[derive(Debug, Clone)] -pub struct GatewayEthInterfaceResource(pub Box>); +pub enum UniversalClient { + L1(Box>), + L2(Box>), +} + +impl From for Box { + fn from(value: UniversalClient) -> Self { + match value { + UniversalClient::L1(client) => Box::new(client), + UniversalClient::L2(client) => Box::new(client), + } + } +} + +#[derive(Debug, Clone)] +pub struct UniversalClientResource(pub UniversalClient); -impl Resource for GatewayEthInterfaceResource { +impl Resource for UniversalClientResource { fn name() -> String { - "common/gateway_eth_interface".into() + "common/universal_client_gateway".into() } } diff --git a/core/node/node_framework/src/implementations/resources/settlement_layer.rs b/core/node/node_framework/src/implementations/resources/settlement_layer.rs index 75ebc828d916..575af13f5bb7 100644 --- a/core/node/node_framework/src/implementations/resources/settlement_layer.rs +++ b/core/node/node_framework/src/implementations/resources/settlement_layer.rs @@ -1,12 +1,21 @@ -use zksync_types::settlement::SettlementMode; +use zksync_types::{settlement::SettlementMode, SLChainId}; use crate::Resource; #[derive(Debug, Clone)] pub struct SettlementModeResource(pub SettlementMode); +#[derive(Debug, Clone)] +pub struct SlChainIdResource(pub SLChainId); + impl Resource for SettlementModeResource { fn name() -> String { "common/settlement_mode".into() } } + +impl Resource for SlChainIdResource { + fn name() -> String { + "common/sl_chain_id".into() + } +} diff --git a/core/node/node_storage_init/src/main_node/genesis.rs b/core/node/node_storage_init/src/main_node/genesis.rs index cef25e87ba7c..08410cf8c7b2 100644 --- a/core/node/node_storage_init/src/main_node/genesis.rs +++ b/core/node/node_storage_init/src/main_node/genesis.rs @@ -2,7 +2,7 @@ use std::fs::File; use anyhow::Context as _; use tokio::sync::watch; -use zksync_config::{ContractsConfig, GenesisConfig}; +use zksync_config::{configs::contracts::ChainSpecificContracts, GenesisConfig}; use zksync_dal::{ConnectionPool, Core, CoreDal as _}; use zksync_node_genesis::GenesisParams; use zksync_object_store::bincode; @@ -13,7 +13,7 @@ use crate::traits::InitializeStorage; #[derive(Debug)] pub struct MainNodeGenesis { pub genesis: GenesisConfig, - pub contracts: ContractsConfig, + pub contracts: ChainSpecificContracts, pub l1_client: Box>, pub pool: ConnectionPool, } @@ -36,7 +36,7 @@ impl InitializeStorage for MainNodeGenesis { zksync_node_genesis::validate_genesis_params( ¶ms, &self.l1_client, - self.contracts.diamond_proxy_addr, + self.contracts.chain_contracts_config.diamond_proxy_addr, ) .await?; @@ -58,7 +58,7 @@ impl InitializeStorage for MainNodeGenesis { zksync_node_genesis::save_set_chain_id_tx( &mut storage, &self.l1_client, - self.contracts.diamond_proxy_addr, + self.contracts.chain_contracts_config.diamond_proxy_addr, ) .await .context("Failed to save SetChainId upgrade transaction")?; diff --git a/core/node/node_sync/src/tree_data_fetcher/mod.rs b/core/node/node_sync/src/tree_data_fetcher/mod.rs index 9f8ac18c39bd..52f808c3acdd 100644 --- a/core/node/node_sync/src/tree_data_fetcher/mod.rs +++ b/core/node/node_sync/src/tree_data_fetcher/mod.rs @@ -8,13 +8,14 @@ use serde::Serialize; use tokio::sync::mpsc; use tokio::sync::watch; use zksync_dal::{Connection, ConnectionPool, Core, CoreDal, DalError}; +use zksync_eth_client::EthInterface; use zksync_health_check::{Health, HealthStatus, HealthUpdater, ReactiveHealthCheck}; use zksync_types::{ block::{L1BatchTreeData, L2BlockHeader}, - Address, L1BatchNumber, L2ChainId, + Address, L1BatchNumber, }; use zksync_web3_decl::{ - client::{DynClient, L1, L2}, + client::{DynClient, L2}, error::EnrichedClientError, }; @@ -129,24 +130,15 @@ impl TreeDataFetcher { /// which may not be committed on L1. pub async fn with_l1_data( mut self, - l1_client: Box>, + l1_client: Box, l1_diamond_proxy_addr: Address, - gateway_client: Option>>, - l2_chain_id: L2ChainId, ) -> anyhow::Result { anyhow::ensure!( self.diamond_proxy_address.is_none(), "L1 tree data provider is already set up" ); - let l1_provider = L1DataProvider::new( - l1_client.for_component("tree_data_fetcher"), - l1_diamond_proxy_addr, - gateway_client.map(|c| c.for_component("tree_data_fetcher")), - self.pool.clone(), - l2_chain_id, - ) - .await?; + let l1_provider = L1DataProvider::new(l1_client, l1_diamond_proxy_addr).await?; self.data_provider.set_l1(l1_provider); self.diamond_proxy_address = Some(l1_diamond_proxy_addr); Ok(self) diff --git a/core/node/node_sync/src/tree_data_fetcher/provider/mod.rs b/core/node/node_sync/src/tree_data_fetcher/provider/mod.rs index c627006f70e7..48741015f91e 100644 --- a/core/node/node_sync/src/tree_data_fetcher/provider/mod.rs +++ b/core/node/node_sync/src/tree_data_fetcher/provider/mod.rs @@ -2,15 +2,12 @@ use std::fmt; use anyhow::Context; use async_trait::async_trait; -use zksync_contracts::bridgehub_contract; -use zksync_dal::{ConnectionPool, Core, CoreDal}; -use zksync_eth_client::{CallFunctionArgs, EthInterface}; -use zksync_system_constants::L2_BRIDGEHUB_ADDRESS; +use zksync_eth_client::EthInterface; use zksync_types::{ - block::L2BlockHeader, web3, Address, L1BatchNumber, L2ChainId, SLChainId, H256, U256, U64, + block::L2BlockHeader, web3, Address, L1BatchNumber, SLChainId, H256, U256, U64, }; use zksync_web3_decl::{ - client::{DynClient, L1, L2}, + client::{DynClient, L2}, error::{ClientRpcContext, EnrichedClientError, EnrichedClientResult}, jsonrpsee::core::ClientError, namespaces::ZksNamespaceClient, @@ -18,7 +15,7 @@ use zksync_web3_decl::{ use super::{ metrics::{ProcessingStage, TreeDataProviderSource, METRICS}, - TreeDataFetcherError, TreeDataFetcherResult, + TreeDataFetcherResult, }; #[cfg(test)] @@ -99,7 +96,7 @@ struct PastL1BatchInfo { #[derive(Debug)] struct SLChainAccess { - client: Box>, + client: Box, chain_id: SLChainId, diamond_proxy_addr: Address, } @@ -116,11 +113,9 @@ struct SLChainAccess { /// (provided it's not too far behind the seal timestamp of the batch). #[derive(Debug)] pub(super) struct L1DataProvider { - l1_chain_data: SLChainAccess, - gateway_chain_data: Option, + chain_data: SLChainAccess, block_commit_signature: H256, past_l1_batch: Option, - pool: ConnectionPool, } impl L1DataProvider { @@ -131,45 +126,23 @@ impl L1DataProvider { const L1_BLOCK_RANGE: U64 = U64([20_000]); pub async fn new( - l1_client: Box>, + l1_client: Box, l1_diamond_proxy_addr: Address, - gateway_client: Option>>, - pool: ConnectionPool, - l2_chain_id: L2ChainId, ) -> anyhow::Result { let l1_chain_id = l1_client.fetch_chain_id().await?; - let l1_chain_data = SLChainAccess { + let chain_data = SLChainAccess { client: l1_client, chain_id: l1_chain_id, diamond_proxy_addr: l1_diamond_proxy_addr, }; - let gateway_chain_data = if let Some(client) = gateway_client { - let gateway_diamond_proxy = CallFunctionArgs::new( - "getZKChain", - zksync_types::ethabi::Token::Uint(l2_chain_id.as_u64().into()), - ) - .for_contract(L2_BRIDGEHUB_ADDRESS, &bridgehub_contract()) - .call(&client) - .await?; - let chain_id = client.fetch_chain_id().await?; - Some(SLChainAccess { - client, - chain_id, - diamond_proxy_addr: gateway_diamond_proxy, - }) - } else { - None - }; let block_commit_signature = zksync_contracts::hyperchain_contract() .event("BlockCommit") .context("missing `BlockCommit` event")? .signature(); Ok(Self { - l1_chain_data, - gateway_chain_data, + chain_data, block_commit_signature, past_l1_batch: None, - pool, }) } @@ -227,16 +200,6 @@ impl L1DataProvider { })?; Ok((number, block.timestamp)) } - - fn chain_data_by_id(&self, searched_chain_id: SLChainId) -> Option<&SLChainAccess> { - if searched_chain_id == self.l1_chain_data.chain_id { - Some(&self.l1_chain_data) - } else if Some(searched_chain_id) == self.gateway_chain_data.as_ref().map(|d| d.chain_id) { - self.gateway_chain_data.as_ref() - } else { - None - } - } } #[async_trait] @@ -246,34 +209,13 @@ impl TreeDataProvider for L1DataProvider { number: L1BatchNumber, last_l2_block: &L2BlockHeader, ) -> TreeDataProviderResult { - let sl_chain_id = self - .pool - .connection_tagged("tree_data_fetcher") - .await - .map_err(|err| TreeDataFetcherError::Internal(err.into()))? - .eth_sender_dal() - .get_batch_commit_chain_id(number) - .await - .map_err(|err| TreeDataFetcherError::Internal(err.into()))?; - let chain_data = match sl_chain_id { - Some(chain_id) => { - let Some(chain_data) = self.chain_data_by_id(chain_id) else { - return Err(TreeDataFetcherError::Internal(anyhow::anyhow!( - "failed to find client for chain id {chain_id}" - ))); - }; - chain_data - } - None => &self.l1_chain_data, - }; - let l1_batch_seal_timestamp = last_l2_block.timestamp; let from_block = self.past_l1_batch.and_then(|info| { assert!( info.number < number, "`batch_details()` must be called with monotonically increasing numbers" ); - if info.chain_id != chain_data.chain_id { + if info.chain_id != self.chain_data.chain_id { return None; } let threshold_timestamp = info.l1_commit_block_timestamp + Self::L1_BLOCK_RANGE.as_u64() / 2; @@ -293,9 +235,11 @@ impl TreeDataProvider for L1DataProvider { let from_block = match from_block { Some(number) => number, None => { - let (approximate_block, steps) = - Self::guess_l1_commit_block_number(&chain_data.client, l1_batch_seal_timestamp) - .await?; + let (approximate_block, steps) = Self::guess_l1_commit_block_number( + self.chain_data.client.as_ref(), + l1_batch_seal_timestamp, + ) + .await?; tracing::debug!( number = number.0, "Guessed L1 block number for L1 batch #{number} commit in {steps} binary search steps: {approximate_block}" @@ -310,7 +254,7 @@ impl TreeDataProvider for L1DataProvider { let number_topic = H256::from_low_u64_be(number.0.into()); let filter = web3::FilterBuilder::default() - .address(vec![chain_data.diamond_proxy_addr]) + .address(vec![self.chain_data.diamond_proxy_addr]) .from_block(web3::BlockNumber::Number(from_block)) .to_block(web3::BlockNumber::Number(from_block + Self::L1_BLOCK_RANGE)) .topics( @@ -320,7 +264,7 @@ impl TreeDataProvider for L1DataProvider { None, ) .build(); - let mut logs = chain_data.client.logs(&filter).await?; + let mut logs = self.chain_data.client.logs(&filter).await?; logs.retain(|log| !log.is_removed() && log.block_number.is_some()); match logs.as_slice() { @@ -341,7 +285,8 @@ impl TreeDataProvider for L1DataProvider { {diff} block(s) after the `from` block from the filter" ); - let l1_commit_block = chain_data + let l1_commit_block = self + .chain_data .client .block(l1_commit_block_number.into()) .await?; @@ -354,7 +299,7 @@ impl TreeDataProvider for L1DataProvider { number, l1_commit_block_number, l1_commit_block_timestamp: l1_commit_block.timestamp, - chain_id: chain_data.chain_id, + chain_id: self.chain_data.chain_id, }); Ok(Ok(root_hash)) } diff --git a/core/node/node_sync/src/tree_data_fetcher/provider/tests.rs b/core/node/node_sync/src/tree_data_fetcher/provider/tests.rs index 14ab34bab10d..6b9d24b3c8d7 100644 --- a/core/node/node_sync/src/tree_data_fetcher/provider/tests.rs +++ b/core/node/node_sync/src/tree_data_fetcher/provider/tests.rs @@ -3,16 +3,18 @@ use assert_matches::assert_matches; use once_cell::sync::Lazy; use test_casing::test_casing; -use zksync_dal::{Connection, ConnectionPool, Core}; +use zksync_contracts::bridgehub_contract; +use zksync_dal::{Connection, ConnectionPool, Core, CoreDal}; use zksync_node_genesis::{insert_genesis_batch, GenesisParams}; use zksync_node_test_utils::create_l2_block; +use zksync_system_constants::L2_BRIDGEHUB_ADDRESS; use zksync_types::{ aggregated_operations::AggregatedActionType, api, ethabi, web3::{BlockId, CallRequest}, L2BlockNumber, ProtocolVersionId, }; -use zksync_web3_decl::client::MockClient; +use zksync_web3_decl::client::{MockClient, L1}; use super::*; use crate::tree_data_fetcher::tests::{ @@ -308,19 +310,10 @@ async fn guessing_l1_commit_block_number() { } } -async fn create_l1_data_provider( - l1_client: Box>, - pool: ConnectionPool, -) -> L1DataProvider { - L1DataProvider::new( - l1_client, - L1_DIAMOND_PROXY_ADDRESS, - None, - pool, - L2ChainId::new(ERA_CHAIN_ID).unwrap(), - ) - .await - .unwrap() +async fn create_l1_data_provider(l1_client: Box>) -> L1DataProvider { + L1DataProvider::new(Box::new(l1_client), L1_DIAMOND_PROXY_ADDRESS) + .await + .unwrap() } async fn test_using_l1_data_provider(l1_batch_timestamps: &[u64]) { @@ -337,7 +330,7 @@ async fn test_using_l1_data_provider(l1_batch_timestamps: &[u64]) { eth_params.push_commit(number, ts + 1_000); // have a reasonable small diff between batch generation and commitment } - let mut provider = create_l1_data_provider(Box::new(eth_params.client()), pool.clone()).await; + let mut provider = create_l1_data_provider(Box::new(eth_params.client())).await; for i in 0..l1_batch_timestamps.len() { let number = L1BatchNumber(i as u32 + 1); let root_hash = provider @@ -398,15 +391,10 @@ async fn using_different_settlement_layers() { params_array[sl_idx].push_commit(number, ts + 1_000); // have a reasonable small diff between batch generation and commitment } - let mut provider = L1DataProvider::new( - Box::new(params_array[0].client()), - L1_DIAMOND_PROXY_ADDRESS, - Some(Box::new(params_array[1].client())), - pool, - L2ChainId::new(ERA_CHAIN_ID).unwrap(), - ) - .await - .unwrap(); + let mut provider = + L1DataProvider::new(Box::new(params_array[0].client()), L1_DIAMOND_PROXY_ADDRESS) + .await + .unwrap(); for i in 0..batch_commit_info.len() { let number = L1BatchNumber(i as u32 + 1); let root_hash = provider @@ -435,7 +423,6 @@ async fn using_different_settlement_layers() { #[tokio::test] async fn detecting_reorg_in_l1_data_provider() { let l1_batch_number = H256::from_low_u64_be(1); - let pool = ConnectionPool::::test_pool().await; // Generate two logs for the same L1 batch #1 let logs = vec![ web3::Log { @@ -463,7 +450,7 @@ async fn detecting_reorg_in_l1_data_provider() { ]; let l1_client = mock_l1_client(200.into(), logs, SLChainId(9)); - let mut provider = create_l1_data_provider(Box::new(l1_client), pool.clone()).await; + let mut provider = create_l1_data_provider(Box::new(l1_client)).await; let output = provider .batch_details(L1BatchNumber(1), &create_l2_block(1)) .await @@ -487,7 +474,7 @@ async fn combined_data_provider_errors() { let mut main_node_client = MockMainNodeClient::default(); main_node_client.insert_batch(L1BatchNumber(2), H256::repeat_byte(2)); let mut provider = CombinedDataProvider::new(main_node_client); - let l1_provider = create_l1_data_provider(Box::new(eth_params.client()), pool.clone()).await; + let l1_provider = create_l1_data_provider(Box::new(eth_params.client())).await; provider.set_l1(l1_provider); // L1 batch #1 should be obtained from L1 diff --git a/core/node/node_sync/src/validate_chain_ids_task.rs b/core/node/node_sync/src/validate_chain_ids_task.rs index 9dcdba9134c8..760459780f04 100644 --- a/core/node/node_sync/src/validate_chain_ids_task.rs +++ b/core/node/node_sync/src/validate_chain_ids_task.rs @@ -20,7 +20,7 @@ pub struct ValidateChainIdsTask { gateway_chain_id: Option, l1_client: Box>, main_node_client: Box>, - gateway_client: Option>>, + gateway_client: Option>, } impl ValidateChainIdsTask { @@ -32,7 +32,7 @@ impl ValidateChainIdsTask { gateway_chain_id: Option, l1_client: Box>, main_node_client: Box>, - gateway_client: Option>>, + gateway_client: Option>, ) -> Self { Self { l1_chain_id, @@ -40,20 +40,20 @@ impl ValidateChainIdsTask { gateway_chain_id, l1_client: l1_client.for_component("chain_ids_validation"), main_node_client: main_node_client.for_component("chain_ids_validation"), - gateway_client: gateway_client.map(|c| c.for_component("chain_ids_validation")), + gateway_client, } } async fn check_client( - l1_client: Option>>, + client: Option>, expected: Option, ) -> anyhow::Result<()> { - let (Some(l1_client), Some(expected)) = (l1_client, expected) else { + let (Some(client), Some(expected)) = (client, expected) else { return Ok(()); }; loop { - match l1_client.fetch_chain_id().await { + match client.fetch_chain_id().await { Ok(chain_id) => { anyhow::ensure!( expected == chain_id, @@ -148,8 +148,10 @@ impl ValidateChainIdsTask { /// Runs the task once, exiting either when all the checks are performed or when the stop signal is received. pub async fn run_once(self, mut stop_receiver: watch::Receiver) -> anyhow::Result<()> { - let l1_client_check = - Self::check_client(Some(self.l1_client), Some(self.l1_chain_id.0.into())); + let l1_client_check = Self::check_client( + Some(Box::new(self.l1_client)), + Some(self.l1_chain_id.0.into()), + ); let main_node_l1_check = Self::check_l1_chain_using_main_node(self.main_node_client.clone(), self.l1_chain_id); let main_node_l2_check = @@ -173,8 +175,11 @@ impl ValidateChainIdsTask { pub async fn run(self, mut stop_receiver: watch::Receiver) -> anyhow::Result<()> { // Since check futures are fused, they are safe to poll after getting resolved; they will never resolve again, // so we'll just wait for another check or a stop signal. - let l1_client_check = - Self::check_client(Some(self.l1_client), Some(self.l1_chain_id.0.into())).fuse(); + let l1_client_check = Self::check_client( + Some(Box::new(self.l1_client)), + Some(self.l1_chain_id.0.into()), + ) + .fuse(); let main_node_l1_check = Self::check_l1_chain_using_main_node(self.main_node_client.clone(), self.l1_chain_id) .fuse(); diff --git a/core/node/state_keeper/src/io/tests/tester.rs b/core/node/state_keeper/src/io/tests/tester.rs index 32a746eecdfb..a7f1b63c68a3 100644 --- a/core/node/state_keeper/src/io/tests/tester.rs +++ b/core/node/state_keeper/src/io/tests/tester.rs @@ -9,7 +9,10 @@ use zksync_config::{ }; use zksync_contracts::BaseSystemContracts; use zksync_dal::{ConnectionPool, Core, CoreDal}; -use zksync_eth_client::{clients::MockSettlementLayer, BaseFees}; +use zksync_eth_client::{ + clients::{DynClient, MockSettlementLayer, L1}, + BaseFees, +}; use zksync_multivm::{ interface::{ tracer::ValidationTraces, TransactionExecutionMetrics, TransactionExecutionResult, @@ -82,11 +85,12 @@ impl Tester { num_samples_for_blob_base_fee_estimate: 10, internal_pubdata_pricing_multiplier: 1.0, max_blob_base_fee: None, - settlement_mode: Default::default(), }; + let client: Box> = Box::new(eth_client.into_client()); + GasAdjuster::new( - GasAdjusterClient::from_l1(Box::new(eth_client.into_client())), + GasAdjusterClient::from(client), gas_adjuster_config, PubdataSendingMode::Calldata, self.commitment_mode, diff --git a/core/tests/loadnext/src/sdk/ethereum/mod.rs b/core/tests/loadnext/src/sdk/ethereum/mod.rs index bbb3514e2a0d..ebf7e9cb0412 100644 --- a/core/tests/loadnext/src/sdk/ethereum/mod.rs +++ b/core/tests/loadnext/src/sdk/ethereum/mod.rs @@ -58,7 +58,7 @@ pub fn l1_erc20_bridge_contract() -> ethabi::Contract { /// via `EthereumProvider::web3` method. #[derive(Debug)] pub struct EthereumProvider { - eth_client: SigningClient, + eth_client: SigningClient, default_bridges: BridgeAddresses, erc20_abi: ethabi::Contract, l1_erc20_bridge_abi: ethabi::Contract, diff --git a/etc/env/file_based/genesis.yaml b/etc/env/file_based/genesis.yaml index 480f798ce4df..91db5d228c64 100644 --- a/etc/env/file_based/genesis.yaml +++ b/etc/env/file_based/genesis.yaml @@ -1,6 +1,6 @@ -genesis_root: 0x7bdb3d822ad837a3611c436d3be457363a08d06d83b74469831482353a7d8277 +genesis_root: 0xb0c55513494d203252aace4605ec22c6a1cd3b04001154043ce31300c40950f0 genesis_rollup_leaf_index: 68 -genesis_batch_commitment: 0x81f5e324a4019e4161fb9dc5058a588aa364a551fdd5c0e8788521e64e7ad596 +genesis_batch_commitment: 0xb5406acbd89f5ebff6304cc2dc5678018a7a717fb4ca9dac3323d9608b357577 genesis_protocol_version: 26 default_aa_hash: 0x010004dbf8be36c421254d005352f8245146906919be0099e8a50d0e78df85e0 bootloader_hash: 0x0100088580465d88420e6369230ee94a32ff356dbcdd407a4be49fc8009b2a81 @@ -8,10 +8,8 @@ l1_chain_id: 9 l2_chain_id: 270 fee_account: '0x0000000000000000000000000000000000000001' prover: - fflonk_snark_wrapper_vk_hash: 0x560b19cfd6bcf1049c6409c18d81db288ab7639db080ed3b48df17ddfbcc4666 dummy_verifier: true snark_wrapper_vk_hash: 0x14f97b81e54b35fe673d8708cc1a19e1ea5b5e348e12d31e39824ed4f42bbca2 + fflonk_snark_wrapper_vk_hash: 0x560b19cfd6bcf1049c6409c18d81db288ab7639db080ed3b48df17ddfbcc4666 genesis_protocol_semantic_version: 0.26.0 l1_batch_commit_data_generator_mode: Rollup -# TODO: uncomment once EVM emulator is present in the `contracts` submodule -# evm_emulator_hash: 0x01000e53aa35d9d19fa99341c2e2901cf93b3668f01569dd5c6ca409c7696b91 diff --git a/zkstack_cli/crates/config/src/chain.rs b/zkstack_cli/crates/config/src/chain.rs index b411b1f882a3..60d8f7dfba77 100644 --- a/zkstack_cli/crates/config/src/chain.rs +++ b/zkstack_cli/crates/config/src/chain.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize, Serializer}; use xshell::Shell; use zkstack_cli_types::{BaseToken, L1BatchCommitmentMode, L1Network, ProverMode, WalletCreation}; use zksync_basic_types::L2ChainId; -use zksync_config::configs::{gateway::GatewayChainConfig, GatewayConfig}; +use zksync_config::configs::{contracts::gateway::GatewayConfig, gateway::GatewayChainConfig}; use crate::{ consts::{ diff --git a/zkstack_cli/crates/config/src/forge_interface/gateway_preparation/input.rs b/zkstack_cli/crates/config/src/forge_interface/gateway_preparation/input.rs index 6c4fc4d764a5..8be292ef495c 100644 --- a/zkstack_cli/crates/config/src/forge_interface/gateway_preparation/input.rs +++ b/zkstack_cli/crates/config/src/forge_interface/gateway_preparation/input.rs @@ -1,7 +1,7 @@ use ethers::utils::hex; use serde::{Deserialize, Serialize}; use zksync_basic_types::{web3::Bytes, Address}; -use zksync_config::configs::GatewayConfig; +use zksync_config::configs::contracts::gateway::GatewayConfig; use crate::{traits::ZkStackConfig, ChainConfig, ContractsConfig}; diff --git a/zkstack_cli/crates/config/src/gateway.rs b/zkstack_cli/crates/config/src/gateway.rs index 67b5ad327cc2..0629c928caed 100644 --- a/zkstack_cli/crates/config/src/gateway.rs +++ b/zkstack_cli/crates/config/src/gateway.rs @@ -1,5 +1,5 @@ use ethers::utils::hex; -use zksync_config::configs::{gateway::GatewayChainConfig, GatewayConfig}; +use zksync_config::configs::{contracts::gateway::GatewayConfig, gateway::GatewayChainConfig}; use crate::{ forge_interface::deploy_gateway_ctm::output::DeployGatewayCTMOutput, diff --git a/zkstack_cli/crates/zkstack/src/commands/chain/convert_to_gateway.rs b/zkstack_cli/crates/zkstack/src/commands/chain/convert_to_gateway.rs index 26c9952f675a..7c6b4c598aca 100644 --- a/zkstack_cli/crates/zkstack/src/commands/chain/convert_to_gateway.rs +++ b/zkstack_cli/crates/zkstack/src/commands/chain/convert_to_gateway.rs @@ -1,5 +1,3 @@ -use std::fmt::format; - use anyhow::Context; use ethers::{abi::parse_abi, contract::BaseContract, types::Bytes, utils::hex}; use lazy_static::lazy_static; @@ -21,7 +19,7 @@ use zkstack_cli_config::{ ChainConfig, EcosystemConfig, }; use zksync_basic_types::H256; -use zksync_config::configs::GatewayConfig; +use zksync_config::configs::gateway::GatewayConfig; use crate::{ messages::MSG_CHAIN_NOT_INITIALIZED, diff --git a/zkstack_cli/crates/zkstack/src/commands/chain/gateway_upgrade.rs b/zkstack_cli/crates/zkstack/src/commands/chain/gateway_upgrade.rs index 793e8b3ae2a6..cf46f89f1727 100644 --- a/zkstack_cli/crates/zkstack/src/commands/chain/gateway_upgrade.rs +++ b/zkstack_cli/crates/zkstack/src/commands/chain/gateway_upgrade.rs @@ -28,12 +28,9 @@ use zkstack_cli_types::L1BatchCommitmentMode; use zksync_basic_types::{Address, U256}; use crate::{ - commands::dev::commands::{ - events_gatherer::DEFAULT_BLOCK_RANGE, - gateway::{ - check_chain_readiness, fetch_chain_info, get_admin_call_builder, - set_upgrade_timestamp_calldata, DAMode, GatewayUpgradeArgsInner, GatewayUpgradeInfo, - }, + commands::dev::commands::gateway::{ + check_chain_readiness, fetch_chain_info, get_admin_call_builder, + set_upgrade_timestamp_calldata, DAMode, GatewayUpgradeArgsInner, GatewayUpgradeInfo, }, messages::MSG_CHAIN_NOT_INITIALIZED, utils::forge::{fill_forge_private_key, WalletOwner}, diff --git a/zkstack_cli/crates/zkstack/src/commands/chain/migrate_from_gateway.rs b/zkstack_cli/crates/zkstack/src/commands/chain/migrate_from_gateway.rs index b2ebcda80a85..dab613038647 100644 --- a/zkstack_cli/crates/zkstack/src/commands/chain/migrate_from_gateway.rs +++ b/zkstack_cli/crates/zkstack/src/commands/chain/migrate_from_gateway.rs @@ -108,9 +108,7 @@ pub async fn run(args: MigrateFromGatewayArgs, shell: &Shell) -> anyhow::Result< ( chain_admin_addr, chain_access_control_restriction.context("chain_access_control_restriction")?, - gateway_chain_chain_config - .chain_admin_addr - .context("l2 chain admin missing")?, + gateway_chain_chain_config.chain_admin_addr, U256::from(chain_config.chain_id.as_u64()), ), ) diff --git a/zkstack_cli/crates/zkstack/src/commands/chain/mod.rs b/zkstack_cli/crates/zkstack/src/commands/chain/mod.rs index a22f736e99e9..5aa9bad784d7 100644 --- a/zkstack_cli/crates/zkstack/src/commands/chain/mod.rs +++ b/zkstack_cli/crates/zkstack/src/commands/chain/mod.rs @@ -5,9 +5,11 @@ use clap::{command, Subcommand}; pub(crate) use create::create_chain_inner; use xshell::Shell; +#[cfg(feature = "gateway")] +use crate::commands::chain::gateway_migration::MigrationDirection; use crate::commands::chain::{ args::create::ChainCreateArgs, deploy_l2_contracts::Deploy2ContractsOption, - gateway_migration::MigrationDirection, genesis::GenesisCommand, init::ChainInitCommand, + genesis::GenesisCommand, init::ChainInitCommand, }; mod accept_chain_ownership; @@ -133,6 +135,7 @@ pub(crate) async fn run(shell: &Shell, args: ChainCommands) -> anyhow::Result<() ChainCommands::NotifyAboutToGatewayUpdate(args) => { gateway_migration::notify_server(args, shell, MigrationDirection::ToGateway).await } + #[cfg(feature = "gateway")] ChainCommands::NotifyAboutFromGatewayUpdate(args) => { gateway_migration::notify_server(args, shell, MigrationDirection::FromGateway).await } diff --git a/zkstack_cli/crates/zkstack/src/commands/dev/commands/gateway_finalize_preparation.rs b/zkstack_cli/crates/zkstack/src/commands/dev/commands/gateway_finalize_preparation.rs index 9d74352a7115..fc3db6d7d563 100644 --- a/zkstack_cli/crates/zkstack/src/commands/dev/commands/gateway_finalize_preparation.rs +++ b/zkstack_cli/crates/zkstack/src/commands/dev/commands/gateway_finalize_preparation.rs @@ -1,8 +1,8 @@ use std::{collections::HashSet, str::FromStr, sync::Arc, time::Duration}; -use clap::{Parser, ValueEnum}; +use clap::Parser; use ethers::{ - abi::{encode, parse_abi, Token}, + abi::parse_abi, contract::{abigen, BaseContract}, providers::{Http, Middleware, Provider}, utils::hex, @@ -12,8 +12,8 @@ use tokio::time::sleep; use xshell::Shell; use zkstack_cli_config::traits::ReadConfig; use zksync_types::{ - ethabi, h256_to_address, h256_to_u256, u256_to_h256, Address, H256, - L2_NATIVE_TOKEN_VAULT_ADDRESS, SHARED_BRIDGE_ETHER_TOKEN_ADDRESS, U256, + h256_to_address, h256_to_u256, u256_to_h256, Address, H256, SHARED_BRIDGE_ETHER_TOKEN_ADDRESS, + U256, }; use super::{events_gatherer::get_logs_for_events, gateway::GatewayUpgradeInfo}; diff --git a/zkstack_cli/crates/zkstack/src/commands/dev/commands/gateway_register_l2_tokens.rs b/zkstack_cli/crates/zkstack/src/commands/dev/commands/gateway_register_l2_tokens.rs index e75241e3ffaa..2a94f1ebb86a 100644 --- a/zkstack_cli/crates/zkstack/src/commands/dev/commands/gateway_register_l2_tokens.rs +++ b/zkstack_cli/crates/zkstack/src/commands/dev/commands/gateway_register_l2_tokens.rs @@ -1,34 +1,8 @@ -use std::{num::NonZeroUsize, str::FromStr, sync::Arc}; - -use anyhow::Context; -use clap::{Parser, ValueEnum}; -use ethers::{ - abi::{encode, parse_abi, Token}, - contract::{abigen, BaseContract}, - providers::{Http, Middleware, Provider}, - signers::Signer, - utils::hex, -}; -use serde::{Deserialize, Serialize}; -use strum::EnumIter; -use xshell::Shell; -use zkstack_cli_config::{ - forge_interface::gateway_ecosystem_upgrade::output::GatewayEcosystemUpgradeOutput, - traits::{ReadConfig, ZkStackConfig}, - ContractsConfig, -}; -use zksync_contracts::{chain_admin_contract, hyperchain_contract, DIAMOND_CUT}; -use zksync_types::{ - ethabi, - url::SensitiveUrl, - web3::{keccak256, Bytes}, - Address, L1BatchNumber, L2BlockNumber, L2ChainId, ProtocolVersionId, H256, - L2_NATIVE_TOKEN_VAULT_ADDRESS, U256, -}; -use zksync_web3_decl::{ - client::{Client, DynClient, L2}, - namespaces::{EthNamespaceClient, UnstableNamespaceClient, ZksNamespaceClient}, -}; +use std::sync::Arc; + +use clap::Parser; +use ethers::{contract::abigen, signers::Signer}; +use zksync_types::{Address, L2_NATIVE_TOKEN_VAULT_ADDRESS}; use super::{ events_gatherer::DEFAULT_BLOCK_RANGE, diff --git a/zkstack_cli/crates/zkstack/src/commands/dev/commands/genesis.rs b/zkstack_cli/crates/zkstack/src/commands/dev/commands/genesis.rs index 29e5f734e528..1acd4fe41701 100644 --- a/zkstack_cli/crates/zkstack/src/commands/dev/commands/genesis.rs +++ b/zkstack_cli/crates/zkstack/src/commands/dev/commands/genesis.rs @@ -17,9 +17,10 @@ pub(crate) async fn run(shell: &Shell) -> anyhow::Result<()> { .load_chain(Some(ecosystem.current_chain().to_string())) .context(MSG_CHAIN_NOT_FOUND_ERR)?; let spinner = Spinner::new(MSG_GENESIS_FILE_GENERATION_STARTED); - let secrets_path = chain.path_to_secrets_config(); + let secrets_path = chain.path_to_secrets_config().canonicalize().unwrap(); let dal = get_core_dal(shell, None).await?; reset_database(shell, ecosystem.link_to_code, dal).await?; + let _dir = shell.push_dir("core"); Cmd::new(cmd!(shell,"cargo run --package genesis_generator --bin genesis_generator -- --config-path={secrets_path}")).run()?; spinner.finish(); Ok(())