CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-web3

A Python library for interacting with Ethereum blockchain

Overall
score

88%

Evaluation88%

1.01x

Agent success when using this tile

Overview
Eval results
Files

account-management.mddocs/

Account Management

Cryptographic account operations including key generation, transaction signing, message signing, account recovery, and secure key management with support for various key formats.

Capabilities

Account Creation and Management

Core account operations for creating and managing Ethereum accounts.

class Account:
    @staticmethod
    def create(extra_entropy: str = '') -> LocalAccount:
        """
        Create new random account.
        
        Parameters:
        - extra_entropy: Additional entropy for key generation
        
        Returns:
        LocalAccount instance with private key and address
        """

    @staticmethod
    def from_key(private_key: Union[PrivateKey, int, bytes, str]) -> LocalAccount:
        """
        Create account from existing private key.
        
        Parameters:
        - private_key: Private key in various formats
        
        Returns:
        LocalAccount instance
        """

    @staticmethod
    def from_mnemonic(
        mnemonic: str,
        passphrase: str = "",
        account_path: str = "m/44'/60'/0'/0/0"
    ) -> LocalAccount:
        """
        Create account from BIP39 mnemonic phrase.
        
        Parameters:
        - mnemonic: BIP39 mnemonic phrase
        - passphrase: Optional passphrase
        - account_path: HD wallet derivation path
        
        Returns:
        LocalAccount instance
        """

    @staticmethod
    def recover_message(
        message: Union[str, bytes],
        signature: Union[str, bytes, Signature]
    ) -> ChecksumAddress:
        """
        Recover address from signed message.
        
        Parameters:
        - message: Original message
        - signature: Message signature
        
        Returns:
        Recovered address
        """

    @staticmethod
    def recover_transaction(serialized_transaction: bytes) -> ChecksumAddress:
        """
        Recover address from signed transaction.
        
        Parameters:
        - serialized_transaction: Signed transaction bytes
        
        Returns:
        Recovered address
        """

Transaction Signing

Transaction creation and signing operations.

class Account:
    @staticmethod
    def sign_transaction(
        transaction_dict: Dict[str, Any],
        private_key: Union[PrivateKey, int, bytes, str]
    ) -> SignedTransaction:
        """
        Sign transaction with private key.
        
        Parameters:
        - transaction_dict: Transaction parameters
        - private_key: Private key for signing
        
        Returns:
        SignedTransaction with hash and raw transaction
        """

    @staticmethod
    def create_access_list_transaction(
        w3: Web3,
        transaction: Dict[str, Any]
    ) -> AccessListTransaction:
        """
        Create EIP-2930 access list transaction.
        
        Parameters:
        - w3: Web3 instance
        - transaction: Transaction parameters
        
        Returns:
        Access list transaction
        """

    @staticmethod
    def create_dynamic_fee_transaction(
        transaction: Dict[str, Any]
    ) -> DynamicFeeTransaction:
        """
        Create EIP-1559 dynamic fee transaction.
        
        Parameters:
        - transaction: Transaction parameters with maxFeePerGas
        
        Returns:
        Dynamic fee transaction
        """

Message Signing

Message signing and verification operations.

class Account:
    @staticmethod
    def sign_message(
        message: Union[str, bytes, EncodableData],
        private_key: Union[PrivateKey, int, bytes, str]
    ) -> SignedMessage:
        """
        Sign arbitrary message with private key.
        
        Parameters:
        - message: Message to sign
        - private_key: Private key for signing
        
        Returns:
        SignedMessage with signature data
        """

    @staticmethod
    def signHash(
        message_hash: bytes,
        private_key: Union[PrivateKey, int, bytes, str]
    ) -> SignedMessage:
        """
        Sign message hash directly.
        
        Parameters:
        - message_hash: Pre-hashed message
        - private_key: Private key for signing
        
        Returns:
        SignedMessage with signature data
        """

Keystore Operations

Keystore file encryption and decryption.

