ape-ethereum

class ape_ethereum.AccessListTransaction(*args, chainId: int | None = 0, to: ChecksumAddress | None = None, sender: ChecksumAddress | None = None, gas: int | None = None, nonce: int | None = None, value: int = 0, data: HexBytes = HexBytes('0x'), type: int = 1, max_fee: int | None = None, max_priority_fee: int | None = None, required_confirmations: int | None = None, signature: TransactionSignature | None = None, gasPrice: int | None = None, accessList: list[ape_ethereum.transactions.AccessList] = None)

EIP-2930 transactions are similar to legacy transaction with an added access list functionality.

class ape_ethereum.BaseEthereumConfig(_case_sensitive: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _secrets_dir: str | Path | None = None, *, default_network: str = 'local', request_headers: dict = {}, **values: Any)

L2 plugins should use this as their config base-class.

class ape_ethereum.BaseTransaction(*args, chainId: int | None = 0, to: ChecksumAddress | None = None, sender: ChecksumAddress | None = None, gas: int | None = None, nonce: int | None = None, value: int = 0, data: HexBytes = HexBytes('0x'), type: int, max_fee: int | None = None, max_priority_fee: int | None = None, required_confirmations: int | None = None, signature: TransactionSignature | None = None)
serialize_transaction() bytes

Serialize the transaction

property txn_hash: HexBytes

The calculated hash of the transaction.

class ape_ethereum.Block(*, num_transactions: int = 0, hash: HexBytes | None = None, number: int | None = None, parentHash: HexBytes = HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), timestamp: int, gasLimit: int, gasUsed: int, baseFeePerGas: int = 0, difficulty: int = 0, totalDifficulty: int = 0, uncles: list[eth_pydantic_types.hex.HexBytes] = [])

Class for representing a block on a chain.

hash: HexBytes | None

The block hash identifier.

parent_hash: HexBytes

The preceeding block’s hash.

property size: int

The size of the block in gas. Most of the time, this field is passed to the model at validation time, but occassionally it is missing (like in eth_subscribe:newHeads), in which case it gets calculated if and only if the user requests it (or during serialization of this model to disk).

class ape_ethereum.CallTrace(*, call_trace_approach: TraceApproach = TraceApproach.GETH_STRUCT_LOG_PARSE, tx: dict, arguments: list[Any] = [], supports_debug_trace_call: bool | None = None)
arguments: list[Any]

Remaining eth-call arguments, minus the transaction.

call_trace_approach: TraceApproach

debug_traceCall must use the struct-log tracer.

get_calltree() CallTreeNode

Get an un-enriched call-tree node.

property raw_trace_frames: Iterator[dict]

The raw trace frames.

property return_value: Any

The return value deduced from the trace.

property transaction: dict

The transaction data (obtained differently on calls versus transactions).

tx: dict

Transaction data. Is a dictionary to allow traces to easily be created near sending the request.

class ape_ethereum.DynamicFeeTransaction(*args, chainId: int | None = 0, to: ChecksumAddress | None = None, sender: ChecksumAddress | None = None, gas: int | None = None, nonce: int | None = None, value: int = 0, data: HexBytes = HexBytes('0x'), type: int = 2, maxFeePerGas: int | None = None, maxPriorityFeePerGas: int | None = None, required_confirmations: int | None = None, signature: TransactionSignature | None = None, accessList: list[ape_ethereum.transactions.AccessList] = None)

Transactions that are post-EIP-1559 and use the maxFeePerGas and maxPriorityFeePerGas fields.

class ape_ethereum.Ethereum(*, name: str, request_header: dict = {}, fee_token_symbol: str = 'ETH', fee_token_decimals: int = 18)
property config: EthereumConfig

The configuration of the ecosystem. See ape.managers.config.ConfigManager for more information on plugin configurations.

Returns:

ape.api.config.PluginConfig

create_transaction(**kwargs) TransactionAPI

Returns a transaction using the given constructor kwargs.

NOTE: This generally should not be called by the user since this API method is used as a hook for Ecosystems to customize how transactions are created.

Returns:

TransactionAPI

classmethod decode_address(raw_address: str | int | HashStr20 | HashBytes20) ChecksumAddress

Convert a raw address to the ecosystem’s native address type.

Parameters:

