ape.api

Accounts

class ape.api.accounts.AccountAPI

Bases: BaseInterfaceModel, BaseAddress

An API class representing an account.

__dir__() List[str]

Display methods to IPython on a.[TAB] tab completion.

Returns:

Method names that IPython uses for tab completion.

Return type:

List[str]

property alias: str | None

A shortened-name for quicker access to the account.

call(txn: TransactionAPI, send_everything: bool = False, private: bool = False, **signer_options) ReceiptAPI

Make a transaction call.

Raises:
  • AccountsError – When the nonce is invalid or the sender does not have enough funds.

  • TransactionError – When the required confirmations are negative.

  • SignatureError – When the user does not sign the transaction.

  • APINotImplementedError – When setting private=True and using a provider that does not support private transactions.

Parameters:
  • txn (TransactionAPI) – An invoke-transaction.

  • send_everything (bool) – True will send the difference from balance and fee. Defaults to False.

  • private (bool) – True will use the send_private_transaction() method.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

ReceiptAPI

check_signature(data: SignableMessage | TransactionAPI | str | EIP712Message | int, signature: MessageSignature | None = None) bool

Verify a message or transaction was signed by this account.

Parameters:
  • data (Union[SignableMessage, TransactionAPI]) – # noqa: E501 The message or transaction to verify.

  • signature (Optional[MessageSignature]) – The signature to check. Defaults to None and is not needed when the first argument is a transaction class.

Returns:

True if the data was signed by this account. False otherwise.

Return type:

bool

declare(contract: ContractContainer, *args, **kwargs) ReceiptAPI

Deploy the “blueprint” of a contract type. For EVM providers, this likely means using EIP-5202, which is implemented in the core ape-ethereum plugin.

Parameters:

contract (ContractContainer) – The contract container to declare.

Returns:

The receipt of the declare transaction.

Return type:

ReceiptAPI

deploy(contract: ContractContainer, *args, publish: bool = False, **kwargs) ContractInstance

Create a smart contract on the blockchain. The smart contract must compile before deploying and a provider must be active.

Parameters:
  • contract (ContractContainer) – The type of contract to deploy.

  • publish (bool) – Set to True to attempt explorer contract verification. Defaults to False.

Returns:

An instance of the deployed contract.

Return type:

ContractInstance

prepare_transaction(txn: TransactionAPI) TransactionAPI

Set default values on a transaction.

Raises:
  • AccountsError – When the account cannot afford the transaction or the nonce is invalid.

  • TransactionError – When given negative required confirmations.

Parameters:

txn (TransactionAPI) – The transaction to prepare.

Returns:

TransactionAPI

abstract sign_message(msg: Any, **signer_options) MessageSignature | None

Sign a message.

Parameters:
  • msg (Any) – The message to sign. Account plugins can handle various types of messages. For example, KeyfileAccount can handle SignableMessage, str, int, and bytes. See these docs # noqa: E501 for more type information on the SignableMessage type.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

The signature corresponding to the message.

Return type:

MessageSignature (optional)

abstract sign_transaction(txn: TransactionAPI, **signer_options) TransactionAPI | None

Sign a transaction.

Parameters:
  • txn (TransactionAPI) – The transaction to sign.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

A signed transaction.

The TransactionAPI returned by this method may not correspond to txn given as input, however returning a properly-formatted transaction here is meant to be executed. Returns None if the account does not have a transaction it wishes to execute.

Return type:

TransactionAPI (optional)

transfer(account: str | ChecksumAddress | BaseAddress, value: str | int | None = None, data: bytes | str | None = None, private: bool = False, **kwargs) ReceiptAPI

Send funds to an account.

Raises:

APINotImplementedError – When setting private=True and using a provider that does not support private transactions.

Parameters:
  • account (Union[str, AddressType, BaseAddress]) – The receiver of the funds.

  • value (Optional[Union[str, int]]) – The amount to send.

  • data (Optional[Union[bytes, str]]) – Extra data to include in the transaction.

  • private (bool) – True asks the provider to make the transaction private. For example, EVM providers typically use the RPC eth_sendPrivateTransaction to achieve this. Local providers may ignore this value.

Returns:

ReceiptAPI

class ape.api.accounts.AccountContainerAPI(*, data_folder: Path, account_type: Type[AccountAPI])

Bases: BaseInterfaceModel

An API class representing a collection of AccountAPI instances.

__contains__(address: ChecksumAddress) bool

Check if the address is an existing account in ape.

Raises:

IndexError – When the given account address is not in this container.

Parameters:

address (AddressType) – An account address.

Returns:

True if ape manages the account with the given address.

Return type:

bool

__delitem__(address: ChecksumAddress)

Delete an account.

Raises:

NotImplementError – When not overridden within a plugin.

Parameters:

address (AddressType) – The address of the account to delete.