class Account:
    @staticmethod
    def encrypt(
        private_key: Union[PrivateKey, int, bytes, str],
        password: str,
        kdf: str = "scrypt",
        iterations: Optional[int] = None
    ) -> Dict[str, Any]:
        """
        Encrypt private key to keystore format.
        
        Parameters:
        - private_key: Private key to encrypt
        - password: Encryption password
        - kdf: Key derivation function ('scrypt' or 'pbkdf2')
        - iterations: KDF iterations (None for default)
        
        Returns:
        Keystore JSON dictionary
        """

    @staticmethod
    def decrypt(keyfile_json: Dict[str, Any], password: str) -> PrivateKey:
        """
        Decrypt keystore file.
        
        Parameters:
        - keyfile_json: Keystore JSON data
        - password: Decryption password
        
        Returns:
        Decrypted private key
        """

Local Account

Local account instance with private key access.

class LocalAccount:
    @property
    def address(self) -> ChecksumAddress:
        """Get account address."""

    @property
    def key(self) -> PrivateKey:
        """Get private key."""

    def sign_message(self, message: Union[str, bytes, EncodableData]) -> SignedMessage:
        """
        Sign message with this account's private key.
        
        Parameters:
        - message: Message to sign
        
        Returns:
        SignedMessage with signature
        """

    def sign_transaction(self, transaction_dict: Dict[str, Any]) -> SignedTransaction:
        """
        Sign transaction with this account's private key.
        
        Parameters:
        - transaction_dict: Transaction parameters
        
        Returns:
        SignedTransaction
        """

    def encrypt(self, password: str, kdf: str = "scrypt") -> Dict[str, Any]:
        """
        Encrypt this account to keystore format.
        
        Parameters:
        - password: Encryption password
        - kdf: Key derivation function
        
        Returns:
        Keystore JSON dictionary
        """

Types

Account-related type definitions.

PrivateKey = NewType('PrivateKey', bytes)

class SignedMessage(NamedTuple):
    messageHash: Hash32
    r: int
    s: int
    v: int
    signature: HexBytes

class SignedTransaction(NamedTuple):
    rawTransaction: HexBytes
    hash: Hash32
    r: int
    s: int  
    v: int

class Signature(NamedTuple):
    v: int
    r: int
    s: int

class AccessListEntry(TypedDict):
    address: ChecksumAddress
    storageKeys: List[Hash32]

class AccessListTransaction(TypedDict):
    chainId: int
    nonce: int
    gasPrice: Wei
    gas: int
    to: ChecksumAddress
    value: Wei
    data: HexBytes
    accessList: List[AccessListEntry]

class DynamicFeeTransaction(TypedDict):
    chainId: int
    nonce: int
    maxFeePerGas: Wei
    maxPriorityFeePerGas: Wei
    gas: int
    to: ChecksumAddress
    value: Wei
    data: HexBytes
    accessList: List[AccessListEntry]

Usage Examples

Creating New Accounts

from web3 import Account

# Create random account
account = Account.create()
print(f"Address: {account.address}")
print(f"Private key: {account.key.hex()}")

# Create account with extra entropy
account = Account.create(extra_entropy="my-extra-randomness")
print(f"Secure address: {account.address}")

# Create account from existing private key
private_key = "0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318"
account = Account.from_key(private_key)
print(f"Restored address: {account.address}")

HD Wallet Support

from web3 import Account

# Create account from mnemonic
mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
account = Account.from_mnemonic(mnemonic)
print(f"HD wallet address: {account.address}")

# Different derivation paths
account1 = Account.from_mnemonic(mnemonic, account_path="m/44'/60'/0'/0/0")
account2 = Account.from_mnemonic(mnemonic, account_path="m/44'/60'/0'/0/1")
print(f"Account 1: {account1.address}")
print(f"Account 2: {account2.address}")

# With passphrase
secure_account = Account.from_mnemonic(
    mnemonic, 
    passphrase="my-secure-passphrase"
)
print(f"Secured address: {secure_account.address}")

Transaction Signing

from web3 import Web3, Account

w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
account = Account.create()

