AnvilNode

Struct AnvilNode 

Source
pub struct AnvilNode { /* private fields */ }
Available on crate feature anvil only.
Expand description

§Community Testcontainers Implementation for Foundry Anvil

This is a community implementation of the Testcontainers interface for Foundry Anvil.

Anvil is Foundry’s fast local Ethereum node for development and testing. It’s an ideal tool for rapid iteration on smart contract development and provides a clean, lightweight alternative to running a full node.

§Example

use testcontainers_modules::{
    anvil::{AnvilNode, ANVIL_PORT},
    testcontainers::runners::AsyncRunner,
};

// Start an Anvil node
let node = AnvilNode::default().start().await?;

// Get the RPC endpoint URL
let host_port = node.get_host_port_ipv4(ANVIL_PORT).await?;
let rpc_url = format!("http://localhost:{host_port}");

// Use with your favorite Ethereum library (alloy, ethers, web3, etc.)
// let provider = Provider::try_from(rpc_url)?;

§Advanced Configuration

use testcontainers_modules::anvil::AnvilNode;

// Configure chain ID and forking
let node = AnvilNode::default()
    .with_chain_id(1337)
    .with_fork_url("https://eth.llamarpc.com")
    .with_fork_block_number(18_000_000)
    .start().await?;

§Usage

The endpoint of the container is intended to be injected into your provider configuration, so that you can easily run tests against a local Anvil instance.

To use the latest Foundry image, you can use the latest() method:

let node = AnvilNode::latest().start().await?;

Users can use a specific Foundry image in their code with ImageExt::with_tag.

use testcontainers::core::ImageExt;
let node = AnvilNode::default().with_tag("nightly").start().await?;

Implementations§

Source§

impl AnvilNode

Source

pub fn latest() -> Self

Create a new AnvilNode with the latest Foundry image

Source

pub fn with_tag(self, tag: impl Into<String>) -> Self

Use a specific Foundry image tag

Source

pub fn with_chain_id(self, chain_id: u64) -> Self

Specify the chain ID - this will be Ethereum Mainnet by default

Source

pub fn with_fork_url(self, fork_url: impl Into<String>) -> Self

Specify the fork URL to fork from a live network

§Example
let node = AnvilNode::default()
    .with_fork_url("https://eth.llamarpc.com")
    .start().await?;
Source

pub fn with_fork_block_number(self, block_number: u64) -> Self

Specify the fork block number (requires with_fork_url to be set)

§Example
let node = AnvilNode::default()
    .with_fork_url("https://eth.llamarpc.com")
    .with_fork_block_number(18_000_000)
    .start().await?;
Source

pub fn with_state_mount(self, host_dir: impl AsRef<Path>) -> Self

Mount a host directory for anvil state at /state inside the container

Use this method to bind mount a host directory to the container’s /state directory. This allows you to persist state across container restarts.

§Arguments
  • host_dir - Path on the host machine to mount (will be mounted to /state in container)
§Note

When using this method, specify container paths (starting with /state/) in with_load_state_path and with_dump_state_path.

§Example
let temp_dir = std::env::temp_dir().join("anvil-state");
let node = AnvilNode::default()
    .with_state_mount(&temp_dir)
    .with_dump_state_path("/state/state.json")
    .start().await?;
Source

pub fn with_load_state_path(self, path: impl Into<String>) -> Self

Configure Anvil to initialize from a previously saved state snapshot. Equivalent to passing --load-state <PATH>.

§Arguments
  • path - Path to the state file (container-internal path, typically /state/... if using with_state_mount)
§Example
let node = AnvilNode::default()
    .with_state_mount("/host/path/to/state")
    .with_load_state_path("/state/state.json")
    .start().await?;
Source

pub fn with_dump_state_path(self, path: impl Into<String>) -> Self

Configure Anvil to dump the state on exit to the given file or directory. Equivalent to passing --dump-state <PATH>.

§Arguments
  • path - Path where state should be saved (container-internal path, typically /state/... if using with_state_mount)
§Example
let node = AnvilNode::default()
    .with_state_mount("/host/path/to/state")
    .with_dump_state_path("/state/state.json")
    .start().await?;