__getitem__(address: ChecksumAddress) AccountAPI

Get an account by address.

Parameters:

address (AddressType) – The address to get. The type is an alias to ChecksumAddress. # noqa: E501

Raises:

IndexError – When there is no local account with the given address.

Returns:

AccountAPI

abstract __len__() int

Number of accounts.

abstract property accounts: Iterator[AccountAPI]

Iterate over all accounts.

Returns:

Iterator[AccountAPI]

abstract property aliases: Iterator[str]

Iterate over all available aliases.

Returns:

Iterator[str]

append(account: AccountAPI)

Add an account to the container.

Raises:

AccountsError – When the account is already in the container.

Parameters:

account (AccountAPI) – The account to add.

remove(account: AccountAPI)

Delete an account.

Raises:

AccountsError – When the account is not known to ape.

Parameters:

account (AccountAPI) – The account to remove.

class ape.api.accounts.ImpersonatedAccount(*, raw_address: ChecksumAddress)

Bases: AccountAPI

An account to use that does not require signing.

property address: ChecksumAddress

The address of this account. Subclasses must override and provide this value.

call(txn: TransactionAPI, send_everything: bool = False, private: bool = False, **kwargs) ReceiptAPI

Make a transaction call.

Raises:
  • AccountsError – When the nonce is invalid or the sender does not have enough funds.

  • TransactionError – When the required confirmations are negative.

  • SignatureError – When the user does not sign the transaction.

  • APINotImplementedError – When setting private=True and using a provider that does not support private transactions.

Parameters:
  • txn (TransactionAPI) – An invoke-transaction.

  • send_everything (bool) – True will send the difference from balance and fee. Defaults to False.

  • private (bool) – True will use the send_private_transaction() method.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

ReceiptAPI

sign_message(msg: Any, **signer_options) MessageSignature | None

Sign a message.

Parameters:
  • msg (Any) – The message to sign. Account plugins can handle various types of messages. For example, KeyfileAccount can handle SignableMessage, str, int, and bytes. See these docs # noqa: E501 for more type information on the SignableMessage type.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

The signature corresponding to the message.

Return type:

MessageSignature (optional)

sign_transaction(txn: TransactionAPI, **signer_options) TransactionAPI | None

Sign a transaction.

Parameters:
  • txn (TransactionAPI) – The transaction to sign.

  • **signer_options – Additional kwargs given to the signer to modify the signing operation.

Returns:

A signed transaction.

The TransactionAPI returned by this method may not correspond to txn given as input, however returning a properly-formatted transaction here is meant to be executed. Returns None if the account does not have a transaction it wishes to execute.

Return type:

TransactionAPI (optional)

class ape.api.accounts.TestAccountAPI

Bases: AccountAPI

Test accounts for ape test (such accounts that use GeneratedDevAccounts) should implement this API instead of AccountAPI directly. This is how they show up in the accounts test fixture.

class ape.api.accounts.TestAccountContainerAPI(*, data_folder: Path, account_type: Type[AccountAPI])

Bases: AccountContainerAPI

Test account containers for ape test (such containers that generate accounts using GeneratedDevAccounts) should implement this API instead of AccountContainerAPI directly. This is how they show up in the accounts test fixture.

abstract generate_account() TestAccountAPI

Generate a new test account

Address

class ape.api.address.Address(address: ChecksumAddress)

Bases: BaseAddress

A generic blockchain address.

Typically, this is used when we do not know the contract type at a given address, or to refer to an EOA the user doesn’t personally control.

property address: ChecksumAddress

The raw address type.

Returns:

An alias to ChecksumAddress. # noqa: E501

Return type:

AddressType

class ape.api.address.BaseAddress

Bases: BaseInterface

A base address API class. All account-types subclass this type.

abstract property address: ChecksumAddress

The address of this account. Subclasses must override and provide this value.

property balance: int

The total balance of the account.

property code: str | bytes | HexBytes

The raw bytes of the smart-contract code at the address.

property codesize: int

The number of bytes in the smart contract.

property history: AccountHistory

The list of transactions that this account has made on the current chain.

property is_contract: bool

True when there is code associated with the address.

property nonce: int

The number of transactions associated with the address.

Compiler

class ape.api.compiler.CompilerAPI(*, compiler_settings: Dict = {})

Bases: BaseInterfaceModel

Compiler plugins, such as for languages like Solidity or Vyper, implement this API.

See the repository for the ape-solidity plugin or the ape-vyper plugin as example implementations of this API.

abstract compile(contract_filepaths: Sequence[Path], base_path: Path | None) List[ContractType]

Compile the given source files. All compiler plugins must implement this function.

Parameters:
  • contract_filepaths (Sequence[pathlib.Path]) – A list of source file paths to compile.

  • base_path (Optional[pathlib.Path]) – Optionally provide the base path, such as the project contracts/ directory. Defaults to None. When using in a project via ape compile, gets set to the project’s contracts/ directory.