# Build transaction
transaction = {
    'nonce': w3.eth.get_nonce(account.address),
    'to': '0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8',
    'value': w3.to_wei(1, 'ether'),
    'gas': 21000,
    'gasPrice': w3.to_wei(20, 'gwei'),
    'chainId': 1
}

# Sign transaction
signed_txn = account.sign_transaction(transaction)
print(f"Signed transaction hash: {signed_txn.hash.hex()}")
print(f"Raw transaction: {signed_txn.rawTransaction.hex()}")

# Send signed transaction
tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
print(f"Transaction hash: {tx_hash.hex()}")

Message Signing and Recovery

from web3 import Account
from eth_account.messages import encode_defunct

account = Account.create()

# Sign message
message = "Hello, Ethereum!"
message_encoded = encode_defunct(text=message)
signed_message = account.sign_message(message_encoded)

print(f"Message hash: {signed_message.messageHash.hex()}")
print(f"Signature: {signed_message.signature.hex()}")

# Recover address from signed message
recovered_address = Account.recover_message(message_encoded, signed_message.signature)
print(f"Original address: {account.address}")
print(f"Recovered address: {recovered_address}")
print(f"Addresses match: {account.address == recovered_address}")

Keystore Operations

from web3 import Account
import json

account = Account.create()
password = "secure-password-123"

# Encrypt account to keystore
keystore = account.encrypt(password)
print("Keystore created:")
print(json.dumps(keystore, indent=2))

# Save keystore to file
with open('keystore.json', 'w') as f:
    json.dump(keystore, f)

# Decrypt keystore
with open('keystore.json', 'r') as f:
    keystore_data = json.load(f)

decrypted_key = Account.decrypt(keystore_data, password)
restored_account = Account.from_key(decrypted_key)

print(f"Original address: {account.address}")
print(f"Restored address: {restored_account.address}")
print(f"Keys match: {account.key == restored_account.key}")

EIP-1559 Dynamic Fee Transactions

from web3 import Web3, Account

w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
account = Account.create()

# EIP-1559 transaction with dynamic fees
transaction = {
    'nonce': w3.eth.get_nonce(account.address),
    'to': '0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8',
    'value': w3.to_wei(1, 'ether'),
    'gas': 21000,
    'maxFeePerGas': w3.to_wei(30, 'gwei'),
    'maxPriorityFeePerGas': w3.to_wei(2, 'gwei'),
    'chainId': 1,
    'type': 2  # EIP-1559
}

signed_txn = account.sign_transaction(transaction)
tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
print(f"EIP-1559 transaction hash: {tx_hash.hex()}")

Access List Transactions (EIP-2930)

from web3 import Web3, Account

w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
account = Account.create()

# EIP-2930 access list transaction
access_list = [
    {
        'address': '0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8',
        'storageKeys': [
            '0x0000000000000000000000000000000000000000000000000000000000000000'
        ]
    }
]

transaction = {
    'nonce': w3.eth.get_nonce(account.address),
    'to': '0x742d35Cc6635C0532925a3b8D5c0d9E3C4B3c8',
    'value': w3.to_wei(1, 'ether'),
    'gas': 21000,
    'gasPrice': w3.to_wei(20, 'gwei'),
    'accessList': access_list,
    'chainId': 1,
    'type': 1  # EIP-2930
}

signed_txn = account.sign_transaction(transaction)
tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
print(f"Access list transaction hash: {tx_hash.hex()}")

Batch Operations

from web3 import Account

# Create multiple accounts
accounts = [Account.create() for _ in range(5)]

# Display all addresses
for i, account in enumerate(accounts):
    print(f"Account {i}: {account.address}")

# Sign the same message with all accounts
message = "Batch signing test"
signatures = []

for account in accounts:
    signed = account.sign_message(encode_defunct(text=message))
    signatures.append({
        'address': account.address,
        'signature': signed.signature.hex()
    })

print(f"Generated {len(signatures)} signatures")

Install with Tessl CLI

npx tessl i tessl/pypi-web3

docs

account-management.md

ens-operations.md

ethereum-operations.md

index.md

middleware.md

providers.md

smart-contracts.md

utilities.md

web3-client.md

tile.json