Skip to main content

anvil/
lib.rs

1//! Anvil is a fast local Ethereum development node.
2
3#![cfg_attr(not(test), warn(unused_crate_dependencies))]
4#![cfg_attr(docsrs, feature(doc_cfg))]
5#![recursion_limit = "256"]
6
7use crate::{
8    error::{NodeError, NodeResult},
9    eth::{
10        EthApi,
11        backend::{info::StorageInfo, mem},
12        fees::{FeeHistoryService, FeeManager},
13        miner::{Miner, MiningMode},
14        pool::Pool,
15        sign::{DevSigner, Signer as EthSigner},
16    },
17    filter::Filters,
18    logging::{LoggingManager, NodeLogLayer},
19    service::NodeService,
20    shutdown::Signal,
21    tasks::TaskManager,
22};
23use alloy_primitives::{Address, U256};
24use alloy_signer_local::PrivateKeySigner;
25use eth::backend::fork::ClientFork;
26use eyre::{Result, WrapErr};
27use foundry_common::provider::{ProviderBuilder, RetryProvider};
28use foundry_primitives::FoundryNetwork;
29use futures::{FutureExt, TryFutureExt};
30use parking_lot::Mutex;
31use server::try_spawn_ipc;
32use std::{
33    net::SocketAddr,
34    pin::Pin,
35    sync::Arc,
36    task::{Context, Poll},
37};
38use tokio::{
39    runtime::Handle,
40    task::{JoinError, JoinHandle},
41};
42use tracing_subscriber::EnvFilter;
43
44#[cfg(feature = "optimism")]
45use op_alloy_rpc_types as _;
46
47pub use foundry_evm::hardfork::EthereumHardfork;
48
49/// contains the background service that drives the node
50mod service;
51
52mod config;
53pub use config::{
54    AccountGenerator, CHAIN_ID, DEFAULT_GAS_LIMIT, ForkChoice, NodeConfig, VERSION_MESSAGE,
55};
56
57mod error;
58/// ethereum related implementations
59pub mod eth;
60/// Evm related abstractions
61mod evm;
62pub use evm::PrecompileFactory;
63
64/// support for polling filters
65pub mod filter;
66/// commandline output
67pub mod logging;
68/// types for subscriptions
69pub mod pubsub;
70/// axum RPC server implementations
71pub mod server;
72/// Futures for shutdown signal
73mod shutdown;
74/// additional task management
75mod tasks;
76
77/// contains cli command
78#[cfg(feature = "cmd")]
79pub mod cmd;
80
81#[cfg(feature = "cmd")]
82pub mod args;
83
84#[cfg(feature = "cmd")]
85pub mod opts;
86
87#[macro_use]
88extern crate foundry_common;
89
90#[macro_use]
91extern crate tracing;
92
93/// Creates the node and runs the server.
94///
95/// Returns the [EthApi] that can be used to interact with the node and the [JoinHandle] of the
96/// task.
97///
98/// # Panics
99///
100/// Panics if any error occurs. For a non-panicking version, use [`try_spawn`].
101///
102///
103/// # Examples
104///
105/// ```no_run
106/// # use anvil::NodeConfig;
107/// # async fn spawn() -> eyre::Result<()> {
108/// let config = NodeConfig::default();
109/// let (api, handle) = anvil::spawn(config).await;
110///
111/// // use api
112///
113/// // wait forever
114/// handle.await.unwrap().unwrap();
115/// # Ok(())
116/// # }
117/// ```
118pub async fn spawn(config: NodeConfig) -> (EthApi<FoundryNetwork>, NodeHandle) {
119    try_spawn(config).await.expect("failed to spawn node")
120}
121
122/// Creates the node and runs the server
123///
124/// Returns the [EthApi] that can be used to interact with the node and the [JoinHandle] of the
125/// task.
126///
127/// # Examples
128///
129/// ```no_run
130/// # use anvil::NodeConfig;
131/// # async fn spawn() -> eyre::Result<()> {
132/// let config = NodeConfig::default();
133/// let (api, handle) = anvil::try_spawn(config).await?;
134///
135/// // use api
136///
137/// // wait forever
138/// handle.await??;
139/// # Ok(())
140/// # }
141/// ```
142pub async fn try_spawn(mut config: NodeConfig) -> Result<(EthApi<FoundryNetwork>, NodeHandle)> {
143    let logger = if config.enable_tracing { init_tracing() } else { Default::default() };
144    logger.set_enabled(!config.silent);
145
146    let init_state = config.init_state.take();
147    let (backend, fork_transaction_replay) = config.setup::<FoundryNetwork>().await?;
148
149    if let Some(state) = init_state {
150        backend.load_state(state).await.wrap_err("failed to load init state")?;
151    }
152
153    if let Some(replay) = fork_transaction_replay {
154        backend
155            .apply_fork_transaction_replay(replay)
156            .await
157            .wrap_err("failed to replay fork transaction prefix")?;
158    }
159
160    backend.commit_startup_fork_cache();
161    let backend = Arc::new(backend);
162
163    if config.enable_auto_impersonate {
164        backend.auto_impersonate_account(true);
165    }
166
167    let fork = backend.get_fork();
168
169    let NodeConfig {
170        signer_accounts,
171        block_time,
172        port,
173        max_transactions,
174        server_config,
175        no_mining,
176        transaction_order,
177        genesis,
178        mixed_mining,
179        ..
180    } = config.clone();
181
182    let pool = Arc::new(Pool::default());
183
184    let mode = if let Some(block_time) = block_time {
185        if mixed_mining {
186            let listener = pool.add_ready_listener();
187            MiningMode::mixed(max_transactions, listener, block_time)
188        } else {
189            MiningMode::interval(block_time)
190        }
191    } else if no_mining {
192        MiningMode::None
193    } else {
194        // get a listener for ready transactions
195        let listener = pool.add_ready_listener();
196        MiningMode::instant(max_transactions, listener)
197    };
198
199    let miner = Miner::new(mode.with_coalescing_window(config.transaction_coalescing_window));
200
201    let dev_signer: Box<dyn EthSigner<foundry_primitives::FoundryNetwork>> =
202        Box::new(DevSigner::new(signer_accounts));
203    let mut signers = vec![dev_signer];
204    if let Some(genesis) = genesis {
205        let genesis_signers = genesis
206            .alloc
207            .values()
208            .filter_map(|acc| acc.private_key)
209            .flat_map(|k| PrivateKeySigner::from_bytes(&k))
210            .collect::<Vec<_>>();
211        if !genesis_signers.is_empty() {
212            signers.push(Box::new(DevSigner::new(genesis_signers)));
213        }
214    }
215
216    let fee_history_cache = Arc::new(Mutex::new(Default::default()));
217    let fee_history_service = FeeHistoryService::new(
218        backend.fees().clone(),
219        backend.new_block_notifications(),
220        Arc::clone(&fee_history_cache),
221        StorageInfo::new(Arc::clone(&backend)),
222    );
223    // create an entry for the best block
224    if let Some(header) = backend.get_block(backend.best_number()).map(|block| block.header) {
225        fee_history_service.insert_cache_entry_for_block(header.hash_slow(), &header);
226    }
227
228    let filters = Filters::default();
229
230    // create the cloneable api wrapper
231    let api = EthApi::new(
232        Arc::clone(&pool),
233        Arc::clone(&backend),
234        Arc::new(signers),
235        fee_history_cache,
236        fee_history_service.fee_history_limit(),
237        miner.clone(),
238        logger,
239        filters.clone(),
240        transaction_order,
241    );
242
243    // spawn the node service
244    let node_service =
245        tokio::task::spawn(NodeService::new(pool, backend, miner, fee_history_service, filters));
246
247    let mut servers = Vec::with_capacity(config.host.len());
248    let mut addresses = Vec::with_capacity(config.host.len());
249
250    for addr in &config.host {
251        let sock_addr = SocketAddr::new(*addr, port);
252
253        // Create a TCP listener.
254        let tcp_listener = tokio::net::TcpListener::bind(sock_addr).await?;
255        addresses.push(tcp_listener.local_addr()?);
256
257        // Spawn the server future on a new task.
258        let srv = server::serve_on(tcp_listener, api.clone(), server_config.clone());
259        servers.push(tokio::task::spawn(srv.map_err(Into::into)));
260    }
261
262    let tokio_handle = Handle::current();
263    let (signal, on_shutdown) = shutdown::signal();
264    let task_manager = TaskManager::new(tokio_handle, on_shutdown);
265
266    let ipc_task =
267        config.get_ipc_path().map(|path| try_spawn_ipc(api.clone(), path)).transpose()?;
268
269    let handle = NodeHandle {
270        config,
271        node_service,
272        servers,
273        ipc_task,
274        addresses,
275        _signal: Some(signal),
276        task_manager,
277    };
278
279    handle.print(fork.as_ref())?;
280
281    Ok((api, handle))
282}
283
284type IpcTask = JoinHandle<()>;
285
286/// A handle to the spawned node and server tasks.
287///
288/// This future will resolve if either the node or server task resolve/fail.
289pub struct NodeHandle {
290    config: NodeConfig,
291    /// The address of the running rpc server.
292    addresses: Vec<SocketAddr>,
293    /// Join handle for the Node Service.
294    node_service: JoinHandle<Result<(), NodeError>>,
295    /// Join handles (one per socket) for the Anvil server.
296    servers: Vec<JoinHandle<Result<(), NodeError>>>,
297    /// The future that joins the ipc server, if any.
298    ipc_task: Option<IpcTask>,
299    /// A signal that fires the shutdown, fired on drop.
300    _signal: Option<Signal>,
301    /// A task manager that can be used to spawn additional tasks.
302    task_manager: TaskManager,
303}
304
305impl Drop for NodeHandle {
306    fn drop(&mut self) {
307        // Fire shutdown signal to make sure anvil instance is terminated.
308        if let Some(signal) = self._signal.take() {
309            let _ = signal.fire();
310        }
311        self.node_service.abort();
312        for server in &self.servers {
313            server.abort();
314        }
315        if let Some(ipc_task) = &self.ipc_task {
316            ipc_task.abort();
317        }
318    }
319}
320
321impl NodeHandle {
322    /// The [NodeConfig] the node was launched with.
323    pub const fn config(&self) -> &NodeConfig {
324        &self.config
325    }
326
327    /// Prints the launch info.
328    pub(crate) fn print(&self, fork: Option<&ClientFork>) -> Result<()> {
329        self.config.print(fork)?;
330        if !self.config.silent {
331            if let Some(ipc_path) = self.ipc_path() {
332                sh_println!("IPC path: {ipc_path}")?;
333            }
334            sh_println!(
335                "Listening on {}",
336                self.addresses
337                    .iter()
338                    .map(|addr| { addr.to_string() })
339                    .collect::<Vec<String>>()
340                    .join(", ")
341            )?;
342        }
343        Ok(())
344    }
345
346    /// The address of the launched server.
347    ///
348    /// **N.B.** this may not necessarily be the same `host + port` as configured in the
349    /// `NodeConfig`, if port was set to 0, then the OS auto picks an available port.
350    pub fn socket_address(&self) -> &SocketAddr {
351        &self.addresses[0]
352    }
353
354    /// Returns the http endpoint.
355    pub fn http_endpoint(&self) -> String {
356        format!("http://{}", self.socket_address())
357    }
358
359    /// Returns the websocket endpoint.
360    pub fn ws_endpoint(&self) -> String {
361        format!("ws://{}", self.socket_address())
362    }
363
364    /// Returns the path of the launched ipc server, if any.
365    pub fn ipc_path(&self) -> Option<String> {
366        self.config.get_ipc_path()
367    }
368
369    /// Constructs a [`RetryProvider`] for this handle's HTTP endpoint.
370    pub fn http_provider(&self) -> RetryProvider {
371        ProviderBuilder::new(&self.http_endpoint()).build().expect("failed to build HTTP provider")
372    }
373
374    /// Constructs a [`RetryProvider`] for this handle's WS endpoint.
375    pub fn ws_provider(&self) -> RetryProvider {
376        ProviderBuilder::new(&self.ws_endpoint()).build().expect("failed to build WS provider")
377    }
378
379    /// Constructs a [`RetryProvider`] for this handle's IPC endpoint, if any.
380    pub fn ipc_provider(&self) -> Option<RetryProvider> {
381        ProviderBuilder::new(&self.config.get_ipc_path()?).build().ok()
382    }
383
384    /// Signer accounts that can sign messages/transactions from the EVM node.
385    pub fn dev_accounts(&self) -> impl Iterator<Item = Address> + '_ {
386        self.config.signer_accounts.iter().map(|wallet| wallet.address())
387    }
388
389    /// Signer accounts that can sign messages/transactions from the EVM node.
390    pub fn dev_wallets(&self) -> impl Iterator<Item = PrivateKeySigner> + '_ {
391        self.config.signer_accounts.iter().cloned()
392    }
393
394    /// Accounts that will be initialised with `genesis_balance` in the genesis block.
395    pub fn genesis_accounts(&self) -> impl Iterator<Item = Address> + '_ {
396        self.config.genesis_accounts.iter().map(|w| w.address())
397    }
398
399    /// Native token balance of every genesis account in the genesis block.
400    pub const fn genesis_balance(&self) -> U256 {
401        self.config.genesis_balance
402    }
403
404    /// Default gas price for all txs.
405    pub fn gas_price(&self) -> u128 {
406        self.config.get_gas_price()
407    }
408
409    /// Returns the shutdown signal.
410    pub const fn shutdown_signal(&self) -> &Option<Signal> {
411        &self._signal
412    }
413
414    /// Returns mutable access to the shutdown signal.
415    ///
416    /// This can be used to extract the Signal.
417    pub const fn shutdown_signal_mut(&mut self) -> &mut Option<Signal> {
418        &mut self._signal
419    }
420
421    /// Returns the task manager that can be used to spawn new tasks.
422    ///
423    /// ```
424    /// use anvil::NodeHandle;
425    /// # fn t(handle: NodeHandle) {
426    /// let task_manager = handle.task_manager();
427    /// let on_shutdown = task_manager.on_shutdown();
428    ///
429    /// task_manager.spawn(async move {
430    ///     on_shutdown.await;
431    ///     // do something
432    /// });
433    ///
434    /// # }
435    /// ```
436    pub const fn task_manager(&self) -> &TaskManager {
437        &self.task_manager
438    }
439}
440
441impl Future for NodeHandle {
442    type Output = Result<NodeResult<()>, JoinError>;
443
444    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
445        let pin = self.get_mut();
446
447        // poll the ipc task
448        if let Some(mut ipc) = pin.ipc_task.take() {
449            if let Poll::Ready(res) = ipc.poll_unpin(cx) {
450                return Poll::Ready(res.map(|()| Ok(())));
451            }
452            pin.ipc_task = Some(ipc);
453        }
454
455        // poll the node service task
456        if let Poll::Ready(res) = pin.node_service.poll_unpin(cx) {
457            return Poll::Ready(res);
458        }
459
460        // poll the axum server handles
461        for server in &mut pin.servers {
462            if let Poll::Ready(res) = server.poll_unpin(cx) {
463                return Poll::Ready(res);
464            }
465        }
466
467        Poll::Pending
468    }
469}
470
471#[doc(hidden)]
472pub fn init_tracing() -> LoggingManager {
473    use tracing_subscriber::prelude::*;
474
475    let manager = LoggingManager::default();
476
477    let _ = if let Ok(rust_log_val) = std::env::var("RUST_LOG")
478        && !rust_log_val.contains('=')
479    {
480        // Mutate the given filter to include `node` logs if it is not already present.
481        // This prevents the unexpected behaviour of not seeing any node logs if a RUST_LOG
482        // is already present that doesn't set it.
483        let rust_log_val = if rust_log_val.contains("node") {
484            rust_log_val
485        } else {
486            format!("{rust_log_val},node=info")
487        };
488
489        let env_filter: EnvFilter =
490            rust_log_val.parse().expect("failed to parse modified RUST_LOG");
491        tracing_subscriber::registry()
492            .with(env_filter)
493            .with(tracing_subscriber::fmt::layer())
494            .try_init()
495    } else {
496        tracing_subscriber::Registry::default()
497            .with(NodeLogLayer::new(manager.clone()))
498            .with(
499                tracing_subscriber::fmt::layer()
500                    .without_time()
501                    .with_target(false)
502                    .with_level(false),
503            )
504            .try_init()
505    };
506
507    manager
508}