Returns:

List[ContractType]

compiler_settings: Dict

Adhoc compiler settings.

property config: PluginConfig

The provider’s configuration.

enrich_error(err: ContractLogicError) ContractLogicError

Enrich a contract logic error using compiler information, such as known PC locations for compiler runtime errors.

Parameters:

err (ContractLogicError) – The exception to enrich.

Returns:

The enriched exception.

Return type:

ContractLogicError

abstract get_versions(all_paths: Sequence[Path]) Set[str]

Retrieve the set of available compiler versions for this plugin to compile all_paths.

Parameters:

all_paths (Sequence[pathlib.Path]) – The list of paths.

Returns:

A set of available compiler versions.

Return type:

Set[str]

abstract property name: str

The name of the compiler.

property settings: PluginConfig

The combination of settings from ape-config.yaml and .compiler_settings.

property supports_source_tracing: bool

Returns True if this compiler is able to provider a source traceback for a given trace.

Config

class ape.api.config.ConfigEnum(value)

Bases: str, Enum

A configuration Enum type. Use this to limit the values of a config item, such as colors "RED", "BLUE", "GREEN", rather than any arbitrary str.

Usage example:

class MyEnum(ConfigEnum):
    FOO = "FOO"
    BAR = "BAR"

class MyConfig(PluginConfig):
    my_enum: MyEnum

model = MyConfig(my_enum="FOO")
class ape.api.config.GenericConfig

Bases: ConfigDict

The default class used when no specialized class is used.

class ape.api.config.PluginConfig(_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, _secrets_dir: str | Path | None = None)

Bases: BaseSettings

A base plugin configuration class. Each plugin that includes a config API must register a subclass of this class.

Convert

class ape.api.convert.ConverterAPI

Bases: BaseInterfaceModel, Generic[ConvertedType]

abstract convert(value: Any) ConvertedType

Convert the given value to the type specified as the generic for this class. Implementations of this API must throw a ConversionError when the item fails to convert properly.

abstract is_convertible(value: Any) bool

Returns True if string value provided by value is convertible using ape.api.convert.ConverterAPI.convert().

Parameters:

value (Any) – The value to check.

Returns:

True when the given value can be converted.

Return type:

bool

Explorers

class ape.api.explorers.ExplorerAPI(*, name: str, network: NetworkAPI)

Bases: BaseInterfaceModel

An API class representing a blockchain explorer for a particular network in a particular ecosystem.

abstract get_address_url(address: ChecksumAddress) str

Get an address URL, such as for a transaction.

Parameters:

address (AddressType) – The address.

Returns:

The URL.

Return type:

str

abstract get_contract_type(address: ChecksumAddress) ContractType | None

Get the contract type for a given address if it has been published to this explorer.

Parameters:

address (AddressType) – The contract address.

Returns:

If not published, returns None.

Return type:

Optional[ContractType]

abstract get_transaction_url(transaction_hash: str) str

Get the transaction URL for the given transaction.

Parameters:

transaction_hash (str) – The transaction hash.

Returns:

The URL.

Return type:

str

abstract publish_contract(address: ChecksumAddress)

Publish a contract to the explorer.

Parameters:

address (AddressType) – The address of the deployed contract.

Networks

class ape.api.networks.EcosystemAPI(*, name: str, data_folder: Path, request_header: Dict, fee_token_symbol: str, fee_token_decimals: int = 18)

Bases: ExtraAttributesMixin, BaseInterfaceModel

A set of related networks, such as Ethereum.

__ape_extra_attributes__() Iterator[ExtraModelAttributes]

Override this method to supply extra attributes to a model in Ape; this allow more properties to be available when invoking __getattr__.

Returns:

A series of instances defining extra model attributes.

Return type:

Iterator[ExtraModelAttributes]

add_network(network_name: str, network: NetworkAPI)

Attach a new network to an ecosystem (e.g. L2 networks like Optimism).

Raises:

NetworkError – When the network already exists.

Parameters:
  • network_name (str) – The name of the network to add.

  • network (NetworkAPI) – The network to add.

property config: PluginConfig

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

Returns:

ape.api.config.PluginConfig

abstract create_transaction(**kwargs) TransactionAPI

Create a transaction using key-value arguments.

Parameters:

**kwargs – Everything the transaction needs initialize.

Returns:

~ape.api.transactions.TransactionAPI

Return type:

class

property custom_network: NetworkAPI

A NetworkAPI for custom networks where the network is either not known, unspecified, or does not have an Ape plugin.

data_folder: Path

The path to the .ape directory.

abstract 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

abstract decode_block(data: Dict) BlockAPI

Decode data to a BlockAPI.

Parameters:

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

Returns:

