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, AccountContainerAPI]

A dict of all AccountContainerAPI instances across all installed plugins.

Returns:

dict[str, AccountContainerAPI]

get_accounts_by_type(type_: Type[AccountAPI]) List[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) AccountAPI

Get an account by its alias.

Raises:

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

Returns:

AccountAPI

property test_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)
__getitem__(account_id: int)
__getitem__(account_id: slice)
__getitem__(account_str: str)

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

__iter__() Iterator[AccountAPI]

Implement iter(self).

__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
can_trace_source(filename: str) bool

Check if Ape is able trace the source lines for the given file. Checks that both the compiler is registered and that it supports the trace_source() API method.

Parameters:

filename (str) – The file to check.

Returns:

True when the source is traceable.

Return type:

bool

compile(contract_filepaths: Sequence[Path | str], settings: Dict | None = None) Dict[str, 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 file-extension as well as when there are contract-type collisions across compilers.

Parameters:
  • contract_filepaths (Sequence[Union[pathlib.Path], str]) – The files to compile, as pathlib.Path objects or path-strs.

  • settings (Optional[Dict]) – Adhoc compiler settings. Defaults to None. Ensure the compiler name key is present in the dict for it to work.

Returns:

A mapping of contract names to their type.

Return type:

Dict[str, ContractType]

compile_source(compiler_name: str, code: str, settings: Dict | None = None, **kwargs) ContractContainer

Compile the given program.

Usage example:

code = '[{"name":"foo","type":"fallback", "stateMutability":"nonpayable"}]'
contract_type = compilers.compile_source(
    "ethpm",
    code,
    contractName="MyContract",
)
Parameters:
  • compiler_name (str) – The name of the compiler to use.

  • code (str) – The source code to compile.

  • settings (Optional[Dict]) – Compiler settings.

  • **kwargs (Any) – Additional overrides for the ethpm_types.ContractType model.

Returns:

A contract container ready to be deployed.

Return type:

ContractContainer

enrich_error(err: ContractLogicError) ContractLogicError

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

Parameters:

err (ContractLogicError) – The exception to enrich.

Returns:

The enriched exception.

Return type:

ContractLogicError

flatten_contract(path: Path) Content

Get the flattened version of a contract via its source path. Delegates to the matching CompilerAPI.

Parameters:

path (pathlib.Path) – The source path of the contract.

Returns:

The flattened contract content.

Return type:

ethpm_types.source.Content

get_imports(contract_filepaths: Sequence[Path], base_path: Path | None = None) 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 (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:

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, 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.TransactionHistory

A container mapping Transaction History to the transaction from the active session.

append(txn_receipt: ReceiptAPI)

Add a transaction to the cache This is useful for sessional-transactions.

Raises:

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

Parameters:

txn_receipt (ReceiptAPI) – The transaction receipt.

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.AccountHistory(*, address: ChecksumAddress, sessional: List[ReceiptAPI] = [])

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

__iter__() Iterator[ReceiptAPI]

So dict(model) works.

__len__() int

The transaction count of the address.

address: ChecksumAddress

The address to get history for.

append(receipt: ReceiptAPI)

Add a receipt to the sessional cache.

Parameters:

receipt (ReceiptAPI) – The receipt to append.

property outgoing: Iterator[ReceiptAPI]

All outgoing transactions, from earliest to latest.

query(*columns: str, start_nonce: int = 0, stop_nonce: int | None = None, engine_to_use: str | None = None) DataFrame

A method for querying transactions made by an account and returning an Iterator. If you do not provide a starting nonce, the first transaction is assumed. If you do not provide a stopping block, the last transaction is assumed. You can pass engine_to_use to short-circuit engine selection.

Raises:

ChainError – When stop_nonce is greater than the account’s current nonce.

Parameters:
  • *columns (str) – columns in the DataFrame to return

  • start_nonce (int) – The first transaction, by nonce, to include in the query. Defaults to 0.

  • stop_nonce (Optional[int]) – The last transaction, by nonce, to include in the query. Defaults to the latest transaction.

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

Returns:

pd.DataFrame

revert_to_block(block_number: int)

Remove all receipts after the given block number.

Parameters:

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

sessional: List[ReceiptAPI]

The receipts from the current Python session.

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.

__delitem__(address: ChecksumAddress)

Delete a cached contract. If using a live network, it will also delete the file-cache for the contract.

Parameters:

address (AddressType) – The address to remove from the cache.

__setitem__(address: ChecksumAddress, 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.

cache_blueprint(blueprint_id: str, contract_type: ContractType)

Cache a contract blueprint.

Parameters:
  • blueprint_id (str) – The ID of the blueprint. For example, in EIP-5202, it would be the address of the deployed blueprint. For Starknet, it would be the class identifier.

  • contract_type (ContractType) – The contract type associated with the blueprint.

cache_deployment(contract_instance: ContractInstance)

Cache the given contract instance’s type and deployment information.

Parameters:

contract_instance (ContractInstance) – The contract to cache.

cache_proxy_info(address: ChecksumAddress, proxy_info: ProxyInfoAPI)

Cache proxy info for a particular address, useful for plugins adding already deployed proxies. When you deploy a proxy locally, it will also call this method.

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

  • proxy_info (ProxyInfo) – The proxy info class to cache.

clear_local_caches()

Reset local caches to a blank state.

get(address: ChecksumAddress, default: ContractType | None = None) ContractType | None

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]

get_blueprint(blueprint_id: str) ContractType | None

Get a cached blueprint contract type.

Parameters:

blueprint_id (str) – The unique identifier used when caching the blueprint.

Returns:

ContractType

classmethod get_container(contract_type: ContractType) ContractContainer

Get a contract container for the given contract type.

Parameters:

contract_type (ContractType) – The contract type to wrap.

Returns:

A container object you can deploy.

Return type:

ContractContainer

get_creation_receipt(address: ChecksumAddress, start_block: int = 0, stop_block: int | None = None) ReceiptAPI

Get the receipt responsible for the initial creation of the contract.

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

  • start_block (int) – The block to start looking from.

  • stop_block (Optional[int]) – The block to stop looking at.

Returns:

ReceiptAPI

get_deployments(contract_container: ContractContainer) List[ContractInstance]

Retrieves previous deployments of a contract container or contract type. Locally deployed contracts are saved for the duration of the script and read from _local_deployments_mapping, while those deployed on a live network are written to disk in deployments_map.json.

Parameters:

contract_container (ContractContainer) – The ContractContainer with deployments.

Returns:

Returns a list of contracts that have been deployed.

Return type:

List[ContractInstance]

get_multiple(addresses: Collection[ChecksumAddress], concurrency: int | None = None) Dict[ChecksumAddress, ContractType]

Get contract types for all given addresses.

Parameters:
  • addresses (List[AddressType) – A list of addresses to get contract types for.

  • concurrency (Optional[int]) – The number of threads to use. Defaults to min(4, len(addresses)).

Returns:

A mapping of addresses to their respective contract types.

Return type:

Dict[AddressType, ContractType]

get_proxy_info(address: ChecksumAddress) ProxyInfoAPI | None

Get proxy information about a contract using its address, either from a local cache, a disk cache, or the provider.

Parameters:

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

Returns:

Optional[ProxyInfoAPI]

instance_at(address: str | ChecksumAddress, contract_type: ContractType | None = None, txn_hash: str | None = None, abi: List[ConstructorABI | FallbackABI | ReceiveABI | MethodABI | EventABI | ErrorABI | StructABI | UnprocessedABI] | Dict | str | Path | None = None) ContractInstance

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.

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

  • ContractNotFoundError – When the contract type is not found.

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.

  • txn_hash (Optional[str]) – The hash of the transaction responsible for deploying the contract, if known. Useful for publishing. Defaults to None.

  • abi (Optional[Union[List[ABI], Dict, str, Path]]) – Use an ABI str, dict, path, or ethpm models to create a contract instance class.

Returns:

ContractInstance

instance_from_receipt(receipt: ReceiptAPI, contract_type: ContractType) ContractInstance

A convenience method for creating instances from receipts.

Parameters:

receipt (ReceiptAPI) – The receipt.

Returns:

ContractInstance

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) 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[BlockAPI]

Iterate over all the current blocks.

Returns:

Iterator[BlockAPI]

__len__() int

The number of blocks in the chain.

Returns:

int

property head: BlockAPI

The latest block.

property height: int

The latest block number.

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

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

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

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

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.

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

Returns:

Iterator[BlockAPI]

query(*columns: str, start_block: int = 0, stop_block: int | None = None, step: int = 1, engine_to_use: str | None = None) 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 (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: int | None = None, step: int = 1, engine_to_use: str | None = None) Iterator[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 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: 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.

get_receipt(transaction_hash: str) ReceiptAPI

Get a transaction receipt from the chain.

Parameters:

transaction_hash (str) – The hash of the transaction.

Returns:

ReceiptAPI

property history: TransactionHistory

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

isolate()

Run code in an isolated context. Requires using a local provider that supports snapshotting.

Usages example:

owner = accounts[0]
with chain.isolate():
    contract = owner.deploy(project.MyContract)
    receipt = contract.fooBar(sender=owner)
mine(num_blocks: int = 1, timestamp: int | None = None, deltatime: int | None = 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: str | int | bytes | None = 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() 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

Config

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

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

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

PROJECT_FOLDER: Path

The path to the ape project.

contracts_folder: 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[DependencyAPI]

A list of project dependencies.

deployments: DeploymentConfigCollection | None

A dict of contract deployments by address and contract type.

get_config(plugin_name: str) 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) ConfigManager

Load the user config file and return this class.

meta: PackageMeta

Metadata about the project.

name: str

The name of the project.

using_project(project_folder: Path, contracts_folder: Path | None = None, **config) 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(_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, *, address: str | bytes, contract_type: str)
class ape.managers.config.DeploymentConfigCollection(root: RootModelRootType = PydanticUndefined)

Converters

class ape.managers.converters.AccountIntConverter
convert(value: BaseAddress) 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: 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

class ape.managers.converters.AddressAPIConverter

A converter that converts an BaseAddress to a :class`~ape.types.address.AddressType`.

convert(value: 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 (Any) – The value to check.

Returns:

True when the given value can be converted.

Return type:

bool

class ape.managers.converters.BytesAddressConverter

A converter that converts a raw bytes address to an AddressType.

convert(value: bytes) ChecksumAddress

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

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 | Tuple | List) 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 (Any) – 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 (Any) – The value to check.

Returns:

True when the given value can be converted.

Return type:

bool

class ape.managers.converters.HexIntConverter

Convert hex values to integers.

NOTE If value is a str, it must begin with “0x”.

convert(value: Any) 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: 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

class ape.managers.converters.IntAddressConverter

A converter that converts an integer address to an AddressType.

convert(value: Any) ChecksumAddress

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

class ape.managers.converters.StringDecimalConverter

Convert string-formatted floating point values to Decimal type.

convert(value: str) Decimal

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

class ape.managers.converters.StringIntConverter
convert(value: str) 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: 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

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: str | 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: str | datetime | timedelta) 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

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: ProviderAPI | None

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

create_custom_provider(connection_str: str, provider_cls: ~typing.Type[~ape.api.providers.ProviderAPI] = <class 'ape_ethereum.provider.EthereumNodeProvider'>, provider_name: str | None = None) ProviderAPI

Create a custom connection to a URI using the EthereumNodeProvider provider. NOTE: This provider will assume EVM-like behavior and this is generally not recommended. Use plugins when possible!

Parameters:
  • connection_str (str) – The connection string of the node, such as its URI when using HTTP.

  • provider_cls (Type[ProviderAPI]) – Defaults to EthereumNodeProvider.

  • provider_name (Optional[str]) – The name of the provider. Defaults to best guess.

Returns:

The Geth provider

implementation that comes with Ape.

Return type:

ProviderAPI

property default_ecosystem: 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: EcosystemAPI

The current ecosystem if connected to one.

Raises:

ProviderNotConnectedError – When there is no active provider at runtime.

Returns:

ProviderAPI

property ecosystem_names: Set[str]

The set of all ecosystem names in ape.

property ecosystems: Dict[str, EcosystemAPI]

All the registered ecosystems in ape, such as ethereum.

fork(provider_name: str | None = None, provider_settings: Dict | None = None, block_number: int | None = None) ProviderContextManager

Fork the currently connected network.

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.

  • block_number (Optional[int]) – Optionally specify the block number you wish to fork. Negative block numbers are relative to HEAD. Defaults to the configured fork block number or HEAD.

Returns:

ProviderContextManager

get_ecosystem(ecosystem_name: str) 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: List[str] | str | None = None, network_filter: List[str] | str | None = None, provider_filter: List[str] | str | None = 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: str | None = None, provider_settings: Dict | None = None) 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: NetworkAPI

The current network if connected to one.

Raises:

ProviderNotConnectedError – When there is no active provider at runtime.

Returns:

NetworkAPI

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. NOTE: Deprecated.

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

Returns:

str

parse_network_choice(network_choice: str | None = None, provider_settings: Dict | None = None, disconnect_after: bool = False, disconnect_on_exit: bool = True) 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.

  • disconnect_after (bool) – Set to True to terminate the connection completely at the end of context. NOTE: May only work if the network was also started from this session.

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

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: 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) Any

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:

