Skip to content

Commit 4da8b5f

Browse files
committed
start anvil
1 parent 15afa21 commit 4da8b5f

File tree

8 files changed

+159
-66
lines changed

8 files changed

+159
-66
lines changed

Cargo.lock

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

protocol-units/da/m1/setup/src/local.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
1+
use crate::M1DaLightNodeSetupOperations;
2+
use celestia_types::nmt::Namespace;
13
use commander::run_command;
24
use dot_movement::DotMovement;
5+
use rand::Rng;
36
use tokio::fs;
47
use tracing::info;
5-
use celestia_types::nmt::Namespace;
6-
use crate::M1DaLightNodeSetupOperations;
7-
use rand::Rng;
88

99
#[derive(Debug, Clone)]
1010
pub struct Local;
1111

1212
impl Local {
13-
1413
pub fn new() -> Self {
1514
Self
1615
}

protocol-units/settlement/mcr/client/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ alloy-transport-ws = { workspace = true }
2727
anyhow = { workspace = true }
2828
async-stream = { workspace = true }
2929
async-trait = { workspace = true }
30+
serde_json = { workspace = true }
3031
movement-types = { workspace = true }
3132
thiserror = { workspace = true }
3233
tokio = { workspace = true }
@@ -37,7 +38,6 @@ tracing-subscriber = { workspace = true }
3738
[dev-dependencies]
3839
alloy-rpc-types = { workspace = true }
3940
futures = { workspace = true }
40-
serde_json = { workspace = true }
4141

4242
[features]
4343
default = ["eth"]
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
pub mod mcr;
22
// pub mod staking;
3+
pub mod utils;

protocol-units/settlement/mcr/client/src/eth_client.rs

+50-49
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,6 @@ use crate::send_eth_tx::SendTxErrorRule;
33
use crate::send_eth_tx::UnderPriced;
44
use crate::send_eth_tx::VerifyRule;
55
use crate::{CommitmentStream, McrSettlementClientOperations};
6-
use mcr_settlement_config::Config;
7-
use movement_types::BlockCommitment;
8-
use movement_types::{Commitment, Id};
9-
106
use alloy::pubsub::PubSubFrontend;
117
use alloy_network::Ethereum;
128
use alloy_network::EthereumSigner;
@@ -24,13 +20,17 @@ use alloy_signer_wallet::LocalWallet;
2420
use alloy_sol_types::sol;
2521
use alloy_transport::BoxTransport;
2622
use alloy_transport_ws::WsConnect;
27-
2823
use anyhow::Context;
24+
use mcr_settlement_config::Config;
25+
use movement_types::BlockCommitment;
26+
use movement_types::{Commitment, Id};
27+
use serde_json::Value as JsonValue;
28+
use std::array::TryFromSliceError;
29+
use std::fs;
30+
use std::path::Path;
2931
use thiserror::Error;
3032
use tokio_stream::StreamExt;
3133

32-
use std::array::TryFromSliceError;
33-
3434
#[derive(Error, Debug)]
3535
pub enum McrEthConnectorError {
3636
#[error(
@@ -252,6 +252,45 @@ where
252252
}
253253
}
254254