BlockAPI

abstract 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

abstract 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]

abstract decode_receipt(data: Dict) ReceiptAPI

Convert data to ReceiptAPI.

Parameters:

data (Dict) – A dictionary of Receipt properties.

Returns:

ReceiptAPI

abstract decode_returndata(abi: MethodABI, raw_data: bytes) 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

property default_network_name: str

The name of the default network in this ecosystem.

Returns:

str

abstract 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

abstract encode_calldata(abi: ConstructorABI | MethodABI, *args: Any) 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

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

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

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

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_calltree(call: CallTreeNode, **kwargs) CallTreeNode

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

Parameters:
  • call (CallTreeNode) – The call tree node to enrich.

  • kwargs – Additional kwargs to help with enrichment.

Returns:

CallTreeNode

fee_token_decimals: int

The number of the decimals the fee token has.

fee_token_symbol: str

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

get_method_selector(abi: MethodABI) HexBytes

Get a contract method selector, typically via hashing such as keccak. Defaults to using keccak but can be overridden in different ecosystems.

Override example:

from ape.api import EcosystemAPI
from eth_pydantic_types import HexBytes

class MyEcosystem(EcosystemAPI):
    def get_method_selector(self, abi: MethodABI) -> HexBytes:
        return HexBytes(abi.selector.encode())  # Simple bytes selector
Parameters:

abi (MethodABI) – The ABI object to use when calculating the selector bytes.

Returns:

The hashed method selector value.

Return type:

HexBytes

get_network(network_name: str) NetworkAPI

Get the network for the given name.

Parameters:

network_name (str) – The name of the network to get.

Raises:

NetworkNotFoundError – When the network is not present.

Returns:

NetworkAPI

get_network_data(network_name: str, provider_filter: Collection[str] | None = None) Dict

Get a dictionary of data about providers in the network.

NOTE: The keys are added in an opinionated order for nicely translating into yaml.

Parameters:
  • network_name (str) – The name of the network to get provider data from.

  • provider_filter (Optional[Collection[str]]) – Optionally filter the providers by name.

Returns:

A dictionary containing the providers in a network.

Return type:

dict

get_proxy_info(address: ChecksumAddress) ProxyInfoAPI | 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]

name: str

The name of the ecosystem. This should be set the same name as the plugin.

property networks: Dict[str, NetworkAPI]

A dictionary of network names mapped to their API implementation.

Returns:

Dict[str, NetworkAPI]

request_header: Dict

A shareable HTTP header for network requests.

serialize_transaction() bytes

Serialize a transaction to bytes.

Returns:

bytes

set_default_network(network_name: str)

Change the default network.

Raises:

NetworkError – When the network does not exist.

Parameters:

network_name (str) – The name of the default network to switch to.

class ape.api.networks.ForkedNetworkAPI(*, name: str, ecosystem: EcosystemAPI, data_folder: Path, request_header: Dict)

Bases: NetworkAPI

property upstream_chain_id: int

The chain Id of the upstream network. For example, when on mainnet-fork, this should always return the chain ID for mainnet. Some providers may use a different chain ID for forked networks while some do not. This property should ALWAYS be that of the forked network, regardless.

property upstream_network: NetworkAPI

The network being forked.

property upstream_provider: UpstreamProvider

The provider used when requesting data before the local fork. Set this in your config under the network settings. When not set, will attempt to use the default provider, if one exists.

use_upstream_provider() ProviderContextManager

Connect to the upstream provider.

Returns:

ProviderContextManager

class ape.api.networks.NetworkAPI(*, name: str, ecosystem: EcosystemAPI, data_folder: Path, request_header: Dict)

Bases: BaseInterfaceModel

A wrapper around a provider for a specific ecosystem.

property auto_gas_multiplier: float

The value to multiply estimated gas by for tx-insurance.

property base_fee_multiplier: float

A multiplier to apply to a transaction base fee.

property block_time: int

The approximate amount of time it takes for a new block to get mined to the chain. Configure in your ape-config.yaml file.

Config example:

ethereum:
  mainnet:
    block_time: 15
property chain_id: int

The ID of the blockchain.

NOTE: Unless overridden, returns same as ape.api.providers.ProviderAPI.chain_id.

property config: PluginConfig

The configuration of the network. See ConfigManager for more information on plugin configurations.

data_folder: Path

The path to the .ape directory.

property default_provider_name: str | None

The name of the default provider or None.

Returns:

Optional[str]

ecosystem: EcosystemAPI

The ecosystem of the network.

property explorer: ExplorerAPI | None

The block-explorer for the given network.

Returns:

ape.api.explorers.ExplorerAPI, optional

get_provider(provider_name: str | None = None, provider_settings: Dict | None = None)

Get a provider for the given name. If given None, returns the default provider.

