ape.utils
ABI
- class ape.utils.abi.CalldataRepr(value)
Bases:
str,EnumControl the display of calldata in Ape.
- abridged = 'abridged'
Show the first and last 4-bytes of the calldata, enough to see the method ID.
- full = 'full'
Show the full calldata.
- class ape.utils.abi.Struct
Bases:
objectA class for contract return values using the struct data-structure.
- items() dict
Override
- class ape.utils.abi.StructParser(method_abi: ConstructorABI | MethodABI | EventABI)
Bases:
objectA 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 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 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.encode_topics(abi: EventABI, topics: dict[str, Any] | None = None) list[HexStr]
Encode the given topics using the given ABI. Useful for searching logs.
- Parameters:
abi (EventABI) – The event.
topics (dict[str, Any] } None) – Topic inputs to encode.
- Returns:
Encoded topics.
- Return type:
list[str]
- ape.utils.abi.is_array(abi_type: str | ABIType) bool
Returns
Trueif 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
Trueif the given output is a tuple where every item is named.
- ape.utils.abi.is_struct(outputs: ABIType | Sequence[ABIType]) bool
Returns
Trueif the given output is a struct.
- ape.utils.abi.returns_array(abi: MethodABI) bool
Returns
Trueif 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,ABCAbstract class that has manager access.
- class ape.utils.basemodel.BaseInterfaceModel
Bases:
BaseInterface,BaseModelAn abstract base-class with manager access on a pydantic base model.
- class ape.utils.basemodel.BaseModel
Bases:
BaseModelAn ape-pydantic BaseModel.
- model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False, cache_clear: Sequence[str] | None = None) Model
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- 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.DiskCacheableModel(*args)
Bases:
BaseModelA model with extra utilities for caching to disk.
- model_dump_file(path: Path | None = None, **kwargs)
Save this model to disk.
- Parameters:
path (Optional[Path]) – Optionally provide the path now if one wasn’t declared at init time. If given a directory, saves the file in that dir with the name of class with a .json suffix.
**kwargs – Extra kwargs to pass to
.model_dump_json().
- model_read_file(path: Path | None = None) dict
Get the file’s raw data. This is different from
model_dump()because it reads directly from the file without validation.
- class ape.utils.basemodel.ExtraAttributesMixin
Bases:
objectA 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:
BaseModelA 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:
objectA 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:
propertyInjected 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
dictusing 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
Noneif 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.ProviderAPIimplementations.- 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
Trueif 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
Trueif 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) –
Truethe variables in path are able to expand to show full path.must_exist (bool) –
Truewill 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.SpecifierSetif 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,
itemifitemis not a coroutine. If given multiple coroutines, returns the result fromasyncio.gather.- Return type:
(Any)
- class ape.utils.misc.singledispatchmethod(func)
Bases:
objectSingle-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
- class ape.utils.os.CacheDirectory(path: Path)
Bases:
objectA directory for caching data where each data item is named
<key>.jsonand is in the directory. You can access the items by their key like a dictionary. This type is used in Ape’s contract-caching for ContractTypes, ProxyInfoAPI, and other model types.
- class ape.utils.os.ChangeDirectory(original_path: Path, new_path: Path, chdir: Callable[[Path], None] | None = None, on_push: Callable[[Path], dict] | None = None, on_pop: Callable[[dict], None] | None = None)
Bases:
objectA context-manager for changing a directory. Initializing it will still change the directory, but you can optionally exit out of it to restore back to the original directory. Additionally, provides hooks to run when each of these events occur.
- ape.utils.os.clean_path(path: Path) str
Replace the home directory with key
$HOMEand 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
$nameor${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
.zipor.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_bandfile_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.suffixwhich 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
targetrelative 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
Truewhen 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:
Trueif 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:
objectA 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:
QueueA queue that can be joined, useful for multi-processing. Borrowed from the
py-gethlibrary.- 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-gethlibrary.
RPC
- class ape.utils.rpc.RPCHeaders(data=None, **kwargs)
Bases:
CaseInsensitiveDictA 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
ProviderNotConnectedErrorwarns 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.request_with_retry(func: Callable, min_retry_delay: int = 1000, retry_backoff_factor: int = 2, max_retry_delay: int = 30000, max_retries: int = 10, retry_jitter: int = 250, is_rate_limit: Callable[[Exception], bool] | None = None)
Make a request with 429/rate-limit retry logic.
- Parameters:
func (Callable) – The function to run with rate-limit handling logic.
min_retry_delay (int) – The amount of milliseconds to wait before retrying the request. Defaults to
1_000(one second).retry_backoff_factor (int) – The multiplier applied to the retry delay after each failed attempt. Defaults to
2.max_retry_delay (int) – The maximum length of the retry delay. Defaults to
30_000(30 seconds).max_retries (int) – The maximum number of retries. Defaults to
10.retry_jitter (int) – A random number of milliseconds up to this limit is added to each retry delay. Defaults to
250milliseconds.is_rate_limit (Callable[[Exception], bool] | None) – A custom handler for detecting rate-limits. Defaults to checking for a 429 status code on an HTTPError.
- 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:
tupleAn account key-pair generated from the test mnemonic. Set the test mnemonic in your
ape-config.yamlfile under thetestsection. Access your test accounts using thetest_accountsproperty.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:
objectColors 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.trace.prettify_dict(dictionary: dict, color: str | None = None, indent: int = 2, wrap_threshold: int = 50) str
Prettify a dictionary.
- Parameters:
dictionary (dict) – The dictionary to prettify.
color (Optional[str]) – The color to use for pretty printing.
- Returns:
str
- ape.utils.trace.prettify_function(method: str, calldata: Any, contract: str | None = None, returndata: Any | None = None, stylize: bool = False, is_create: bool = False, depth: int = 0) str
Prettify the given method call-string to a displayable, prettier string. Useful for displaying traces and decoded calls.
- Parameters:
method (str) – the method call-string to prettify.
calldata (Any) – Arguments to the method.
contract (str | None) – The contract name called.
returndata (Any) – Returned values from the method.
stylize (bool) –
Trueto use rich styling.is_create (bool) – Set to
Trueif creating a contract for better styling.depth (int) – The depth in the trace (or output) this function gets displayed.
- Returns:
str
- ape.utils.trace.prettify_inputs(inputs: Any, stylize: bool = False) str
Prettify the inputs to a function or event (or alike).
- Parameters:
inputs (Any) – the inputs to prettify.
stylize (bool) –
Trueto use rich styling.
- Returns:
str
- ape.utils.trace.prettify_list(ls: list | tuple, depth: int = 0, indent: int = 2, wrap_threshold: int = 50) str
Prettify a list of values for displaying.
- Parameters:
ls (list) – the list to prettify.
depth (int) – The depth the list appears in a tree structure (for traces).
- Returns:
str