raw_address (RawAddress) – The address to convert.

Returns:

AddressType

decode_block(data: dict) BlockAPI

Decode data to a BlockAPI.

Parameters:

data (Dict) – A dictionary of data to decode.

Returns:

BlockAPI

decode_calldata(abi: ConstructorABI | MethodABI, calldata: bytes) dict

Decode method calldata.

Parameters:
  • abi (Union[ConstructorABI, MethodABI]) – The method called.

  • calldata (bytes) – The raw calldata bytes.

Returns:

A mapping of input names to decoded values. If an input is anonymous, it should use the stringified index of the input as the key.

Return type:

Dict

decode_custom_error(data: HexBytes, address: ChecksumAddress, **kwargs) CustomError | None

Decode a custom error class from an ABI defined in a contract.

Parameters:
  • data (HexBytes) – The error data containing the selector and input data.

  • address (AddressType) – The address of the contract containing the error.

  • **kwargs – Additional init kwargs for the custom error class.

Returns:

If it able to decode one, else None.

Return type:

Optional[CustomError]

decode_logs(logs: Sequence[dict], *events: EventABI) Iterator[ContractLog]

Decode any contract logs that match the given event ABI from the raw log data.

Parameters:
  • logs (Sequence[Dict]) – A list of raw log data from the chain.

  • *events (EventABI) – Event definitions to decode.

Returns:

Iterator[ContractLog]

decode_primitive_value(value: Any, output_type: str | tuple | list) str | HexBytes | int | tuple | list

Decode a primitive value-type given its ABI type as a str and the value itself. This method is a hook for converting addresses, HexBytes, or other primitive data-types into friendlier Python equivalents.

Parameters:
  • value (Any) – The value to decode.

  • output_type (Union[str, tuple, list]) – The value type.

Returns:

Union[str, HexBytes, tuple]

decode_receipt(data: dict) ReceiptAPI

Convert data to ReceiptAPI.

Parameters:

data (Dict) – A dictionary of Receipt properties.

Returns:

ReceiptAPI

decode_returndata(abi: MethodABI, raw_data: bytes) tuple[Any, ...]

Get the result of a contract call.

Arg:

abi (MethodABI): The method called. raw_data (bytes): Raw returned data.

Returns:

All of the values returned from the contract function.

Return type:

Any

classmethod encode_address(address: ChecksumAddress) str | int | HashStr20 | HashBytes20

Convert the ecosystem’s native address type to a raw integer or str address.

Parameters:

address (AddressType) – The address to convert.

Returns:

RawAddress

encode_calldata(abi: ConstructorABI | MethodABI, *args) HexBytes

Encode method calldata.

Parameters:
  • abi (Union[ConstructorABI, MethodABI]) – The ABI of the method called.

  • *args (Any) – The arguments given to the method.

Returns:

The encoded calldata of the arguments to the given method.

Return type:

HexBytes

encode_contract_blueprint(contract_type: ContractType, *args, **kwargs) TransactionAPI

Encode a unique type of transaction that allows contracts to be created from other contracts, such as EIP-5202 or Starknet’s Declare transaction type.

Parameters:
  • contract_type (ContractType) – The type of contract to create a blueprint for. This is the type of contract that will get created by factory contracts.

  • *args (Any) – Calldata, if applicable.

  • **kwargs (Any) – Transaction specifications, such as value.

Returns:

TransactionAPI

encode_deployment(deployment_bytecode: HexBytes, abi: ConstructorABI, *args, **kwargs) BaseTransaction

Create a deployment transaction in the given ecosystem. This may require connecting to other networks.

Parameters:
  • deployment_bytecode (HexBytes) – The bytecode to deploy.

  • abi (ConstructorABI) – The constructor interface of the contract.

  • *args (Any) – Constructor arguments.

  • **kwargs (Any) – Transaction arguments.

Returns:

~ape.api.transactions.TransactionAPI

Return type:

class

encode_transaction(address: ChecksumAddress, abi: MethodABI, *args, **kwargs) BaseTransaction

Encode a transaction object from a contract function’s ABI and call arguments. Additionally, update the transaction arguments with the overrides in kwargs.

Parameters:
  • address (AddressType) – The address of the contract.

  • abi (MethodABI) – The function to call on the contract.

  • *args (Any) – Function arguments.

  • **kwargs (Any) – Transaction arguments.