ApeAttributeError – 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, a ContractNamespace, or any attribute.

__str__() str

Return str(self).

property compiler_cache_folder: Path

The path to the project’s compiler source cache folder.

property compiler_data: List[Compiler]

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

property contracts: Dict[str, ContractType]

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

Returns:

Dict[str, ContractType]

property contracts_folder: Path

The path to project’s contracts/ directory.

Returns:

pathlib.Path

property dependencies: Dict[str, Dict[str, DependencyAPI]]

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

extensions_with_missing_compilers(extensions: List[str] | None = None) Set[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:

Set[str]

extract_manifest() PackageManifest

Extracts a package manifest from the project.

Returns:

ethpm_types.manifest.PackageManifest

get_compiler_data(compile_if_needed: bool = True) List[Compiler]

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

Parameters:

compile_if_needed (bool) – Set to False to only return cached compiler data. Defaults to True.

Returns:

List[Compiler]

get_contract(contract_name: str) 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: Path, contracts_folder: Path | None = None, name: str | None = None, version: str | None = None) 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: Path

The path to the interfaces/ directory of the project.

Returns:

pathlib.Path

load_contracts(file_paths: Iterable[Path] | Path | None = None, use_cache: bool = True) Dict[str, 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[Iterable[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: Path | str) Path | None

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, str) – A sub-path to a contract or a source ID.

Returns:

The path if it exists, else None.

Return type:

pathlib.Path

property meta: 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: Path

The project path.

property project_types: List[Type[ProjectAPI]]

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

property scripts_folder: Path

The path to the scripts/ directory of the project.

Returns:

pathlib.Path

property source_paths: List[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: Dict[str, Source]

A mapping of source identifier to ethpm_types.Source object.

property sources_missing: bool

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

property tests_folder: Path

The path to the tests/ directory of the project.

Returns:

pathlib.Path

track_deployment(contract: ContractInstance)

Indicate that a contract deployment should be included in the package manifest upon publication.

NOTE: Deployments are automatically tracked for contracts. However, only deployments passed to this method are included in the final, publishable manifest.

Parameters:

contract (ContractInstance) – The contract to track as a deployment of the project.

property tracked_deployments: Dict[Bip122Uri, Dict[str, ContractInstance]]

Deployments that have been explicitly tracked via track_deployment(). These deployments will be included in the final package manifest upon publication of this package.

class ape.managers.project.dependency.GithubDependency(*, name: str, version: str | None = None, contracts_folder: str = 'contracts', exclude: List[str] = ['package.json', 'package-lock.json', '**/.build/**/*.json'], config_override: Dict = {}, github: str, ref: str | None = 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
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

github: str

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

ref: str | None

The branch or tag to use.

NOTE: Will be ignored if given a version.

property uri: Url

The URI to use when listing in a PackageManifest.

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', '**/.build/**/*.json'], config_override: Dict = {}, local: str)

A dependency that is already downloaded on the local machine.

Config example:

dependencies:
  - name: Dependency
    local: path/to/dependency
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

property uri: Url

The URI to use when listing in a PackageManifest.

version: str

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

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.NpmDependency(*, name: str, version: str | None = None, contracts_folder: str = 'contracts', exclude: List[str] = ['package.json', 'package-lock.json', '**/.build/**/*.json'], config_override: Dict = {}, npm: str)

A dependency from the Node Package Manager (NPM).

Config example:

dependencies:
  - name: safe-singleton-factory
    npm: "@gnosis.pm/safe-singleton-factory"
    version: 1.0.14
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

npm: str

The NPM repo ID e.g. the organization name followed by the repo name, such as "@gnosis.pm/safe-singleton-factory".

property uri: Url

The URI to use when listing in a PackageManifest.

property version_from_json: str | None

The version from package.json in the installed package. Requires having run npm install.

property version_from_local_json: str | None

The version from your project’s package.json, if exists.

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.BaseProject(*, path: Path, contracts_folder: Path, name: str | None = None, version: str | None = None, config_file_name: str = 'ape-config.yaml')
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

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.

process_config_file(**kwargs) bool

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

property source_paths: List[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]

class ape.managers.project.types.ApeProject(*, path: Path, contracts_folder: Path, name: str | None = None, version: str | None = None, config_file_name: str = 'ape-config.yaml')

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

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

process_config_file(**kwargs) bool

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

Query

class ape.managers.query.DefaultQueryProvider

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

estimate_query(query: BlockQuery | BlockTransactionQuery | AccountTransactionQuery | ContractCreationQuery | ContractEventQuery | ContractMethodQuery) int | None
estimate_query(query: BlockQuery) int | None
estimate_query(query: BlockTransactionQuery) int
estimate_query(query: ContractCreationQuery) int
estimate_query(query: ContractEventQuery) int
estimate_query(query: AccountTransactionQuery) 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: BlockQuery | BlockTransactionQuery | AccountTransactionQuery | ContractCreationQuery | ContractEventQuery | ContractMethodQuery) Iterator
perform_query(query: BlockQuery) Iterator
perform_query(query: BlockTransactionQuery) Iterator[TransactionAPI]
perform_query(query: ContractCreationQuery) Iterator[ReceiptAPI]
perform_query(query: ContractEventQuery) Iterator[ContractLog]
perform_query(query: AccountTransactionQuery) Iterator[ReceiptAPI]

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, QueryAPI]

A dict of all QueryAPI instances across all installed plugins.

Returns:

dict[str, QueryAPI]

query(query: BlockQuery | BlockTransactionQuery | AccountTransactionQuery | ContractCreationQuery | ContractEventQuery | ContractMethodQuery, engine_to_use: str | None = None) Iterator[BaseInterfaceModel]
Parameters:
  • query (QueryType) – The type of query to execute

  • engine_to_use (Optional[str]) – Short-circuit selection logic using a specific engine. Defaults is set by performance-based selection logic.

Raises: QueryEngineError: When given an invalid or

inaccessible engine_to_use value.

Returns:

Iterator[BaseInterfaceModel]