Skip to content

Commit

Permalink
- Use alloy Anvil Binding Object to spawn an instance
Browse files Browse the repository at this point in the history
- Delete Manual created Anvil Runner object
- Delete unnecesary libraries from Cargo.toml
  • Loading branch information
fabrobles92 committed Jun 11, 2024
1 parent a1641ee commit 866aa6a
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 164 deletions.
49 changes: 21 additions & 28 deletions Cargo.lock

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

37 changes: 21 additions & 16 deletions crates/katana/rpc/rpc/tests/messaging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;

use alloy::network::EthereumSigner;
use alloy::node_bindings::Anvil;
use alloy::primitives::{Uint, U256};
use alloy::providers::{ProviderBuilder, WalletProvider};
use alloy::signers::wallet::LocalWallet;
use alloy::sol;
use cainome::cairo_serde::EthAddress;
use cainome::rs::abigen;
use dojo_world::utils::TransactionWaiter;
use katana_primitives::utils::transaction::{
compute_l1_handler_tx_hash, compute_l1_to_l2_message_hash, compute_l2_to_l1_message_hash,
};
use katana_runner::{AnvilRunner, KatanaRunner, KatanaRunnerConfig};
use katana_runner::{KatanaRunner, KatanaRunnerConfig};
use serde_json::json;
use starknet::accounts::{Account, ConnectedAccount};
use starknet::contract::ContractFactory;
Expand All @@ -22,6 +26,7 @@ use starknet::core::utils::get_contract_address;
use starknet::macros::selector;
use starknet::providers::Provider;
use tempfile::tempdir;
use url::Url;

mod common;

Expand All @@ -44,22 +49,28 @@ abigen!(CairoMessagingContract, "crates/katana/rpc/rpc/tests/test_data/cairo_l1_
#[tokio::test(flavor = "multi_thread")]
async fn test_messaging() {
// Prepare Anvil + Messaging Contracts
let anvil_runner = AnvilRunner::new().await.unwrap();
let l1_provider = anvil_runner.provider();
let anvil_runner = Anvil::default().spawn();

let l1_provider = {
let wallet: LocalWallet = anvil_runner.keys()[0].clone().into();
ProviderBuilder::new()
.with_recommended_fillers()
.signer(EthereumSigner::from(wallet))
.on_http(Url::from_str(&anvil_runner.endpoint()).unwrap())
};

// Deploy the core messaging contract on L1
let core_contract = StarknetContract::deploy(l1_provider).await.unwrap();
let core_contract = StarknetContract::deploy(&l1_provider).await.unwrap();
// Deploy test contract on L1 used to send/receive messages to/from L2
let l1_test_contract =
Contract1::deploy(l1_provider, dbg!(*core_contract.address())).await.unwrap();
let l1_test_contract = Contract1::deploy(&l1_provider, *core_contract.address()).await.unwrap();

// Prepare Katana + Messaging Contract
let messaging_config = json!({
"chain": "ethereum",
"rpc_url": anvil_runner.endpoint,
"rpc_url": anvil_runner.endpoint(),
"contract_address": core_contract.address().to_string(),
"sender_address": anvil_runner.address(),
"private_key": anvil_runner.secret_key(),
"sender_address": l1_provider.default_signer_address(),
"private_key": "",
"interval": 2,
"from_block": 0
})
Expand All @@ -71,14 +82,8 @@ async fn test_messaging() {

let katana_runner = KatanaRunner::new_with_config(KatanaRunnerConfig {
n_accounts: 2,
disable_fee: false,
block_time: None,
port: None,
// program_name: Some("/Users/kariy/.dojo/bin/katana".to_string()),
program_name: None,
run_name: None,
messaging: Some(path.to_str().unwrap().to_string()),
log_path: None,
..Default::default()
})
.unwrap();

Expand Down
6 changes: 2 additions & 4 deletions crates/katana/runner/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,5 @@ alloy = { git = "https://github.com/alloy-rs/alloy", rev = "7128c53", features =
"providers",
"provider-http",
"signer-wallet",
] }

reqwest = "0.12.4"
hyper = "0.14.20"
"node-bindings"
] }
116 changes: 0 additions & 116 deletions crates/katana/runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,19 @@ mod utils;

