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: cli scaffolding #3

Merged
merged 3 commits into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,7 @@ target/
/.helix/

# CLI default out dir for CSV files
out/
output/

# Environment files
.env
25 changes: 25 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ members = ["bin/*", "crates/*"]
resolver = "2"

[workspace.package]
name = "mevboost-relay-api"
version = "0.1.1"
edition = "2021"
license = "MIT"
Expand All @@ -19,6 +18,7 @@ tracing-subscriber = "0.3.17"
serde = { version = "1.0.192", features = ["derive"] }
clap = { version = "4.4.7", features = ["derive"] }
tokio = { version = "1.12.0", features = ["full"] }
# beacon-api-client = { git = "https://github.com/ralexstokes/ethereum-consensus.git" }

[profile.dev]
opt-level = 1
Expand Down
7 changes: 7 additions & 0 deletions bin/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,10 @@ anyhow.workspace = true
inquire.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
tokio.workspace = true
serde.workspace = true
serde_json.workspace = true

csv = "1.3.0"
# url = "2.2.2"
# beacon-api-client = { git = "https://github.com/ralexstokes/ethereum-consensus.git" }
192 changes: 183 additions & 9 deletions bin/cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,196 @@
use clap::Parser;
use std::path::Path;

use clap::{Parser, Subcommand, ValueEnum};
use mevboost_relay_api::{
types::{BuilderBidsReceivedOptions, PayloadDeliveredQueryOptions},
Client,
};

#[derive(Parser)]
#[clap(author = "Chainbound")]
#[command(author, version, about, long_about = None)]
// #[command(propagate_version = true)]
struct Args {
#[clap(long, short = 'r', default_value = "flashbots")]
relay_name: String,
/// The subcommand to execute.
#[clap(subcommand)]
command: Command,
/// The output method to use. Default: human readable text.
#[clap(long, short = 'o', default_value = "human")]
output: OutputMethod,
/// The path to write the output to. If not provided,
/// will default to the current working directory.
#[clap(long, short = 'p')]
path: Option<String>,
}

#[derive(Default, ValueEnum, Clone)]
enum OutputMethod {
/// Output in human readable format
#[default]
Human,
/// Output in CSV format
Csv,
/// Output in JSON format
Json,
}

#[derive(Subcommand)]
enum Command {
/// Get the payloads delivered to proposers for a given slot.
#[clap(name = "payloads-delivered")]
PayloadsDelivered { slot: u64 },

/// Get the block bids received by the relay for a given slot.
#[clap(name = "block-bids")]
BlockBids {
#[clap(long)]
slot: Option<u64>,
#[clap(long)]
block_hash: Option<String>,
},

/// Get the timestamp of the winning bid for a given slot.
#[clap(name = "winning-bid-timestamp")]
WinningBidTimestamp { slot: u64 },
}

fn main() -> anyhow::Result<()> {
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = Args::parse();
let _ = tracing_subscriber::fmt::try_init();

let client = mevboost_relay_api::Client::default();
if !client.relays.contains_key(args.relay_name.as_str()) {
anyhow::bail!("Relay `{}` not found in list of relays.", args.relay_name)
let client = Client::default();

let mut output_file_path = args
.path
.map(Into::into)
.unwrap_or(std::env::current_dir()?.join("output"));

match args.command {
Command::PayloadsDelivered { slot } => {
let payloads = client
.get_payloads_delivered_bidtraces_on_all_relays(&PayloadDeliveredQueryOptions {
slot: Some(slot),
..Default::default()
})
.await?;

match args.output {
OutputMethod::Human => println!("{:#?}", &payloads),
OutputMethod::Csv => unimplemented!(),
OutputMethod::Json => {
output_file_path = output_file_path
.join("payloads-delivered")
.join(format!("{}.json", slot));
write_json(output_file_path.clone(), payloads)?;
}
}
}

Command::BlockBids { slot, block_hash } => {
if slot.is_none() && block_hash.is_none() {
anyhow::bail!("Must provide either a slot or block hash");
}

let block_bids = client
.get_builder_blocks_received_on_all_relays(&BuilderBidsReceivedOptions {
slot,
block_hash: block_hash.clone(),
..Default::default()
})
.await?;

let query_name = if let Some(slot) = slot {
format!("slot-{}", slot)
} else {
format!(
"block-hash-{}",
block_hash
.as_ref()
.unwrap()
.chars()
.take(8)
.collect::<String>()
)
};
output_file_path = output_file_path.join(format!("block-bids-{}", query_name));

match args.output {
OutputMethod::Human => println!("{:#?}", &block_bids),
OutputMethod::Csv => unimplemented!(),
OutputMethod::Json => {
for (relay, bids) in block_bids {
if bids.is_empty() {
continue;
}

let filename = format!("{}.json", relay);
println!("Writing {} bids to {}", bids.len(), filename);
write_json(output_file_path.join(filename), bids)?;
}
}
}
}

Command::WinningBidTimestamp { slot } => {
let payloads = client
.get_payloads_delivered_bidtraces_on_all_relays(&PayloadDeliveredQueryOptions {
slot: Some(slot),
..Default::default()
})
.await?;

for (relay, relay_payloads) in payloads {
if relay_payloads.is_empty() {
continue;
}

let block_hash = relay_payloads[0].block_hash.clone();
let block_bids = client
.get_builder_blocks_received(
relay,
&BuilderBidsReceivedOptions {
slot: Some(slot),
block_hash: Some(block_hash),
..Default::default()
},
)
.await?;

let timestamp = block_bids[0].timestamp_ms;
println!(
"The winning bid for slot {} was submitted to {} at: {}",
slot, relay, timestamp
)
}
}
}

Ok(())
}

#[allow(unused)]
fn write_csv<T: serde::Serialize>(path: impl AsRef<Path>, data: Vec<T>) -> anyhow::Result<()> {
let path = path.as_ref();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}

// TODO
let mut res = csv::Writer::from_path(path)?;
for row in data {
res.serialize(row)?;
}
res.flush()?;
Ok(())
}

#[allow(unused)]
fn write_json<T: serde::Serialize>(path: impl AsRef<Path>, data: T) -> anyhow::Result<()> {
let path = path.as_ref();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}

let mut res = std::fs::File::create(path)?;
serde_json::to_writer_pretty(&mut res, &data)?;
Ok(())
}
Loading
Loading