ape.utils

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(sender: typing.Optional[typing.Union[ReceiptAPI, AddressType]] = None, transaction_hash: typing.Optional[str] = None, 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: ape.utils.basemodel.ManagerAccessMixin

A class for parsing a call trace, used in the show_trace() method, which uses the response from get_call_trace() and the evm-trace Python package.

Usage example:

parser = CallTraceParser(sender=sender, transaction_hash=txn_hash, verbose=verbose)
call_tree = self.provider.get_call_tree(txn_hash)
root = parser.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.

Parameters

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

Returns

A rich tree from the rich library.

Return type

rich.Tree

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:

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

Alias for field number 0

private_key

Alias for field number 1

class ape.utils.GithubClient

Bases: object

An HTTP client for the Github API.

property ape_org: github.Organization.Organization

//github.com/ApeWorX).

Type

The ApeWorX organization on Github (https

property available_plugins: Set[str]

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

Returns

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

Return type

Set[str]

clone_repo(repo_path: str, target_path: pathlib.Path, branch: Optional[str] = None, scheme: str = 'http')

Clone a repository from Github.

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

  • scheme (str) – The git scheme to use when cloning. Defaults to ssh.

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

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

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

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

Returns

github.GitRelease.GitRelease

get_repo(repo_path: str) github.Repository.Repository

Get a repository from GitHub.

Parameters

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

Returns

github.Repository.Repository

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.

join(timeout=None)

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

Override

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.

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

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

Returns

The same input values only decoded into structs when applicable.

Return type

Any

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.

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

Returns

A list of equal-length strings with padded spaces.

Return type

List[str]

ape.utils.allow_disconnected(fn: Callable)

A decorator that instead of raising ProviderNotConnectedError warns and returns None.

Usage example:

from typing import Optional
from ape.types import SnapshotID
from ape.utils import return_none_when_disconnected

@allow_disconnected
def try_snapshot(self) -> Optional[SnapshotID]:
    return self.chain.snapshot()
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.

Parameters

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

Returns

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

Return type

str

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")
'VALUE'
Parameters

root (dict) – Nested keys to form arguments.

Returns

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.

Parameters

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

Returns

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

Return type

str

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.

Parameters
  • 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'/{}".

Returns

List of development accounts.

Return type

List[GeneratedDevAccount]

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.

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

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

Returns

A list of files in the given directory.

Return type

List[pathlib.Path]

ape.utils.get_package_version(obj: Any) str

Get the version of a single package.

Parameters

obj – object to search inside for __version__.

Returns

version string.

Return type

str

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.

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

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

Returns

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

Return type

pathlib.Path

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.

Parameters

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

Returns

bool

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.

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

Returns

Configured settings parsed from a config file.

Return type

Dict (dict)

ape.utils.parse_type(type: Dict[str, Any]) Union[str, Tuple, List]

Parses ABIType.dict() into Python types. Deprecated: Use EcosystemAPI implemented methods.

ape.utils.raises_not_implemented(fn)

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.

Parameters

abi (MethodABI) – An ABI method.

Returns

bool

ape.utils.run_until_complete(item: Any) Any

Completes the given coroutine and returns its value.

Parameters

item (Any) – A return value from a potentially async method.

Returns

The value that results in awaiting the coroutine.

Else, item if item is not a coroutine.

Return type

(Any)

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.

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

  • progress_bar_description (str) – Downloading word.

Returns

Content in bytes to show the progress.

Return type

bytes

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.