class ape.utils.BaseInterface

Bases: ape.utils.basemodel.ManagerAccessMixin, abc.ABC

Abstract class that has manager access.

class ape.utils.BaseInterfaceModel

Bases: ape.utils.basemodel.BaseInterface, pydantic.main.BaseModel

An abstract base-class with manager access on a pydantic base model.

dict(*args, **kwargs) Dict

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

json(*args, **kwargs) str

Generate a JSON representation of the model, include and exclude arguments as per dict().

encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().

class ape.utils.CallTraceParser(receipt: ReceiptAPI, verbose: bool = False, wrap_threshold: int = 50, indent: int = 2, color_set: typing.Union[ape.utils.trace.TraceStyles, typing.Type[ape.utils.trace.TraceStyles]] = <class 'ape.utils.trace.TraceStyles'>)

Bases: object

A class for parsing a call trace, used in the show_trace() method, which uses the response from :method:`~ape.api.providers.ProviderAPI.get_call_trace` and the evm-trace Python package.

Usage example:

tree_factory = CallTraceParser(self, verbose=verbose)
call_tree = self.provider.get_call_tree(self.txn_hash)
root = tree_factory.parse_as_tree(call_tree)
parse_as_tree(call: evm_trace.base.CallTreeNode) rich.tree.Tree

Create rich.Tree containing the nodes in a call trace for display purposes.


call (CallTreeNode) – A node object from the evm-trace library.


A rich tree from the rich library.

Return type


class ape.utils.GeneratedDevAccount(address, private_key)

Bases: tuple

An account key-pair generated from the test mnemonic. Set the test mnemonic in your ape-config.yaml file under the test section. Access your test accounts using the test_accounts property.

Config example:

  mnemonic: test test test test test test test test test test test junk
  number_of_accounts: 10

Alias for field number 0


Alias for field number 1

class ape.utils.GithubClient

Bases: object

An HTTP client for the Github API.

property ape_org: github.Organization.Organization