Source

pub fn with_state_interval(self, seconds: u64) -> Self

Configure periodic state persistence interval in seconds. Equivalent to passing --state-interval <SECONDS>.

§Example
let node = AnvilNode::default()
    .with_state_mount("/host/path/to/state")
    .with_dump_state_path("/state/state.json")
    .with_state_interval(30) // Save every 30 seconds
    .start().await?;

Trait Implementations§

Source§

impl Clone for AnvilNode

Source§

fn clone(&self) -> AnvilNode

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for AnvilNode

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for AnvilNode

Source§

fn default() -> AnvilNode

Returns the “default value” for a type. Read more
Source§

impl Image for AnvilNode

Source§

fn cmd(&self) -> impl IntoIterator<Item = impl Into<Cow<'_, str>>>

Returns the CMD this image needs to be created with.
Source§

fn entrypoint(&self) -> Option<&str>

Returns the entrypoint this image needs to be created with.
Source§

fn env_vars( &self, ) -> impl IntoIterator<Item = (impl Into<Cow<'_, str>>, impl Into<Cow<'_, str>>)>

Returns the environment variables that needs to be set when a container is created.
Source§

fn mounts(&self) -> impl IntoIterator<Item = &Mount>

Returns the mounts that needs to be created when a container is created.
Source§

fn expose_ports(&self) -> &[ContainerPort]

Returns the ports that needs to be exposed when a container is created. Read more
Source§

fn name(&self) -> &str

The name of the docker image to pull from the Docker Hub registry.
Source§

fn tag(&self) -> &str

Implementations are encouraged to include a tag that will not change (i.e. NOT latest) in order to prevent test code from randomly breaking because the underlying docker suddenly changed.
Source§

fn ready_conditions(&self) -> Vec<WaitFor>

Returns a list of conditions that need to be met before a started container is considered ready. Read more
Source§

fn copy_to_sources(&self) -> impl IntoIterator<Item = &CopyToContainer>

Returns the files to be copied into the container at startup.
Source§

fn exec_after_start( &self, cs: ContainerState, ) -> Result<Vec<ExecCommand>, TestcontainersError>

Returns the commands that needs to be executed after a container is started i.e. commands to be run in a running container. Read more
Source§

fn exec_before_ready( &self, cs: ContainerState, ) -> Result<Vec<ExecCommand>, TestcontainersError>

Returns commands that will be executed after the container has started, but before the Image::ready_conditions are awaited for. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, I> AsyncRunner<I> for T
where T: Into<ContainerRequest<I>> + Send, I: Image,

Source§

fn start<'async_trait>( self, ) -> Pin<Box<dyn Future<Output = Result<ContainerAsync<I>, TestcontainersError>> + Send + 'async_trait>>
where T: 'async_trait,

Starts the container and returns an instance of ContainerAsync.
Source§

fn pull_image<'async_trait>( self, ) -> Pin<Box<dyn Future<Output = Result<ContainerRequest<I>, TestcontainersError>> + Send + 'async_trait>>
where T: 'async_trait,

Pulls the image from the registry. Useful if you want to pull the image before starting the container.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<RI, I> ImageExt<I> for RI
where RI: Into<ContainerRequest<I>>, I: Image,

Source§

fn with_cmd( self, cmd: impl IntoIterator<Item = impl Into<String>>, ) -> ContainerRequest<I>

Returns a new ContainerRequest with the specified (overridden) CMD (Image::cmd). Read more
Source§

fn with_name(self, name: impl Into<String>) -> ContainerRequest<I>

Overrides the fully qualified image name (consists of {domain}/{owner}/{image}). Can be used to specify a custom registry or owner.
Source§

fn with_tag(self, tag: impl Into<String>) -> ContainerRequest<I>

Overrides the image tag. Read more
Source§

fn with_container_name(self, name: impl Into<String>) -> ContainerRequest<I>

Sets the container name.
Source§

fn with_platform(self, platform: impl Into<String>) -> ContainerRequest<I>

Sets the platform the container will be run on. Read more
Source§

