Skip to main content

A secure and reusable Anvil Ethereum test container manager

Project description

Anvil Test Container

A Python library for managing Anvil Ethereum test containers with security and ease of use in mind. This library provides a clean interface for running and interacting with Anvil instances in Docker containers, making it perfect for testing Ethereum smart contracts and DApps.

Features

This library offers several key features for Ethereum development and testing:

Core Functionality

  • Automated container lifecycle management
  • Ethereum chain forking and manipulation
  • Secure command execution
  • Transaction handling
  • Block time control

Advanced Features

  • Chain state snapshots and restoration
  • Health monitoring and diagnostics
  • Container log access
  • Resource cleanup and management
  • Environment variable handling

Security

  • Input validation for Ethereum addresses
  • Command injection protection
  • Secure transaction handling
  • Safe environment variable management
  • Resource isolation

Installation

You can install the library using pip:

pip install anvil-testcontainer

Or with Poetry (recommended):

poetry add anvil-testcontainer

Prerequisites

  • Python 3.8 or higher
  • Docker installed and running
  • Access to an Ethereum node for forking (e.g., Infura, Alchemy)

Quick Start

Here's a simple example to get you started:

from anvil_testcontainer import AnvilContainer

# Using context manager for automatic cleanup
with AnvilContainer("https://eth-mainnet.alchemyapi.io/v2/your-key") as anvil:
    # Get Web3 instance
    web3 = anvil.get_web3()
    
    # Check current block number
    print(f"Current block: {web3.eth.block_number}")
    
    # Advance time by one day
    anvil.move_time(86400)

Advanced Usage

Configuration

Use the ContainerConfig class for more control:

from anvil_testcontainer import AnvilContainer, ContainerConfig

config = ContainerConfig(
    fork_url="https://eth-mainnet.alchemyapi.io/v2/your-key",
    fork_block_number=14000000,
    image="ghcr.io/foundry-rs/foundry:nightly",
    port=8545,
    timeout=60,
    env_vars={"ETHERSCAN_API_KEY": "your-key"}
)

with AnvilContainer(config) as anvil:
    # Create a snapshot
    snapshot_id = anvil.create_snapshot()
    
    # Execute a transaction
    tx_hash = anvil.send_transaction(
        from_address="0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
        to_address="0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
        value=100000000000000000  # 0.1 ETH
    )
    
    # Check transaction receipt
    receipt = anvil.get_web3().eth.wait_for_transaction_receipt(tx_hash)
    
    # Revert to snapshot if needed
    anvil.revert_snapshot(snapshot_id)

Health Monitoring

Monitor container health and access logs:

with AnvilContainer(config) as anvil:
    # Check container health
    if anvil.verify_health():
        print("Container is healthy")
    
    # Access container logs
    logs = anvil.get_logs()
    print(logs)

API Reference

AnvilContainer

The main class for container management.

Basic Methods

  • start(): Start the container
  • stop(): Stop the container
  • get_web3(): Get Web3 instance
  • move_time(seconds: int): Advance blockchain time
  • reset_fork(block_number: int): Reset to specific block

Advanced Methods

  • create_snapshot(): Create chain state snapshot
  • revert_snapshot(snapshot_id: str): Restore chain state
  • send_transaction(...): Execute transaction
  • verify_health(): Check container health
  • get_logs(): Retrieve container logs

ContainerConfig

Configuration class for container initialization.

ContainerConfig(
    fork_url: str,
    fork_block_number: Optional[int] = None,
    image: str = "ghcr.io/foundry-rs/foundry:nightly",
    port: int = 8545,
    timeout: int = 60,
    env_vars: Optional[Dict[str, str]] = None
)

Error Handling

The library provides custom exceptions for better error handling:

from anvil_testcontainer import ValidationError

try:
    with AnvilContainer(config) as anvil:
        anvil.send_transaction(
            from_address="invalid_address",
            to_address="0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
            value=1000000000000000000
        )
except ValidationError as e:
    print(f"Validation failed: {e}")

Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add or update tests
  5. Submit a pull request

Development Setup

# Clone repository
git clone https://github.com/epappas/anvil-testcontainer.git
cd anvil-testcontainer

# Install dependencies
poetry install

# Run tests
poetry run pytest

Testing

Run the test suite:

poetry run pytest

With coverage:

poetry run pytest --cov=anvil_testcontainer

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For support, please:

  1. Check the documentation
  2. Search existing issues
  3. Create a new issue if needed

Acknowledgments

  • Foundry team for Anvil
  • OpenZeppelin for security best practices
  • Web3.py team for Ethereum interaction capabilities

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

anvil_testcontainer-0.1.3.tar.gz (9.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

anvil_testcontainer-0.1.3-py3-none-any.whl (9.4 kB view details)

Uploaded Python 3

File details

Details for the file anvil_testcontainer-0.1.3.tar.gz.

File metadata

  • Download URL: anvil_testcontainer-0.1.3.tar.gz
  • Upload date:
  • Size: 9.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.12.5 Linux/5.15.153.1-microsoft-standard-WSL2

File hashes

Hashes for anvil_testcontainer-0.1.3.tar.gz
Algorithm Hash digest
SHA256 b414cc04a1be32688770dbbfd71a29bc0198f6fbe4d70e5e6e552fe375f25edc
MD5 c7d17d34bc5d82a1792a38e9c8ee61a1
BLAKE2b-256 e8a60db52c53c22d65069f2ec70bbfb54a352d712bc85bc87851fdd489814c08

See more details on using hashes here.

File details

Details for the file anvil_testcontainer-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: anvil_testcontainer-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 9.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.12.5 Linux/5.15.153.1-microsoft-standard-WSL2

File hashes

Hashes for anvil_testcontainer-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 d1c6c798ea0f708043f75b59eab6ab3cccd62d4f951d4363ab3f934304631d4f
MD5 eaaebeb48d00d28a65f0b3d92fe50e8e
BLAKE2b-256 7e31b20bd68e022df26c7c5f480173c4a21106dd9120e91538376a5a07b069a0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page