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) AccountAPI

Get an account by its alias.

Raises:

KeyError – 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: Path | str | Iterable[Path | str], project: ProjectManager | None = None, settings: dict | None = None) Iterator[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 (Union[Path, str, Iterable[Union[Path, str]]]) – The files to compile, as pathlib.Path objects or path-strs.

  • project (Optional[ProjectManager]) – Optionally compile a different project that the one from the current-working directory.

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

Returns:

An iterator of contract types.

Return type:

Iterator[ContractType]

compile_source(compiler_name: str, code: str, project: ProjectManager | None = None, 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.

  • project (Optional[ProjectManager]) – Optionally compile a different project that the one from the current-working directory.

  • 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, **kwargs) 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_custom_error(err: ContractLogicError) CustomError | None

Get a custom error for the given contract logic error using the contract-type found from address-data in the error. Returns None if the given error is not a custom-error or it is not able to find the associated contract type or address.

Parameters:

err (ContractLogicError) – The error to enrich as a custom error.

Returns:

Optional[CustomError]

get_imports(contract_filepaths: Sequence[Path], project: ProjectManager | 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.

  • project (Optional[ProjectManager]) – Optionally provide the project.

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.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[ape.api.transactions.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.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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[ape.api.transactions.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_metadata(address: ChecksumAddress) ContractCreation | None

Get contract creation metadata containing txn_hash, deployer, factory, block.

Parameters:

address (AddressType) – The address of the contract.

Returns:

Optional[ContractCreation]

get_deployments(contract_container: ContractContainer) list[ape.contracts.base.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[eth_typing.evm.ChecksumAddress, ethpm_types.contract_type.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 | HexBytes | None = None, abi: list[Union[ethpm_types.abi.ConstructorABI, ethpm_types.abi.FallbackABI, ethpm_types.abi.ReceiveABI, ethpm_types.abi.MethodABI, ethpm_types.abi.EventABI, ethpm_types.abi.ErrorABI, ethpm_types.abi.StructABI, ethpm_types.abi.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[Union[str, HexBytes]]) – 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 | None = None, request_header: dict | None = None)

An Ape configuration manager, controlled by ape-config.yaml files. NOTE: This is a singleton wrapper class that points to the local project’s config. For the config field definitions, see ApeConfig.

classmethod extract_config(manifest: PackageManifest, **overrides) ApeConfig

Calculate the ape-config data from a package manifest.

Parameters:
  • manifest (PackageManifest) – The manifest.

  • **overrides – Custom config settings.

Returns:

Config data.

Return type:

ApeConfig

property global_config: ApeConfig

Root-level configurations, loaded from the data folder. NOTE: This only needs to load once and applies to all projects.

isolate_data_folder() Iterator[Path]

Change Ape’s DATA_FOLDER to point a temporary path, in a context, for testing purposes. Any data cached to disk will not persist.

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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

  • to_type (to_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, to_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.

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ape.managers.converters.HexConverter

A converter that converts str to HexBytes. NOTE: This utility converter ensures that all bytes args can accept hex too

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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("node"):
   ...
property active_provider: ProviderAPI | None

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

create_custom_provider(connection_str: str, provider_cls: 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 custom_networks: list[dict]

Custom network data defined in various ape-config files or added adhoc to the network manager.

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, ape.api.networks.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, ::node would default to :ethereum:local:node 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.

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.ContractManager(project: LocalProject, sources: SourceManager)

Local contract-type loader. Only dict-like behavior is public.

get(name: str, compile_missing: bool = True, check_for_changes: bool = True) ContractContainer | None

Get a contract by name.

Parameters:
  • name (str) – The name of the contract.

  • compile_missing (bool) – Set to False to not attempt compiling if the contract can’t be found. Note: modified sources are re-compiled regardless of this flag.

  • check_for_changes (bool) – Set to False if avoiding checking for changes.

Returns:

ContractContainer | None

class ape.managers.project.Dependency(api: DependencyAPI, project: ProjectManager | None = None)

A wrapper around a dependency. Users will not create this class directly but access them from project.dependencies.

__eq__(other: Any) bool

Return self==value.

__hash__()

Return hash(self).

compile(use_cache: bool = True, config_override: dict | None = None) dict[str, ape.contracts.base.ContractContainer]

Compile a dependency.

Parameters:
  • use_cache (bool) – Set to False to force a re-compile.

  • config_override (Optional[dict]) – Optionally override the configuration, which may be needed for compiling.

Returns:

dict[str, ContractContainer]

install(use_cache: bool = True, config_override: dict | None = None) ProjectManager

Install this dependency.

Parameters:
  • use_cache (bool) – To force a re-install, like a refresh, set this to False.

  • config_override (dict) – Optionally change the configurtion during install.

Returns:

The resulting project, ready for compiling.

Return type:

ProjectManager

property name: str

The short-name of the dependency, used for remappings.

property package_id: str

The long-name of the dependency, used as an ID.

property project: ProjectManager

The “project” of the dependency, use like any other project in Ape (compile and interact with its contracts).

unpack(path: Path) Iterator[Dependency]

Move dependencies into a .cache folder. Also unpacks dependencies of dependencies. Ideal for tmp-projects.

Parameters:

path (Path) – The destination where to unpack sources.

Returns:

Iterates over every dependency unpacked, so the user knows the dependencies of dependencies.

property uri: str

The dependency’s URI for refreshing.

property version: str

The version of the dependency. Combined with the package_id, you have a full identifier of the package.

class ape.managers.project.DependencyManager(project: ProjectManager | None = None)

Manage dependencies for an Ape project. Note: Every project gets its own dependency-set (DependencyManager).

add(dependency: dict | DependencyAPI) Dependency

Add the dependency API data. This sets up a dependency such that it can be fetched.

Parameters:

dependency (dict | DependencyAPI) – The API data necessary for fetching the dependency.

Returns:

~ape.managers.project.Dependency

Return type:

class

decode_dependency(**item: Any) DependencyAPI

Decode data into a DependencyAPI.

Parameters:

**item – The same data you put in your dependencies: config.

Raises:

ProjectError – When unable to handle the given API data.

Returns:

DependencyAPI

get_dependency(dependency_id: str, version: str, allow_install: bool = True) Dependency

Get a dependency.

Parameters:
  • dependency_id (str) – The package ID of the dependency. You can also provide the short-name of the dependency.

  • version (str) – The version identifier.

  • allow_install (bool) – If the dependendency API is known but the project is not installed, attempt to install it. Defaults to True.

Raises:

ProjectError – When unable to find the dependency.

Returns:

~ape.managers.project.Dependency

Return type:

class

get_versions(name: str) Iterator[Dependency]

Get all installed versions of a dependency.

Parameters:

name (str) – The name of the dependency.

Returns:

Iterator[Dependency]

install(**dependency: Any) Dependency | list[ape.managers.project.Dependency]

Install dependencies.

Parameters:

**dependency – Dependency data, same to what you put in dependencies: config. When excluded, installs all project-specified dependencies. Also, use use_cache=False to force a re-install.

Returns:

Dependency when given data else a list of them, one for each specified.

property installed: Iterator[Dependency]

All installed dependencies, regardless of their project affiliation.

property packages_cache: PackagesCache

Where all dependency files go.

property specified: Iterator[Dependency]

All dependencies specified in the config.

unpack(base_path: Path, cache_name: str = '.cache')

Move dependencies into a .cache folder. Ideal for isolated, temporary projects.

Parameters:
  • base_path (Path) – The target path.

  • cache_name (str) – The cache folder name to create at the target path. Defaults to .cache because that is what is what ape-solidity uses.

property uri_map: dict[str, pydantic_core._pydantic_core.Url]

A map of URIs for filling out the dependencies field in a package manifest. NOTE: Only uses specified dependencies! Make sure you are specifying all the needed dependencies in your config file instead of only relying on globally-installed packages.

class ape.managers.project.DependencyVersionMap(name: str)

A mapping of versions to dependencies. This class exists to allow both v-prefixed versions as well none v-prefixed versions.

__contains__(version: Any) bool

True if the dictionary has the specified key, else False.

__getitem__(version: str) ProjectManager

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

get(version: str, default: ProjectManager | None = None) ProjectManager | None

Return the value for key if key is in the dictionary, else default.

class ape.managers.project.LocalProject(*args, **kwargs)

Manage project(s).

Usage example:

from ape import project, Project

# Interact with local project contracts.
project.MyToken.deploy(sender=...)

# Interact with projects located elsewhere.
other_project = Project("Path/somewhere/else")
other_project.TokenSwapper.deploy(sender=...)
property config: ApeConfig

The project configuration (including global defaults).

property contracts: ContractManager

Container for managing contracts from local sources.

property contracts_folder: Path

The root contract source directory.

property deployments: DeploymentManager

Project deployment manager for adding and reading deployments.

property exclusions: set[Union[str, re.Pattern]]

Source-file exclusion glob patterns.

extract_manifest() PackageManifest

Get a finalized manifest for publishing.

Returns:

PackageManifest

property in_tempdir: bool

True when this project is in the temporary directory, meaning existing only in the temporary directory namespace.

property interfaces_folder: Path

The root interface source directory.

isolate_in_tempdir(**config_override) Iterator[LocalProject]

Clone this project to a temporary directory and return its project.vers_settings[“outputSelection”]

load_manifest() PackageManifest

Load a publish-able manifest.

Returns:

ethpm_types.PackageManifest

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.

property project_api: ProjectAPI

The ‘type’ of project this is, such as an Ape project or a Brownie project (or something else).

refresh_sources()

Check for file-changes. Typically, you don’t need to call this method. This method exists for when changing files mid-session, you can “refresh” and Ape will know about the changes.

reload_config()

Reload the local ape-config.yaml file. This is useful if the file was modified in the active python session.

property sources: SourceManager

All the sources in the project.

unpack(destination: Path, config_override: dict | None = None) LocalProject

Unpack the project to a location using the information from the manifest. Converts a manifest-based project to a local one.

update_manifest(**kwargs)

Change manifest values. Overwrites.

Parameters:

**kwargs – Top-level manifest attributes.

class ape.managers.project.Project(*args, **kwargs)

Base class for projects. Projects can come from either manifests or local source-paths.

add_compiler_data(compiler_data: Iterable[Compiler]) list[ethpm_types.source.Compiler]

Add compiler data to the existing cached manifest.

Parameters:

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

Returns:

The full list of compilers.

Return type:

List[ethpm_types.source.Compiler]

property dependencies: DependencyManager

Project dependencies.

property is_compiled: bool

True if the project is compiled at all. Does not ensure the compilation is up-to-date.

isolate_in_tempdir(**config_override) Iterator[LocalProject]

Clone this project to a temporary directory and return its project.

reconfigure(**overrides)

Change a project’s config.

Parameters:

**overrides – Config key-value pairs. Completely overridesfe existing.

unpack(destination: Path, config_override: dict | None = None) LocalProject

Unpack the project to a location using the information from the manifest. Converts a manifest-based project to a local one.

update_manifest(**kwargs)

Change manifest values. Overwrites.

Parameters:

**kwargs – Top-level manifest attributes.

class ape.managers.project.ProjectManager(*args, **kwargs)

The root project manager in Ape that can also create other projects.

classmethod from_manifest(manifest: PackageManifest | Path | str, config_override: dict | None = None) Project

Create an Ape project using only a manifest.

Parameters:
  • manifest (Union[PackageManifest, Path, str]) – Either a manifest or a path to a manifest file.

  • config_override (Optional[Dict]) – Optionally provide a config override.

Returns:

ProjectManifest

classmethod from_python_library(package_name: str, config_override: dict | None = None) LocalProject

Create an Ape project instance from an installed Python package. This is useful for when Ape or Vyper projects are published to pypi.

Parameters:
  • package_name (str) – The name of the package’s folder that would appear in site-packages.

  • config_override (dict | None) – Optionally override the configuration for this project.

Returns:

LocalProject

class ape.managers.project.SourceManager(root_path: Path, get_contracts_path: Callable, exclude_globs: set[Union[str, re.Pattern]] | None = None)

A manager of a local-project’s sources-paths. Access via project.sources. Allows source-access from both source_id as well as path. Handles detecting modified sources as well as excluded sources. Is meant to resemble a PackageManifest’s source dict but with more functionality for active development.

get(source_id: str) Source | None

Get a Source by source_id.

Parameters:

source_id (str) – The source identifier.

Returns:

Source | None

is_excluded(path: Path) bool

Check if the given path is considered an “excluded” file based on the configured ignore-patterns.

Parameters:

path (Path) – The path to check.

Returns:

bool

lookup(path_id: str | Path) Path | None

Look-up a path by given a sub-path or a source ID.

Parameters:

path_id (Union[str, Path]) – Either part of a path or a source ID.

Returns:

The full path to the source file.

Return type:

Path

property paths: Iterator[Path]

All contract sources paths.

refresh()

Reset file-caches to handle session-changes. (Typically not needed to be called by users).

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: 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: 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, ape.api.query.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]