Returns:

~ape.api.transactions.TransactionAPI

Return type:

class

enrich_trace(trace: TraceAPI, **kwargs) TraceAPI

Enhance the data in the call tree using information about the ecosystem.

Parameters:
  • trace (TraceAPI) – The trace to enrich.

  • **kwargs – Additional kwargs to control enrichment, defined at the plugin level.

Returns:

TraceAPI

fee_token_symbol: str

The token symbol for the currency that pays for fees, such as ETH.

get_proxy_info(address: ChecksumAddress) ProxyInfo | None

Information about a proxy contract such as proxy type and implementation address.

Parameters:

address (AddressType) – The address of the contract.

Returns:

Returns None if the contract does not use any known proxy pattern.

Return type:

Optional[ProxyInfoAPI]

get_python_types(abi_type: ABIType) type | Sequence

Get the Python types for a given ABI type.

Parameters:

abi_type (ABIType) – The ABI type to get the Python types for.

Returns:

The Python types for the given ABI type.

Return type:

Union[Type, Sequence]

class ape_ethereum.EthereumConfig(_case_sensitive: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _secrets_dir: str | Path | None = None, *, default_network: str = 'local', request_headers: dict = {}, mainnet: ~ape_ethereum.ecosystem.NetworkConfig = NetworkConfig(required_confirmations=2, default_provider='node', block_time=13, transaction_acceptance_timeout=120, default_transaction_type=<TransactionType.DYNAMIC: 2>, max_receipt_retries=20, gas_limit='auto', base_fee_multiplier=1.4, request_headers={}), holesky: ~ape_ethereum.ecosystem.NetworkConfig = NetworkConfig(required_confirmations=2, default_provider='node', block_time=13, transaction_acceptance_timeout=120, default_transaction_type=<TransactionType.DYNAMIC: 2>, max_receipt_retries=20, gas_limit='auto', base_fee_multiplier=1.4, request_headers={}), sepolia: ~ape_ethereum.ecosystem.NetworkConfig = NetworkConfig(required_confirmations=2, default_provider='node', block_time=15, transaction_acceptance_timeout=120, default_transaction_type=<TransactionType.DYNAMIC: 2>, max_receipt_retries=20, gas_limit='auto', base_fee_multiplier=1.4, request_headers={}), **values: ~typing.Any)
class ape_ethereum.EthereumNodeProvider(*args, name: str = 'node', network: NetworkAPI, provider_settings: dict = {}, request_header: dict = {'User-Agent': "web3.py/6.20.1/<class 'web3.providers.rpc.HTTPProvider'>"}, block_page_size: int = 5000, concurrency: int = 16)
block_page_size: int

The amount of blocks to fetch in a response, as a default. This is particularly useful for querying logs across a block range.

concurrency: int

How many parallel threads to use when fetching logs.

connect()

Connect a to a provider, such as start-up a process or create an HTTP connection.

property connection_id: str | None

A connection ID to uniquely identify and manage multiple connections to providers, especially when working with multiple providers of the same type, like multiple Geth –dev nodes.

property connection_str: str

The str representing how to connect to the node, such as an HTTP URL or an IPC path.

disconnect()

Disconnect from a provider, such as tear-down a process or quit an HTTP session.

property http_uri: str | None

The connected HTTP URI. If using providers like ape-node, configure your URI and that will be returned here instead.

name: str

The name of the provider (should be the plugin name).

request_header: dict

A header to set on HTTP/RPC requests.

property ws_uri: str | None

Return the raw WS/WSS URI to connect to this provider, if supported.

class ape_ethereum.ForkedNetworkConfig(_case_sensitive: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _secrets_dir: str | Path | None = None, *, required_confirmations: int = 0, default_provider: str | None = 'node', block_time: int = 0, transaction_acceptance_timeout: int = 120, default_transaction_type: TransactionType = TransactionType.DYNAMIC, max_receipt_retries: int = 20, gas_limit: Literal['auto', 'max'] | int | str | AutoGasLimit = 'auto', base_fee_multiplier: float = 1.0, request_headers: dict = {}, upstream_provider: str | None = None, **values: Any)
upstream_provider: str | None

The provider to use as the upstream-provider for this forked network.