255+
pub struct AnvilAddressEntry {
256+
pub address: String,
257+
pub private_key: String,
258+
}
259+
260+
/// Read the Anvil config file keys and return all address/private key.
261+
pub fn read_anvil_json_file_addresses<P: AsRef<Path>>(
262+
anvil_conf_path: P,
263+
) -> Result<Vec<AnvilAddressEntry>, anyhow::Error> {
264+
let file_content = fs::read_to_string(anvil_conf_path)?;
265+
266+
let json_value: JsonValue = serde_json::from_str(&file_content)?;
267+
268+
// Extract the available_accounts and private_keys fields
269+
let available_accounts_iter = json_value["available_accounts"]
270+
.as_array()
271+
.expect("available_accounts should be an array")
272+
.iter()
273+
.map(|v| {
274+
let s = v.as_str().expect("available_accounts elements should be strings");
275+
s.to_owned()
276+
});
277+
278+
let private_keys_iter = json_value["private_keys"]
279+
.as_array()
280+
.expect("private_keys should be an array")
281+
.iter()
282+
.map(|v| {
283+
let s = v.as_str().expect("private_keys elements should be strings");
284+
s.to_owned()
285+
});
286+
287+
let res = available_accounts_iter
288+
.zip(private_keys_iter)
289+
.map(|(address, private_key)| AnvilAddressEntry { address, private_key })
290+
.collect::<Vec<_>>();
291+
Ok(res)
292+
}
293+
255294
#[cfg(test)]
256295
#[cfg(feature = "integration-tests")]
257296
mod tests {
@@ -265,8 +304,6 @@ mod tests {
265304
use movement_types::Commitment;
266305

267306
use anyhow::Context;
268-
use serde_json::Value as JsonValue;
269-
270307
use std::env;
271308
use std::fs;
272309

@@ -290,7 +327,10 @@ mod tests {
290327
let rpc_url = format!("http://localhost:{rpc_port}");
291328
let ws_url = format!("ws://localhost:{rpc_port}");
292329

293-
let anvil_addresses = read_anvil_json_file_addresses()?;
330+
let anvil_conf_file = env::var("ANVIL_JSON_PATH").context(
331+
"ANVIL_JSON_PATH env var is not defined. It should point to the anvil json file",
332+
)?;
333+
let anvil_addresses = crate::eth::utils::read_anvil_json_file_addresses(&anvil_conf_file)?;
294334

295335
//Do SC ceremony init stake calls.
296336
do_genesis_ceremonial(&anvil_addresses, &rpc_url).await?;
@@ -400,45 +440,6 @@ mod tests {
400440
Ok(())
401441
}
402442

403-
struct AnvilAddressEntry {
404-
address: String,
405-
private_key: String,
406-
}
407-
408-
fn read_anvil_json_file_addresses() -> Result<Vec<AnvilAddressEntry>, anyhow::Error> {
409-
let anvil_conf_file = env::var("ANVIL_JSON_PATH").context(
410-
"ANVIL_JSON_PATH env var is not defined. It should point to the anvil json file",
411-
)?;
412-
let file_content = fs::read_to_string(anvil_conf_file)?;
413-
414-
let json_value: JsonValue = serde_json::from_str(&file_content)?;
415-
416-
// Extract the available_accounts and private_keys fields
417-
let available_accounts_iter = json_value["available_accounts"]
418-
.as_array()
419-
.expect("available_accounts should be an array")
420-
.iter()
421-
.map(|v| {
422-
let s = v.as_str().expect("available_accounts elements should be strings");
423-
s.to_owned()
424-
});
425-
426-
let private_keys_iter = json_value["private_keys"]
427-
.as_array()
428-
.expect("private_keys should be an array")
429-
.iter()
430-
.map(|v| {
431-
let s = v.as_str().expect("private_keys elements should be strings");
432-
s.to_owned()
433-
});
434-
435-
let res = available_accounts_iter
436-
.zip(private_keys_iter)
437-
.map(|(address, private_key)| AnvilAddressEntry { address, private_key })
438-
.collect::<Vec<_>>();
439-
Ok(res)
440-
}
441-
442443
fn read_mcr_sc_adress() -> Result<Address, anyhow::Error> {
443444
let file_path = env::var("MCR_SC_ADDRESS_FILE")?;
444445
let addr_str = fs::read_to_string(file_path)?;

protocol-units/settlement/mcr/config/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ publish.workspace = true
1111
rust-version.workspace = true
1212

1313
[dependencies]
14-
serde = { workspace = true }
14+
serde = { workspace = true , features = ["derive"] }
1515

1616
[dev-dependencies]
1717
anyhow = { workspace = true }

protocol-units/settlement/mcr/setup/Cargo.toml

+4
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,16 @@ rust-version.workspace = true
1212

1313
[dependencies]
1414
mcr-settlement-config = { workspace = true }
15+
mcr-settlement-client = { workspace = true }
1516
dot-movement = { workspace = true }
17+
commander = { workspace = true }
1618

1719
alloy-primitives = { workspace = true }
1820

1921
anyhow = { workspace = true }
2022
k256 = { workspace = true }
23+
rand = { workspace = true }
24+
tokio = { workspace = true }
2125
tracing = { workspace = true }
2226

2327
[lints]

protocol-units/settlement/mcr/setup/src/local.rs

+95-11
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
use super::Setup;
2-
3-
use dot_movement::DotMovement;
4-
use mcr_settlement_config::Config;
5-
62
use alloy_primitives::hex;
7-
3+
use commander::run_command;
4+
use dot_movement::DotMovement;
85
use k256::ecdsa::SigningKey;
9-
use tracing::info;
10-
6+
use mcr_settlement_config::Config;
7+
use rand::{thread_rng, Rng};
8+
use std::env;
119
use std::future::Future;
10+
use tracing::info;
1211

1312
const DEFAULT_ETH_RPC_PORT: u16 = 8545;
1413
const DEFAULT_ETH_WS_PORT: u16 = 8545;
@@ -40,18 +39,103 @@ impl Setup for Local {
4039
_dot_movement: &DotMovement,
4140
mut config: Config,
4241
) -> impl Future<Output = Result<Config, anyhow::Error>> + Send {
43-
async move {
44-
// Can't use rand 0.7 while k256 is on rand 0.6
45-
let mut rng = k256::elliptic_curve::rand_core::OsRng;
42+
//define a temporary chain Id for Anvil
43+
let mut rng = thread_rng(); // rng is not send.
44+
let id: u16 = rng.gen_range(100, 32768);
45+
let chain_id = id.to_string();
4646

47-
info!("setting up MCR Ethereum client");
47+
tracing::info!("Init Settlement local conf");
4848

49+
async move {
4950
if config.rpc_url.is_none() {
5051
config.rpc_url = Some(format!("http://localhost:{}", self.eth_rpc_port));
5152
}
5253
if config.ws_url.is_none() {
5354
config.ws_url = Some(format!("http://localhost:{}", self.eth_ws_port));
5455
}
56+
57+
tracing::info!("Run Settlement local conf");
58+
//start local process and deploy smart contract.
59+
60+
//define working directory of Anvil
61+
let mut path = std::env::current_dir()?;
62+
let storage_path = env::var("MOVEMENT_BASE_STORAGE_PATH").unwrap_or_else(|_| {
63+
tracing::info!(
64+
"MOVEMENT_BASE_STORAGE_PATH not set. Use the default value: .movement",
65+
);
66+
".movement".to_string()
67+
});
68+
path.push(storage_path);
69+
path.push("anvil/mcr");
70+
path.push(chain_id.clone());
71+
tokio::fs::create_dir_all(&path).await?;
72+
tracing::info!("dir exist:{}", path.exists());
73+
path.push("anvil.json");
74+
75+
let anvil_path = path.to_string_lossy().to_string();
76+
tracing::info!("anvil_path: {:?}", anvil_path);
77+
78+
tokio::spawn({
79+
let anvil_path = anvil_path.clone();
80+
let chain_id = chain_id.clone();
81+
async move {
82+
let result = run_command(
83+
"anvil",
84+
&[
85+
"--chain-id",
86+
&chain_id,
87+
"--config-out",
88+
&anvil_path,
89+
"--port",
90+
&DEFAULT_ETH_RPC_PORT.to_string(),
91+
],
92+
)
93+
.await;
94+
tracing::info!("Anvil start result:{result:?}");
95+
}
96+
});
97+
98+
//wait Anvil to start
99+
let _ = tokio::time::sleep(tokio::time::Duration::from_millis(2000)).await;
100+
tracing::info!("after start:{}", path.exists());
101+
102+
// Deploy MCR smart contract.
103+
let anvil_addresses =
104+
mcr_settlement_client::eth_client::read_anvil_json_file_addresses(&*anvil_path)?;
105+
let settlement_private_key = &anvil_addresses[1].private_key;
106+
let settlement_address = &anvil_addresses[1].address;
107+
108+
let mut solidity_path = std::env::current_dir()?;
109+
solidity_path.push("protocol-units/settlement/mcr/contracts");
110+
let solidity_path = solidity_path.to_string_lossy();
111+
tracing::info!("solidity_path: {:?}", solidity_path);
112+
let mcr_address = run_command(
113+
"forge",
114+
&[
115+
"script",
116+
"DeployMCRLegacy",
117+
"--root",
118+
&solidity_path,
119+
"--broadcast",
120+
"--chain-id",
121+
&chain_id,
122+
"--sender",
123+
&settlement_address,
124+
"--rpc-url",
125+
&config.rpc_url.clone().unwrap(),
126+
"--private-key",
127+
&settlement_private_key,
128+
],
129+
)
130+
.await?
131+
.trim()
132+
.to_string();
133+
134+
// Can't use rand 0.7 while k256 is on rand 0.6
135+
let mut rng = k256::elliptic_curve::rand_core::OsRng;
136+
137+
info!("setting up MCR Ethereum client mcr_address:{mcr_address}");
138+
55139
if config.signer_private_key.is_none() {
56140
let key = SigningKey::random(&mut rng);
57141
let key_bytes = key.to_bytes();

0 commit comments

Comments
 (0)