ape.managers

Accounts

class ape.managers.accounts.AccountManager

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: Iterator[str]

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: Dict[str, ape.api.accounts.AccountContainerAPI]

A dict 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: ape.managers.accounts.TestAccountManager

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

TestAccountContainer

class ape.managers.accounts.TestAccountManager(iterable=(), /)
__contains__(address: ChecksumAddress) bool

Return key in self.

__getitem__(account_id)

x.__getitem__(y) <==> x[y]

__len__() int

Return len(self).

Compilers

class ape.managers.compilers.CompilerManager

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]

get_imports(contract_filepaths: List[pathlib.Path], base_path: Optional[pathlib.Path]) Dict[str, List[str]]

Combine import dicts from all compilers, where the key is a contract’s source_id and the value is a list of import source_ids.

Parameters
  • contract_filepaths (List[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

A dictionary like {source_id: [import_source_id, ...], ...}

Return type

Dict[str, List[str]]

get_references(imports_dict: Dict[str, List[str]]) Dict[str, List[str]]

Provide a mapping containing all referenced source_ids for a given project. Each entry contains a source_id as a key and list of source_ids that reference a given contract.

Parameters

imports_dict (Dict[str, List[str]]) – A dictionary of source_ids from all compilers.

Returns

A dictionary like {source_id: [referring_source_id, ...], ...}

Return type

Dict[str, List[str]]

property registered_compilers: Dict[str, ape.api.compiler.CompilerAPI]

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

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

__getitem__(address: Union[ape.api.address.BaseAddress, ChecksumAddress, str]) List[ape.api.transactions.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.transactions.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. NOTE: The receipt is accessible in the list returned from __getitem__().

items() Iterator[Tuple[ChecksumAddress, List[ape.api.transactions.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

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: ape.api.providers.BlockAPI

The latest block.

property height: int

The latest block number.

poll_blocks(start_block: Optional[int] = None, stop_block: 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 or a stop is given.

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_block (Optional[int]) – The block number to start with. Defaults to the pending block number.

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

Returns

Iterator[BlockAPI]

query(*columns: List[str], start_block: int = 0, stop_block: Optional[int] = None, step: int = 1, engine_to_use: Optional[str] = None) pandas.core.frame.DataFrame

A method for querying blocks and returning an Iterator. If you do not provide a starting block, the 0 block is assumed. If you do not provide a stopping block, the last block is assumed. You can pass engine_to_use to short-circuit engine selection.

Raises

ChainError – When stop_block is greater than the chain length.

Parameters
  • columns (List[str]) – columns in the DataFrame to return

  • start_block (int) – The first block, by number, to include in the query. Defaults to 0.

  • stop_block (Optional[int]) – The last block, by number, to include in the query. Defaults to the latest block.

  • step (int) – The number of blocks to iterate between block numbers. Defaults to 1.

  • engine_to_use (Optional[str]) – query engine to use, bypasses query engine selection algorithm.

Returns

pd.DataFrame

range(start_or_stop: int, stop: Optional[int] = None, step: int = 1, engine_to_use: Optional[str] = None) Iterator[ape.api.providers.BlockAPI]

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

Raises
Parameters
  • start_or_stop (int) – When given just a single value, it is the stop. Otherwise, it is the start. This mimics the behavior of range built-in Python function.

  • stop (Optional[int]) – The block number to stop before. Also the total number of blocks to get. If not setting a start value, is set by the first argument.

  • step (Optional[int]) – The value to increment by. Defaults to 1. number of blocks to get. Defaults to the latest block.

  • engine_to_use (Optional[str]) – query engine to use, bypasses query engine selection algorithm.

Returns

Iterator[BlockAPI]

class ape.managers.chain.ChainManager

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: ape.managers.chain.AccountHistory

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

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 blocks: ape.managers.chain.BlockContainer

The list of blocks on the chain.

property chain_id: int

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

property gas_price: int

The price for what it costs to transact.

mine(num_blocks: int = 1, timestamp: Optional[int] = None, deltatime: Optional[int] = None) None

Mine any given number of blocks.

Raises

ValueError – When a timestamp AND a deltatime argument are both passed

Parameters
  • num_blocks (int) – Choose the number of blocks to mine. Defaults to 1 block.

  • timestamp (Optional[int]) – Designate a time (in seconds) to begin mining. Defaults to None.

  • deltatime (Optional[int]) – Designate a change in time (in seconds) to begin mining. Defaults to None

property pending_timestamp: int

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 local networks only.

Raises

NotImplementedError – When the active provider does not support snapshotting.

Returns

The snapshot ID.

Return type

SnapshotID

class ape.managers.chain.ContractCache

A collection of cached contracts. Contracts can be cached in two ways:

  1. An in-memory cache of locally deployed contracts

  2. A cache of contracts per network (only permanent networks are stored this way)

When retrieving a contract, if a ExplorerAPI is used, it will be cached to disk for faster look-up next time.

__setitem__(address: ChecksumAddress, contract_type: ethpm_types.contract_type.ContractType)

Cache the given contract type. Contracts are cached in memory per session. In live networks, contracts also get cached to disk at .ape/{ecosystem_name}/{network_name}/contract_types/{address}.json for faster look-up next time.

Parameters
  • address (AddressType) – The on-chain address of the contract.

  • contract_type (ContractType) – The contract’s type.

get(address: ChecksumAddress, default: Optional[ethpm_types.contract_type.ContractType] = None) Optional[ethpm_types.contract_type.ContractType]

Get a contract type by address. If the contract is cached, it will return the contract from the cache. Otherwise, if on a live network, it fetches it from the ExplorerAPI.

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

  • default (Optional[ContractType]) – A default contract when none is found. Defaults to None.

Returns

The contract type if it was able to get one,

otherwise the default parameter.

Return type

Optional[ContractType]

instance_at(address: Union[str, ChecksumAddress], contract_type: Optional[ethpm_types.contract_type.ContractType] = None) ape.api.address.BaseAddress

Get a contract at the given address. If the contract type of the contract is known, either from a local deploy or a ExplorerAPI, it will use that contract type. You can also provide the contract type from which it will cache and use next time. If the contract type is not known, returns a BaseAddress object; otherwise returns a ContractInstance (subclass).

Raises

TypeError – When passing an invalid type for the contract_type arguments (expects ContractType).

Parameters
  • address (Union[str, AddressType]) – The address of the plugin. If you are using the ENS plugin, you can also provide an ENS domain name.

  • contract_type (Optional[ContractType]) – Optionally provide the contract type in case it is not already known.

Returns

Will be a

ContractInstance if the contract type is discovered, which is a subclass of the BaseAddress class.

Return type

BaseAddress

Config

class ape.managers.config.ConfigManager(*, DATA_FOLDER: pathlib.Path, REQUEST_HEADER: Dict, PROJECT_FOLDER: pathlib.Path, name: str = '', version: str = '', meta: ethpm_types.manifest.PackageMeta = PackageMeta(authors=None, license=None, description=None, keywords=None, links=None), contracts_folder: pathlib.Path = None, dependencies: List[ape.api.projects.DependencyAPI] = [], deployments: ape.managers.config.DeploymentConfigCollection = None, default_ecosystem: str = 'ethereum', transaction_acceptance_timeout: int = 120)

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
DATA_FOLDER: pathlib.Path

The path to the ape directory such as $HOME/.ape.

PROJECT_FOLDER: pathlib.Path

The path to the ape project.

__hash__ = None
contracts_folder: pathlib.Path

The path to the project’s contracts/ directory (differs by project structure).

default_ecosystem: str

The default ecosystem to use. Defaults to "ethereum".

dependencies: List[ape.api.projects.DependencyAPI]

A list of project dependencies.

deployments: Optional[ape.managers.config.DeploymentConfigCollection]

A dict of contract deployments by address and contract type.

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

Get a plugin config.

Parameters

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

Returns

PluginConfig

load(force_reload: bool = False) ape.managers.config.ConfigManager

Load the user config file and return this class.

meta: ethpm_types.manifest.PackageMeta

Metadata about the project.

name: str

The name of the project.

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.

using_project(project_folder: pathlib.Path, contracts_folder: Optional[pathlib.Path] = None) Generator[ProjectManager, None, None]

Temporarily change the project context.

Usage example:

from pathlib import Path
from ape import config, Project

project_path = Path("path/to/project")
contracts_path = project_path / "contracts"

with config.using_project(project_path):
    my_project = Project(project_path)
Parameters
  • project_folder (pathlib.Path) – The path of the context’s project.

  • contracts_folder (Optional[pathlib.Path]) – The path to the context’s source files. Defaults to <project_path>/contracts.

Returns

Generator

version: str

The project’s version.

class ape.managers.config.DeploymentConfig(_env_file: Optional[Union[str, os.PathLike]] = '<object object>', _env_file_encoding: Optional[str] = None, _env_nested_delimiter: Optional[str] = None, _secrets_dir: Optional[Union[str, os.PathLike]] = None, *, address: Union[str, bytes], contract_type: str)
__hash__ = None
class ape.managers.config.DeploymentConfigCollection(data: Dict, valid_ecosystems: Dict, valid_networks: List[str])

Converters

class ape.managers.converters.AddressAPIConverter

A converter that converts an BaseAddress to a AddressType.

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

Convert the given value to AddressType.

Parameters

value (str) – The value to convert.

Returns

An alias to ChecksumAddress. # noqa: E501

Return type

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

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

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

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

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

class ape.managers.converters.TimestampConverter

Converts either a string, datetime object, or a timedelta object to a timestamp. No timezone required, but should be formatted to UTC.

convert(value: Union[str, datetime.datetime, datetime.timedelta]) int

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.

is_convertible(value: Union[str, datetime.datetime, datetime.timedelta]) 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

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 active_provider: Optional[ape.api.providers.ProviderAPI]

The currently connected provider if one exists. Otherwise, returns None.

property default_ecosystem: ape.api.networks.EcosystemAPI

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 ecosystem_names: Set[str]

The set of all ecosystem names in ape.

property ecosystems: Dict[str, ape.api.networks.EcosystemAPI]

All the registered ecosystems in ape, such as ethereum.

get_ecosystem(ecosystem_name: str) ape.api.networks.EcosystemAPI

Get the ecosystem for the given name.

Parameters

ecosystem_name (str) – The name of the ecosystem to get.

Raises

NetworkError – When the ecosystem is not found.

Returns

EcosystemAPI

get_network_choices(ecosystem_filter: Optional[Union[List[str], str]] = None, network_filter: Optional[Union[List[str], str]] = None, provider_filter: Optional[Union[List[str], str]] = None) Iterator[str]

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:local: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.

Parameters
  • ecosystem_filter (Optional[Union[List[str], str]]) – Get only the specified ecosystems. Defaults to getting all ecosystems.

  • network_filter (Optional[Union[List[str], str]]) – Get only the specified networks. Defaults to getting all networks in ecosystems.

  • provider_filter (Optional[Union[List[str], str]]) – Get only the specified providers. Defaults to getting all providers in networks.

Returns

An iterator over all the network-choice possibilities.

Return type

Iterator[str]

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 get_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 get_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_data: Dict

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 network_names: Set[str]

The set of all network names in ape.

property networks_yaml: str

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 get_network_choices() for all available choices (or use CLI command ape networks list).

Raises

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

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

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

Returns

ProviderContextManager

property provider_names: Set[str]

The set of all provider names in ape.

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.manager.ProjectManager(path: pathlib.Path)

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) Union[ape.contracts.base.ContractContainer, ape.contracts.base.ContractNamespace]

Get a contract container from an existing contract type in the local project using . access.

NOTE: To get a dependency contract, use dependencies.

Usage example:

from ape import project

contract = project.MyContract
Raises

AttributeError – When the given name is not a contract in the project.

Parameters

attr_name (str) – The name of the contract in the project.

Returns

ContractContainer

__str__() str

Return str(self).

property compiler_data: List[ethpm_types.source.Compiler]

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

Returns

List[Compiler]

property contracts: Dict[str, ethpm_types.contract_type.ContractType]

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

Returns

Dict[str, ContractType]

property contracts_folder: pathlib.Path

The path to project’s contracts/ directory.

Returns

pathlib.Path

property dependencies: Dict[str, Dict[str, ape.api.projects.DependencyAPI]]

The package manifests of all dependencies mentioned in this project’s ape-config.yaml file.

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]

extract_manifest() ethpm_types.manifest.PackageManifest

Extracts a package manifest from the project

Returns

ethpm_types.manifest.PackageManifest

get_contract(contract_name: str) ape.contracts.base.ContractContainer

Get a contract container from an existing contract type in the local project by name.

NOTE: To get a dependency contract, use dependencies.

Raises

KeyError – When the given name is not a contract in the project.

Parameters

contract_name (str) – The name of the contract in the project.

Returns

ContractContainer

get_project(path: pathlib.Path, contracts_folder: Optional[pathlib.Path] = None, name: Optional[str] = None, version: Optional[str] = None) ape.api.projects.ProjectAPI

Get the project at the given path. Returns the first ProjectAPI it finds where it is valid.

Parameters
  • path (pathlib.Path) – The path to the project.

  • contracts_folder (pathlib.Path) – The path to the contracts folder. Defaults to <path>/contracts.

  • name (str) – The name of the project. Only necessary when this project is a dependency. Defaults to None.

  • version (str) – The project’s version. Only necessary when this project is a dependency. Defaults to None.

Returns

ProjectAPI

property interfaces_folder: pathlib.Path

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 (Optional[Union[List[Path], Path]]) – Provide one or more contract file-paths to load. If excluded, will load all the contracts.

  • use_cache (Optional[bool]) – 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-folder>/HelloWorld.sol.

Another example is to give it contracts/HelloWorld.sol and it also returns <absolute-project-path>/<contracts-folder>/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 meta: ethpm_types.manifest.PackageMeta

Metadata about the active project as per EIP https://eips.ethereum.org/EIPS/eip-2678#the-package-meta-object Use when publishing your package manifest.

path: pathlib.Path

The project path.

property project_types: List[Type[ape.api.projects.ProjectAPI]]

The available ProjectAPI types available, such as ApeProject, which is the default.

property scripts_folder: pathlib.Path

The path to the scripts/ directory of the project.

Returns

pathlib.Path

property source_paths: List[pathlib.Path]

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: bool

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

property tests_folder: pathlib.Path

The path to the tests/ directory of the project.

Returns

pathlib.Path

class ape.managers.project.dependency.GithubDependency(*, name: str, version: str = None, contracts_folder: str = 'contracts', exclude: List[str] = ['package.json', 'package-lock.json'], github: str, branch: str = None)

A dependency from Github. Use the github key in your dependencies: section of your ape-config.yaml file to declare a dependency from GitHub.

Config example:

dependencies:
  - name: OpenZeppelin
    github: OpenZeppelin/openzeppelin-contracts
    version: 4.4.0
__hash__ = None
branch: Optional[str]

Will be ignored if given a version.

Type

The branch to use. NOTE

extract_manifest() ethpm_types.manifest.PackageManifest

Create a ProjectAPI implementation, 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.

Returns

ProjectAPI

github: str

The Github repo ID e.g. the organization name followed by the repo name, such as dapphub/erc20.

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.managers.project.dependency.LocalDependency(*, name: str, version: str = 'local', contracts_folder: str = 'contracts', exclude: List[str] = ['package.json', 'package-lock.json'], local: str)

A dependency that is already downloaded on the local machine.

Config example:

dependencies:
  - name: Dependency
    local: path/to/dependency
__hash__ = None
extract_manifest() ethpm_types.manifest.PackageManifest

Create a ProjectAPI implementation, 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.

Returns

ProjectAPI

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.managers.project.types.ApeProject(*, path: pathlib.Path, contracts_folder: pathlib.Path, name: str = None, version: str = None, created_temporary_config_file: bool = False)

The default implementation of the ProjectAPI. By default, the :class:`~ape.managers.project.ProjectManager uses an ApeProject at the current-working directory.

__hash__ = None
class ape.managers.project.types.BaseProject(*, path: pathlib.Path, contracts_folder: pathlib.Path, name: str = None, version: str = None, created_temporary_config_file: bool = False)
__hash__ = None
create_manifest(file_paths: Optional[List[pathlib.Path]] = None, use_cache: bool = True) ethpm_types.manifest.PackageManifest

Create a manifest from the project.

Parameters
  • file_paths (Optional[List]) – 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

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 source_paths: List[pathlib.Path]

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. :rtype: List[pathlib.Path]

class ape.managers.project.types.BrownieProject(*, path: pathlib.Path, contracts_folder: pathlib.Path, name: str = None, version: str = None, created_temporary_config_file: bool = False, BROWNIE_CONFIG_FILE_NAME: str = 'brownie-config.yaml')
__hash__ = None
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.

Query

class ape.managers.query.DefaultQueryProvider

Default implementation of the ape.api.query.QueryAPI Allows for the query of blockchain data using connected provider

__hash__ = None
estimate_query(query: Union[BlockQuery, BlockTransactionQuery, AccountTransactionQuery, ContractEventQuery, ContractMethodQuery]) Optional[int]

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]

perform_query(query: Union[BlockQuery, BlockTransactionQuery, AccountTransactionQuery, ContractEventQuery, ContractMethodQuery]) Iterator

Executes the query using best performing estimate_query query engine.

Parameters

query (QueryType) – query to execute

Returns

Iterator

class ape.managers.query.QueryManager

A singleton that manages query engines and performs queries.

Parameters

query (QueryType) – query to execute

Usage example:

biggest_block_size = chain.blocks.query("size").max()
property engines: Dict[str, ape.api.query.QueryAPI]

A dict of all QueryAPI instances across all installed plugins.

Returns

dict[str, QueryAPI]

query(query: Union[BlockQuery, BlockTransactionQuery, AccountTransactionQuery, ContractEventQuery, ContractMethodQuery], engine_to_use: Optional[str] = None) Iterator[ape.api.query.QueryAPI]
Parameters
  • query (QueryType) – The type of query to execute

  • engine_to_use (Optional[str]) – Short-circuit selection logic using a specific engine. Defaults to None.

Raises: QueryEngineError: When given an

invalid or inaccessible engine_to_use value.

Returns

Iterator[QueryAPI]