fn with_network(self, network: impl Into<String>) -> ContainerRequest<I>

Sets the network the container will be connected to.
Source§

fn with_label( self, key: impl Into<String>, value: impl Into<String>, ) -> ContainerRequest<I>

Adds the specified label to the container. Read more
Source§

fn with_labels( self, labels: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>, ) -> ContainerRequest<I>

Adds the specified labels to the container. Read more
Source§

fn with_env_var( self, name: impl Into<String>, value: impl Into<String>, ) -> ContainerRequest<I>

Adds an environment variable to the container.
Source§

fn with_host( self, key: impl Into<String>, value: impl Into<Host>, ) -> ContainerRequest<I>

Adds a host to the container.
Source§

fn with_hostname(self, hostname: impl Into<String>) -> ContainerRequest<I>

Configures hostname for the container.
Source§

fn with_mount(self, mount: impl Into<Mount>) -> ContainerRequest<I>

Adds a mount to the container.
Source§

fn with_copy_to( self, target: impl Into<CopyTargetOptions>, source: impl Into<CopyDataSource>, ) -> ContainerRequest<I>

Copies data or a file/dir into the container. Read more
Source§

fn with_mapped_port( self, host_port: u16, container_port: ContainerPort, ) -> ContainerRequest<I>

Adds a port mapping to the container, mapping the host port to the container’s internal port. Read more
Source§

fn with_ulimit( self, name: &str, soft: i64, hard: Option<i64>, ) -> ContainerRequest<I>

Adds a resource ulimit to the container. Read more
Source§

fn with_privileged(self, privileged: bool) -> ContainerRequest<I>

Sets the container to run in privileged mode.
Source§

fn with_cap_add(self, capability: impl Into<String>) -> ContainerRequest<I>

Adds the capabilities to the container
Source§

fn with_cap_drop(self, capability: impl Into<String>) -> ContainerRequest<I>

Drops the capabilities from the container’s capabilities
Source§

fn with_cgroupns_mode(self, cgroupns_mode: CgroupnsMode) -> ContainerRequest<I>

cgroup namespace mode for the container. Possible values are: Read more
Source§

fn with_userns_mode(self, userns_mode: &str) -> ContainerRequest<I>

Sets the usernamespace mode for the container when usernamespace remapping option is enabled.
Source§

fn with_shm_size(self, bytes: u64) -> ContainerRequest<I>

Sets the shared memory size in bytes
Source§

fn with_startup_timeout(self, timeout: Duration) -> ContainerRequest<I>

Sets the startup timeout for the container. The default is 60 seconds.
Source§

fn with_working_dir(self, working_dir: impl Into<String>) -> ContainerRequest<I>

Sets the working directory. The default is defined by the underlying image, which in turn may default to /.
Source§

fn with_log_consumer( self, log_consumer: impl LogConsumer + 'static, ) -> ContainerRequest<I>

Adds the log consumer to the container. Read more
Source§

fn with_user(self, user: impl Into<String>) -> ContainerRequest<I>

Sets the user that commands are run as inside the container.
Source§

fn with_readonly_rootfs(self, readonly_rootfs: bool) -> ContainerRequest<I>

Sets the container’s root filesystem to be mounted as read-only
Source§

fn with_security_opt( self, security_opt: impl Into<String>, ) -> ContainerRequest<I>

Sets security options for the container
Source§

fn with_ready_conditions( self, ready_conditions: Vec<WaitFor>, ) -> ContainerRequest<I>

Overrides ready conditions. Read more
Source§

fn with_health_check(self, health_check: Healthcheck) -> ContainerRequest<I>

Sets a custom health check for the container. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<T> IntoResult<T> for T

Source§

impl<T> IntoResult<T> for T

Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, I> SyncRunner<I> for T
where T: Into<ContainerRequest<I>> + Send, I: Image,

Source§

fn start(self) -> Result<Container<I>, TestcontainersError>

Starts the container and returns an instance of Container.
Source§

fn pull_image(self) -> Result<ContainerRequest<I>, TestcontainersError>

Pulls the image from the registry. Useful if you want to pull the image before starting the container.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more