Parameters:
  • provider_name (str, optional) – The name of the provider to get. Defaults to None. When None, returns the default provider.

  • provider_settings (dict, optional) – Settings to apply to the provider. Defaults to None.

Returns:

ProviderAPI

property is_adhoc: bool

Is a custom network from CLI only, e.g. was not configured in any CLI value and is mostly an “unknown” network.

property is_dev: bool

True when using a local network, including forks.

property is_fork: bool

True when using a forked network.

property is_local: bool

True when using the local network.

name: str

The name of the network.

property network_id: int

The ID of the network.

NOTE: Unless overridden, returns same as chain_id.

property providers

The providers of the network, such as Infura, Alchemy, or Geth.

Returns:

Dict[str, partial[ProviderAPI]]

publish_contract(address: ChecksumAddress)

A convenience method to publish a contract to the explorer.

Raises:

NetworkError – When there is no explorer for this network.

Parameters:

address (AddressType) – The address of the contract.

request_header: Dict

A shareable network HTTP header.

property required_confirmations: int

The default amount of confirmations recommended to wait before considering a transaction “confirmed”. Confirmations refer to the number of blocks that have been added since the transaction’s block.

set_default_provider(provider_name: str)

Change the default provider.

Raises:

NetworkError – When the given provider is not found.

Parameters:

provider_name (str) – The name of the provider to switch to.

property transaction_acceptance_timeout: int

The amount of time to wait for a transaction to be accepted on the network. Does not include waiting for block-confirmations. Defaults to two minutes. Local networks use smaller timeouts.

use_default_provider(provider_settings: Dict | None = None, disconnect_after: bool = False) ProviderContextManager

Temporarily connect and use the default provider. When entering the context, it calls method ape.api.providers.ProviderAPI.connect() and when exiting, it calls method ape.api.providers.ProviderAPI.disconnect().

NOTE: If multiple providers exist, uses whatever was “first” registered.

Usage example:

from ape import networks
mainnet = networks.ethereum.mainnet  # An instance of NetworkAPI
with mainnet.use_default_provider():
    ...
Parameters:
  • provider_settings (dict, optional) – Settings to override the provider.

  • disconnect_after (bool) – Set to True to force a disconnect after ending the context. This defaults to False so you can re-connect to the same network, such as in a multi-chain testing scenario.

Returns:

ProviderContextManager

use_provider(provider: str | ProviderAPI, provider_settings: Dict | None = None, disconnect_after: bool = False, disconnect_on_exit: bool = True) ProviderContextManager

Use and connect to a provider in a temporary context. When entering the context, it calls method ape.api.providers.ProviderAPI.connect() and when exiting, it calls method ape.api.providers.ProviderAPI.disconnect().

Usage example:

from ape import networks

mainnet = networks.ethereum.mainnet  # An instance of NetworkAPI
with mainnet.use_provider("infura"):
    ...
Parameters:
  • provider (Union[str, ProviderAPI]) – The provider instance or the name of the provider to use.

  • provider_settings (dict, optional) – Settings to apply to the provider. Defaults to None.

  • disconnect_after (bool) – Set to True to force a disconnect after ending the context. This defaults to False so you can re-connect to the same network, such as in a multi-chain testing scenario.

  • disconnect_on_exit (bool) – Whether to disconnect on the exit of the python session. Defaults to True.

Returns:

ProviderContextManager

verify_chain_id(chain_id: int)

Verify a chain ID for this network.

Parameters:

chain_id (int) – The chain ID to verify.

Raises:

NetworkMismatchError – When the network is not local or adhoc and has a different hardcoded chain ID than the given one.

class ape.api.networks.ProviderContextManager(provider: ProviderAPI, disconnect_after: bool = False, disconnect_on_exit: bool = True)

Bases: ManagerAccessMixin

A context manager for temporarily connecting to a network. When entering the context, calls the ape.api.providers.ProviderAPI.connect() method. And conversely, when exiting, calls the ape.api.providers.ProviderPAI.disconnect() method, unless in a multi-chain context, in which case it disconnects all providers at the very end of the Python session.

The method ape.api.networks.NetworkAPI.use_provider() returns an instance of this context manager.

Usage example:

from ape import networks

mainnet = networks.ethereum.mainnet  # An instance of NetworkAPI
with mainnet.use_provider("infura"):
    ...

# Or, using choice-strings:

with networks.parse_network_choice("ethereum:local:test"):
    ...
property empty: bool

True when there are no providers in the context.

class ape.api.networks.ProxyInfoAPI(*, target: ChecksumAddress)

Bases: BaseModel

Information about a proxy contract.

target: ChecksumAddress

The address of the implementation contract.

ape.api.networks.create_network_type(chain_id: int, network_id: int) Type[NetworkAPI]

Easily create a NetworkAPI subclass.

Projects

