CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-eth-brownie

A Python framework for Ethereum smart contract deployment, testing and interaction.

Pending
Overview
Eval results
Files

accounts.mddocs/

Account Management

Comprehensive account management system for handling private keys, external signers, and transaction broadcasting with gas optimization and error handling capabilities.

Capabilities

Account Container

The global accounts container manages multiple account types and provides unified access to local accounts, hardware wallets, and external signers.

class Accounts:
    """
    Container for managing multiple accounts.
    
    Available as global singleton 'accounts' after importing brownie.
    """
    def __len__(self) -> int:
        """Return number of available accounts."""
        
    def __getitem__(self, index: int) -> LocalAccount:
        """Get account by index."""
        
    def __iter__(self):
        """Iterate over available accounts."""
        
    def add(self, private_key: str) -> LocalAccount:
        """
        Add account from private key.
        
        Args:
            private_key: Hexadecimal private key string
            
        Returns:
            LocalAccount instance for the added account
        """
        
    def load(self, filename: str, password: str = None) -> LocalAccount:
        """
        Load encrypted account from file.
        
        Args:
            filename: Path to encrypted account file
            password: Password to decrypt the account
            
        Returns:
            LocalAccount instance for the loaded account
        """
        
    def new(self, password: str = None) -> LocalAccount:
        """
        Generate new random account.
        
        Args:
            password: Optional password to encrypt the account
            
        Returns:
            LocalAccount instance for the new account
        """
        
    def clear(self) -> None:
        """Remove all accounts from the container."""
        
    def default(self) -> LocalAccount:
        """Get the default account (accounts[0])."""

Local Account

Local accounts handle private key management and transaction signing with comprehensive transaction options and gas management.

class LocalAccount:
    """
    Account with local private key for signing transactions.
    
    Attributes:
        address (str): Account's Ethereum address
        private_key (str): Account's private key (read-only)
        nonce (int): Current account nonce
    """
    
    def __init__(self, address: str, private_key: str):
        """Initialize local account with address and private key."""
        
    def balance(self) -> Wei:
        """
        Get account balance in wei.
        
        Returns:
            Wei: Current account balance
        """
        
    def transfer(
        self, 
        to: str, 
        amount: Union[int, str, Wei], 
        gas_limit: int = None,
        gas_price: int = None,
        max_fee: int = None,
        priority_fee: int = None,
        nonce: int = None,
        required_confs: int = 1,
        allow_revert: bool = False,
        silent: bool = False
    ) -> TransactionReceipt:
        """
        Transfer ether to another account.
        
        Args:
            to: Recipient address
            amount: Amount to transfer (in wei or string with units)
            gas_limit: Gas limit for transaction
            gas_price: Gas price (legacy transactions)
            max_fee: Maximum fee per gas (EIP-1559)
            priority_fee: Priority fee per gas (EIP-1559)
            nonce: Transaction nonce (auto if None)
            required_confs: Required confirmations
            allow_revert: Allow reverted transactions
            silent: Suppress console output
            
        Returns:
            TransactionReceipt: Transaction receipt
        """
        
    def deploy(
        self,
        contract,
        *args,
        amount: Union[int, str, Wei] = 0,
        gas_limit: int = None,
        gas_price: int = None,
        max_fee: int = None,
        priority_fee: int = None,
        nonce: int = None,
        required_confs: int = 1,
        allow_revert: bool = False,
        silent: bool = False,
        publish_source: bool = False
    ) -> Contract:
        """
        Deploy a contract.
        
        Args:
            contract: Contract class or container to deploy
            *args: Constructor arguments
            amount: Ether to send with deployment
            gas_limit: Gas limit for deployment
            gas_price: Gas price (legacy transactions)
            max_fee: Maximum fee per gas (EIP-1559)
            priority_fee: Priority fee per gas (EIP-1559)
            nonce: Transaction nonce (auto if None)
            required_confs: Required confirmations
            allow_revert: Allow reverted deployments
            silent: Suppress console output
            publish_source: Publish source to block explorer
            
        Returns:
            Contract: Deployed contract instance
        """
        
    def estimate_gas(
        self,
        to: str,
        amount: Union[int, str, Wei] = 0,
        data: str = "0x"
    ) -> int:
        """
        Estimate gas for a transaction.
        
        Args:
            to: Transaction recipient
            amount: Ether amount to send
            data: Transaction data
            
        Returns:
            int: Estimated gas amount
        """
        
    def get_deployment_address(self, nonce: int = None) -> str:
        """
        Calculate contract deployment address.
        
        Args:
            nonce: Nonce to use for calculation (current if None)
            
        Returns:
            str: Predicted deployment address
        """