class ape_ethereum.NetworkConfig(_case_sensitive: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _secrets_dir: str | Path | None = None, *, required_confirmations: int = 0, default_provider: str | None = 'node', block_time: int = 0, transaction_acceptance_timeout: int = 120, default_transaction_type: TransactionType = TransactionType.DYNAMIC, max_receipt_retries: int = 20, gas_limit: Literal['auto', 'max'] | int | str | AutoGasLimit = 'auto', base_fee_multiplier: float = 1.0, request_headers: dict = {}, **values: Any)

The Ethereum network config base class for each network, e.g. "mainnet", `"local", etc.

base_fee_multiplier: float

A multiplier to apply to a transaction base fee.

block_time: int

Approximate amount of time for a block to be added to the network.

default_provider: str | None

The default provider to use. If set to None, ape will rely on an external plugin supplying the provider implementation, such as ape-hardhat supplying forked-network providers.

default_transaction_type: TransactionType

The default type of transaction to use.

gas_limit: Literal['auto', 'max'] | int | str | AutoGasLimit

The gas limit override to use for the network. If set to "auto", ape will estimate gas limits based on the transaction. If set to "max" the gas limit will be set to the maximum block gas limit for the network. Otherwise an int can be used to specify an explicit gas limit amount (either base 10 or 16).

The default for local networks is "max", otherwise "auto".

max_receipt_retries: int

Maximum number of retries when getting a receipt from a transaction before failing.

request_headers: dict

Optionally config extra request headers whenever using this network.

required_confirmations: int

The amount of blocks to wait before considering a transaction ‘confirmed’.

transaction_acceptance_timeout: int

The amount tof time before failing when sending a transaction and it leaving the mempool.

class ape_ethereum.Receipt(*, contract_address: ChecksumAddress | None = None, block_number: int, gas_used: int, logs: list[dict] = [], status: int, txn_hash: HexStr, transaction: TransactionAPI, gas_limit: int, gas_price: int)
property debug_logs_typed: list[tuple[Any]]

Extract messages to console outputted by contracts via print() or console.log() statements

decode_logs(abi: list[Union[ethpm_types.abi.EventABI, ape.contracts.base.ContractEvent]] | EventABI | ContractEvent | None = None) ContractLogContainer

Decode the logs on the receipt.

Parameters:

abi (EventABI) – The ABI of the event to decode into logs.

Returns:

list[ContractLog]

property failed: bool

Whether the receipt represents a failing transaction. Ecosystem plugins override this property when their receipts are able to be failing.

property method_called: MethodABI | None

The method ABI of the method called to produce this receipt.

raise_for_status()

Handle provider-specific errors regarding a non-successful TransactionStatusEnum.

property ran_out_of_gas: bool

Check if a transaction ran out of gas and failed.

Returns:

True when the transaction failed and used the same amount of gas as the given gas_limit.

Return type:

bool

show_events(file: ~typing.IO[str] = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)

Show the events from the receipt.

show_gas_report(file: ~typing.IO[str] = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)

Display a gas report for the calls made in this transaction.

show_source_traceback(file: ~typing.IO[str] = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)

Show a receipt traceback mapping to lines in the source code. Only works when the contract type and source code are both available, like in local projects.

show_trace(verbose: bool = False, file: ~typing.IO[str] = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)

Display the complete sequence of contracts and methods called during the transaction.

Parameters:
  • verbose (bool) – Set to True to include more information.

  • file (IO[str]) – The file to send output to. Defaults to stdout.

property source_traceback: SourceTraceback

A Pythonic style traceback for both failing and non-failing receipts. Requires a provider that implements :meth:~ape.api.providers.ProviderAPI.get_transaction_trace`.

property total_fees_paid: int

The total amount of fees paid for the transaction.

class ape_ethereum.SharedBlobReceipt(*, contract_address: ChecksumAddress | None = None, block_number: int, gas_used: int, logs: list[dict] = [], status: int, txn_hash: HexStr, transaction: TransactionAPI, gas_limit: int, gas_price: int, blobGasUsed: int | None = None, blobGasPrice: int)

An EIP-4844” blob transaction.

blob_gas_price: int

The blob-gas price, independent from regular gas price.

blob_gas_used: int | None

The total amount of blob gas consumed by the transactions within the block.

