A Python framework for Ethereum smart contract deployment, testing and interaction.
—
Blockchain network connections, RPC node management, chain state control, and multi-network configuration for development, testing, and production environments.
Global functions for managing blockchain network connections and configuration.
def connect(network: str = None, launch_rpc: bool = True) -> None:
"""
Connect to a blockchain network.
Args:
network: Network name from brownie-config.yaml (None for default)
launch_rpc: Launch local RPC node if needed
Raises:
ConnectionError: If connection fails
MainnetUndefined: If connecting to mainnet without configuration
"""
def disconnect() -> None:
"""Disconnect from current network and stop local RPC if running."""
def is_connected() -> bool:
"""
Check if connected to a network.
Returns:
bool: True if connected to a network
"""
def show_active() -> str:
"""
Display currently active network information.
Returns:
str: Active network name
"""
def gas_limit(*args) -> Union[int, None]:
"""
Get or set global gas limit for transactions.
Args:
*args: New gas limit value (empty to get current)
Returns:
int: Current gas limit setting
"""
def gas_price(*args) -> Union[int, None]:
"""
Get or set global gas price for legacy transactions.
Args:
*args: New gas price in wei (empty to get current)
Returns:
int: Current gas price setting
"""
def max_fee(*args) -> Union[int, None]:
"""
Get or set global max fee per gas for EIP-1559 transactions.
Args:
*args: New max fee in wei (empty to get current)
Returns:
int: Current max fee setting
"""
def priority_fee(*args) -> Union[int, None]:
"""
Get or set global priority fee per gas for EIP-1559 transactions.
Args:
*args: New priority fee in wei (empty to get current)
Returns:
int: Current priority fee setting
"""The Chain class provides blockchain state management including snapshots, time manipulation, and mining control for testing environments.
class Chain:
"""
Blockchain state manager for development and testing.
Available as global singleton 'chain' after importing brownie.
Attributes:
height (int): Current block height
time (int): Latest block timestamp
id (int): Chain ID of connected network
"""
def __len__(self) -> int:
"""Get current block height."""
def __getitem__(self, index: int) -> dict:
"""
Get block information by number.
Args:
index: Block number
Returns:
dict: Block data including hash, timestamp, transactions
"""
def snapshot(self) -> str:
"""
Take a snapshot of current blockchain state.
Returns:
str: Snapshot ID for later reversion
"""
def revert(self, snapshot_id: str = None) -> None:
"""
Revert blockchain state to a snapshot.
Args:
snapshot_id: Snapshot ID (latest if None)
"""
def reset(self) -> None:
"""Reset blockchain to initial state (block 0)."""
def undo(self, num_transactions: int = 1) -> None:
"""
Undo recent transactions.
Args:
num_transactions: Number of transactions to undo
"""
def redo(self, num_transactions: int = 1) -> None:
"""
Redo previously undone transactions.
Args:
num_transactions: Number of transactions to redo
"""
def mine(self, blocks: int = 1, timestamp: int = None) -> None:
"""
Mine empty blocks.
Args:
blocks: Number of blocks to mine
timestamp: Timestamp for mined blocks (auto if None)
"""
def sleep(self, seconds: int) -> None:
"""
Advance blockchain time without mining blocks.
Args:
seconds: Seconds to advance
"""
def set_time(self, timestamp: int) -> None:
"""
Set blockchain time to specific timestamp.
Args:
timestamp: Unix timestamp
"""
def get_transaction(self, txid: str) -> TransactionReceipt:
"""
Get transaction by hash.
Args:
txid: Transaction hash
Returns:
TransactionReceipt: Transaction details
"""
def new_block(self, timestamp: int = None) -> None:
"""
Mine a new block with optional timestamp.
Args:
timestamp: Block timestamp (auto if None)
"""The Rpc class manages local RPC node processes for development and testing.
class Rpc:
"""
RPC node process manager for local development networks.
Available as global singleton 'rpc' after importing brownie.
Attributes:
is_active (bool): Whether RPC node is running
endpoint (str): RPC endpoint URL
port (int): RPC port number
"""
def launch(self, cmd: str = None, **kwargs) -> None:
"""
Launch local RPC node process.
Args:
cmd: Custom command to launch RPC (auto-detect if None)
**kwargs: Additional RPC configuration options
"""
def attach(self, laddr: str) -> None:
"""
Attach to existing RPC node.
Args:
laddr: RPC endpoint address
"""
def kill(self, confirm: bool = True) -> None:
"""
Stop the RPC node process.
Args:
confirm: Require confirmation before stopping
"""
def snapshot(self) -> str:
"""
Take RPC-level snapshot of blockchain state.
Returns:
str: Snapshot ID
"""
def revert(self, snapshot_id: str) -> None:
"""
Revert to RPC-level snapshot.
Args:
snapshot_id: Snapshot ID to revert to
"""
def mine(self, blocks: int = 1) -> None:
"""
Mine blocks via RPC.
Args:
blocks: Number of blocks to mine
"""
def sleep(self, seconds: int) -> None:
"""
Advance time via RPC.
Args:
seconds: Seconds to advance
"""
def reset(self) -> None:
"""Reset RPC node to initial state."""Enhanced Web3 instance with brownie-specific functionality and middleware.
class Web3:
"""
Enhanced Web3 instance with brownie-specific functionality.
Available as global singleton 'web3' after importing brownie.
Attributes:
eth: Ethereum interface
net: Network interface
personal: Personal account interface
txpool: Transaction pool interface
admin: Admin interface (if available)
miner: Miner interface (if available)
"""
def __init__(self):
"""Initialize enhanced Web3 instance."""
def isConnected(self) -> bool:
"""Check if Web3 is connected to provider."""
def middleware_onion(self):
"""Access Web3 middleware stack."""
def clientVersion(self) -> str:
"""Get client version string."""
# Standard Web3 methods available through eth interface
def toWei(self, value: Union[int, float, str], unit: str) -> int:
"""Convert value to wei."""
def fromWei(self, value: int, unit: str) -> Union[int, float]:
"""Convert wei to other units."""
def toHex(self, value: Union[int, str, bytes]) -> str:
"""Convert value to hexadecimal string."""
def isAddress(self, address: str) -> bool:
"""Check if string is valid Ethereum address."""
def toChecksumAddress(self, address: str) -> str:
"""Convert address to checksum format."""The TxHistory class manages and filters transaction history for analysis and debugging.
class TxHistory:
"""
Transaction history manager with filtering and analysis capabilities.
Available as global singleton 'history' after importing brownie.
"""
def __len__(self) -> int:
"""Get number of transactions in history."""
def __getitem__(self, index: int) -> TransactionReceipt:
"""
Get transaction by index.
Args:
index: Transaction index
Returns:
TransactionReceipt: Transaction at index
"""
def __iter__(self):
"""Iterate over transaction history."""
def clear(self) -> None:
"""Clear transaction history."""
def filter(self, **kwargs) -> list:
"""
Filter transactions by criteria.
Args:
**kwargs: Filter criteria (sender, receiver, function, etc.)
Returns:
list: Filtered transaction receipts
"""
def from_sender(self, account: str) -> list:
"""
Get transactions from specific sender.
Args:
account: Sender address
Returns:
list: Transactions from sender
"""
def to_receiver(self, account: str) -> list:
"""
Get transactions to specific receiver.
Args:
account: Receiver address
Returns:
list: Transactions to receiver
"""
def of_address(self, account: str) -> list:
"""
Get transactions involving specific address.
Args:
account: Address to search for
Returns:
list: Transactions involving address
"""The Multicall class enables batching multiple contract calls into a single transaction for gas optimization.
class Multicall:
"""
Multicall utility for batching contract calls.
Available as global singleton 'multicall' after importing brownie.
"""
def __init__(self, address: str = None):
"""
Initialize multicall with contract address.
Args:
address: Multicall contract address (auto-detect if None)
"""
def __enter__(self):
"""Enter multicall context manager."""
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit multicall context and execute batched calls."""
def flush(self) -> None:
"""Execute all queued calls and clear the queue."""import brownie
from brownie import network
# Connect to development network
network.connect('development')
print(f"Connected to: {network.show_active()}")
# Connect to testnet
network.connect('sepolia')
# Connect to mainnet
network.connect('mainnet')
# Check connection status
if network.is_connected():
print("Connected to network")
else:
print("Not connected")
# Disconnect
network.disconnect()from brownie import network
# Set global gas settings
network.gas_limit(3000000)
network.gas_price("20 gwei")
# EIP-1559 settings
network.max_fee("30 gwei")
network.priority_fee("2 gwei")
# Check current settings
print(f"Gas limit: {network.gas_limit()}")
print(f"Gas price: {network.gas_price()}")from brownie import chain, accounts
# Take snapshot before test
snapshot = chain.snapshot()
print(f"Snapshot taken: {snapshot}")
# Perform operations
account = accounts[0]
initial_balance = account.balance()
# Mine some blocks
chain.mine(10)
print(f"Block height: {chain.height}")
# Advance time
chain.sleep(3600) # 1 hour
print(f"Block time: {chain.time()}")
# Revert to snapshot
chain.revert(snapshot)
print(f"Reverted to snapshot, height: {chain.height}")
# Reset to genesis
chain.reset()from brownie import rpc
# Launch local RPC node
rpc.launch('ganache-cli', accounts=10, mnemonic='test test test')
# Take RPC snapshot
snapshot_id = rpc.snapshot()
# Perform operations
# ...
# Revert RPC state
rpc.revert(snapshot_id)
# Stop RPC node
rpc.kill()from brownie import history, accounts
# View transaction history
print(f"Total transactions: {len(history)}")
# Get specific transaction
if len(history) > 0:
latest_tx = history[-1]
print(f"Latest transaction: {latest_tx.txid}")
# Filter transactions
sender_txs = history.from_sender(accounts[0].address)
print(f"Transactions from account[0]: {len(sender_txs)}")
# Filter by multiple criteria
filtered_txs = history.filter(
sender=accounts[0].address,
function='transfer'
)
# Clear history
history.clear()from brownie import multicall, project
# Load contracts
token = project.Token.at("0x...")
vault = project.Vault.at("0x...")
# Batch multiple calls
with multicall:
token_balance = token.balanceOf(accounts[0])
vault_balance = vault.balanceOf(accounts[0])
total_supply = token.totalSupply()
# All calls executed in single transaction
print(f"Token balance: {token_balance}")
print(f"Vault balance: {vault_balance}")
print(f"Total supply: {total_supply}")from brownie import web3
# Check connection
print(f"Connected: {web3.isConnected()}")
print(f"Client: {web3.clientVersion}")
# Unit conversions
wei_amount = web3.toWei(1, 'ether')
eth_amount = web3.fromWei(wei_amount, 'ether')
# Address utilities
address = "0x742d35Cc6634C0532925a3b8D8D944d0Cdbc1234"
checksum_addr = web3.toChecksumAddress(address.lower())
is_valid = web3.isAddress(address)
# Access standard Web3 interfaces
latest_block = web3.eth.get_block('latest')
network_id = web3.net.versionfrom brownie import network, chain, accounts, rpc
# Setup development environment
network.connect('development')
network.gas_limit(6000000)
network.gas_price("10 gwei")
# Take initial snapshot
initial_state = chain.snapshot()
try:
# Deploy contracts and run tests
account = accounts[0]
# ... test operations ...
# Take checkpoint before risky operation
checkpoint = chain.snapshot()
# Perform risky operation
# ... risky code ...
except Exception as e:
print(f"Error occurred: {e}")
# Revert to checkpoint
chain.revert(checkpoint)
finally:
# Clean up - revert to initial state
chain.revert(initial_state)
network.disconnect()# Type aliases for network operations
NetworkType = str
BlockIdentifier = Union[int, str] # Block number or 'latest'/'pending'
SnapshotId = str
GasSettings = Dict[str, Union[int, str]]
FilterCriteria = Dict[str, Any]Install with Tessl CLI
npx tessl i tessl/pypi-eth-brownie@1.21.1