ape.managers

Accounts

class ape.managers.accounts.AccountManager(config: ape.managers.config.ConfigManager, converters: ape.managers.converters.ConversionManager, plugin_manager: pluggy.manager.PluginManager, network_manager: ape.managers.networks.NetworkManager)

The AccountManager is a container of containers for AccountAPI objects. All containers must subclass AccountContainerAPI and are treated as singletons.

Import the accounts manager singleton from the root ape namespace.

Usage example:

from ape import accounts  # "accounts" is the AccountManager singleton

my_accounts = accounts.load("dev")
__contains__(address: ChecksumAddress)bool

Determine if the given address matches an account in ape.

Parameters

address (AddressType) – The address to check.

Returns

True when the given address is found.

Return type

bool

__len__()int

The number of accounts managed by all account plugins.

Returns

int

property aliases

All account aliases from every account-related plugin. The “alias” is part of the AccountAPI. Use the account alias to load an account using method load().

Returns

Iterator[str]

property containers

The list of all AccountContainerAPI instances across all installed plugins.

Returns

dict[str, AccountContainerAPI]

get_accounts_by_type(type_: Type[ape.api.accounts.AccountAPI])List[ape.api.accounts.AccountAPI]

Get a list of accounts by their type.

Parameters

type (Type[AccountAPI]) – The type of account to get.

Returns

List[AccountAPI]

load(alias: str)ape.api.accounts.AccountAPI

Get an account by its alias.

Raises

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

Returns

AccountAPI

property test_accounts

Accounts generated from the configured test mnemonic. These accounts are also the subject of a fixture available in the test plugin called accounts. Configure these accounts, such as the mnemonic and / or number-of-accounts using the test section of the ape-config.yaml file.

Usage example:

def test_my_contract(accounts):
   # The "accounts" fixture uses the AccountsManager.test_accounts()
   sender = accounts[0]
   receiver = accounts[1]
   ...
Returns

List[TestAccountAPI]

Compilers

class ape.managers.compilers.CompilerManager(config: ape.managers.config.ConfigManager, plugin_manager: ape.plugins.PluginManager)

The singleton that manages CompilerAPI instances. Each compiler plugin typically contains a single CompilerAPI.

NOTE: Typically, users compile their projects using the CLI via ape compile, which uses the CompilerAPI under-the-hood.

Usage example:

from ape import compilers  # "compilers" is the CompilerManager singleton
compile(contract_filepaths: List[pathlib.Path])Dict[str, ethpm_types.contract_type.ContractType]

Invoke ape.ape.compiler.CompilerAPI.compile() for each of the given files. For example, use the ape-solidity plugin to compile '.sol' files.

Raises

CompilerError – When there is no compiler found for the given extension as well as when there is a contract-type collision across compilers.

Parameters

contract_filepaths (List[pathlib.Path]) – The list of files to compile, as pathlib.Path objects.

Returns

A mapping of contract names to their type.

Return type

Dict[str, ContractType]

property registered_compilers

Each compile-able file extension mapped to its respective CompilerAPI instance.

Returns

The mapping of file-extensions to compiler API classes.

Return type

Dict[str, CompilerAPI]

Chain

class ape.managers.chain.AccountHistory(_networks: ape.managers.networks.NetworkManager, _map: Dict[ChecksumAddress, List[ape.api.providers.ReceiptAPI]] = {})

A container mapping account addresses to the transaction from the active session.

__getitem__(address: Union[ape.api.address.AddressAPI, ChecksumAddress, str])List[ape.api.providers.ReceiptAPI]

Get the list of transactions from the active session for the given address.

Parameters

address (AddressType) – The sender of the desired transactions.

Returns

The list of transactions. If there are no recorded transactions, returns an empty list.

Return type

List[TransactionAPI]

__iter__()Iterator[ChecksumAddress]

Iterate through the accounts listed in the history map.

Returns

List[str]

append(txn_receipt: ape.api.providers.ReceiptAPI)

Add a transaction to the stored list for the given account address.

Raises

ChainError – When trying to append a transaction receipt that is already in the list.

Parameters

txn_receipt (ReceiptAPI) – The transaction receipt to append. NOTE: The receipt is accessible in the list returned from __getitem__().

items()Iterator[Tuple[ChecksumAddress, List[ape.api.providers.ReceiptAPI]]]

Iterate through the list of address-types to list of transaction receipts.

Returns

Iterator[Tuple[AddressType, ReceiptAPI]]

revert_to_block(block_number: int)

Remove all receipts past the given block number.

Parameters

block_number (int) – The block number to revert to.

class ape.managers.chain.BlockContainer(_networks: ape.managers.networks.NetworkManager)