class ape_ethereum.SharedBlobTransaction(*args, chainId: int | None = 0, to: ChecksumAddress = '0x0000000000000000000000000000000000000000', sender: ChecksumAddress | None = None, gas: int | None = None, nonce: int | None = None, value: int = 0, data: HexBytes = HexBytes('0x'), type: int = 2, maxFeePerGas: int | None = None, maxPriorityFeePerGas: int | None = None, required_confirmations: int | None = None, signature: TransactionSignature | None = None, accessList: list[ape_ethereum.transactions.AccessList] = None, maxFeePerBlobGas: int = 0, blobVersionedHashes: list[eth_pydantic_types.hex.HexBytes] = None)

EIP-4844 transactions.

receiver: ChecksumAddress

Overridden because EIP-4844 states it cannot be nil.

class ape_ethereum.StaticFeeTransaction(*args, chainId: int | None = 0, to: ChecksumAddress | None = None, sender: ChecksumAddress | None = None, gas: int | None = None, nonce: int | None = None, value: int = 0, data: HexBytes = HexBytes('0x'), type: int = 0, max_fee: int | None = None, max_priority_fee: int | None = None, required_confirmations: int | None = None, signature: TransactionSignature | None = None, gasPrice: int | None = None)

Transactions that are pre-EIP-1559 and use the gasPrice field.

class ape_ethereum.Trace(*, call_trace_approach: TraceApproach | None = None)

Set to True to use an ERC-20’s SYMBOL as the contract’s identifier. Is True when showing pretty traces without gas tables. When gas is involved, Ape must use the .name as the identifier for all contracts.

call_trace_approach: TraceApproach | None

When None, attempts to deduce.

property debug_logs: Iterable[tuple[Any]]

Calls from console.log() and print() from a transactions call tree.

property enriched_calltree: dict

The fully enriched calltree node.

abstract get_calltree() CallTreeNode

Get an un-enriched call-tree node.

get_gas_report(exclude: Sequence[ContractFunctionPath] | None = None) dict[str, dict[str, list[int]]]

Get the gas report.

get_raw_calltree() dict

Get a raw calltree for deeper analysis.

get_raw_frames() Iterator[dict]

Get raw trace frames for deeper analysis.

abstract property raw_trace_frames: Iterator[dict]

The raw trace frames.

property return_value: Any

The return value deduced from the trace.

property revert_message: str | None

The revert message deduced from the trace.

show(verbose: bool = False, file: ~typing.IO[str] = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)

Show the enriched trace.

show_gas_report(verbose: bool = False, file: ~typing.IO[str] = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)

Show the gas report.

abstract property transaction: dict

The transaction data (obtained differently on calls versus transactions).

class ape_ethereum.TransactionStatusEnum(value)

An Enum class representing the status of a transaction.

FAILING = 0

The transaction has failed or is in the process of failing.

NO_ERROR = 1

The transaction is successful and is confirmed or is in the process of getting confirmed.

class ape_ethereum.TransactionTrace(*, call_trace_approach: TraceApproach | None = None, transaction_hash: str, debug_trace_transaction_parameters: dict = {'enableMemory': True})
get_calltree() CallTreeNode

Get an un-enriched call-tree node.

property raw_trace_frames: Iterator[dict]

The raw trace "structLogs" from debug_traceTransaction for deeper investigation.

property transaction: dict

The transaction data (obtained differently on calls versus transactions).

class ape_ethereum.TransactionType(value)

Transaction enumerable type constants defined by EIP-2718.

class ape_ethereum.Web3Provider(*args, name: str, network: NetworkAPI, provider_settings: dict = {}, request_header: dict = {}, block_page_size: int = 100, concurrency: int = 4)

A base provider mixin class that uses the web3.py python package.

property base_fee: int

The minimum value required to get your transaction included on the next block. Only providers that implement EIP-1559 will use this property.

Raises:

NotImplementedError – When this provider does not implement EIP-1559.

property call_trace_approach: TraceApproach | None

The default tracing approach to use when building up a call-tree. By default, Ape attempts to use the faster approach. Meaning, if geth-call-tracer or parity are available, Ape will use one of those instead of building a call-trace entirely from struct-logs.

property chain_id: int

The blockchain ID. See ChainList for a comprehensive list of IDs.

