ape.managers#
Accounts#
- class ape.managers.accounts.AccountManager#
The
AccountManageris a container of containers forAccountAPIobjects. All containers must subclassAccountContainerAPIand are treated as singletons.Import the accounts manager singleton from the root
apenamespace.Usage example:
from ape import accounts # "accounts" is the AccountManager singleton my_accounts = accounts.load("dev")
- __contains__(address: Annotated[ChecksumAddress, _AddressValidator]) bool#
Determine if the given address matches an account in
ape.- Parameters:
address (
AddressType) – The address to check.- Returns:
Truewhen the given address is found.- Return type:
bool
- __len__() int#
The number of accounts managed by all account plugins.
- Returns:
int
- __repr__() str#
Return repr(self).
- 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 methodload().- Returns:
Iterator[str]
- property containers: dict[str, AccountContainerAPI]#
A dict of all
AccountContainerAPIinstances 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:
KeyError – When there is no local account with the given alias.
- Returns:
- resolve_address(account_id: BaseAddress | AddressType | str | int | bytes) Annotated[ChecksumAddress, _AddressValidator] | None#
Resolve the given input to an address.
- Parameters:
( (account_id) – class:~ape.api.address.BaseAddress, str, int, bytes): The input to resolve. It handles anything that converts to an AddressType like an ENS or a BaseAddress. It also handles account aliases Ape is aware of, or int or bytes address values.
- Returns:
AddressType| None
- property test_accounts: TestAccountManager#
Accounts generated from the configured test mnemonic. These accounts are also the subject of a fixture available in the
testplugin calledaccounts. Configure these accounts, such as the mnemonic and / or number-of-accounts using thetestsection 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: Annotated[ChecksumAddress, _AddressValidator]) 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).
- __repr__() str#
Return repr(self).
- property hd_path: str#
The HD path used for generating the test accounts.
- impersonate_account(address: Annotated[ChecksumAddress, _AddressValidator]) ImpersonatedAccount#
Impersonate an account for testing purposes.
- Parameters:
address (AddressType) – The address to impersonate.
- property mnemonic: str#
The seed phrase for generated test accounts.
- property number_of_accounts: int#
The number of test accounts to generate and fund by default.
- stop_impersonating(address: Annotated[ChecksumAddress, _AddressValidator])#
End the impersonating of an account, if it is being impersonated.
- Parameters:
address (AddressType) – The address to stop impersonating.
Compilers#
- class ape.managers.compilers.CompilerManager#
The singleton that manages
CompilerAPIinstances. Each compiler plugin typically contains a singleCompilerAPI.NOTE: Typically, users compile their projects using the CLI via
ape compile, which uses theCompilerAPIunder-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:
Truewhen the source is traceable.- Return type:
bool
- compile(contract_filepaths: Path | str | Iterable[Path | str], project: ProjectManager | None = None, settings: dict | None = None, excluded_compilers: list[str] | 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 (Path | str | Iterable[Path | str]) – The files to compile, as
pathlib.Pathobjects or path-strs.project (Optional[
ProjectManager]) – Optionally compile a different project that the one from the current-working directory.settings (dict | None) – 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_container = 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 (dict | None) – Compiler settings.
**kwargs (Any) – Additional overrides for the
ethpm_types.ContractTypemodel.
- 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:
- 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
Noneif 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:
CustomError| None
- 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 (
ProjectManager| None) – 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, CompilerAPI]#
Each compile-able file extension mapped to its respective
CompilerAPIinstance.- 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: Annotated[ChecksumAddress, _AddressValidator], 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.
- __pydantic_computed_fields__: ClassVar[Dict[str, ComputedFieldInfo]] = {}#
A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.
- __pydantic_extra_info__: ClassVar[PydanticExtraInfo | None] = None#
A wrapper around the __pydantic_extra__ annotation, if explicitly annotated on a model.
This is a private attribute, not meant to be used outside Pydantic.
- __pydantic_fields__: ClassVar[Dict[str, FieldInfo]] = {'address': FieldInfo(annotation=NewType, required=True, metadata=[<class 'ape.types.address._AddressValidator'>]), 'sessional': FieldInfo(annotation=list[ReceiptAPI], required=False, default=[])}#
A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.
- __pydantic_setattr_handlers__: ClassVar[Dict[str, Callable[[BaseModel, str, Any], None]]] = {}#
__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__
- __signature__: ClassVar[Signature] = <Signature (*, address: typing.Annotated[eth_typing.evm.ChecksumAddress, <class 'ape.types.address._AddressValidator'>], sessional: list[ape.api.transactions.ReceiptAPI] = []) -> None>#
The synthesized __init__ [Signature][inspect.Signature] of the model.
- address: Annotated[ChecksumAddress, _AddressValidator]#
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_useto short-circuit engine selection.- Raises:
ChainError – When
stop_nonceis 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 (int | None) – The last transaction, by nonce, to include in the query. Defaults to the latest transaction.
engine_to_use (str | None) – 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:
An in-memory cache of locally deployed contracts
A cache of contracts per network (only permanent networks are stored this way)
When retrieving a contract, if a
ExplorerAPIis used, it will be cached to disk for faster look-up next time.- __delitem__(address: Annotated[ChecksumAddress, _AddressValidator])#
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: Annotated[ChecksumAddress, _AddressValidator], item: ContractType | ProxyInfoAPI | ContractCreation)#
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}.jsonfor faster look-up next time.- Parameters:
address (AddressType) – The on-chain address of the contract.
item (ContractType | ProxyInfoAPI | ContractCreation) – The contract’s type, proxy info, or creation metadata.
- 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_contract_creation(address: Annotated[ChecksumAddress, _AddressValidator], contract_creation: ContractCreation, ecosystem_key: str | None = None, network_key: str | None = None)#
Cache a contract creation object.
- Parameters:
address (AddressType) – The address of the contract.
contract_creation (ContractCreation) – The object to cache.
ecosystem_key (str | None) – The ecosystem key. Defaults to the connected ecosystem’s name.
network_key (str | None) – The network key. Defaults to the connected network’s name.
- cache_contract_type(address: Annotated[ChecksumAddress, _AddressValidator], contract_type: ContractType, ecosystem_key: str | None = None, network_key: str | None = None)#
Cache a contract type at the given address for the given network. If not connected, you must provider both
ecosystem_key:andnetwork_key::.- Parameters:
address (AddressType) – The address key.
contract_type (ContractType) – The contract type to cache.
ecosystem_key (str | None) – The ecosystem key. Defaults to the connected ecosystem’s name.
network_key (str | None) – The network key. Defaults to the connected network’s name.
- cache_deployment(contract_instance: ContractInstance, proxy_info: ProxyInfoAPI | None = None, detect_proxy: bool = True)#
Cache the given contract instance’s type and deployment information.
- Parameters:
contract_instance (
ContractInstance) – The contract to cache.proxy_info (ProxyInfoAPI | None) – Pass in the proxy info, if it is known, to avoid the potentially expensive look-up.
detect_proxy (bool) – Set to
Falseto avoid detecting if the contract is a proxy.
- cache_proxy_info(address: Annotated[ChecksumAddress, _AddressValidator], 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.
- property deployments: DeploymentDiskCache#
A manager for contract deployments across networks.
- get(address: Annotated[ChecksumAddress, _AddressValidator], default: ContractType | None = None, fetch_from_explorer: bool = True, fetch_from_disk: bool = True, proxy_info: ProxyInfoAPI | None = None, detect_proxy: bool = True, replace: bool = False) 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 (ContractType | None) – A default contract when none is found. Defaults to
None.fetch_from_explorer (bool) – Set to
Falseto avoid fetching from an explorer. Defaults toTrue. Only fetches if it needs to (uses disk & memory caching otherwise).fetch_from_disk (bool) – Set to
Falseto avoid reading (and merging) the disk-cached ABI for this address. Defaults toTrue.proxy_info (ProxyInfoAPI | None) – Pass in the proxy info, if it is known, to avoid the potentially expensive look-up.
detect_proxy (bool) – Set to
Falseto avoid detecting if it is a proxy.replace (bool) – Set to
Trueto overwrite the cached contract type instead of merging with it. Useful when a cached ABI is corrupt. WhenTrueand onlydefaultis given, the cache is replaced withdefault. WhenTrueandfetch_from_exploreris alsoTrue, the cache is replaced with the explorer result (or the merge of the explorer result anddefault, when both are present). Defaults toFalse.
- Returns:
- The contract type if it was able to get one,
otherwise the default parameter.
- Return type:
ContractType | None
- 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:
- get_creation_metadata(address: Annotated[ChecksumAddress, _AddressValidator]) ContractCreation | None#
Get contract creation metadata containing txn_hash, deployer, factory, block.
- Parameters:
address (AddressType) – The address of the contract.
- Returns:
ContractCreation| None
- 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 indeployments_map.json.- Parameters:
contract_container (
ContractContainer) – TheContractContainerwith deployments.- Returns:
Returns a list of contracts that have been deployed.
- Return type:
list[
ContractInstance]
- get_multiple(addresses: Collection[Annotated[ChecksumAddress, _AddressValidator]], concurrency: int | None = None) dict[Annotated[ChecksumAddress, _AddressValidator], ContractType]#
Get contract types for all given addresses.
- Parameters:
addresses (list[AddressType) – A list of addresses to get contract types for.
concurrency (int | None) – 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: Annotated[ChecksumAddress, _AddressValidator]) 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:
ProxyInfoAPI| None
- instance_at(address: str | Annotated[ChecksumAddress, _AddressValidator], contract_type: ContractType | None = None, txn_hash: str | HexBytes | None = None, abi: list[ConstructorABI | FallbackABI | ReceiveABI | MethodABI | EventABI | ErrorABI | StructABI | UnprocessedABI] | dict | str | Path | None = None, fetch_from_explorer: bool = True, fetch_from_disk: bool = True, proxy_info: ProxyInfoAPI | None = None, detect_proxy: bool = True, replace: bool = False) 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 (str | AddressType) – The address of the plugin. If you are using the ENS plugin, you can also provide an ENS domain name.
contract_type (ContractType | None) – Optionally provide the contract type in case it is not already known.
txn_hash (str | HexBytes | None) – The hash of the transaction responsible for deploying the contract, if known. Useful for publishing. Defaults to
None.abi (list[ABI] | dict | str | Path | None) – Use an ABI str, dict, path, or ethpm models to create a contract instance class.
fetch_from_explorer (bool) – Set to
Falseto avoid fetching from the explorer. Defaults toTrue. Won’t fetch unless it needs to (uses disk & memory caching first).fetch_from_disk (bool) – Set to
Falseto avoid reading (and merging) the disk-cached ABI for this address. Defaults toTrue.proxy_info (ProxyInfoAPI | None) – Pass in the proxy info, if it is known, to avoid the potentially expensive look-up.
detect_proxy (bool) – Set to
Falseto avoid detecting if the contract is a proxy.replace (bool) – Set to
Trueto overwrite a (possibly corrupt) cached contract type rather than merging with it. With onlycontract_typegiven, the cache is replaced with that. Withfetch_from_explorer=Trueand nocontract_type, the cache is replaced with the explorer result. With both, the cache is replaced with their merge. Defaults toFalse.
- Returns:
- classmethod instance_from_receipt(receipt: ReceiptAPI, contract_type: ContractType) ContractInstance#
A convenience method for creating instances from receipts.
- Parameters:
receipt (
ReceiptAPI) – The receipt.contract_type (ContractType) – The deployed contract type.
- Returns:
- use_temporary_caches()#
Create temporary context where there are no cached items. Useful for testing.
- 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,
-1would be the latest block and-2would be the block prior to that one, and so on.- Parameters:
block_number (int) – The number of the block to get.
- Returns:
- __len__() int#
The number of blocks in the chain.
- Returns:
int
- 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_blockis 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 (int | None) – The block number to start with. Defaults to the pending block number.
stop_block (int | None) – Optionally set a future block number to stop at. Defaults to never-ending.
required_confirmations (int | None) – 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 (float | None) – The amount of time to wait for a new block before timing out. Defaults to 10 seconds for local networks or
50 * block_timefor 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_useto short-circuit engine selection.- Raises:
ChainError – When
stop_blockis 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 (int | None) – 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 (str | None) – 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:
ChainError – When
stopis greater than the chain length.ChainError – When
stopis less thanstart_block.ChainError – When
stopis less than 0.ChainError – When
startis less than 0.
- 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
rangebuilt-in Python function.stop (int | None) – 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 (int | None) – The value to increment by. Defaults to
1. number of blocks to get. Defaults to the latest block.engine_to_use (str | None) – 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
apenamespace.Usage example:
from ape import chain- __repr__() str#
Return repr(self).
- 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 contracts: ContractCache#
A manager for cached contract-types, proxy info, and more.
- property gas_price: int#
The price for what it costs to transact.
- get_balance(address: BaseAddress | Annotated[ChecksumAddress, _AddressValidator] | str, block_id: BlockID | None = None) int#
Get the balance of the given address. If
ape-ensis installed, you can pass ENS names.- Parameters:
address (BaseAddress, AddressType | str) – An address, ENS, or account/contract.
block_id (
BlockID| None) – The block ID. Defaults to latest.
- Returns:
The account balance.
- Return type:
int
- get_block_at(time: datetime | int, block_time_secs: int | None = None) BlockAPI#
Search for a block closest to time
time.IMPORTANT: This method returns the closest block at or after
time.- Parameters:
time – (datetime | int): Time of block to search for.
block_time_secs – (int | None): The average amount of time between blocks. Influenced the search algorithm. Defaults to the configured block time for this chain.
- Returns:
The first block mined at or after
time.- Return type:
- 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 (int | None) – Designate a time (in seconds) to begin mining. Defaults to None.
deltatime (int | None) – 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: SnapshotID | 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 (
SnapshotID| None) – The snapshot ID. Defaults to the most recent snapshot ID.
- set_balance(account: BaseAddress | Annotated[ChecksumAddress, _AddressValidator] | str, amount: int | str)#
Set an account balance, only works on development chains.
- Parameters:
account (BaseAddress, AddressType | str) – The account.
amount (int | str) – The new balance.
- snapshot() SnapshotID#
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.yamlfiles. NOTE: This is a singleton wrapper class that points to the local project’s config. For the config field definitions, seeApeConfig.- __repr__() str#
Return repr(self).
- __str__() str#
Return str(self).
- 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(keep: Iterable[str] | str | None = None) 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.
- Parameters:
keep (Iterable[str] | str | None) – Optionally, pass in a key of subdirectory names to include in the new isolated data folder. For example, pass ing
"packages"to avoid having to re-download dependencies in an isolated environment.- Returns:
The temporary data folder.
- Return type:
Iterator[Path]
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
ConversionErrorwhen the item fails to convert properly.Usage example:
from ape import convert from ape.types import AddressType convert("1 gwei", int) # 1000000000 convert("1 ETH", int) # 1000000000000000000 convert("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes) # HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5') convert("vitalik.eth", AddressType) # with ape-ens plugin installed # '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
- is_convertible(value: Any) bool#
Returns
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen the given value can be converted.- Return type:
bool
- class ape.managers.converters.AddressAPIConverter#
A converter that converts an
BaseAddressto a :class`~ape.types.address.AddressType`.- convert(value: BaseAddress) Annotated[ChecksumAddress, _AddressValidator]#
Convert the given value to
AddressType.- Parameters:
value (str) – The value to convert.
- Returns:
An alias to ChecksumAddress. # noqa: E501
- Return type:
- is_convertible(value: Any) bool#
Returns
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen 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) Annotated[ChecksumAddress, _AddressValidator]#
Convert the given value to the type specified as the generic for this class. Implementations of this API must throw a
ConversionErrorwhen the item fails to convert properly.Usage example:
from ape import convert from ape.types import AddressType convert("1 gwei", int) # 1000000000 convert("1 ETH", int) # 1000000000000000000 convert("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes) # HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5') convert("vitalik.eth", AddressType) # with ape-ens plugin installed # '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
- is_convertible(value: Any) bool#
Returns
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen 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 rootapenamespace.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
ConverterAPIinstances 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
- get_converter(name: str) ConverterAPI#
Get a converter plugin by name.
- Parameters:
name (str) – The name of the converter.
- Returns:
The converter.
- Return type:
ConverterAPI
- get_converters_by_type(converter_type: type) list[ConverterAPI]#
Get all the converters for the given type.
- Parameters:
converter_type (type) – The type to get converters for.
- Returns:
All registered converters for the given type.
- Return type:
list[ConverterAPI]
- 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:
Truewhen 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
strto aAddressType.- convert(value: str) Annotated[ChecksumAddress, _AddressValidator]#
Convert the given value to a
AddressType.- Parameters:
value (str) – The address
strto convert.- Returns:
- is_convertible(value: Any) bool#
Returns
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen the given value can be converted.- Return type:
bool
- class ape.managers.converters.HexConverter#
A converter that converts
strtoHexBytes. 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
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen 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
ConversionErrorwhen the item fails to convert properly.Usage example:
from ape import convert from ape.types import AddressType convert("1 gwei", int) # 1000000000 convert("1 ETH", int) # 1000000000000000000 convert("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes) # HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5') convert("vitalik.eth", AddressType) # with ape-ens plugin installed # '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
- is_convertible(value: Any) bool#
Returns
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen the given value can be converted.- Return type:
bool
- class ape.managers.converters.HexIterableConverter#
Convert list of hex values to single concatenated
HexBytesvalue.- convert(value: Any) bytes#
Convert the given value to the type specified as the generic for this class. Implementations of this API must throw a
ConversionErrorwhen the item fails to convert properly.Usage example:
from ape import convert from ape.types import AddressType convert("1 gwei", int) # 1000000000 convert("1 ETH", int) # 1000000000000000000 convert("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes) # HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5') convert("vitalik.eth", AddressType) # with ape-ens plugin installed # '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
- is_convertible(value: Any) bool#
Returns
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen 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) Annotated[ChecksumAddress, _AddressValidator]#
Convert the given value to the type specified as the generic for this class. Implementations of this API must throw a
ConversionErrorwhen the item fails to convert properly.Usage example:
from ape import convert from ape.types import AddressType convert("1 gwei", int) # 1000000000 convert("1 ETH", int) # 1000000000000000000 convert("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes) # HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5') convert("vitalik.eth", AddressType) # with ape-ens plugin installed # '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
- is_convertible(value: Any) bool#
Returns
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen 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
ConversionErrorwhen the item fails to convert properly.Usage example:
from ape import convert from ape.types import AddressType convert("1 gwei", int) # 1000000000 convert("1 ETH", int) # 1000000000000000000 convert("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes) # HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5') convert("vitalik.eth", AddressType) # with ape-ens plugin installed # '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
- is_convertible(value: Any) bool#
Returns
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen 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
ConversionErrorwhen the item fails to convert properly.Usage example:
from ape import convert from ape.types import AddressType convert("1 gwei", int) # 1000000000 convert("1 ETH", int) # 1000000000000000000 convert("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes) # HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5') convert("vitalik.eth", AddressType) # with ape-ens plugin installed # '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
- is_convertible(value: Any) bool#
Returns
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen 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
ConversionErrorwhen the item fails to convert properly.Usage example:
from ape import convert from ape.types import AddressType convert("1 gwei", int) # 1000000000 convert("1 ETH", int) # 1000000000000000000 convert("0x283Af0B28c62C092C9727F1Ee09c02CA627EB7F5", bytes) # HexBytes('0x283af0b28c62c092c9727f1ee09c02ca627eb7f5') convert("vitalik.eth", AddressType) # with ape-ens plugin installed # '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
- is_convertible(value: str | datetime | timedelta) bool#
Returns
Trueif string value provided byvalueis convertible usingape.api.convert.ConverterAPI.convert().- Parameters:
value (Any) – The value to check.
- Returns:
Truewhen 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
--networkcommand 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.
- property connected: bool#
Truewhen there is an active provider.
- create_custom_provider(connection_str: str, provider_cls: type[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 toEthereumNodeProvider.provider_name (str | None) – The name of the provider. Defaults to best guess.
- Returns:
- The Geth provider
implementation that comes with Ape.
- Return type:
- 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:
- 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 asethereum.
- 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. WhenNone, returns the default provider.provider_settings (dict, optional) – Settings to apply to the provider. Defaults to
None.block_number (int | None) – 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:
- 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:
- 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:providerand shortened options also appear in the list. For example,::nodewould default to:ethereum:local:nodeand both will be in the returned list. The values come from eachProviderAPIthat is installed.Use the CLI command
ape networks listto list all the possible network combinations.- Parameters:
ecosystem_filter (list[str] | str | None) – Get only the specified ecosystems. Defaults to getting all ecosystems.
network_filter (list[str] | str | None) – Get only the specified networks. Defaults to getting all networks in ecosystems.
provider_filter (list[str] | str | None) – 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
ProviderAPIfrom a network choice. A network choice is any value returned fromget_network_choices(). Use the CLI commandape networks listto 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:
- get_request_headers(ecosystem_name: str, network_name: str, provider_name: str) RPCHeaders#
All request headers to be used when connecting to this network.
- get_running_node(pid: int) SubprocessProvider#
Get a running subprocess provider for the given
pid.- Parameters:
pid (int) – The process ID.
- Returns:
~ape.api.providers.SubprocessProvider
- Return type:
class
- kill_node_process(*process_ids: int) dict[int, NodeProcessData]#
Kill a node process managed by Ape.
- Parameters:
*process_ids (int) – The process ID to kill.
- Returns:
The process data of all terminated processes.
- Return type:
dict[str,
NodeProcessData]
- property network: NetworkAPI#
The current network if connected to one.
- Raises:
ProviderNotConnectedError – When there is no active provider at runtime.
- Returns:
- 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 commandape 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.
- property running_nodes: NodeProcessMap#
All running development nodes managed by 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.
- class ape.managers.networks.NodeProcessData(*, network_choice: str, ipc_path: Path | None = None, http_uri: str | None = None, ws_uri: str | None = None)#
Cached data for node subprocesses managed by Ape.
- http_uri: str | None#
The HTTP URI this node process exposes.
- ipc_path: Path | None#
The IPC path this node process communicates on.
- network_choice: str#
The network triple
ecosystem:network:node.
- ws_uri: str | None#
The websockets URI this node process exposes.
- class ape.managers.networks.NodeProcessMap(*args, nodes: dict[int, NodeProcessData] = {})#
All managed running network subprocesses.
Project#
- class ape.managers.project.ContractManager(project: LocalProject, sources: SourceManager)#
Local contract-type loader. Only dict-like behavior is public.
- __repr__() str#
Return repr(self).
- 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
Falseto 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
Falseif 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).
- __repr__() str#
Return repr(self).
- property api_path: Path#
The path to the dependency’s API data-file. This data is necessary for managing the installation of the dependency.
- property clean_package_id: str#
The package ID hiding the user information.
- compile(use_cache: bool = True, config_override: dict | None = None, allow_install: bool = False) dict[str, ContractContainer]#
Compile a dependency.
- Parameters:
use_cache (bool) – Set to
Falseto force a re-compile.config_override (dict | None) – Optionally override the configuration, which may be needed for compiling.
allow_install (bool) – Set to
Trueto allow installing.
- Returns:
dict[str,
ContractContainer]
- property compiled: bool#
True if installed and compiled.
- install(use_cache: bool = True, config_override: dict | None = None, recurse: bool = True) ProjectManager#
Install this dependency.
- Parameters:
use_cache (bool) – To force reinstalling, like a refresh, set this to
False.config_override (dict) – Optionally change the configuration during install.
recurse (bool) – Set to
Falseto avoid installing dependency of dependencies.
- Returns:
The resulting project, ready for compiling.
- Return type:
- property installed: bool#
Installed does not mean the dependency is compiled!
- Type:
Truewhen a project is available. Note
- property manifest_path: Path#
The path to the dependency’s manifest. When compiling, the artifacts go here.
- 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).
- property project_path: Path#
The path to the dependency’s project root. When installing, this is where the project files go.
- 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).
- __repr__() str#
Return repr(self).
- 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
- property all: Iterator[Dependency]#
All installed dependencies, regardless of their project affiliation. NOTE: By “installed” here, we simply mean the API files are cached and known by Ape. However, it does not guarantee the project is installed.
- 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:
- 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 dependency 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_dependency_api(package_id: str, version: str | None = None) DependencyAPI#
Get a dependency API. If not given version and there are multiple, returns the latest.
- Parameters:
package_id (str) – The package ID or name of the dependency.
version (str) – The version of the dependency.
- Returns:
- get_project_dependencies(use_cache: bool = True, config_override: dict | None = None, name: str | None = None, version: str | None = None, allow_install: bool = True, strict: bool = False, recurse: bool = True) Iterator[Dependency]#
Get dependencies specified in the project’s
ape-config.yamlfile.- Parameters:
use_cache (bool) – Set to
Falseto force-reinstall dependencies. Defaults toTrue. Does not work withallow_install=False.config_override (dict | None) – Override shared configuration for each dependency.
name (str | None) – Optionally only get dependencies with a certain name.
version (str | None) – Optionally only get dependencies with certain version.
allow_install (bool) – Set to
Falseto not allow installing uninstalled specified dependencies.strict (bool) –
Truerequires the dependency to either be installed or install properly.recurse (bool) – Set to
Falseto not recursively install dependencies of dependencies.
- Returns:
Iterator[
Dependency]
- get_versions(name: str, allow_install: bool = True) Iterator[Dependency]#
Get all installed versions of a dependency.
- Parameters:
name (str) – The name of the dependency.
allow_install (bool) – Set to
Falseto not allow installing.
- Returns:
Iterator[
Dependency]
- install(**dependency: Any) Dependency | list[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=Falseto force re-installing andrecurse=Falseto avoid installing dependencies of dependencies.- Returns:
Dependencywhen given data else a list of them, one for each specified.
- property installed: Iterator[Dependency]#
Use
.all. Deprecated because of confusion between this and uninstalled dependencies Ape still nows about but require an extra install step, such as fetching from GitHub.- Type:
DEPRECATED
- 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
.cachebecause that is whatape-solidityuses.
- property uri_map: dict[str, 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]
- __repr__() str#
Return repr(self).
- 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.DeploymentManager(project: LocalProject)#
- __iter__() Iterator[ContractInstance]#
Get project deployments.
- Returns:
Iterator[ethpm_types.ContractInstance]
- property instance_map: dict[str, dict[str, ContractInstance]]#
The mapping needed for deployments publishing in an ethpm manifest.
- track(contract: ContractInstance, allow_dev: bool = False)#
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.allow_dev (bool) – Set to
Trueif simulating in a local dev environment.
- 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=...)
- __repr__()#
Return repr(self).
- chdir(path: Path | None = None)#
Change the local project to the new path.
- Parameters:
path (Path) – The path of the new project. If not given, defaults to the project’s path.
- 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[str | Pattern]#
Source-file exclusion glob patterns.
- extract_manifest() PackageManifest#
Get a finalized manifest for publishing.
- Returns:
PackageManifest
- property in_tempdir: bool#
Truewhen 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 path: Path#
The path to the project’s “base” (where contract source IDs are relative to).
- 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.
- within_project_path()#
A context-manager for changing the current working directory to the project’s
.path. Then, switching back to whatever the current directory was before calling this method.
- class ape.managers.project.MultiProject(*, path: Path, apis: list[ProjectAPI] = [])#
A project with more than 1 valid project API configs, such as a Foundry project containing an
ape-config.yamlfile.- __pydantic_computed_fields__: ClassVar[Dict[str, ComputedFieldInfo]] = {}#
A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.
- __pydantic_extra_info__: ClassVar[PydanticExtraInfo | None] = None#
A wrapper around the __pydantic_extra__ annotation, if explicitly annotated on a model.
This is a private attribute, not meant to be used outside Pydantic.
- __pydantic_fields__: ClassVar[Dict[str, FieldInfo]] = {'apis': FieldInfo(annotation=list[ProjectAPI], required=False, default=[]), 'path': FieldInfo(annotation=Path, required=True)}#
A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.
- __pydantic_setattr_handlers__: ClassVar[Dict[str, Callable[[BaseModel, str, Any], None]]] = {}#
__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__
- __signature__: ClassVar[Signature] = <Signature (*, path: pathlib.Path, apis: list[ape.api.projects.ProjectAPI] = []) -> None>#
The synthesized __init__ [Signature][inspect.Signature] of the model.
- apis: list[ProjectAPI]#
An ordered list of APIs to use. The last items take precedence as their configs merge.
- extract_config(**overrides) ApeConfig#
Extra configuration from the project so that Ape understands the dependencies and how to compile everything.
- Parameters:
**overrides – Config overrides.
- Returns:
ApeConfig
- property is_valid: bool#
Return
Truewhen detecting a project of this type.
- class ape.managers.project.PackagesCache#
- cache_api(api: DependencyAPI) Path#
Cache a dependency JSON for usage outside the project.
- get_api_path(package_id: str, version: str) Path#
Path to the manifest filepath the dependency project uses as a base.
- get_manifest_path(package_id: str, version: str) Path#
Path to the manifest filepath the dependency project uses as a base.
- get_project_path(package_id: str, version: str) Path#
Path to the dir of the cached project.
- get_project_versions_path(package_id: str) Path#
The path to all the versions (projects) of a dependency.
- isolate_changes()#
Allows you to make changes affecting the Ape packages cache in a context. For example, temporarily install local “dev” packages for testing purposes.
- class ape.managers.project.Project(*args, **kwargs)#
Base class for projects. Projects can come from either manifests or local source-paths.
- __repr__() str#
Return repr(self).
- add_compiler_data(compiler_data: Iterable[Compiler]) list[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 overrides 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.
- __repr__() str#
Return repr(self).
- classmethod from_manifest(manifest: PackageManifest | Path | str, config_override: dict | None = None) Project#
Create an Ape project using only a manifest.
- Parameters:
manifest (PackageManifest | Path | str) – Either a manifest or a path to a manifest file.
config_override (dict | None) – 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:
- class ape.managers.project.SourceManager(root_path: Path, get_contracts_path: Callable, exclude_globs: set[str | Pattern] | None = None)#
A manager of a local-project’s source-paths. Access via
project.sources. Allows source-access from bothsource_idandpath. 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.- __repr__() str#
Return repr(self).
- get(source_id: str) Source | None#
Get a Source by source_id.
- Parameters:
source_id (str) – The source identifier.
- Returns:
Source | None
- get_source_paths(include_missing_compilers: bool = False) Iterator[Path]#
Get contract source paths.
- Parameters:
include_missing_compilers (bool) – Set to
Trueto include the source path even if its extension is not for a known compiler. Defaults toFalse.- Returns:
Iterator[Path]
- is_excluded(path: Path, exclude_missing_compilers: bool = True) bool#
Check if the given path is considered an “excluded” file based on the configured ignore-patterns.
- Parameters:
path (Path) – The path to check.
exclude_missing_compilers (bool) – Set to
Falseto not consider sources with missing compilers as “excluded”.
- Returns:
bool
- lookup(path_id: str | Path) Path | None#
Look-up a path by given a sub-path or a source ID.
- property paths: Iterator[Path]#
All contract source 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
Noneif 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_queryquery 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
QueryAPIinstances 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 executeengine_to_use (str | None) – Short-circuit selection logic using a specific engine. Defaults is set by performance-based selection logic.
- Raises:
When given an invalid or
inaccessible
engine_to_usevalue.- Returns:
Iterator[
BaseInterfaceModel]