use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::str::FromStr;
use std::sync::mpsc::{self};
use std::thread;
use std::time::Duration;

use alloy::network::{Ethereum, EthereumSigner};
use alloy::primitives::Address;
use alloy::providers::fillers::{
ChainIdFiller, FillProvider, GasFiller, JoinFill, NonceFiller, SignerFiller,
};
use alloy::providers::{Identity, ProviderBuilder, RootProvider};
use alloy::signers::wallet::LocalWallet;
use alloy::transports::http::Http;
use anyhow::{Context, Result};
use assert_fs::TempDir;
use hyper::http::request;
use hyper::{Client as HyperClient, Response, StatusCode};
use katana_primitives::contract::ContractAddress;
use katana_primitives::genesis::allocation::{DevAllocationsGenerator, DevGenesisAccount};
use katana_primitives::FieldElement;
use reqwest::Client;
pub use runner_macro::{katana_test, runner};
use starknet::providers::jsonrpc::HttpTransport;
use starknet::providers::JsonRpcClient;
use tokio::sync::Mutex;
use tokio::time;
use url::Url;
use utils::find_free_port;

Expand Down Expand Up @@ -215,109 +202,6 @@ fn determine_default_program_path() -> String {
if let Ok(bin) = std::env::var("KATANA_RUNNER_BIN") { bin } else { "katana".to_string() }
}

type Provider = FillProvider<
JoinFill<
JoinFill<JoinFill<JoinFill<Identity, GasFiller>, NonceFiller>, ChainIdFiller>,
SignerFiller<EthereumSigner>,
>,
RootProvider<Http<Client>>,
Http<Client>,
Ethereum,
>;

#[derive(Debug)]
pub struct AnvilRunner {
process: Child,
provider: Provider,
pub endpoint: String,
address: Address,
secret_key: String,
}

impl AnvilRunner {
pub async fn new() -> Result<Self> {
let port = find_free_port();

let process = Command::new("anvil")
.arg("--port")
.arg(&port.to_string())
.arg("--silent")
.arg("--disable-block-gas-limit")
.spawn()
.expect("Could not start background Anvil");

let endpoint = format!("http://127.0.0.1:{port}");

if !is_anvil_up(&endpoint).await {
panic!("Error bringing up Anvil")
}
let secret_key =
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80".to_string();
let wallet: LocalWallet = secret_key.parse().unwrap();

let address = wallet.address();

let provider = ProviderBuilder::new()
.with_recommended_fillers()
.signer(EthereumSigner::from(wallet))
.on_http(Url::from_str(&endpoint).unwrap());
Ok(AnvilRunner { process, endpoint, provider, address, secret_key })
}

pub fn provider(&self) -> &Provider {
&self.provider
}

pub fn endpoint(&self) -> String {
self.endpoint.clone()
}

pub fn address(&self) -> Address {
self.address
}

pub fn secret_key(&self) -> String {
self.secret_key.clone()
}
}

impl Drop for AnvilRunner {
fn drop(&mut self) {
self.process.kill().expect("Cannot kill process");
}
}

async fn post_dummy_request(url: &String) -> Result<Response<hyper::Body>, hyper::Error> {
let req = request::Request::post(url)
.header("content-type", "application/json")
.body(hyper::Body::from(
serde_json::json!({
"jsonrpc": "2.0",
"method": "eth_blockNumberfuiorhgorueh",
"params": [],
"id": "1"
})
.to_string(),
))
.unwrap();

HyperClient::new().request(req).await
}

async fn is_anvil_up(endpoint: &String) -> bool {
let mut retries = 0;
let max_retries = 10;
while retries < max_retries {
if let Ok(anvil_block_rsp) = post_dummy_request(endpoint).await {
assert_eq!(anvil_block_rsp.status(), StatusCode::OK);
return true;
}
retries += 1;
tokio::time::sleep(time::Duration::from_millis(500)).await;
}
false
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit 866aa6a

Please sign in to comment.