External Signers

Support for external signing services and hardware wallets through standardized interfaces.

class ClefAccount:
    """
    Account using Clef external signer.
    
    Attributes:
        address (str): Account's Ethereum address
    """
    
    def __init__(self, address: str):
        """Initialize Clef account with address."""
        
    def transfer(self, to: str, amount: Union[int, str, Wei], **kwargs) -> TransactionReceipt:
        """Transfer ether using Clef signer."""
        
    def deploy(self, contract, *args, **kwargs) -> Contract:
        """Deploy contract using Clef signer."""

class PublicKeyAccount:
    """
    Read-only account (no signing capability).
    
    Attributes:
        address (str): Account's Ethereum address
    """
    
    def __init__(self, address: str):
        """Initialize public key account with address."""
        
    def balance(self) -> Wei:
        """Get account balance."""

Transaction Management

class TransactionReceipt:
    """
    Transaction receipt with events, logs, and execution details.
    
    Attributes:
        txid (str): Transaction hash
        sender (str): Transaction sender address
        receiver (str): Transaction receiver address
        value (Wei): Ether amount transferred
        gas_limit (int): Gas limit set for transaction
        gas_used (int): Actual gas consumed
        gas_price (int): Gas price paid per unit
        nonce (int): Transaction nonce
        block_number (int): Block number where transaction was mined
        timestamp (int): Block timestamp
        status (int): Transaction status (1=success, 0=failure)
        events (dict): Decoded event logs
        logs (list): Raw event logs
        return_value: Return value from contract call
        revert_msg (str): Revert message if transaction failed
    """
    
    def __init__(self, txid: str):
        """Initialize transaction receipt."""
        
    def call_trace(self) -> list:
        """Get detailed call trace for debugging."""
        
    def traceback(self) -> None:
        """Print formatted traceback for failed transactions."""
        
    def info(self) -> None:
        """Print formatted transaction information."""
        
    def wait(self, required_confs: int = 1, timeout: int = None) -> 'TransactionReceipt':
        """
        Wait for transaction confirmation.
        
        Args:
            required_confs: Number of confirmations to wait for
            timeout: Timeout in seconds
            
        Returns:
            TransactionReceipt: Self after confirmation
        """

Usage Examples

Basic Account Operations

from brownie import accounts, network

# Connect to network
network.connect('development')

# Access local development accounts
account = accounts[0]
print(f"Account address: {account.address}")
print(f"Account balance: {account.balance()}")

# Add account from private key
new_account = accounts.add('0x416b8a7d9290502f5661da81f0cf43893e3d19cb9aea3c426cfb36e8186e9c09')

# Generate new random account
random_account = accounts.new()

Ether Transfers

from brownie import accounts, Wei

account1 = accounts[0]
account2 = accounts[1]

# Transfer 1 ether
tx = account1.transfer(account2, "1 ether")
print(f"Transaction hash: {tx.txid}")
print(f"Gas used: {tx.gas_used}")

# Transfer with specific gas settings
tx = account1.transfer(
    account2, 
    Wei("0.5 ether"),
    gas_limit=21000,
    gas_price="20 gwei"
)

# EIP-1559 transaction
tx = account1.transfer(
    account2,
    Wei("0.1 ether"),
    max_fee="30 gwei",
    priority_fee="2 gwei"
)

Contract Deployment

from brownie import accounts, project

# Load project and get account
p = project.load()
account = accounts[0]

# Deploy contract with constructor arguments
contract = account.deploy(p.MyContract, "constructor_arg", 42)

# Deploy with ether and custom gas
contract = account.deploy(
    p.MyContract,
    amount="1 ether",
    gas_limit=3000000,
    publish_source=True
)

Error Handling

from brownie import accounts, reverts

account = accounts[0]

# Handle transaction failures
try:
    tx = account.transfer("invalid_address", "1 ether")
except ValueError as e:
    print(f"Transaction failed: {e}")

# Allow reverted transactions
tx = account.transfer(
    some_contract_address, 
    "1 ether", 
    allow_revert=True
)

if tx.status == 0:
    print(f"Transaction reverted: {tx.revert_msg}")
    tx.traceback()  # Print detailed error trace

Type Definitions

# Type aliases for account-related operations
AccountType = Union[LocalAccount, ClefAccount, PublicKeyAccount]
TxParams = Dict[str, Union[int, str, bool]]
GasStrategy = Union[str, dict, Callable]

Install with Tessl CLI

npx tessl i tessl/pypi-eth-brownie@1.21.1

docs

accounts.md

cli.md

contracts.md

conversion-testing.md

index.md

network.md

project.md

tile.json