class ape.api.projects.DependencyAPI(*, name: str, version: str | None = None, contracts_folder: str = 'contracts', exclude: List[str] = ['package.json', 'package-lock.json', '**/.build/**/*.json'], config_override: Dict = {})

Bases: ExtraAttributesMixin, BaseInterfaceModel

A base-class for dependency sources, such as GitHub or IPFS.

property cached_manifest: PackageManifest | None

The manifest from the .ape/packages/<dependency-name>/<version-id> if it exists and is valid.

compile(use_cache: bool = True) PackageManifest

Compile the contract types in this dependency into a package manifest.

Parameters:

use_cache (bool) – Defaults to True. Set to False to force a re-compile.

NOTE: By default, dependency’s compile lazily.

config_override: Dict

Extra settings to include in the dependency’s configuration.

property contracts: Dict[str, ContractContainer]

A mapping of name to contract type of all the contracts in this dependency.

contracts_folder: str

The name of the dependency’s contracts/ directory. This is where ape will look for source files when compiling the manifest for this dependency.

NOTE: This must be the name of a directory in the project.

exclude: List[str]

A list of glob-patterns for excluding files in dependency projects.

abstract extract_manifest(use_cache: bool = True) PackageManifest

Create a PackageManifest definition, presumably by downloading and compiling the dependency.

Implementations may use self.project_manager to call method get_project() to dynamically get the correct ProjectAPI. based on the project’s structure.

Parameters:

use_cache (bool) – Defaults to True. Set to False to force a re-install.

Returns:

PackageManifest

name: str

The name of the dependency.

abstract property uri: Url

The URI to use when listing in a PackageManifest.

version: str | None

The version of the dependency. Omit to use the latest.

abstract property version_id: str

The ID to use as the sub-directory in the download cache. Most often, this is either a version number or a branch name.

class ape.api.projects.ProjectAPI(*, path: Path, contracts_folder: Path, name: str | None = None, version: str | None = None, config_file_name: str = 'ape-config.yaml')

Bases: BaseInterfaceModel

An abstract base-class for working with projects. This class can also be extended to a plugin for supporting non-ape projects.

add_compiler_data(compiler_data: Sequence[Compiler]) List[Compiler]

Add compiler data to the existing cached manifest.

Parameters:

compiler_data (List[ethpm_types.Compiler]) – Compilers to add.

Returns:

The full list of compilers.

Return type:

List[ethpm_types.source.Compiler]

property cached_manifest: PackageManifest | None

The PackageManifest at manifest_cachefile if it exists and is valid.

contracts_folder: Path

The path to the contracts in the project.

abstract create_manifest(file_paths: Sequence[Path] | None = None, use_cache: bool = True) PackageManifest

Create a manifest from the project.

Parameters:
  • file_paths (Optional[Sequence[Path]]) – An optional list of paths to compile from this project.

  • use_cache (bool) – Set to False to clear caches and force a re-compile.

Returns:

PackageManifest

abstract property is_valid: bool

True if the project at the given path matches this project type. Useful for figuring out the best ProjectAPI to use when compiling a project.

property manifest_cachefile: Path

The path to the project’s cached manifest. The manifest is a cached file representing the project and is useful for sharing, such as uploading to IPFS.

Returns:

pathlib.Path

name: str | None

The name of this project when another project uses it as a dependency.

path: Path

The project path.

process_config_file(**kwargs) bool

Process the project’s config file. Returns True if had to create a temporary ape-config.yaml file.

replace_manifest(manifest: PackageManifest) PackageManifest

Replace the entire cached manifest.

Parameters:

manifest (ethpm_types.manifest.PackageManifest) – The manifest to use.

update_manifest(**kwargs) PackageManifest

Add additional package manifest parts to the cache.

Parameters:

**kwargs – Fields from ethpm_types.manifest.PackageManifest.

version: str | None

The version of the project whe another project uses it as a dependency.

Providers

class ape.api.providers.BlockAPI(*, num_transactions: int = 0, hash: Any | None = None, number: int | None = None, parentHash: Any = HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), size: int, timestamp: int)

Bases: BaseInterfaceModel

An abstract class representing a block and its attributes.

class ape.api.providers.ProviderAPI(*, name: str, network: NetworkAPI, provider_settings: Dict = {}, data_folder: Path, request_header: Dict, block_page_size: int = 100, concurrency: int = 4)

Bases: BaseInterfaceModel

An abstraction of a connection to a network in an ecosystem. Example ProviderAPI implementations include the ape-infura plugin or the ape-hardhat plugin.

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.

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.

abstract property chain_id: int

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

concurrency: int

How many parallel threads to use when fetching logs.

property config: PluginConfig

The provider’s configuration.

abstract 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.

data_folder: Path

The path to the .ape directory.

abstract disconnect()

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

abstract 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

abstract property gas_price: int

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

abstract 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

