Skip to content

Commit

Permalink
refactoring println in forge script and passing it through shell
Browse files Browse the repository at this point in the history
  • Loading branch information
i-m-aditya committed Jan 26, 2023
1 parent d69efd2 commit 67835b1
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 50 deletions.
39 changes: 19 additions & 20 deletions cli/src/cmd/forge/script/broadcast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use ethers::{
utils::format_units,
};
use eyre::{bail, ContextCompat, WrapErr};
use foundry_common::{estimate_eip1559_fees, try_get_http_provider, RetryProvider};
use foundry_common::{estimate_eip1559_fees, shell, try_get_http_provider, RetryProvider};
use futures::StreamExt;
use std::{cmp::min, collections::HashSet, ops::Mul, sync::Arc};
use tracing::trace;
Expand Down Expand Up @@ -132,11 +132,11 @@ impl ScriptArgs {
{
let mut pending_transactions = vec![];

println!(
shell::println(format!(
"##\nSending transactions [{} - {}].",
batch_number * batch_size,
batch_number * batch_size + min(batch_size, batch.len()) - 1
);
))?;
for (tx, kind) in batch.into_iter() {
let tx_hash = self.send_transaction(
provider.clone(),
Expand Down Expand Up @@ -175,7 +175,7 @@ impl ScriptArgs {
deployment_sequence.save()?;

if !sequential_broadcast {
println!("##\nWaiting for receipts.");
shell::println("##\nWaiting for receipts.")?;
clear_pendings(provider.clone(), deployment_sequence, None).await?;
}
}
Expand All @@ -185,8 +185,8 @@ impl ScriptArgs {
}
}

println!("\n\n==========================");
println!("\nONCHAIN EXECUTION COMPLETE & SUCCESSFUL.");
shell::println("\n\n==========================")?;
shell::println("\nONCHAIN EXECUTION COMPLETE & SUCCESSFUL.")?;

let (total_gas, total_gas_price, total_paid) = deployment_sequence.receipts.iter().fold(
(U256::zero(), U256::zero(), U256::zero()),
Expand All @@ -199,12 +199,12 @@ impl ScriptArgs {
let paid = format_units(total_paid, 18).unwrap_or_else(|_| "N/A".to_string());
let avg_gas_price = format_units(total_gas_price / deployment_sequence.receipts.len(), 9)
.unwrap_or_else(|_| "N/A".to_string());
println!(
shell::println(format!(
"Total Paid: {} ETH ({} gas * avg {} gwei)",
paid.trim_end_matches('0'),
total_gas,
avg_gas_price.trim_end_matches('0').trim_end_matches('.')
);
))?;

Ok(())
}
Expand Down Expand Up @@ -317,10 +317,10 @@ impl ScriptArgs {
}

if !self.broadcast {
println!("\nSIMULATION COMPLETE. To broadcast these transactions, add --broadcast and wallet configuration(s) to the previous command. See forge script --help for more.");
shell::println("\nSIMULATION COMPLETE. To broadcast these transactions, add --broadcast and wallet configuration(s) to the previous command. See forge script --help for more.")?;
}
} else {
println!("\nIf you wish to simulate on-chain transactions pass a RPC URL.");
shell::println("\nIf you wish to simulate on-chain transactions pass a RPC URL.")?;
}
}
Ok(())
Expand Down Expand Up @@ -395,7 +395,7 @@ impl ScriptArgs {
known_contracts: &ContractsByArtifact,
) -> eyre::Result<VecDeque<TransactionWithMetadata>> {
let gas_filled_txs = if self.skip_simulation {
println!("\nSKIPPING ON CHAIN SIMULATION.");
shell::println("\nSKIPPING ON CHAIN SIMULATION.")?;
txs.into_iter()
.map(|btx| {
let mut tx = TransactionWithMetadata::from_typed_transaction(btx.transaction);
Expand Down Expand Up @@ -495,7 +495,6 @@ impl ScriptArgs {
}

new_sequence.push_back(tx);

// We only create a [`ScriptSequence`] object when we collect all the rpc related
// transactions.
if let Some(next_tx) = txes_iter.peek() {
Expand Down Expand Up @@ -536,24 +535,24 @@ impl ScriptArgs {
provider_info.gas_price()?
};

println!("\n==========================");
println!("\nChain {}", provider_info.chain);
shell::println("\n==========================")?;
shell::println(format!("\nChain {}", provider_info.chain))?;

println!(
shell::println(format!(
"\nEstimated gas price: {} gwei",
format_units(per_gas, 9)
.unwrap_or_else(|_| "[Could not calculate]".to_string())
.trim_end_matches('0')
.trim_end_matches('.')
);
println!("\nEstimated total gas used for script: {total_gas}");
println!(
))?;
shell::println(format!("\nEstimated total gas used for script: {total_gas}"))?;
shell::println(format!(
"\nEstimated amount required: {} ETH",
format_units(total_gas.saturating_mul(per_gas), 18)
.unwrap_or_else(|_| "[Could not calculate]".to_string())
.trim_end_matches('0')
);
println!("\n==========================");
))?;
shell::println("\n==========================")?;
}
}
Ok(deployments)
Expand Down
6 changes: 4 additions & 2 deletions cli/src/cmd/forge/script/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use forge::{
trace::{CallTraceDecoder, Traces},
CallKind,
};
use foundry_common::RpcUrl;
use foundry_common::{shell, RpcUrl};
use futures::future::join_all;
use parking_lot::RwLock;
use std::{collections::VecDeque, sync::Arc};
Expand Down Expand Up @@ -244,7 +244,9 @@ impl ScriptArgs {
) -> HashMap<RpcUrl, ScriptRunner> {
let sender = script_config.evm_opts.sender;

eprintln!("\n## Setting up ({}) EVMs.", script_config.total_rpcs.len());
if !shell::verbosity().is_silent() {
eprintln!("\n## Setting up ({}) EVMs.", script_config.total_rpcs.len());
}

let futs = script_config
.total_rpcs
Expand Down
41 changes: 23 additions & 18 deletions cli/src/cmd/forge/script/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ use forge::{
CallKind,
};
use foundry_common::{
abi::format_token, evm::EvmArgs, ContractsByArtifact, RpcUrl, CONTRACT_MAX_SIZE, SELECTOR_LEN,
abi::format_token, evm::EvmArgs, shell, ContractsByArtifact, RpcUrl, CONTRACT_MAX_SIZE,
SELECTOR_LEN,
};
use foundry_config::{figment, Config};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -256,7 +257,7 @@ impl ScriptArgs {
}
}
Err(_) => {
println!("{:x?}", (&returned));
shell::println(format!("{:x?}", (&returned)))?;
}
}

Expand All @@ -277,7 +278,7 @@ impl ScriptArgs {
eyre::bail!("Unexpected error: No traces despite verbosity level. Please report this as a bug: https://github.com/foundry-rs/foundry/issues/new?assignees=&labels=T-bug&template=BUG-FORM.yml");
}

println!("Traces:");
shell::println("Traces:")?;
for (kind, trace) in &mut result.traces {
let should_include = match kind {
TraceKind::Setup => verbosity >= 5,
Expand All @@ -287,22 +288,22 @@ impl ScriptArgs {

if should_include {
decoder.decode(trace).await;
println!("{trace}");
shell::println(format!("{trace}"))?;
}
}
println!();
shell::println(String::new())?;
}

if result.success {
println!("{}", Paint::green("Script ran successfully."));
shell::println(format!("{}", Paint::green("Script ran successfully.")))?;
}

if script_config.evm_opts.fork_url.is_none() {
println!("Gas used: {}", result.gas_used);
shell::println(format!("Gas used: {}", result.gas_used))?;
}

if result.success && !result.returned.is_empty() {
println!("\n== Return ==");
shell::println("\n== Return ==")?;
match func.decode_output(&result.returned) {
Ok(decoded) => {
for (index, (token, output)) in decoded.iter().zip(&func.outputs).enumerate() {
Expand All @@ -313,20 +314,24 @@ impl ScriptArgs {
} else {
index.to_string()
};
println!("{}: {internal_type} {}", label.trim_end(), format_token(token));
shell::println(format!(
"{}: {internal_type} {}",
label.trim_end(),
format_token(token)
))?;
}
}
Err(_) => {
println!("{:x?}", (&result.returned));
shell::println(format!("{:x?}", (&result.returned)))?;
}
}
}

let console_logs = decode_console_logs(&result.logs);
if !console_logs.is_empty() {
println!("\n== Logs ==");
shell::println("\n== Logs ==")?;
for log in console_logs {
println!(" {log}");
shell::println(log)?;
}
}

Expand All @@ -351,7 +356,7 @@ impl ScriptArgs {
let console_logs = decode_console_logs(&result.logs);
let output = JsonResult { logs: console_logs, gas_used: result.gas_used, returns };
let j = serde_json::to_string(&output)?;
println!("{j}");
shell::println(j)?;

Ok(())
}
Expand All @@ -378,7 +383,7 @@ impl ScriptArgs {
let sender = tx.from.expect("no sender");
if let Some(ns) = new_sender {
if sender != ns {
println!("You have more than one deployer who could predeploy libraries. Using `--sender` instead.");
shell::println("You have more than one deployer who could predeploy libraries. Using `--sender` instead.")?;
return Ok(None)
}
} else if sender != evm_opts.sender {
Expand Down Expand Up @@ -577,12 +582,12 @@ impl ScriptArgs {

if deployment_size > CONTRACT_MAX_SIZE {
prompt_user = self.broadcast;
println!(
shell::println(format!(
"{}",
Paint::red(format!(
"`{name}` is above the EIP-170 contract size limit ({deployment_size} > {CONTRACT_MAX_SIZE})."
))
);
))?;
}
}
}
Expand Down Expand Up @@ -677,12 +682,12 @@ impl ScriptConfig {
/// error. [library support]
fn check_multi_chain_constraints(&self, libraries: &Libraries) -> eyre::Result<()> {
if self.has_multiple_rpcs() || (self.missing_rpc && !self.total_rpcs.is_empty()) {
eprintln!(
shell::eprintln(format!(
"{}",
Paint::yellow(
"Multi chain deployment is still under development. Use with caution."
)
);
))?;
if !libraries.libs.is_empty() {
eyre::bail!(
"Multi chain deployment does not support library linking at the moment."
Expand Down
6 changes: 3 additions & 3 deletions cli/src/cmd/forge/script/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use ethers::{
types::transaction::eip2718::TypedTransaction,
};
use eyre::{ContextCompat, WrapErr};
use foundry_common::{fs, SELECTOR_LEN};
use foundry_common::{fs, shell, SELECTOR_LEN};
use foundry_config::Config;
use serde::{Deserialize, Serialize};
use std::{
Expand Down Expand Up @@ -110,8 +110,8 @@ impl ScriptSequence {
)?),
&self,
)?;

println!("\nTransactions saved to: {path}\n");
shell::println(format!("\nTransactionsdffs saved to: {path}\n"))?;
// println!("\nTransactions saved to: {path}\n");
}

Ok(())
Expand Down
14 changes: 7 additions & 7 deletions common/src/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,17 @@ where
}

/// Prints the given message to the shell
pub fn print(msg: impl fmt::Display) -> io::Result<()> {
with_shell(|shell| shell.write_stdout(msg))
pub fn println(msg: impl fmt::Display) -> io::Result<()> {
with_shell(|shell| if !shell.verbosity.is_silent() { shell.write_stdout(msg) } else { Ok(()) })
}
/// Prints the given message to the shell
pub fn print_json<T: Serialize>(obj: &T) -> serde_json::Result<()> {
with_shell(|shell| shell.print_json(obj))
}

/// Prints the given message to the shell
pub fn eprint(msg: impl fmt::Display) -> io::Result<()> {
with_shell(|shell| shell.write_stderr(msg))
pub fn eprintln(msg: impl fmt::Display) -> io::Result<()> {
with_shell(|shell| if !shell.verbosity.is_silent() { shell.write_stderr(msg) } else { Ok(()) })
}

/// Returns the configured verbosity
Expand Down Expand Up @@ -175,7 +175,7 @@ unsafe impl Sync for WriteShellOut {}
impl ShellWrite for WriteShellOut {
fn write(&self, fragment: impl fmt::Display) -> io::Result<()> {
if let Ok(mut lock) = self.0.lock() {
write!(lock, "{fragment}")?;
writeln!(lock, "{fragment}")?;
}
Ok(())
}
Expand Down Expand Up @@ -225,7 +225,7 @@ impl ShellOut {
ShellOut::Stream => {
let stdout = io::stdout();
let mut handle = stdout.lock();
write!(handle, "{fragment}")?;
writeln!(handle, "{fragment}")?;
}
ShellOut::Write(ref w) => {
w.write(fragment)?;
Expand All @@ -240,7 +240,7 @@ impl ShellOut {
ShellOut::Stream => {
let stderr = io::stderr();
let mut handle = stderr.lock();
write!(handle, "{fragment}")?;
writeln!(handle, "{fragment}")?;
}
ShellOut::Write(ref w) => {
w.write(fragment)?;
Expand Down
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ binop_separator = "Back"
trailing_comma = "Vertical"
trailing_semicolon = false
use_field_init_shorthand = true
edition = "2021"

0 comments on commit 67835b1

Please sign in to comment.