A list of blocks on the chain.

Usages example:

from ape import chain

latest_block = chain.blocks[-1]
__getitem__(block_number: int)ape.api.providers.BlockAPI

Get a block by number. Negative numbers start at the chain head and move backwards. For example, -1 would be the latest block and -2 would be the block prior to that one, and so on.

Parameters

block_number (int) – The number of the block to get.

Returns

BlockAPI

__iter__()Iterator[ape.api.providers.BlockAPI]

Iterate over all the current blocks.

Returns

Iterator[BlockAPI]

__len__()int

The number of blocks in the chain.

Returns

int

property head

The latest block.

property height

The latest block number.

poll_blocks(start: Optional[int] = None, required_confirmations: Optional[int] = None)Iterator[ape.api.providers.BlockAPI]

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

Usage example:

from ape import chain

for new_block in chain.blocks.poll_blocks():
    print(f"New block found: number={new_block.number}")
Parameters
  • start (Optional[int]) – The block number to start with. Defaults to the pending block number.

  • required_confirmations (Optional[int]) –

    The amount of confirmations to wait before yielding the block. The more confirmations, the less likely a reorg

    will occur.

Returns

Iterator[BlockAPI]

range(start: int = 0, stop: Optional[int] = None)Iterator[ape.api.providers.BlockAPI]

Iterate over blocks. Works similarly to python range().

Parameters
  • start (int) – The first block, by number, to include in the range. Defaults to 0.

  • stop (Optional[int]) – The block number to stop before. Also the total number of blocks to get.

Returns

Iterator[BlockAPI]

class ape.managers.chain.ChainManager(_networks: ape.managers.networks.NetworkManager, _snapshots: List[Union[str, int, bytes]] = [], _chain_id_map: Dict[str, int] = {}, _block_container_map: Dict[int, ape.managers.chain.BlockContainer] = {}, _account_history_map: Dict[int, ape.managers.chain.AccountHistory] = {})

A class for managing the state of the active blockchain. Also handy for querying data about the chain and managing local caches. Access the chain manager singleton from the root ape namespace.

Usage example:

from ape import chain
property account_history

A mapping of transactions from the active session to the account responsible.

property base_fee

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 blocks

The list of blocks on the chain.

property chain_id

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

property gas_price

The price for what it costs to transact.

property pending_timestamp

The current epoch time of the chain, as an int. You can also set the timestamp for development purposes.

Usage example:

from ape import chain

chain.pending_timestamp += 3600
restore(snapshot_id: Optional[Union[str, int, bytes]] = None)

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

Raises
  • NotImplementedError – When the active provider does not support snapshotting.

  • UnknownSnapshotError – When the snapshot ID is not cached.

  • ChainError – When there are no snapshot IDs to select from.

Parameters

snapshot_id (Optional[SnapshotID]) – The snapshot ID. Defaults to the most recent snapshot ID.