create_access_list(transaction: TransactionAPI, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None) list[ape_ethereum.transactions.AccessList]

Get the access list for a transaction use eth_createAccessList.

Parameters:
  • transaction (TransactionAPI) – The transaction to check.

  • block_id (BlockID) – Optionally specify a block ID. Defaults to using the latest block.

Returns:

list[AccessList]

estimate_gas_cost(txn: TransactionAPI, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None) int

Estimate the cost of gas for a transaction.

Parameters:
  • txn (TransactionAPI) – The transaction to estimate the gas for.

  • block_id (Optional[BlockID]) – The block ID to use when estimating the transaction. Useful for checking a past estimation cost of a transaction.

Returns:

The estimated cost of gas to execute the transaction reported in the fee-currency’s smallest unit, e.g. Wei. If the provider’s network has been configured with a gas limit override, it will be returned. If the gas limit configuration is “max” this will return the block maximum gas limit.

Return type:

int

property gas_price: int

The price for what it costs to transact (pre-EIP-1559).

get_balance(address: ChecksumAddress, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None) int

Get the balance of an account.

Parameters:
  • address (AddressType) – The address of the account.

  • block_id (BlockID) – Optionally specify a block ID. Defaults to using the latest block.

Returns:

The account balance.

Return type:

int

get_block(block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending']) BlockAPI

Get a block.

Parameters:

block_id (BlockID) – The ID of the block to get. Can be "latest", "earliest", "pending", a block hash or a block number.

Raises:

BlockNotFoundError – Likely the exception raised when a block is not found (depends on implementation).

Returns:

The block for the given ID.

Return type:

BlockID

get_code(address: ChecksumAddress, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None) str | bytes | HexBytes

Get the bytes a contract.

Parameters:
  • address (AddressType) – The address of the contract.

  • block_id (Optional[BlockID]) – The block ID for checking a previous account nonce.

Returns:

The contract bytecode.

Return type:

ContractCode

get_contract_logs(log_filter: LogFilter) Iterator[ContractLog]

Get logs from contracts.

Parameters:

log_filter (LogFilter) – A mapping of event ABIs to topic filters. Defaults to getting all events.

Returns:

Iterator[ContractLog]

get_nonce(address: ChecksumAddress, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None) int

Get the number of times an account has transacted.

Parameters:
  • address (AddressType) – The address of the account.

  • block_id (Optional[BlockID]) – The block ID for checking a previous account nonce.

Returns:

int

get_receipt(txn_hash: str, required_confirmations: int = 0, timeout: int | None = None, **kwargs) ReceiptAPI

Get the information about a transaction from a transaction hash.

Parameters:
  • txn_hash (str) – The hash of the transaction to retrieve.

  • kwargs – Any other kwargs that other providers might allow when fetching a receipt.

Returns:

The receipt of the transaction with the given hash.

Return type:

ReceiptAPI

get_storage(address: ChecksumAddress, slot: int, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None) HexBytes

Gets the raw value of a storage slot of a contract.

Parameters:
  • address (AddressType) – The address of the contract.

  • slot (int) – Storage slot to read the value of.

  • block_id (Optional[BlockID]) – The block ID for checking a previous storage value.

Returns:

The value of the storage slot.

Return type:

HexBytes

get_transaction_trace(transaction_hash: str, **kwargs) TraceAPI

Provide a detailed description of opcodes.

Parameters:

transaction_hash (Union[HexBytes, str]) – The hash of a transaction to trace.

Returns:

A transaction trace.

Return type:

TraceAPI

get_transactions_by_account_nonce(account: ChecksumAddress, start_nonce: int = 0, stop_nonce: int = -1) Iterator[ReceiptAPI]

Get account history for the given account.

Parameters:
  • account (AddressType) – The address of the account.

  • start_nonce (int) – The nonce of the account to start the search with.

  • stop_nonce (int) – The nonce of the account to stop the search with.

Returns:

Iterator[ReceiptAPI]

get_transactions_by_block(block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending']) Iterator[TransactionAPI]

Get the information about a set of transactions from a block.

Parameters:

block_id (BlockID) – The ID of the block.

Returns:

class: ~ape.api.transactions.TransactionAPI]

Return type:

Iterator[

get_virtual_machine_error(exception: Exception, **kwargs) VirtualMachineError

Get a virtual machine error from an error returned from your RPC.

Parameters:

exception (Exception) – The error returned from your RPC client.

Returns:

An error representing what

went wrong in the call.

Return type:

VirtualMachineError

property http_uri: str | None

The connected HTTP URI. If using providers like ape-node, configure your URI and that will be returned here instead.

property is_connected: bool

True if currently connected to the provider. False otherwise.

make_request(rpc: str, parameters: Iterable | None = None) Any

Make a raw RPC request to the provider. Advanced featues such as tracing may utilize this to by-pass unnecessary class-serializations.

property max_gas: int

The max gas limit value you can use.

poll_blocks(stop_block: int | None = None, required_confirmations: int | None = None, new_block_timeout: int | None = None) Iterator[BlockAPI]

Poll new blocks.

NOTE: When a chain reorganization occurs, this method logs an error and yields the missed blocks, even if they were previously yielded with different block numbers.

NOTE: This is a daemon method; it does not terminate unless an exception occurs or a stop_block is given.

Parameters:
  • stop_block (Optional[int]) – Optionally set a future block number to stop at. Defaults to never-ending.

  • required_confirmations (Optional[int]) – The amount of confirmations to wait before yielding the block. The more confirmations, the less likely a reorg will occur. Defaults to the network’s configured required confirmations.

  • new_block_timeout (Optional[float]) – The amount of time to wait for a new block before timing out. Defaults to 10 seconds for local networks or 50 * block_time for live networks.

Returns:

Iterator[BlockAPI]

poll_logs(stop_block: int | None = None, address: ChecksumAddress | None = None, topics: list[Union[str, list[str]]] | None = None, required_confirmations: int | None = None, new_block_timeout: int | None = None, events: list[ethpm_types.abi.EventABI] | None = None) Iterator[ContractLog]

Poll new blocks. Optionally set a start block to include historical blocks.

NOTE: This is a daemon method; it does not terminate unless an exception occurs.

Usage example:

for new_log in contract.MyEvent.poll_logs():
    print(f"New event log found: block_number={new_log.block_number}")
Parameters:
  • stop_block (Optional[int]) – Optionally set a future block number to stop at. Defaults to never-ending.

  • address (Optional[str]) – The address of the contract to filter logs by. Defaults to all addresses.

  • topics (Optional[list[Union[str, list[str]]]]) – The topics to filter logs by. Defaults to all topics.

  • required_confirmations (Optional[int]) – The amount of confirmations to wait before yielding the block. The more confirmations, the less likely a reorg will occur. Defaults to the network’s configured required confirmations.

  • new_block_timeout (Optional[int]) – The amount of time to wait for a new block before quitting. Defaults to 10 seconds for local networks or 50 * block_time for live networks.

  • events (Optional[list[EventABI]]) – An optional list of events to listen on.

Returns:

Iterator[ContractLog]

prepare_transaction(txn: TransactionAPI) TransactionAPI

Set default values on the transaction.

Raises:

TransactionError – When given negative required confirmations.

Parameters:

txn (TransactionAPI) – The transaction to prepare.

Returns:

TransactionAPI

property priority_fee: int

A miner tip to incentivize them to include your transaction in a block.

Raises:

NotImplementedError – When the provider does not implement EIP-1559 typed transactions.

send_call(txn: TransactionAPI, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None, state: dict | None = None, **kwargs: Any) HexBytes

Execute a new transaction call immediately without creating a transaction on the block chain.

Parameters:
  • txnTransactionAPI

  • block_id (Optional[BlockID]) – The block ID to use to send a call at a historical point of a contract. Useful for checking a past estimation cost of a transaction.

  • state (Optional[dict]) – Modify the state of the blockchain prior to sending the call, for testing purposes.

  • **kwargs – Provider-specific extra kwargs.

Returns:

The result of the transaction call.

Return type:

str

send_transaction(txn: TransactionAPI) ReceiptAPI

Send a transaction to the network.

Parameters:

txn (TransactionAPI) – The transaction to send.

Returns:

ReceiptAPI

stream_request(method: str, params: Iterable, iter_path: str = 'result.item')

Stream a request, great for large requests like events or traces.

Parameters:
  • method (str) – The RPC method to call.

  • params (Iterable) – Parameters for the method.s

  • iter_path (str) – The response dict-path to the items.

Returns:

An iterator of items.

property supports_tracing: bool

True when the provider can provide transaction traces.

update_settings(new_settings: dict)

Change a provider’s setting, such as configure a new port to run on. May require a reconnect.

Parameters:

new_settings (dict) – The new provider settings.

property web3: Web3

Access to the web3 object as if you did Web3(HTTPProvider(uri)).

property ws_uri: str | None

Return the raw WS/WSS URI to connect to this provider, if supported.

ape_ethereum.assert_web3_provider_uri_env_var_not_set()

Environment variable $WEB3_PROVIDER_URI causes problems when used with Ape (ignores Ape’s networks). Use this validator to eliminate the concern.

Raises:

ProviderError – If environment variable WEB3_PROVIDER_URI exists in os.environ.

ape-ethereum.multicall

class ape_ethereum.multicall.Call(address: ChecksumAddress = '0xcA11bde05977b3631167028862bE2a173976CA11', supported_chains: list[int] | None = None)

Bases: BaseMulticall

Create a sequence of calls to execute at once using eth_call via the Multicall3 contract.

Usage example:

from ape_ethereum import multicall

call = multicall.Call()
call.add(contract.myMethod, *call_args)
call.add(contract.myMethod, *call_args)
...  # Add as many calls as desired
call.add(contract.myMethod, *call_args)
a, b, ..., z = call()  # Performs multicall
# or, using a builder pattern:
call = multicall.Call()
    .add(contract.myMethod, *call_args)
    .add(contract.myMethod, *call_args)
    ...  # Add as many calls as desired
    .add(contract.myMethod, *call_args)
a, b, ..., z = call()  # Performs multicall
__call__(**call_kwargs) Iterator[Any]

Perform the Multicall call. This call will trigger again every time the Call object is called.

Raises:

UnsupportedChainError – If there is not an instance of Multicall3 deployed on the current chain at the expected address.

Parameters:

**call_kwargs – the kwargs to pass through to the call handler.

Returns:

the sequence of values produced by performing each call stored

by this instance.

Return type:

Iterator[Any]

add(call: ContractMethodHandler, *args, **kwargs)

Adds a call to the Multicall session object.

Raises:

InvalidOption – If one of the kwarg modifiers is not able to be used.

Parameters:
  • call (ContractMethodHandler) – The method to call.

  • *args – The arguments to invoke the method with.

  • allowFailure (bool) – Whether the call is allowed to fail.

  • value (int) – The amount of ether to forward with the call.

Returns:

returns itself

to emulate a builder pattern.

Return type:

BaseMulticall

as_transaction(**txn_kwargs) TransactionAPI

Encode the Multicall transaction as a TransactionAPI object, but do not execute it.

Returns:

TransactionAPI

class ape_ethereum.multicall.Transaction(address: ChecksumAddress = '0xcA11bde05977b3631167028862bE2a173976CA11', supported_chains: list[int] | None = None)

Bases: BaseMulticall

Create a sequence of calls to execute at once using eth_sendTransaction via the Multicall3 contract.

Usage example:

from ape_ethereum.multicall import Transaction

txn = Transaction()
txn.add(contract.myMethod, *call_args)
txn.add(contract.myMethod, *call_args)
...  # Add as many calls as desired to execute
txn.add(contract.myMethod, *call_args)
a, b, ..., z = txn(sender=my_signer).return_data  # Sends the multicall transaction
# or, using a builder pattern:
txn = Transaction()
    .add(contract.myMethod, *call_args)
    .add(contract.myMethod, *call_args)
    ...  # Add as many calls as desired to execute
    .add(contract.myMethod, *call_args)
a, b, ..., z = txn(sender=my_signer).return_data  # Sends the multicall transaction
__call__(**txn_kwargs) ReceiptAPI

Execute the Multicall transaction. The transaction will broadcast again every time the Transaction object is called.

Raises:

UnsupportedChain – If there is not an instance of Multicall3 deployed on the current chain at the expected address.

Parameters:

**txn_kwargs – the kwargs to pass through to the transaction handler.

Returns:

ReceiptAPI

as_transaction(**txn_kwargs) TransactionAPI

Encode the Multicall transaction as a TransactionAPI object, but do not execute it.

Returns:

TransactionAPI