ape.utils
ABI
- class ape.utils.abi.Struct
Bases:
object
A class for contract return values using the struct data-structure.
- items() dict
Override
- class ape.utils.abi.StructParser(method_abi: ConstructorABI | MethodABI | EventABI)
Bases:
object
A utility class responsible for parsing structs out of values.
- decode_output(values: 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:
values (Union[list, tuple]) – A list of of output values.
- Returns:
The same input values only decoded into structs when applicable.
- Return type:
Any
- 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).
- encode_input(values: list | tuple | dict) Any
Convert dicts and other objects to struct inputs.
- Parameters:
values (Union[list, tuple]) – A list of of input values.
- Returns:
The same input values only decoded into structs when applicable.
- Return type:
Any
- ape.utils.abi.create_struct(name: str, types: Sequence[ABIType], output_values: Sequence) Any
Create a dataclass representing an ABI struct that can be used as inputs or outputs. The struct properties can be accessed via
.
notation, as keys in a dictionary, or numeric tuple access.NOTE: This method assumes you already know the values to give to the struct properties.
- Parameters:
name (str) – The name of the struct.
(list[ABIType] (types) – The types of values in the struct.
output_values (list[Any]) – The struct property values.
- Returns:
The struct dataclass.
- Return type:
Any
- ape.utils.abi.is_array(abi_type: str | 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.abi.is_named_tuple(outputs: Sequence[ABIType], output_values: Sequence) bool
Returns
True
if the given output is a tuple where every item is named.
- ape.utils.abi.is_struct(outputs: ABIType | Sequence[ABIType]) bool
Returns
True
if the given output is a struct.
- ape.utils.abi.returns_array(abi: MethodABI) bool
Returns
True
if the given method ABI likely returns an array.- Parameters:
abi (MethodABI) – An ABI method.
- Returns:
bool
Basemodel
TODO: In 0.9, move this module to ape.types.
- class ape.utils.basemodel.BaseInterface
Bases:
ManagerAccessMixin
,ABC
Abstract class that has manager access.
- class ape.utils.basemodel.BaseInterfaceModel
Bases:
BaseInterface
,BaseModel
An abstract base-class with manager access on a pydantic base model.
- class ape.utils.basemodel.BaseModel
Bases:
BaseModel
An ape-pydantic BaseModel.
- model_copy(*, update: dict[str, Any] | None = None, deep: bool = False, cache_clear: Sequence[str] | None = None) Model
Usage docs: https://docs.pydantic.dev/2.9/concepts/serialization/#model_copy
Returns a copy of the model.
- Parameters:
update – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.
deep – Set to True to make a deep copy of the model.
- Returns:
New model instance.
- class ape.utils.basemodel.ExtraAttributesMixin
Bases:
object
A mixin to use on models that provide
ExtraModelAttributes
. NOTE: Must come _before_ your base-model class in subclass tuple to function.
- class ape.utils.basemodel.ExtraModelAttributes(*, name: str, attributes: Any | Callable[[], Any] | Callable[[str], Any], include_getattr: bool = True, include_getitem: bool = False, additional_error_message: str | None = None)
Bases:
BaseModel
A class for defining extra model attributes.
- additional_error_message: str | None
An additional error message to include at the end of the normal IndexError message.
- attributes: Any | Callable[[], Any] | Callable[[str], Any]
The attributes. The following types are supported:
A model or dictionary to lookup attributes.
A callable with no arguments, for lazily evaluating a model or dictionary for lookup.
A callable with a single argument that is the attribute name. This style of lookup cannot be used for optionals.
- get(name: str) Any | None
Get an attribute.
- Parameters:
name (str) – The name of the attribute.
- Returns:
The attribute if it exists, else
None
.- Return type:
Optional[Any]
- include_getattr: bool
Whether to use these in
__getattr__
.
- include_getitem: bool
Whether to use these in
__getitem__
.
- name: str
The name of the attributes. This is important in instances such as when an attribute is missing, we can show a more accurate exception message.
- class ape.utils.basemodel.ManagerAccessMixin
Bases:
object
A mixin for accessing Ape’s manager at the class level.
Usage example:
from ape.utils import ManagerAccessMixin
- class MyClass(ManagerAccessMixin):
- def my_function(self):
accounts = self.account_manager # And so on!
- Project
alias of
ProjectManager
- class ape.utils.basemodel.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.
- class ape.utils.basemodel.manager_access(fn)
Bases:
property
Miscellaneous
- ape.utils.misc.extract_nested_value(root: Mapping, *args: str) dict | None
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.misc.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.misc.get_current_timestamp_ms() int
Get the current UNIX timestamp in milliseconds.
- Returns:
int
- ape.utils.misc.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.misc.is_evm_precompile(address: str) bool
Returns
True
if the given address string is a known Ethereum pre-compile address.- Parameters:
address (str)
- Returns:
bool
- ape.utils.misc.is_zero_hex(address: str) bool
Returns
True
if the hex str is only zero. NOTE: Empty hexes like"0x"
are considered zero.- Parameters:
address (str) – The address to check.
- Returns:
bool
- ape.utils.misc.load_config(path: 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 throwTypeError
.- 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
- ape.utils.misc.log_instead_of_fail(default: Any | None = None)
A decorator for logging errors instead of raising. This is useful for methods like __repr__ which shouldn’t fail.
- ape.utils.misc.pragma_str_to_specifier_set(pragma_str: str) SpecifierSet | None
Convert the given pragma str to a
packaging.version.SpecifierSet
if possible.- Parameters:
pragma_str (str) – The str to convert.
- Returns:
Optional[packaging.version.SpecifierSet]
- ape.utils.misc.raises_not_implemented(fn)
Decorator for raising helpful not implemented error.
- ape.utils.misc.run_until_complete(*item: Any) Any
Completes the given coroutine and returns its value.
- Parameters:
*item (Any) – A coroutine or any return value from an async method. If not given a coroutine, returns the given item. Provide multiple coroutines to run tasks in parallel.
- Returns:
The value that results in awaiting the coroutine. Else,
item
ifitem
is not a coroutine. If given multiple coroutines, returns the result fromasyncio.gather
.- Return type:
(Any)
- class ape.utils.misc.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.misc.to_int(value: Any) int
Convert the given value, such as hex-strs or hex-bytes, to an integer.
OS
- ape.utils.os.clean_path(path: Path) str
Replace the home directory with key
$HOME
and return the path as a str. This is used for outputting paths with less doxxing.- Parameters:
path (Path) – The path to sanitize.
- Returns:
A sanitized path-str.
- Return type:
str
- ape.utils.os.create_tempdir(name: str | None = None) Iterator[Path]
Create a temporary directory. Differs from
TemporaryDirectory()
context-call alone because it automatically resolves the path.- Parameters:
name (Optional[str]) – Optional provide a name of the directory. Else, defaults to root of
tempfile.TemporaryDirectory()
(resolved).- Returns:
Context managing the temporary directory.
- Return type:
Iterator[Path]
- ape.utils.os.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.os.extract_archive(archive_file: Path, destination: Path | None = None)
Extract an archive file. Supports
.zip
or.tar.gz
.
- ape.utils.os.get_all_files_in_directory(path: Path, pattern: Pattern | str | None = None, max_files: int | None = None) list[Path]
Returns all the files in a directory structure (recursive).
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 tofile_a
,file_b
andfile_c
.- Parameters:
path (pathlib.Path) – A directory containing files of interest.
pattern (Optional[Union[Pattern, str]]) – Optionally provide a regex pattern to match.
max_files (Optional[int]) – Optionally set a max file count. This is useful because huge file structures will be very slow.
- Returns:
A list of files in the given directory.
- Return type:
list[pathlib.Path]
- ape.utils.os.get_full_extension(path: Path | str) str
For a path like
Path("Contract.t.sol")
, returns.t.sol
, unlike the regular Path property.suffix
which returns.sol
.- Parameters:
path (Path | str) – The path with an extension.
- Returns:
The full suffix
- Return type:
str
- ape.utils.os.get_package_path(package_name: str) Path
Get the path to a package from site-packages.
- Parameters:
package_name (str) – The name of the package.
- Returns:
Path
- ape.utils.os.get_relative_path(target: Path, anchor: Path) Path
Compute the relative path of
target
relative toanchor
, which may or may not share a common ancestor.NOTE ON PERFORMANCE: Both paths must be absolute to use this method. If you know both methods are absolute, this method is a performance boost. If you have to first call .absolute() on the paths, use target.relative_to(anchor) instead; as it will be faster in that case.
- 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
- ape.utils.os.in_tempdir(path: Path) bool
Returns
True
when the given path is in a temporary directory.- Parameters:
path (Path) – The path to check.
- Returns:
bool
- ape.utils.os.is_relative_to(path: Path, target: Path) bool
Search a path and determine its relevancy.
- Parameters:
path (str) – Path represents a filesystem to find.
target (str) – Path represents a filesystem to match.
- Returns:
True
if the path is relative to the target path orFalse
.- Return type:
bool
- ape.utils.os.path_match(path: str | Path, *exclusions: str) bool
A better glob-matching function. For example:
>>> from pathlib import Path >>> p = Path("test/to/.build/me/2/file.json") >>> p.match("**/.build/**") False >>> from ape.utils.os import path_match >>> path_match(p, "**/.build/**") True
- ape.utils.os.run_in_tempdir(fn: Callable[[Path], Any], name: str | None = None)
Run the given function in a temporary directory with its path resolved.
- Parameters:
fn (Callable) – A function that takes a path. It gets called with the resolved path to the temporary directory.
name (Optional[str]) – Optionally name the temporary directory.
- Returns:
The result of the function call.
- Return type:
Any
- class ape.utils.os.use_temp_sys_path(path: Path, exclude: list[Path] | None = None)
Bases:
object
A context manager to manage injecting and removing paths from a user’s sys paths without permanently modifying it.
Process
- class ape.utils.process.JoinableQueue(maxsize=0)
Bases:
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.
- ape.utils.process.spawn(target, *args, **kwargs)
Spawn a new daemon thread. Borrowed from the
py-geth
library.
RPC
- class ape.utils.rpc.RPCHeaders(data=None, **kwargs)
Bases:
CaseInsensitiveDict
A dict-like data-structure for HTTP-headers. It is case-insensitive and appends user-agent strings rather than overrides.
- ape.utils.rpc.allow_disconnected(fn: Callable)
A decorator that instead of raising
ProviderNotConnectedError
warns and returnsNone
.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.rpc.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
Testing
- class ape.utils.testing.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 thetest
section. Access your test accounts using thetest_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
- ape.utils.testing.generate_dev_accounts(mnemonic: str = 'test test test test test test test test test test test junk', number_of_accounts: int = 10, hd_path: str = "m/44'/60'/0'/0", start_index: int = 0) list[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 (str) – Hard Wallets/HD Keys derivation path format. Defaults to
"m/44'/60'/0'/0"
.start_index (int) – The index to start from in the path. Defaults to 0.
- Returns:
List of development accounts.
- Return type:
list[
GeneratedDevAccount
]
Trace
- class ape.utils.trace.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.