abstract 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

abstract 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

abstract 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]

abstract 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

abstract get_receipt(txn_hash: str, **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

abstract 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

Return the raw HTTP/HTTPS URI to connect to this provider, if supported.

abstract property is_connected: bool

True if currently connected to the provider. False otherwise.

abstract property max_gas: int

The max gas limit value you can use.

name: str

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

network: NetworkAPI

A reference to the network this provider provides.

property network_choice: str

The connected network choice string.

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.

provider_settings: Dict

The settings for the provider, as overrides to the configuration.

request_header: Dict

A header to set on HTTP/RPC requests.

abstract send_call(txn: TransactionAPI, block_id: int | HexStr | HexBytes | Literal['earliest', 'latest', 'pending'] | None = None, state: Dict | None = None, **kwargs) 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_private_transaction(txn: TransactionAPI, **kwargs) ReceiptAPI

Send a transaction through a private mempool (if supported by the Provider).

Raises:

APINotImplementedError – If using a non-local network and not implemented by the provider.

Parameters:
  • txn (TransactionAPI) – The transaction to privately publish.

  • **kwargs – Additional kwargs to be optionally handled by the provider.

Returns:

ReceiptAPI

abstract send_transaction(txn: TransactionAPI) ReceiptAPI

Send a transaction to the network.

Parameters:

txn (TransactionAPI) – The transaction to send.

Returns:

ReceiptAPI

property settings: PluginConfig

The combination of settings from ape-config.yaml and .provider_settings.

property supports_tracing: bool

True when the provider can provide transaction traces.

abstract 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 ws_uri: str | None

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

class ape.api.providers.SubprocessProvider(*, name: str, network: NetworkAPI, provider_settings: Dict = {}, data_folder: Path, request_header: Dict, block_page_size: int = 100, concurrency: int = 4, PROCESS_WAIT_TIMEOUT: int = 15, process: Popen | None = None, is_stopping: bool = False, stdout_queue: JoinableQueue | None = None, stderr_queue: JoinableQueue | None = None)

Bases: ProviderAPI

A provider that manages a process, such as for ganache.

abstract build_command() List[str]

Get the command as a list of str. Subclasses should override and add command arguments if needed.

Returns:

The command to pass to subprocess.Popen.

Return type:

List[str]

connect()

Start the process and connect to it. Subclasses handle the connection-related tasks.

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.

disconnect()

Stop the process if it exists. Subclasses override this method to do provider-specific disconnection tasks.

abstract property process_name: str

The name of the process, such as Hardhat node.

start(timeout: int = 20)

Start the process and wait for its RPC to be ready.

stop()

Kill the process.

class ape.api.providers.TestProviderAPI(*, name: str, network: NetworkAPI, provider_settings: Dict = {}, data_folder: Path, request_header: Dict, block_page_size: int = 100, concurrency: int = 4)

Bases: ProviderAPI

An API for providers that have development functionality, such as snapshotting.

abstract mine(num_blocks: int = 1)

Advance by the given number of blocks.

Parameters:

num_blocks (int) – The number of blocks allotted to mine. Defaults to 1.

abstract revert(snapshot_id: str | int | bytes)

Regress the current call using the given snapshot ID. Allows developers to go back to a previous state.

Parameters:

snapshot_id (str) – The snapshot ID.

abstract set_timestamp(new_timestamp: int)

Change the pending timestamp.

Parameters:

new_timestamp (int) – The timestamp to set.

Returns:

The new timestamp.

Return type:

int

abstract snapshot() str | int | bytes

Record the current state of the blockchain with intent to later call the method revert() to go back to this point. This method is for local networks only.

Returns:

The snapshot ID.

Return type:

SnapshotID

class ape.api.providers.UpstreamProvider(*, name: str, network: NetworkAPI, provider_settings: Dict = {}, data_folder: Path, request_header: Dict, block_page_size: int = 100, concurrency: int = 4)

Bases: ProviderAPI

A provider that can also be set as another provider’s upstream.

Transactions

class ape.api.transactions.ReceiptAPI(*, contract_address: ChecksumAddress | None = None, block_number: int, gas_used: int, logs: List[dict] = [], status: int, txn_hash: str, transaction: TransactionAPI)

Bases: ExtraAttributesMixin, BaseInterfaceModel

An abstract class to represent a transaction receipt. The receipt contains information about the transaction, such as the status and required confirmations.

NOTE: Use a required_confirmations of 0 in your transaction to not wait for confirmations.

Get a receipt by making transactions in ape, such as interacting with a ape.contracts.base.ContractInstance.

await_confirmations() ReceiptAPI

Wait for a transaction to be considered confirmed.

Returns:

The receipt that is now confirmed.

Return type:

ReceiptAPI

property debug_logs_lines: List[str]

Return any debug log data outputted by the transaction as strings suitable for printing

property debug_logs_typed: List[Tuple[Any]]

Return any debug log data outputted by the transaction.

abstract decode_logs(abi: List[EventABI | 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 events: ContractLogContainer

All the events that were emitted from this call.

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() NoReturn | None

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

abstract 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

property return_value: Any

Obtain the final return value of the call. Requires tracing to function, since this is not available from the receipt object.

show_debug_logs()

Output debug logs to logging system

abstract property total_fees_paid: int

The total amount of fees paid for the transaction.

property trace: Iterator[TraceFrame]

The trace of the transaction, if available from your provider.

track_coverage()

Track this receipt’s source code coverage in the on-going session coverage report. Requires using a provider that supports transaction traces to track full coverage. Else, is limited to receipt-level tracking. This gets called when running tests with the --coverage flag.

track_gas()

Track this receipt’s gas in the on-going session gas-report. Requires using a provider that supports transaction traces to get full data. Else, is limited to receipt-level data. This gets called when running tests with the --gas flag.

class ape.api.transactions.TransactionAPI(*, 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)

Bases: BaseInterfaceModel

An API class representing a transaction. Ecosystem plugins implement one or more of transaction APIs depending on which schemas they permit, such as typed-transactions from EIP-1559.

property receipt: ReceiptAPI | None

This transaction’s associated published receipt, if it exists.

abstract serialize_transaction() bytes

Serialize the transaction

property total_transfer_value: int

The total amount of WEI that a transaction could use. Useful for determining if an account balance can afford to submit the transaction.

property trace: Iterator[TraceFrame]

The transaction trace. Only works if this transaction was published and you are using a provider that support tracing.

Raises:

APINotImplementedError – When using a provider that does not support tracing.

abstract property txn_hash: HexBytes

The calculated hash of the transaction.

Query

class ape.api.query.AccountTransactionQuery(*, columns: Sequence[str], account: ChecksumAddress, start_nonce: int = 0, stop_nonce: int)

Bases: _BaseQuery

A QueryType that collects properties of TransactionAPI over a range of transactions made by account between start_nonce and stop_nonce.

class ape.api.query.BlockQuery(*, columns: Sequence[str], start_block: int = 0, stop_block: int, step: int = 1)

Bases: _BaseBlockQuery

A QueryType that collects properties of BlockAPI over a range of blocks between start_block and stop_block.

class ape.api.query.BlockTransactionQuery(*, columns: Sequence[str], block_id: Any)

Bases: _BaseQuery

A QueryType that collects properties of TransactionAPI over a range of transactions collected inside the BlockAPI` object represented by ``block_id.

class ape.api.query.ContractCreationQuery(*, columns: Sequence[str], start_block: int = 0, stop_block: int, step: int = 1, contract: ChecksumAddress)

Bases: _BaseBlockQuery

class ape.api.query.ContractEventQuery(*, columns: Sequence[str], start_block: int = 0, stop_block: int, step: int = 1, contract: List[ChecksumAddress] | ChecksumAddress, event: EventABI, search_topics: Dict[str, Any] | None = None)

Bases: _BaseBlockQuery

A QueryType that collects members from event over a range of logs emitted by contract between start_block and stop_block.

class ape.api.query.ContractMethodQuery(*, columns: Sequence[str], start_block: int = 0, stop_block: int, step: int = 1, contract: ChecksumAddress, method: MethodABI, method_args: Dict[str, Any])

Bases: _BaseBlockQuery

A QueryType that collects return values from calling method in contract over a range of blocks between start_block and stop_block.

class ape.api.query.QueryAPI

Bases: BaseInterface

abstract estimate_query(query: BlockQuery | BlockTransactionQuery | AccountTransactionQuery | ContractCreationQuery | ContractEventQuery | ContractMethodQuery) int | None

Estimation of time needed to complete the query. The estimation is returned as an int representing milliseconds. A value of None indicates that the query engine is not available for use or is unable to complete the query.

Parameters:

query (QueryType) – Query to estimate.

Returns:

Represents milliseconds, returns None if unable to execute.

Return type:

Optional[int]

abstract perform_query(query: BlockQuery | BlockTransactionQuery | AccountTransactionQuery | ContractCreationQuery | ContractEventQuery | ContractMethodQuery) Iterator

Executes the query using best performing estimate_query query engine.

Parameters:

query (QueryType) – query to execute

Returns:

Iterator

update_cache(query: BlockQuery | BlockTransactionQuery | AccountTransactionQuery | ContractCreationQuery | ContractEventQuery | ContractMethodQuery, result: Iterator[BaseInterfaceModel])

Allows a query plugin the chance to update any cache using the results obtained from other query plugins. Defaults to doing nothing, override to store cache data.

Parameters:
  • query (QueryType) – query that was executed

  • result (Iterator) – the result of the query