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

chore: tables cleanup #6328

Merged
merged 1 commit into from
Nov 16, 2023
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
42 changes: 18 additions & 24 deletions crates/cast/bin/cmd/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@ use alloy_primitives::{B256, U256};
use cast::Cast;
use clap::Parser;
use comfy_table::{presets::ASCII_MARKDOWN, Table};
use ethers_core::{
abi::ethabi::ethereum_types::BigEndianHash,
types::{BlockId, NameOrAddress},
};
use ethers_core::types::{BlockId, NameOrAddress};
use ethers_providers::Middleware;
use eyre::Result;
use foundry_block_explorers::Client;
Expand Down Expand Up @@ -195,52 +192,49 @@ async fn fetch_and_print_storage(
Ok(())
} else {
let layout = artifact.storage_layout.as_ref().unwrap().clone();
let values = fetch_storage_values(provider, address, &layout).await?;
let values = fetch_storage_slots(provider, address, &layout).await?;
print_storage(layout, values, pretty)
}
}

/// Overrides the `value` field in [StorageLayout] with the slot's value to avoid creating new data
/// structures.
async fn fetch_storage_values(
async fn fetch_storage_slots(
provider: RetryProvider,
address: NameOrAddress,
layout: &StorageLayout,
) -> Result<Vec<String>> {
// TODO: Batch request; handle array values
) -> Result<Vec<B256>> {
// TODO: Batch request
let futures: Vec<_> = layout
.storage
.iter()
.map(|slot| {
let slot_h256 = B256::from(U256::from_str(&slot.slot)?);
Ok(provider.get_storage_at(address.clone(), slot_h256.to_ethers(), None))
let slot = B256::from(U256::from_str(&slot.slot)?);
Ok(provider.get_storage_at(address.clone(), slot.to_ethers(), None))
})
.collect::<Result<_>>()?;

// TODO: Better format values according to their Solidity type
join_all(futures).await.into_iter().map(|value| Ok(format!("{}", value?.into_uint()))).collect()
join_all(futures).await.into_iter().map(|r| Ok(r?.to_alloy())).collect()
}

fn print_storage(layout: StorageLayout, values: Vec<String>, pretty: bool) -> Result<()> {
fn print_storage(layout: StorageLayout, values: Vec<B256>, pretty: bool) -> Result<()> {
if !pretty {
println!("{}", serde_json::to_string_pretty(&serde_json::to_value(layout)?)?);
return Ok(())
}

let mut table = Table::new();
table.load_preset(ASCII_MARKDOWN);
table.set_header(vec!["Name", "Type", "Slot", "Offset", "Bytes", "Value", "Contract"]);
table.set_header(["Name", "Type", "Slot", "Offset", "Bytes", "Value", "Contract"]);

for (slot, value) in layout.storage.into_iter().zip(values) {
let storage_type = layout.types.get(&slot.storage_type);
table.add_row(vec![
slot.label,
storage_type.as_ref().map_or("?".to_string(), |t| t.label.clone()),
slot.slot,
slot.offset.to_string(),
storage_type.as_ref().map_or("?".to_string(), |t| t.number_of_bytes.clone()),
value,
slot.contract,
table.add_row([
slot.label.as_str(),
storage_type.map_or("?", |t| &t.label),
&slot.slot,
&slot.offset.to_string(),
&storage_type.map_or("?", |t| &t.number_of_bytes),
&value.to_string(),
&slot.contract,
]);
}

Expand Down
4 changes: 2 additions & 2 deletions crates/common/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ impl Display for SizeReport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
let mut table = Table::new();
table.load_preset(ASCII_MARKDOWN);
table.set_header(vec![
table.set_header([
Cell::new("Contract").add_attribute(Attribute::Bold).fg(Color::Blue),
Cell::new("Size (kB)").add_attribute(Attribute::Bold).fg(Color::Blue),
Cell::new("Margin (kB)").add_attribute(Attribute::Bold).fg(Color::Blue),
Expand All @@ -222,7 +222,7 @@ impl Display for SizeReport {
_ => Color::Red,
};

table.add_row(vec![
table.add_row([
Cell::new(name).fg(color),
Cell::new(contract.size as f64 / 1000.0).fg(color),
Cell::new(margin as f64 / 1000.0).fg(color),
Expand Down
28 changes: 13 additions & 15 deletions crates/forge/bin/cmd/inspect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl InspectArgs {
println!("{}", serde_json::to_string_pretty(&to_value(&artifact.gas_estimates)?)?);
}
ContractArtifactField::StorageLayout => {
print_storage_layout(&artifact.storage_layout, pretty)?;
print_storage_layout(artifact.storage_layout.as_ref(), pretty)?;
}
ContractArtifactField::DevDoc => {
println!("{}", serde_json::to_string_pretty(&to_value(&artifact.devdoc)?)?);
Expand Down Expand Up @@ -210,12 +210,10 @@ pub fn print_abi(abi: &JsonAbi, pretty: bool) -> Result<()> {
Ok(())
}

pub fn print_storage_layout(storage_layout: &Option<StorageLayout>, pretty: bool) -> Result<()> {
if storage_layout.is_none() {
eyre::bail!("Could not get storage layout")
}

let storage_layout = storage_layout.as_ref().unwrap();
pub fn print_storage_layout(storage_layout: Option<&StorageLayout>, pretty: bool) -> Result<()> {
let Some(storage_layout) = storage_layout else {
eyre::bail!("Could not get storage layout");
};

if !pretty {
println!("{}", serde_json::to_string_pretty(&to_value(storage_layout)?)?);
Expand All @@ -224,17 +222,17 @@ pub fn print_storage_layout(storage_layout: &Option<StorageLayout>, pretty: bool

let mut table = Table::new();
table.load_preset(ASCII_MARKDOWN);
table.set_header(vec!["Name", "Type", "Slot", "Offset", "Bytes", "Contract"]);
table.set_header(["Name", "Type", "Slot", "Offset", "Bytes", "Contract"]);

for slot in &storage_layout.storage {
let storage_type = storage_layout.types.get(&slot.storage_type);
table.add_row(vec![
slot.label.clone(),
storage_type.as_ref().map_or("?".to_string(), |t| t.label.clone()),
slot.slot.clone(),
slot.offset.to_string(),
storage_type.as_ref().map_or("?".to_string(), |t| t.number_of_bytes.clone()),
slot.contract.clone(),
table.add_row([
slot.label.as_str(),
storage_type.map_or("?", |t| &t.label),
&slot.slot,
&slot.offset.to_string(),
&storage_type.map_or("?", |t| &t.number_of_bytes),
&slot.contract,
]);
}

Expand Down
16 changes: 8 additions & 8 deletions crates/forge/bin/cmd/selectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,14 +172,14 @@ impl SelectorsSubcommands {
println!("No colliding method selectors between the two contracts.");
} else {
let mut table = Table::new();
table.set_header(vec![
table.set_header([
String::from("Selector"),
first_contract.name,
second_contract.name,
]);
colliding_methods.iter().for_each(|t| {
table.add_row(vec![t.0, t.1, t.2]);
});
for method in colliding_methods.iter() {
table.add_row([method.0, method.1, method.2]);
}
println!("{} collisions found:", colliding_methods.len());
println!("{table}");
}
Expand Down Expand Up @@ -243,24 +243,24 @@ impl SelectorsSubcommands {

let mut table = Table::new();

table.set_header(vec!["Type", "Signature", "Selector"]);
table.set_header(["Type", "Signature", "Selector"]);

for func in abi.functions() {
let sig = func.signature();
let selector = func.selector();
table.add_row(vec!["Function", &sig, &hex::encode_prefixed(selector)]);
table.add_row(["Function", &sig, &hex::encode_prefixed(selector)]);
}

for event in abi.events() {
let sig = event.signature();
let selector = event.selector();
table.add_row(vec!["Event", &sig, &hex::encode_prefixed(selector)]);
table.add_row(["Event", &sig, &hex::encode_prefixed(selector)]);
}

for error in abi.errors() {
let sig = error.signature();
let selector = error.selector();
table.add_row(vec!["Error", &sig, &hex::encode_prefixed(selector)]);
table.add_row(["Error", &sig, &hex::encode_prefixed(selector)]);
}

println!("{table}");
Expand Down
10 changes: 5 additions & 5 deletions crates/forge/src/gas_report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,16 +134,16 @@ impl Display for GasReport {

let mut table = Table::new();
table.load_preset(ASCII_MARKDOWN);
table.set_header(vec![Cell::new(format!("{name} contract"))
table.set_header([Cell::new(format!("{name} contract"))
.add_attribute(Attribute::Bold)
.fg(Color::Green)]);
table.add_row(vec![
table.add_row([
Cell::new("Deployment Cost").add_attribute(Attribute::Bold).fg(Color::Cyan),
Cell::new("Deployment Size").add_attribute(Attribute::Bold).fg(Color::Cyan),
]);
table.add_row(vec![contract.gas.to_string(), contract.size.to_string()]);
table.add_row([contract.gas.to_string(), contract.size.to_string()]);

table.add_row(vec![
table.add_row([
Cell::new("Function Name").add_attribute(Attribute::Bold).fg(Color::Magenta),
Cell::new("min").add_attribute(Attribute::Bold).fg(Color::Green),
Cell::new("avg").add_attribute(Attribute::Bold).fg(Color::Yellow),
Expand All @@ -157,7 +157,7 @@ impl Display for GasReport {
let fn_display =
if sigs.len() == 1 { fname.clone() } else { sig.replace(':', "") };

table.add_row(vec![
table.add_row([
Cell::new(fn_display).add_attribute(Attribute::Bold),
Cell::new(gas_info.min.to_string()).fg(Color::Green),
Cell::new(gas_info.mean.to_string()).fg(Color::Yellow),
Expand Down