Skip to content

Commit

Permalink
chore: stop using RuntimeOrHandle (#7860)
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes committed May 6, 2024
1 parent 6ded857 commit e7f9b75
Show file tree
Hide file tree
Showing 27 changed files with 63 additions and 63 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ tikv-jemallocator = "0.5.4"
num-format = "0.4.4"
yansi = { version = "1.0", features = ["detect-tty", "detect-env"] }
tempfile = "3.10"
tokio = "1"

axum = "0.7"
hyper = "1.0"
Expand Down
4 changes: 2 additions & 2 deletions crates/anvil/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ tracing.workspace = true
tracing-subscriber = { workspace = true, features = ["env-filter", "fmt"] }

# async
tokio = { version = "1", features = ["time"] }
tokio = { workspace = true, features = ["time"] }
parking_lot = "0.12"
futures = "0.3"
async-trait = "0.1"
Expand Down Expand Up @@ -99,7 +99,7 @@ alloy-json-rpc.workspace = true
alloy-pubsub.workspace = true
foundry-test-utils.workspace = true
similar-asserts.workspace = true
tokio = { version = "1", features = ["full"] }
tokio = { workspace = true, features = ["full"] }

[features]
default = ["cli"]
Expand Down
2 changes: 1 addition & 1 deletion crates/cast/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ regex = { version = "1", default-features = false }
rpassword = "7"
semver = "1"
tempfile.workspace = true
tokio = { version = "1", features = ["macros", "signal"] }
tokio = { workspace = true, features = ["macros", "signal"] }
tracing.workspace = true
yansi.workspace = true
evmole = "0.3.1"
Expand Down
29 changes: 7 additions & 22 deletions crates/cheatcodes/src/evm/fork.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ use alloy_primitives::{B256, U256};
use alloy_provider::Provider;
use alloy_rpc_types::Filter;
use alloy_sol_types::SolValue;
use eyre::WrapErr;
use foundry_common::provider::ProviderBuilder;
use foundry_compilers::utils::RuntimeOrHandle;
use foundry_evm_core::fork::CreateFork;

impl Cheatcode for activeForkCall {
Expand Down Expand Up @@ -227,11 +225,10 @@ impl Cheatcode for rpcCall {
let url =
ccx.ecx.db.active_fork_url().ok_or_else(|| fmt_err!("no active fork URL found"))?;
let provider = ProviderBuilder::new(&url).build()?;
let method: &'static str = Box::new(method.clone()).leak();
let params_json: serde_json::Value = serde_json::from_str(params)?;
let result = RuntimeOrHandle::new()
.block_on(provider.raw_request(method.into(), params_json))
.map_err(|err| fmt_err!("{method:?}: {err}"))?;
let result =
foundry_common::block_on(provider.raw_request(method.clone().into(), params_json))
.map_err(|err| fmt_err!("{method:?}: {err}"))?;

let result_as_tokens = crate::json::json_value_to_token(&result)
.map_err(|err| fmt_err!("failed to parse result: {err}"))?;
Expand All @@ -256,24 +253,12 @@ impl Cheatcode for eth_getLogsCall {
ccx.ecx.db.active_fork_url().ok_or_else(|| fmt_err!("no active fork URL found"))?;
let provider = ProviderBuilder::new(&url).build()?;
let mut filter = Filter::new().address(*target).from_block(from_block).to_block(to_block);
for (i, topic) in topics.iter().enumerate() {
// todo: needed because rust wants to convert FixedBytes<32> to U256 to convert it back
// to FixedBytes<32> and then to Topic for some reason removing the
// From<U256> impl in alloy does not fix the situation, and it is not possible to impl
// From<FixedBytes<32>> either because of a conflicting impl
match i {
0 => filter = filter.event_signature(*topic),
1 => filter = filter.topic1(*topic),
2 => filter = filter.topic2(*topic),
3 => filter = filter.topic3(*topic),
_ => unreachable!(),
};
for (i, &topic) in topics.iter().enumerate() {
filter.topics[i] = topic.into();
}

// todo: handle the errors somehow
let logs = RuntimeOrHandle::new()
.block_on(provider.get_logs(&filter))
.wrap_err("failed to get logs")?;
let logs = foundry_common::block_on(provider.get_logs(&filter))
.map_err(|e| fmt_err!("failed to get logs: {e}"))?;

let eth_logs = logs
.into_iter()
Expand Down
7 changes: 3 additions & 4 deletions crates/cheatcodes/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use alloy_signer_wallet::{
LocalWallet, MnemonicBuilder,
};
use alloy_sol_types::SolValue;
use foundry_evm_core::{constants::DEFAULT_CREATE2_DEPLOYER, utils::RuntimeOrHandle};
use foundry_evm_core::constants::DEFAULT_CREATE2_DEPLOYER;
use k256::{
ecdsa::SigningKey,
elliptic_curve::{sec1::ToEncodedPoint, Curve},
Expand Down Expand Up @@ -202,9 +202,8 @@ pub(super) fn sign_with_wallet<DB: DatabaseExt>(
.get(&signer)
.ok_or_else(|| fmt_err!("signer with address {signer} is not available"))?;

let sig = RuntimeOrHandle::new()
.block_on(wallet.sign_hash(digest))
.map_err(|err| fmt_err!("{err}"))?;
let sig =
foundry_common::block_on(wallet.sign_hash(digest)).map_err(|err| fmt_err!("{err}"))?;

let recovered = sig.recover_address_from_prehash(digest).map_err(|err| fmt_err!("{err}"))?;
assert_eq!(recovered, signer);
Expand Down
2 changes: 1 addition & 1 deletion crates/chisel/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ serde.workspace = true
solang-parser.workspace = true
strum = { workspace = true, features = ["derive"] }
time = { version = "0.3", features = ["formatting"] }
tokio = { version = "1", features = ["full"] }
tokio = { workspace = true, features = ["full"] }
yansi.workspace = true
tracing.workspace = true

Expand Down
9 changes: 5 additions & 4 deletions crates/chisel/src/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -689,7 +689,7 @@ impl ChiselDispatcher {
let failed = !res.success;
if new_session_source.config.traces || failed {
if let Ok(decoder) =
Self::decode_traces(&new_session_source.config, &mut res)
Self::decode_traces(&new_session_source.config, &mut res).await
{
if let Err(e) = Self::show_traces(&decoder, &mut res).await {
return DispatchResult::CommandFailed(e.to_string())
Expand Down Expand Up @@ -834,7 +834,8 @@ impl ChiselDispatcher {
// If traces are enabled or there was an error in execution, show the execution
// traces.
if new_source.config.traces || failed {
if let Ok(decoder) = Self::decode_traces(&new_source.config, &mut res) {
if let Ok(decoder) = Self::decode_traces(&new_source.config, &mut res).await
{
if let Err(e) = Self::show_traces(&decoder, &mut res).await {
return DispatchResult::CommandFailed(e.to_string())
};
Expand Down Expand Up @@ -888,7 +889,7 @@ impl ChiselDispatcher {
/// ### Returns
///
/// Optionally, a [CallTraceDecoder]
pub fn decode_traces(
pub async fn decode_traces(
session_config: &SessionSourceConfig,
result: &mut ChiselResult,
// known_contracts: &ContractsByArtifact,
Expand All @@ -903,7 +904,7 @@ impl ChiselDispatcher {

let mut identifier = TraceIdentifiers::new().with_etherscan(
&session_config.foundry_config,
session_config.evm_opts.get_remote_chain_id(),
session_config.evm_opts.get_remote_chain_id().await,
)?;
if !identifier.is_empty() {
for (_, trace) in &mut result.traces {
Expand Down
2 changes: 1 addition & 1 deletion crates/chisel/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ impl SessionSource {

let Some((stack, memory, _)) = &res.state else {
// Show traces and logs, if there are any, and return an error
if let Ok(decoder) = ChiselDispatcher::decode_traces(&source.config, &mut res) {
if let Ok(decoder) = ChiselDispatcher::decode_traces(&source.config, &mut res).await {
ChiselDispatcher::show_traces(&decoder, &mut res).await?;
}
let decoded_logs = decode_console_logs(&res.logs);
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ regex = { version = "1", default-features = false }
serde.workspace = true
strsim = "0.10"
strum = { workspace = true, features = ["derive"] }
tokio = { version = "1", features = ["macros"] }
tokio = { workspace = true, features = ["macros"] }
tracing-error = "0.2"
tracing-subscriber = { workspace = true, features = ["registry", "env-filter", "fmt"] }
tracing.workspace = true
Expand Down
1 change: 0 additions & 1 deletion crates/cli/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,6 @@ pub fn now() -> Duration {
}

/// Runs the `future` in a new [`tokio::runtime::Runtime`]
#[allow(unused)]
pub fn block_on<F: Future>(future: F) -> F::Output {
let rt = tokio::runtime::Runtime::new().expect("could not start tokio rt");
rt.block_on(future)
Expand Down
4 changes: 2 additions & 2 deletions crates/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ serde_json.workspace = true
serde.workspace = true
tempfile.workspace = true
thiserror = "1"
tokio = "1"
tokio.workspace = true
tracing.workspace = true
url = "2"
walkdir = "2"
Expand All @@ -59,4 +59,4 @@ num-format.workspace = true
[dev-dependencies]
foundry-macros.workspace = true
similar-asserts.workspace = true
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
13 changes: 13 additions & 0 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,16 @@ pub use constants::*;
pub use contracts::*;
pub use traits::*;
pub use transactions::*;

/// Block on a future using the current tokio runtime on the current thread.
pub fn block_on<F: std::future::Future>(future: F) -> F::Output {
block_on_handle(&tokio::runtime::Handle::current(), future)
}

/// Block on a future using the current tokio runtime on the current thread with the given handle.
pub fn block_on_handle<F: std::future::Future>(
handle: &tokio::runtime::Handle,
future: F,
) -> F::Output {
tokio::task::block_in_place(|| handle.block_on(future))
}
3 changes: 1 addition & 2 deletions crates/evm/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ repository.workspace = true
[dependencies]
foundry-cheatcodes-spec.workspace = true
foundry-common.workspace = true
foundry-compilers.workspace = true
foundry-config.workspace = true
foundry-macros.workspace = true

Expand Down Expand Up @@ -52,7 +51,7 @@ rustc-hash.workspace = true
serde = "1"
serde_json = "1"
thiserror = "1"
tokio = { version = "1", features = ["time", "macros"] }
tokio = { workspace = true, features = ["time", "macros"] }
tracing = "0.1"
url = "2"

Expand Down
9 changes: 4 additions & 5 deletions crates/evm/core/src/opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use alloy_provider::Provider;
use alloy_rpc_types::Block;
use eyre::WrapErr;
use foundry_common::{provider::ProviderBuilder, ALCHEMY_FREE_TIER_CUPS};
use foundry_compilers::utils::RuntimeOrHandle;
use foundry_config::{Chain, Config};
use revm::primitives::{BlockEnv, CfgEnv, TxEnv};
use serde::{Deserialize, Deserializer, Serialize};
Expand Down Expand Up @@ -166,11 +165,11 @@ impl EvmOpts {
/// - mainnet if `fork_url` contains "mainnet"
/// - the chain if `fork_url` is set and the endpoints returned its chain id successfully
/// - mainnet otherwise
pub fn get_chain_id(&self) -> u64 {
pub async fn get_chain_id(&self) -> u64 {
if let Some(id) = self.env.chain_id {
return id;
}
self.get_remote_chain_id().unwrap_or(Chain::mainnet()).id()
self.get_remote_chain_id().await.unwrap_or(Chain::mainnet()).id()
}

/// Returns the available compute units per second, which will be
Expand All @@ -188,7 +187,7 @@ impl EvmOpts {
}

/// Returns the chain ID from the RPC, if any.
pub fn get_remote_chain_id(&self) -> Option<Chain> {
pub async fn get_remote_chain_id(&self) -> Option<Chain> {
if let Some(ref url) = self.fork_url {
if url.contains("mainnet") {
trace!(?url, "auto detected mainnet chain");
Expand All @@ -201,7 +200,7 @@ impl EvmOpts {
.ok()
.unwrap_or_else(|| panic!("Failed to establish provider to {url}"));

if let Ok(id) = RuntimeOrHandle::new().block_on(provider.get_chain_id()) {
if let Ok(id) = provider.get_chain_id().await {
return Some(Chain::from(id));
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/evm/core/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ use alloy_json_abi::{Function, JsonAbi};
use alloy_primitives::{Address, FixedBytes, U256};
use alloy_rpc_types::{Block, Transaction};
use eyre::ContextCompat;
pub use foundry_compilers::utils::RuntimeOrHandle;
use foundry_config::NamedChain;
pub use revm::primitives::State as StateChangeset;
use revm::{
db::WrapDatabaseRef,
handler::register::EvmHandler,
Expand All @@ -19,6 +17,8 @@ use revm::{
};
use std::{cell::RefCell, rc::Rc, sync::Arc};

pub use revm::primitives::State as StateChangeset;

/// Depending on the configured chain id and block number this should apply any specific changes
///
/// - checks for prevrandao mixhash after merge
Expand Down
2 changes: 1 addition & 1 deletion crates/evm/evm/src/executors/tracing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl TracingExecutor {

let fork = evm_opts.get_fork(config, env.clone());

Ok((env, fork, evm_opts.get_remote_chain_id()))
Ok((env, fork, evm_opts.get_remote_chain_id().await))
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/evm/traces/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ hex.workspace = true
itertools.workspace = true
once_cell = "1"
serde = "1"
tokio = { version = "1", features = ["time", "macros"] }
tokio = { workspace = true, features = ["time", "macros"] }
tracing = "0.1"
yansi.workspace = true

Expand Down
3 changes: 1 addition & 2 deletions crates/evm/traces/src/identifier/etherscan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use foundry_block_explorers::{
};
use foundry_common::compile::{self, ContractSources};
use foundry_config::{Chain, Config};
use foundry_evm_core::utils::RuntimeOrHandle;
use futures::{
future::{join_all, Future},
stream::{FuturesUnordered, Stream, StreamExt},
Expand Down Expand Up @@ -129,7 +128,7 @@ impl TraceIdentifier for EtherscanIdentifier {
}
}

let fetched_identities = RuntimeOrHandle::new().block_on(
let fetched_identities = foundry_common::block_on(
fetcher
.map(|(address, metadata)| {
let label = metadata.contract_name.clone();
Expand Down
2 changes: 1 addition & 1 deletion crates/forge/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ similar = { version = "2", features = ["inline"] }
solang-parser.workspace = true
strum = { workspace = true, features = ["derive"] }
thiserror = "1"
tokio = { version = "1", features = ["time"] }
tokio = { workspace = true, features = ["time"] }
toml = { version = "0.8", features = ["preserve_order"] }
toml_edit = "0.22.4"
watchexec = "2.3.2"
Expand Down
2 changes: 1 addition & 1 deletion crates/forge/bin/cmd/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ impl TestArgs {
return Ok(TestOutcome::new(results, self.allow_failure));
}

let remote_chain_id = runner.evm_opts.get_remote_chain_id();
let remote_chain_id = runner.evm_opts.get_remote_chain_id().await;

// Run tests.
let (tx, rx) = channel::<(String, SuiteResult)>();
Expand Down
2 changes: 1 addition & 1 deletion crates/forge/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn main() -> Result<()> {
if cmd.is_watch() {
utils::block_on(watch::watch_build(cmd))
} else {
cmd.run().map(|_| ())
cmd.run().map(drop)
}
}
ForgeSubcommand::Debug(cmd) => utils::block_on(cmd.run()),
Expand Down
7 changes: 5 additions & 2 deletions crates/forge/src/multi_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ impl MultiContractRunner {
///
/// Each Executor gets its own instance of the `Backend`.
pub fn test(&mut self, filter: &dyn TestFilter, tx: mpsc::Sender<(String, SuiteResult)>) {
let handle = tokio::runtime::Handle::current();
trace!("running all tests");

// The DB backend that serves all the data.
Expand All @@ -163,7 +164,8 @@ impl MultiContractRunner {
);

contracts.par_iter().for_each_with(tx, |tx, &(id, contract)| {
let result = self.run_tests(id, contract, db.clone(), filter);
let _guard = handle.enter();
let result = self.run_tests(id, contract, db.clone(), filter, &handle);
let _ = tx.send((id.identifier(), result));
})
}
Expand All @@ -174,6 +176,7 @@ impl MultiContractRunner {
contract: &TestContract,
db: Backend,
filter: &dyn TestFilter,
handle: &tokio::runtime::Handle,
) -> SuiteResult {
let identifier = artifact_id.identifier();
let mut span_name = identifier.as_str();
Expand Down Expand Up @@ -220,7 +223,7 @@ impl MultiContractRunner {
&self.revert_decoder,
self.debug,
);
let r = runner.run_tests(filter, &self.test_options, known_contracts);
let r = runner.run_tests(filter, &self.test_options, known_contracts, handle);

debug!(duration=?r.duration, "executed all tests in contract");

Expand Down
Loading

0 comments on commit e7f9b75

Please sign in to comment.