Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(toolbox): refactor config to its own crate #2063

Merged
merged 13 commits into from
May 30, 2024
405 changes: 381 additions & 24 deletions zk_toolbox/Cargo.lock

Large diffs are not rendered by default.

7 changes: 6 additions & 1 deletion zk_toolbox/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
[workspace]
members = ["crates/common",
members = [
"crates/common",
"crates/config",
"crates/zk_inception",
"crates/zk_supervisor",
]
Expand All @@ -20,15 +22,18 @@ keywords = ["zk", "cryptography", "blockchain", "ZKStack", "zkSync"]
[workspace.dependencies]
# Local dependencies
common = { path = "crates/common" }
config = { path = "crates/config" }

# External dependencies
alloy-primitives = { version = "0.7.4", features = ["serde", "getrandom", "rand"] }
anyhow = "1.0.82"
clap = { version = "4.4", features = ["derive", "wrap_help"] }
cliclack = "0.2.5"
console = "0.15.8"
ethers = "2.0"
human-panic = "2.0"
once_cell = "1.19.0"
rand = "0.8.5"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_yaml = "0.9"
Expand Down
4 changes: 2 additions & 2 deletions zk_toolbox/crates/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ description.workspace = true
keywords.workspace = true

[dependencies]
alloy-primitives.workspace = true
anyhow.workspace = true
clap.workspace = true
cliclack.workspace = true
Expand All @@ -21,9 +22,8 @@ serde.workspace = true
serde_json.workspace = true
serde_yaml.workspace = true
sqlx.workspace = true
strum.workspace = true
strum_macros.workspace = true
toml.workspace = true
url.workspace = true
xshell.workspace = true
futures.workspace = true
futures.workspace = true
11 changes: 6 additions & 5 deletions zk_toolbox/crates/common/src/ethereum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,21 @@ use ethers::prelude::Signer;
use ethers::{
core::k256::ecdsa::SigningKey,
middleware::MiddlewareBuilder,
prelude::SignerMiddleware,
prelude::{Http, LocalWallet, Provider},
prelude::{SignerMiddleware, H256},
providers::Middleware,
types::{Address, TransactionRequest},
types::{Address as EthersAddress, TransactionRequest},
};
aon marked this conversation as resolved.
Show resolved Hide resolved

use crate::wallets::Wallet;
use alloy_primitives::{Address, B256};

pub fn create_ethers_client(
private_key: H256,
private_key: B256,
l1_rpc: String,
chain_id: Option<u32>,
) -> anyhow::Result<SignerMiddleware<Provider<Http>, ethers::prelude::Wallet<SigningKey>>> {
let mut wallet = LocalWallet::from_bytes(private_key.as_bytes())?;
let mut wallet = LocalWallet::from_bytes(private_key.as_slice())?;
if let Some(chain_id) = chain_id {
wallet = wallet.with_chain_id(chain_id);
}
Expand All @@ -37,7 +38,7 @@ pub async fn distribute_eth(
let mut nonce = client.get_transaction_count(client.address(), None).await?;
for address in addresses {
let tx = TransactionRequest::new()
.to(address)
.to(EthersAddress::from_slice(address.as_slice()))
.value(amount)
.nonce(nonce)
.chain_id(chain_id);
Expand Down
29 changes: 28 additions & 1 deletion zk_toolbox/crates/common/src/files.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,35 @@
use std::path::Path;

use serde::Serialize;
use serde::{de::DeserializeOwned, Serialize};
use xshell::Shell;

pub fn read_yaml_file<T>(shell: &Shell, file_path: impl AsRef<Path>) -> anyhow::Result<T>
where
T: DeserializeOwned,
{
let content = shell.read_file(file_path)?;
let yaml = serde_yaml::from_str(&content)?;
Ok(yaml)
}

pub fn read_toml_file<T>(shell: &Shell, file_path: impl AsRef<Path>) -> anyhow::Result<T>
where
T: DeserializeOwned,
{
let content = shell.read_file(file_path)?;
let toml = toml::from_str(&content)?;
Ok(toml)
}

pub fn read_json_file<T>(shell: &Shell, file_path: impl AsRef<Path>) -> anyhow::Result<T>
where
T: DeserializeOwned,
{
let content = shell.read_file(file_path)?;
let json = serde_json::from_str(&content)?;
Ok(json)
}

pub fn save_yaml_file(
shell: &Shell,
file_path: impl AsRef<Path>,
Expand Down
16 changes: 8 additions & 8 deletions zk_toolbox/crates/common/src/forge.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use std::path::{Path, PathBuf};
use std::str::FromStr;

use alloy_primitives::{hex::ToHex, Address, B256, U256};
use clap::{Parser, ValueEnum};
use ethers::abi::Address;
use ethers::middleware::Middleware;
use ethers::prelude::{LocalWallet, Signer, U256};
use ethers::{abi::AbiEncode, types::H256};
use ethers::prelude::{LocalWallet, Signer};
use serde::{Deserialize, Serialize};
use strum_macros::Display;
use xshell::{cmd, Shell};
Expand Down Expand Up @@ -92,17 +91,17 @@ impl ForgeScript {
}

/// Adds the private key of the deployer account.
pub fn with_private_key(mut self, private_key: H256) -> Self {
pub fn with_private_key(mut self, private_key: B256) -> Self {
self.args.add_arg(ForgeScriptArg::PrivateKey {
private_key: private_key.encode_hex(),
});
self
}
// Do not start the script if balance is not enough
pub fn private_key(&self) -> Option<H256> {
pub fn private_key(&self) -> Option<B256> {
self.args.args.iter().find_map(|a| {
if let ForgeScriptArg::PrivateKey { private_key } = a {
Some(H256::from_str(private_key).unwrap())
Some(B256::from_str(private_key).unwrap())
} else {
None
}
Expand All @@ -121,9 +120,9 @@ impl ForgeScript {

pub fn address(&self) -> Option<Address> {
self.private_key().and_then(|a| {
LocalWallet::from_bytes(a.as_bytes())
LocalWallet::from_bytes(a.as_slice())
.ok()
.map(|a| a.address())
.map(|a| Address::from_slice(a.address().as_bytes()))
})
}

Expand All @@ -136,6 +135,7 @@ impl ForgeScript {
};
let client = create_ethers_client(private_key, rpc_url, None)?;
let balance = client.get_balance(client.address(), None).await?;
let balance = U256::from_limbs(balance.0);
Ok(balance > minimum_value)
}
}
Expand Down
2 changes: 1 addition & 1 deletion zk_toolbox/crates/common/src/slugify.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub fn slugify(data: &str) -> String {
data.trim().replace(" ", "-")
data.trim().replace(' ', "-")
}
26 changes: 13 additions & 13 deletions zk_toolbox/crates/common/src/wallets.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
use alloy_primitives::{Address, B256};
use ethers::{
core::rand::Rng,
signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer},
types::{H160, H256},
};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Wallet {
pub address: H160,
pub private_key: Option<H256>,
pub address: Address,
pub private_key: Option<B256>,
}

impl Wallet {
pub fn random(rng: &mut impl Rng) -> Self {
let private_key = H256(rng.gen());
let local_wallet = LocalWallet::from_bytes(private_key.as_bytes()).unwrap();
let private_key = B256::random_with(rng);
let local_wallet = LocalWallet::from_bytes(private_key.as_slice()).unwrap();

Self {
address: local_wallet.address(),
address: Address::from_slice(local_wallet.address().as_bytes()),
private_key: Some(private_key),
}
}

pub fn new_with_key(private_key: H256) -> Self {
let local_wallet = LocalWallet::from_bytes(private_key.as_bytes()).unwrap();
pub fn new_with_key(private_key: B256) -> Self {
let local_wallet = LocalWallet::from_bytes(private_key.as_slice()).unwrap();
Self {
address: local_wallet.address(),
address: Address::from_slice(local_wallet.address().as_bytes()),
private_key: Some(private_key),
}
}
Expand All @@ -35,14 +35,14 @@ impl Wallet {
.phrase(mnemonic)
.derivation_path(&format!("{}/{}", base_path, index))?
.build()?;
let private_key = H256::from_slice(&wallet.signer().to_bytes());
let private_key = B256::from_slice(&wallet.signer().to_bytes());
Ok(Self::new_with_key(private_key))
}

pub fn empty() -> Self {
Self {
address: H160::zero(),
private_key: Some(H256::zero()),
address: Address::ZERO,
private_key: Some(B256::ZERO),
}
}
}
Expand All @@ -57,7 +57,7 @@ fn test_load_localhost_wallets() {
.unwrap();
assert_eq!(
wallet.address,
H160::from_slice(
Address::from_slice(
&ethers::utils::hex::decode("0xa61464658AfeAf65CccaaFD3a512b69A83B77618").unwrap()
)
);
Expand Down
25 changes: 25 additions & 0 deletions zk_toolbox/crates/config/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[package]
name = "config"
version.workspace = true
edition.workspace = true
homepage.workspace = true
license.workspace = true
authors.workspace = true
exclude.workspace = true
repository.workspace = true
description.workspace = true
keywords.workspace = true

[dependencies]
alloy-primitives.workspace = true
anyhow.workspace = true
clap.workspace = true
common.workspace = true
rand.workspace = true
serde.workspace = true
serde_json.workspace = true
strum.workspace = true
strum_macros.workspace = true
thiserror.workspace = true
url.workspace = true
xshell.workspace = true
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ use serde::{Deserialize, Serialize, Serializer};
use xshell::Shell;

use crate::{
configs::{ContractsConfig, GenesisConfig, ReadConfig, SaveConfig, WalletsConfig},
consts::{CONTRACTS_FILE, GENESIS_FILE, L1_CONTRACTS_FOUNDRY, WALLETS_FILE},
types::{BaseToken, ChainId, L1BatchCommitDataGeneratorMode, L1Network, ProverMode},
wallets::{create_localhost_wallets, WalletCreation},
create_localhost_wallets,
forge_interface::consts::{CONTRACTS_FILE, GENESIS_FILE, L1_CONTRACTS_FOUNDRY, WALLETS_FILE},
traits::{ReadConfig, SaveConfig},
BaseToken, ChainId, ContractsConfig, GenesisConfig, L1BatchCommitDataGeneratorMode, L1Network,
ProverMode, WalletCreation, WalletsConfig,
};

/// Chain configuration file. This file is created in the chain
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use ethers::{addressbook::Address, types::H256};
use serde::{Deserialize, Serialize};

use crate::configs::{
forge_interface::deploy_ecosystem::output::DeployL1Output, ReadConfig, SaveConfig,
use crate::{
forge_interface::deploy_ecosystem::output::DeployL1Output,
traits::{ReadConfig, SaveConfig},
};
use alloy_primitives::{Address, B256};

#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct ContractsConfig {
pub create2_factory_addr: Address,
pub create2_factory_salt: H256,
pub create2_factory_salt: B256,
pub ecosystem_contracts: EcosystemContracts,
pub bridges: BridgesContracts,
pub l1: L1Contracts,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,15 @@ use thiserror::Error;
use xshell::Shell;

use crate::{
configs::{
forge_interface::deploy_ecosystem::input::{
Erc20DeploymentConfig, InitialDeploymentConfig,
},
ChainConfig, ChainConfigInternal, ContractsConfig, ReadConfig, SaveConfig, WalletsConfig,
},
consts::{
create_localhost_wallets,
forge_interface::consts::{
CONFIG_NAME, CONTRACTS_FILE, ERC20_DEPLOYMENT_FILE, INITIAL_DEPLOYMENT_FILE,
L1_CONTRACTS_FOUNDRY, WALLETS_FILE,
},
types::{ChainId, L1Network, ProverMode},
wallets::{create_localhost_wallets, WalletCreation},
forge_interface::deploy_ecosystem::input::{Erc20DeploymentConfig, InitialDeploymentConfig},
miscellaneous::{ChainId, L1Network, ProverMode},
traits::{ReadConfig, SaveConfig},
ChainConfig, ChainConfigInternal, ContractsConfig, WalletCreation, WalletsConfig,
};

/// Ecosystem configuration file. This file is created in the chain
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use ethers::prelude::Address;
use crate::traits::{ReadConfig, SaveConfig};
use alloy_primitives::Address;
use serde::{Deserialize, Serialize};

use crate::configs::{ReadConfig, SaveConfig};

impl ReadConfig for AcceptOwnershipInput {}
impl SaveConfig for AcceptOwnershipInput {}

Expand Down
Loading
Loading