snapshot()Union[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 development networks only.

Raises

NotImplementedError – When the active provider does not support snapshotting.

Returns

The snapshot ID.

Return type

SnapshotID

Config

class ape.managers.config.ConfigManager(DATA_FOLDER: pathlib.Path, REQUEST_HEADER: Dict, PROJECT_FOLDER: pathlib.Path, plugin_manager: ape.plugins.PluginManager, name: str = '', version: str = '', dependencies: Dict[str, str] = {}, deployments: Dict[str, Dict[str, List[ape.managers.config.DeploymentConfig]]] = {}, _plugin_configs_by_project: Dict[str, Dict[str, ape.api.config.ConfigItem]] = {})

The singleton responsible for managing the ape-config.yaml project file. The config manager is useful for loading plugin configurations which contain settings that determine how ape functions. When developing plugins, you may want to have settings that control how the plugin works. When developing scripts in a project, you may want to parametrize how it runs. The config manager is how you can access those settings at runtime.

Access the ConfigManager from the ape namespace directly via:

Usage example:

from ape import config  # "config" is the ConfigManager singleton

# Example: load the "ape-test" plugin and access the mnemonic
test_mnemonic = config.get_config("test").mnemonic
__str__()str

The JSON-text version of the project config data.

Returns

str

get_config(plugin_name: str)ape.api.config.ConfigItem

Get a plugin config.

Parameters

plugin_name (str) – The name of the plugin to get the config for.

Returns

ConfigItem

serialize()Dict

Convert the project config file, ape-config.yaml, to a dictionary.

Returns

dict

class ape.managers.config.DeploymentConfig(address: Union[str, bytes], contract_type: str, **kwargs)

Converters

class ape.managers.converters.AddressAPIConverter(config: ape.api.config.ConfigItem, networks: NetworkManager, converter: ConversionManager, **kwargs)

A converter that converts an AddressAPI to a AddressType.

convert(value: ape.api.address.AddressAPI)ChecksumAddress

Convert the given value to AddressType.

Parameters

value (str) – The value to convert.

Returns

AddressType

is_convertible(value: Any)bool

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

Parameters

value (str) – The value to check.

Returns

True when the given value can be converted.

Return type

bool

class ape.managers.converters.ConversionManager(config: ape.managers.config.ConfigManager, plugin_manager: ape.plugins.PluginManager, networks: ape.managers.networks.NetworkManager)

A singleton that manages all the converters.

NOTE: typically, users will not interact with this class directly, but rather its convert() method, which is accessible from the root ape namespace.

Usage example:

from ape import convert

amount = convert("1 gwei", int)
convert(value: Any, type: Type)Any

Convert the given value to the given type. This method accesses all ConverterAPI instances known to ape` and selects the appropriate one, so long that it exists.

Raises

ConversionError – When there is not a registered converter for the given arguments.

Parameters
  • value (any) – The value to convert.

  • type (type) – The type to convert the value to.

Returns

The same given value but with the new given type.

Return type

any

is_type(value: Any, type: Type)bool

Check if the value is the given type. If given an AddressType, will also check that it is checksummed.

Parameters
  • value (any) – The value to check.

  • type (type) – The type to check against.

Returns

True when we consider the given value to be the given type.

Return type

bool

class ape.managers.converters.HexAddressConverter(config: ape.api.config.ConfigItem, networks: NetworkManager, converter: ConversionManager, **kwargs)

A converter that converts a checksummed address str to a AddressType.

convert(value: str)ChecksumAddress

Convert the given value to a AddressType.

Parameters

value (str) – The address str to convert.

Returns

AddressType

is_convertible(value: Any)bool

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

Parameters

value (str) – The value to check.

Returns

True when the given value can be converted.

Return type

bool

class ape.managers.converters.HexConverter(config: ape.api.config.ConfigItem, networks: NetworkManager, converter: ConversionManager, **kwargs)

A converter that converts str to HexBytes.

convert(value: str)bytes

Convert the given value to HexBytes.

Parameters

value (str) – The value to convert.

Returns

bytes

is_convertible(value: Any)bool

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

Parameters

value (str) – The value to check.

Returns

True when the given value can be converted.

Return type

bool

class ape.managers.converters.ListTupleConverter(config: ape.api.config.ConfigItem, networks: NetworkManager, converter: ConversionManager, **kwargs)

A converter that converts all items in a tuple or list recursively.

convert(value: Union[List, Tuple])Union[List, Tuple]

Convert the items inside the given list or tuple.

Parameters

value (Union[List, Tuple]) – The collection to convert.

Returns

Depending on the input

Return type

Union[list, tuple]

is_convertible(value: Any)bool

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

Parameters

value (str) – The value to check.

Returns

True when the given value can be converted.

Return type

bool

Networks

class ape.managers.networks.NetworkManager(config: ape.managers.config.ConfigManager, plugin_manager: pluggy.manager.PluginManager, _active_provider: Optional[ape.api.providers.ProviderAPI] = None, _default: Optional[str] = None, _ecosystems_by_project: Dict[str, Dict[str, ape.api.networks.EcosystemAPI]] = {})

The set of all blockchain network ecosystems registered from the plugin system. Typically, you set the provider via the --network command line option. However, use this singleton for more granular access to networks.

Usage example:

from ape import networks

# "networks" is the NetworkManager singleton
with networks.ethereum.mainnet.use_provider("geth"):
   ...
property default_ecosystem

The default ecosystem. Call set_default_ecosystem() to change the default ecosystem. If a default is not set and there is only a single ecosystem installed, such as Ethereum, then get that ecosystem.

property ecosystems

All the registered ecosystems in ape, such as ethereum.

get_provider_from_choice(network_choice: Optional[str] = None, provider_settings: Optional[Dict] = None)ape.api.providers.ProviderAPI

Get a ProviderAPI from a network choice. A network choice is any value returned from network_choices. Use the CLI command ape networks list to list all the possible network combinations.

Raises

NetworkError – When the given network choice does not match any known network.

Parameters
  • network_choice (str, optional) – The network choice (see network_choices). Defaults to the default ecosystem, network, and provider combination.

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

Returns

ProviderAPI

property network_choices

The set of all possible network choices available as a “network selection” e.g. --network [ECOSYSTEM:NETWORK:PROVIDER].

Each value is in the form ecosystem:network:provider and shortened options also appear in the list. For example, ::geth would default to :ethereum:development:geth and both will be in the returned list. The values come from each ProviderAPI that is installed.

Use the CLI command ape networks list to list all the possible network combinations.

Returns

An iterator over all the network-choice possibilities.

Return type

Iterator[str]

property network_data

Get a dictionary containing data about networks in the ecosystem.

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

Returns

dict

property networks_yaml

Get a yaml str representing all the networks in all the ecosystems.

View the result via CLI command ape networks list --format yaml.

Returns

str

parse_network_choice(network_choice: Optional[str] = None, provider_settings: Optional[Dict] = None)ape.api.networks.ProviderContextManager

Parse a network choice into a context manager for managing a temporary connection to a provider. See network_choices for all available choices (or use CLI command ape networks list).

Parameters
  • network_choice (str, optional) – The network choice (see network_choices). Defaults to the default ecosystem, network, and provider combination.

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

Returns

ProviderContextManager

set_default_ecosystem(ecosystem_name: str)

Change the default ecosystem.

Raises

NetworkError – When the given ecosystem name is unknown.

Parameters

ecosystem_name (str) – The name of the ecosystem to set as the default.

Project

class ape.managers.project.ProjectManager(path: pathlib.Path, config: ape.managers.config.ConfigManager, converter: ape.managers.converters.ConversionManager, compilers: ape.managers.compilers.CompilerManager, networks: ape.managers.networks.NetworkManager, dependencies: Dict[str, ethpm_types.manifest.PackageManifest] = {}, *args, **kwargs)

A manager for accessing contract-types, dependencies, and other project resources. Additionally, compile contracts using the load_contracts() method.

Use ape.project to reference the current project and ape.Project to reference this class uninitialized.

Raises

ProjectError – When the project’s dependencies are invalid.

Usage example:

from ape import project  # "project" is the ProjectManager for the active project
from ape import Project  # Is a ProjectManager

# MyContractType (example) is contract type in the active project
contract_type = project.MyContactType
__getattr__(attr_name: str)ape.contracts.base.ContractContainer

Get a contract container from an existing contract type or dependency name using . access.

Usage example:

from ape import project

contract = project.MyContract
Parameters

attr_name (str) – The name of the contract or dependency.

Returns

ContractContainer

__str__()str

Return str(self).

property cached_manifest

The cached PackageManifest. If nothing has been compiled, then no manifest will exist, and this will return None.

property compiler_data

A list of objects representing the raw-data specifics of a compiler.

Returns

List[Compiler]

property contracts

A dictionary of contract names to their type. See load_contracts() for more information.

Returns

Dict[str, ContractType]

property contracts_folder

The path to project’s contracts/ directory.

Returns

pathlib.Path

extensions_with_missing_compilers(extensions: Optional[List[str]])List[str]

All file extensions in the contracts/ directory (recursively) that do not correspond to a registered compiler.

Parameters

extensions (List[str], optional) – If provided, returns only extensions that are in this list. Useful for checking against a subset of source files.

Returns

A list of file extensions found in the contracts/ directory that do not have associated compilers installed.

Return type

List[str]

property interfaces_folder

The path to the interfaces/ directory of the project.

Returns

pathlib.Path

load_contracts(file_paths: Optional[Union[List[pathlib.Path], pathlib.Path]] = None, use_cache: bool = True)Dict[str, ethpm_types.contract_type.ContractType]

Compile and get the contract types in the project. This is called when invoking the CLI command ape compile as well as prior to running scripts or tests in ape, such as from ape run or ape test.

Parameters
  • file_paths (List[pathlib.Path] or pathlib.Path], optional) – Provide one or more contract file-paths to load. If excluded, will load all the contracts.

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

Returns

A dictionary of contract names to their types for each compiled contract.

Return type

Dict[str, ContractType]

lookup_path(key_contract_path: pathlib.Path)Optional[pathlib.Path]

Figure out the full path of the contract from the given key_contract_path.

For example, give it HelloWorld and it returns <absolute-project-path>/contracts/HelloWorld.sol.

Another example is to give it contracts/HelloWorld.sol and it also returns <absolute-project-path>/contracts/HelloWorld.sol.

Parameters

key_contract_path (pathlib.Path) – A sub-path to a contract.

Returns

The path if it exists, else None.

Return type

pathlib.Path

property manifest_cachefile

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

property scripts_folder

The path to the scripts/ directory of the project.

Returns

pathlib.Path

property sources

All the source files in the project. Excludes files with extensions that don’t have a registered compiler.

Returns

A list of a source file paths in the project.

Return type

List[pathlib.Path]

property sources_missing

True when there are no contracts anywhere to be found in the project. False otherwise.

property tests_folder

The path to the tests/ directory of the project.

Returns

pathlib.Path