The ApeWorX organization on Github (https

property available_plugins: Set[str]

The available ape plugins, found from looking at the ApeWorx Github organization.


The plugin names as 'ape_plugin_name' (module-like).

Return type


clone_repo(repo_path: str, target_path: pathlib.Path, branch: Optional[str] = None) pygit2.repository.Repository

Clone a repository from Github.

  • repo_path (str) – The path on Github to the repository, e.g. OpenZeppelin/openzeppelin-contracts.

  • target_path (Path) – The local path to store the repo.

  • branch (Optional[str]) – The branch to clone. Defaults to the default branch.



download_package(repo_path: str, version: str, target_path: pathlib.Path)

Download a package from Github. This is useful for managing project dependencies.

  • repo_path (str) – The path on Github to the repository, such as OpenZeppelin/openzeppelin-contracts.

  • version (str) – Number to specify update types to the downloaded package.

  • target_path (path) – A path in your local filesystem to save the downloaded package.

get_release(repo_path: str, version: str) github.GitRelease.GitRelease

Get a release from Github.

  • repo_path (str) – The path on Github to the repository, e.g. OpenZeppelin/openzeppelin-contracts.

  • version (str) – The version of the release to get. Pass in "latest" to get the latest release.



get_repo(repo_path: str) github.Repository.Repository

Get a repository from GitHub.


repo_path (str) – The path to the repository, such as OpenZeppelin/openzeppelin-contracts.



class ape.utils.JoinableQueue(maxsize=0)

Bases: queue.Queue

A queue that can be joined, useful for multi-processing. Borrowed from the py-geth library.


Blocks until all items in the Queue have been gotten and processed.

The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete.

When the count of unfinished tasks drops to zero, join() unblocks.

class ape.utils.Struct

Bases: object

A class for contract return values using the struct data-structure.

items() Dict


class ape.utils.StructParser(method_abi: ethpm_types.abi.MethodABI)

Bases: object

A utility class responsible for parsing structs out of values.

property default_name: str

The default struct return name for unnamed structs. This value is also used for named tuples where the tuple does not have a name (but each item in the tuple does have a name).

parse(output_types: List[ethpm_types.abi.ABIType], values: Union[List, Tuple]) Any

Parse a list of output types and values into structs. Values are only altered when they are a struct. This method also handles structs within structs as well as arrays of structs.

  • output_types (List[ABIType]) – The list of output ABI types.

  • values (Union[List, Tuple]) – A list of of output values.


The same input values only decoded into structs when applicable.

Return type


class ape.utils.TraceStyles

Bases: object

Colors to use when displaying a call trace. Each item in the class points to the part of the trace it colors.

CONTRACTS = '#ff8c00'

Contract type names.

DELEGATE = '#d75f00'

The part ‘(delegate)’ that appears before delegate calls.

GAS_COST = 'dim'

The gas used of the call.

INPUTS = 'bright_magenta'

Method arguments.

METHODS = 'bright_green'

Method names; not including arguments or return values.

OUTPUTS = 'bright_blue'

Method return values.

VALUE = '#00afd7'

The transaction value, when it’s > 0.

ape.utils.add_padding_to_strings(str_list: List[str], extra_spaces: int = 0, space_character: str = ' ') List[str]

Append spacing to each string in a list of strings such that they all have the same length.

  • str_list (List[str]) – The list of strings that need padding.

  • extra_spaces (int) – Optionally append extra spacing. Defaults to 0.

  • space_character (str) – The character to use in the padding. Defaults to " ".


A list of equal-length strings with padded spaces.

Return type


ape.utils.expand_environment_variables(contents: str) str

Replace substrings of the form $name or ${name} in the given path with the value of environment variable name.


contents (str) – A path-like object representing a file system. A path-like object is either a string or bytes object representing a path.


The given content with all environment variables replaced with their values.

Return type


ape.utils.extract_nested_value(root: Mapping, *args: str) Optional[Dict]

Dig through a nested dict using the given keys and return the last-found object.

Usage example:

>>> extract_nested_value({"foo": {"bar": {"test": "VALUE"}}}, "foo", "bar", "test")

root (dict) – Nested keys to form arguments.


The final value if it exists else None if the tree ends at any point.

Return type

dict, optional

ape.utils.gas_estimation_error_message(tx_error: Exception) str

Get an error message containing the given error and an explanation of how the gas estimation failed, as in ape.api.providers.ProviderAPI implementations.


tx_error (Exception) – The error that occurred when trying to estimate gas.


An error message explaining that the gas failed and that the transaction will likely revert.

Return type


ape.utils.generate_dev_accounts(mnemonic: str = 'test test test test test test test test test test test junk', number_of_accounts: int = 10, hd_path_format="m/44'/60'/0'/{}") List[ape.utils.testing.GeneratedDevAccount]

Create accounts from the given test mnemonic. Use these accounts (or the mnemonic) in chain-genesis for testing providers.

  • mnemonic (str) – mnemonic phrase or seed words.

  • number_of_accounts (int) – Number of accounts. Defaults to 10.

  • hd_path_format (str) – Hard Wallets/HD Keys derivation path format. Defaults to "m/44'/60'/0'/{}".


List of development accounts.

Return type


ape.utils.get_all_files_in_directory(path: pathlib.Path, pattern: Optional[Union[Pattern, str]] = None) List[pathlib.Path]

Returns all the files in a directory structure.

For example, given a directory structure like:

dir_a: dir_b, file_a, file_b
dir_b: file_c

and you provide the path to dir_a, it will return a list containing the paths to file_a, file_b and file_c.

  • path (pathlib.Path) – A directory containing files of interest.

  • pattern (Optional[Union[Pattern, str]]) – Optionally provide a regex pattern to match.


A list of files in the given directory.

Return type


ape.utils.get_package_version(obj: Any) str

Get the version of a single package.


obj – object to search inside for __version__.


version string.

Return type


ape.utils.get_relative_path(target: pathlib.Path, anchor: pathlib.Path) pathlib.Path

Compute the relative path of target relative to anchor, which may or may not share a common ancestor. NOTE: Both paths must be absolute.

  • target (pathlib.Path) – The path we are interested in.

  • anchor (pathlib.Path) – The path we are starting from.


The new path to the target path from the anchor path.

Return type


class ape.utils.injected_before_use(fget=None, fset=None, fdel=None, doc=None)

Bases: property

Injected properties are injected class variables that must be set before use NOTE: do not appear in a Pydantic model’s set of properties.

ape.utils.is_array(abi_type: Union[str, ethpm_types.abi.ABIType]) bool

Returns True if the given type is a probably an array.


abi_type (Union[str, ABIType]) – The type to check.



ape.utils.is_named_tuple(outputs: List[ethpm_types.abi.ABIType], output_values: Union[List, Tuple]) bool

Returns True if the given output is a tuple where every item is named.

ape.utils.is_struct(outputs: Union[ethpm_types.abi.ABIType, List[ethpm_types.abi.ABIType]]) bool

Returns True if the given output is a struct.

ape.utils.load_config(path: pathlib.Path, expand_envars=True, must_exist=False) Dict

Load a configuration file into memory. A file at the given path must exist or else it will throw OSError. The configuration file must be a .json or .yaml or else it will throw TypeError.

  • path (str) – path to filesystem to find.

  • expand_envars (bool) – True the variables in path are able to expand to show full path.

  • must_exist (bool) – True will be set if the configuration file exist and is able to be load.


Configured settings parsed from a config file.

Return type

Dict (dict)


Decorator for raising helpful not implemented error.

ape.utils.returns_array(abi: ethpm_types.abi.MethodABI) bool

Returns True if the given method ABI likely returns an array.


abi (MethodABI) – An ABI method.



class ape.utils.singledispatchmethod(func)

Bases: object

Single-dispatch generic method descriptor.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

register(cls, func) func

Registers a new implementation for the given cls on a generic_method.

ape.utils.spawn(target, *args, **kwargs)

Spawn a new daemon thread. Borrowed from the py-geth library.

ape.utils.stream_response(download_url: str, progress_bar_description: str = 'Downloading') bytes

Download HTTP content by streaming and returning the bytes. Progress bar will be displayed in the CLI.

  • download_url (str) – String to get files to download.

  • progress_bar_description (str) – Downloading word.


Content in bytes to show the progress.

Return type


class ape.utils.use_temp_sys_path(path: pathlib.Path)

Bases: object

A context manager to manage injecting and removing paths from a user’s sys paths without permanently modifying it.