code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get(self, name: str) -> Optional[Any]:
"""
Get an attribute.
Args:
name (str): The name of the attribute.
Returns:
Optional[Any]: The attribute if it exists, else ``None``.
"""
res = self._get(name)
if res is not None:
re... |
Get an attribute.
Args:
name (str): The name of the attribute.
Returns:
Optional[Any]: The attribute if it exists, else ``None``.
| get | python | ApeWorX/ape | src/ape/utils/basemodel.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py | Apache-2.0 |
def __getattr__(self, name: str) -> Any:
"""
An overridden ``__getattr__`` implementation that takes into
account :meth:`~ape.utils.basemodel.ExtraAttributesMixin.__ape_extra_attributes__`.
"""
_assert_not_ipython_check(name)
private_attrs = (self.__pydantic_private__ or ... |
An overridden ``__getattr__`` implementation that takes into
account :meth:`~ape.utils.basemodel.ExtraAttributesMixin.__ape_extra_attributes__`.
| __getattr__ | python | ApeWorX/ape | src/ape/utils/basemodel.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py | Apache-2.0 |
def __dir__(self) -> list[str]:
"""
**NOTE**: Should integrate options in IPython tab-completion.
https://ipython.readthedocs.io/en/stable/config/integrating.html
"""
# Filter out protected/private members
return [member for member in super().__dir__() if not member.start... |
**NOTE**: Should integrate options in IPython tab-completion.
https://ipython.readthedocs.io/en/stable/config/integrating.html
| __dir__ | python | ApeWorX/ape | src/ape/utils/basemodel.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py | Apache-2.0 |
def _model_read_file(cls, path: Path) -> dict:
"""
Get the file's raw data. This is different from ``model_dump()`` because it
reads directly from the file without validation.
"""
if json_str := path.read_text(encoding="utf8") if path.is_file() else "":
return json.lo... |
Get the file's raw data. This is different from ``model_dump()`` because it
reads directly from the file without validation.
| _model_read_file | python | ApeWorX/ape | src/ape/utils/basemodel.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py | Apache-2.0 |
def model_dump_file(self, path: Optional[Path] = None, **kwargs):
"""
Save this model to disk.
Args:
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... |
Save this model to disk.
Args:
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 kwar... | model_dump_file | python | ApeWorX/ape | src/ape/utils/basemodel.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py | Apache-2.0 |
def model_validate_file(cls, path: Path, **kwargs):
"""
Validate a file.
Args:
path (Optional[Path]): Optionally provide the path now
if one wasn't declared at init time.
**kwargs: Extra kwargs to pass to ``.model_validate_json()``.
"""
data... |
Validate a file.
Args:
path (Optional[Path]): Optionally provide the path now
if one wasn't declared at init time.
**kwargs: Extra kwargs to pass to ``.model_validate_json()``.
| model_validate_file | python | ApeWorX/ape | src/ape/utils/basemodel.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/basemodel.py | Apache-2.0 |
def _get_distributions(pkg_name: Optional[str] = None) -> list:
"""
Get a mapping of top-level packages to their distributions.
"""
distros = []
all_distros = distributions()
for dist in all_distros:
package_names = (dist.read_text("top_level.txt") or "").split()
for name in pac... |
Get a mapping of top-level packages to their distributions.
| _get_distributions | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def pragma_str_to_specifier_set(pragma_str: str) -> Optional[SpecifierSet]:
"""
Convert the given pragma str to a ``packaging.version.SpecifierSet``
if possible.
Args:
pragma_str (str): The str to convert.
Returns:
``Optional[packaging.version.SpecifierSet]``
"""
pragma_pa... |
Convert the given pragma str to a ``packaging.version.SpecifierSet``
if possible.
Args:
pragma_str (str): The str to convert.
Returns:
``Optional[packaging.version.SpecifierSet]``
| pragma_str_to_specifier_set | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def get_package_version(obj: Any) -> str:
"""
Get the version of a single package.
Args:
obj: object to search inside for ``__version__``.
Returns:
str: version string.
"""
# If value is already cached/static
if hasattr(obj, "__version__"):
return obj.__version__
... |
Get the version of a single package.
Args:
obj: object to search inside for ``__version__``.
Returns:
str: version string.
| get_package_version | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def 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 throw ``TypeError``.
Args:
path (s... |
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``.
Args:
path (str): path to filesystem to find.
expand_envars (bool): ``True`` the variab... | load_config | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def 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 :class:`ape.api.providers.ProviderAPI` implementations.
Args:
tx_error (Exception): The error that occurred when trying to... |
Get an error message containing the given error and an explanation of how the
gas estimation failed, as in :class:`ape.api.providers.ProviderAPI` implementations.
Args:
tx_error (Exception): The error that occurred when trying to estimate gas.
Returns:
str: An error message explaining... | gas_estimation_error_message | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def 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'
Args:... |
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'
Args:
root (dict): Nested keys to form arguments.
Returns:
dic... | extract_nested_value | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def 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.
Args:
str_list (list[str]): The list of strings that need padding.
... |
Append spacing to each string in a list of strings such that
they all have the same length.
Args:
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 ... | add_padding_to_strings | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def raises_not_implemented(fn):
"""
Decorator for raising helpful not implemented error.
"""
def inner(*args, **kwargs):
raise _create_raises_not_implemented_error(fn)
# This is necessary for doc strings to show up with sphinx
inner.__doc__ = fn.__doc__
return inner |
Decorator for raising helpful not implemented error.
| raises_not_implemented | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def to_int(value: Any) -> int:
"""
Convert the given value, such as hex-strs or hex-bytes, to an integer.
"""
if isinstance(value, int):
return value
elif isinstance(value, str):
return int(value, 16) if is_0x_prefixed(value) else int(value)
elif isinstance(value, bytes):
... |
Convert the given value, such as hex-strs or hex-bytes, to an integer.
| to_int | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def run_until_complete(*item: Any) -> Any:
"""
Completes the given coroutine and returns its value.
Args:
*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.
... |
Completes the given coroutine and returns its value.
Args:
*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:
(Any): The value that results ... | run_until_complete | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def is_evm_precompile(address: str) -> bool:
"""
Returns ``True`` if the given address string is a known
Ethereum pre-compile address.
Args:
address (str):
Returns:
bool
"""
try:
address = address.replace("0x", "")
return 0 < sum(int(x) for x in address) < 1... |
Returns ``True`` if the given address string is a known
Ethereum pre-compile address.
Args:
address (str):
Returns:
bool
| is_evm_precompile | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def is_zero_hex(address: str) -> bool:
"""
Returns ``True`` if the hex str is only zero.
**NOTE**: Empty hexes like ``"0x"`` are considered zero.
Args:
address (str): The address to check.
Returns:
bool
"""
try:
if addr := address.replace("0x", ""):
ret... |
Returns ``True`` if the hex str is only zero.
**NOTE**: Empty hexes like ``"0x"`` are considered zero.
Args:
address (str): The address to check.
Returns:
bool
| is_zero_hex | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def _dict_overlay(mapping: dict[str, Any], overlay: dict[str, Any], depth: int = 0):
"""Overlay given overlay structure on a dict"""
for key, value in overlay.items():
if isinstance(value, dict):
if key not in mapping:
mapping[key] = dict()
_dict_overlay(mapping[k... | Overlay given overlay structure on a dict | _dict_overlay | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def log_instead_of_fail(default: Optional[Any] = None):
"""
A decorator for logging errors instead of raising.
This is useful for methods like __repr__ which shouldn't fail.
"""
def wrapper(fn):
@functools.wraps(fn)
def wrapped(*args, **kwargs):
try:
if a... |
A decorator for logging errors instead of raising.
This is useful for methods like __repr__ which shouldn't fail.
| log_instead_of_fail | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def as_our_module(cls_or_def: _MOD_T, doc_str: Optional[str] = None) -> _MOD_T:
"""
Ape sometimes reclaims definitions from other packages, such as
class:`~ape.types.signatures.SignableMessage`). When doing so, the doc str
may be different than ours, and the module may still refer to
the original pa... |
Ape sometimes reclaims definitions from other packages, such as
class:`~ape.types.signatures.SignableMessage`). When doing so, the doc str
may be different than ours, and the module may still refer to
the original package. This method steals the given class as-if
it were ours. Logic borrowed from s... | as_our_module | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def derive_public_key(private_key: bytes) -> HexBytes:
"""
Derive the public key for the given private key.
Args:
private_key (bytes): The private key.
Returns:
HexBytes: The public key.
"""
pk = keys.PrivateKey(private_key)
public_key = f"{pk.public_key}"[2:]
return He... |
Derive the public key for the given private key.
Args:
private_key (bytes): The private key.
Returns:
HexBytes: The public key.
| derive_public_key | python | ApeWorX/ape | src/ape/utils/misc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/misc.py | Apache-2.0 |
def get_relative_path(target: Path, anchor: Path) -> Path:
"""
Compute the relative path of ``target`` relative to ``anchor``,
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 metho... |
Compute the relative path of ``target`` relative to ``anchor``,
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... | get_relative_path | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def get_all_files_in_directory(
path: Path, pattern: Optional[Union[Pattern, str]] = None, max_files: Optional[int] = 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... |
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 to ``file_a``, ``file_b`` and ``file_c``.
Args... | get_all_files_in_directory | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def get_full_extension(path: Union[Path, str]) -> str:
"""
For a path like ``Path("Contract.t.sol")``,
returns ``.t.sol``, unlike the regular Path
property ``.suffix`` which returns ``.sol``.
Args:
path (Path | str): The path with an extension.
Returns:
str: The full suffix
... |
For a path like ``Path("Contract.t.sol")``,
returns ``.t.sol``, unlike the regular Path
property ``.suffix`` which returns ``.sol``.
Args:
path (Path | str): The path with an extension.
Returns:
str: The full suffix
| get_full_extension | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def create_tempdir(name: Optional[str] = None) -> Iterator[Path]:
"""
Create a temporary directory. Differs from ``TemporaryDirectory()``
context-call alone because it automatically resolves the path.
Args:
name (Optional[str]): Optional provide a name of the directory.
Else, default... |
Create a temporary directory. Differs from ``TemporaryDirectory()``
context-call alone because it automatically resolves the path.
Args:
name (Optional[str]): Optional provide a name of the directory.
Else, defaults to root of ``tempfile.TemporaryDirectory()``
(resolved).
... | create_tempdir | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def run_in_tempdir(
fn: Callable[[Path], Any],
name: Optional[str] = None,
):
"""
Run the given function in a temporary directory with its path
resolved.
Args:
fn (Callable): A function that takes a path. It gets called
with the resolved path to the temporary directory.
... |
Run the given function in a temporary directory with its path
resolved.
Args:
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:
Any: T... | run_in_tempdir | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def in_tempdir(path: Path) -> bool:
"""
Returns ``True`` when the given path is in a temporary directory.
Args:
path (Path): The path to check.
Returns:
bool
"""
temp_dir = os.path.normpath(f"{Path(gettempdir()).resolve()}")
normalized_path = os.path.normpath(path)
retu... |
Returns ``True`` when the given path is in a temporary directory.
Args:
path (Path): The path to check.
Returns:
bool
| in_tempdir | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def path_match(path: Union[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, "**/... |
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
| path_match | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def 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.
Args:
path (Path): The path to sanitize.
Returns:
str: A sanitized path-str.
"""
home = Path.home()
... |
Replace the home directory with key ``$HOME`` and return
the path as a str. This is used for outputting paths
with less doxxing.
Args:
path (Path): The path to sanitize.
Returns:
str: A sanitized path-str.
| clean_path | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def get_package_path(package_name: str) -> Path:
"""
Get the path to a package from site-packages.
Args:
package_name (str): The name of the package.
Returns:
Path
"""
try:
dist = distribution(package_name)
except PackageNotFoundError as err:
raise ValueErro... |
Get the path to a package from site-packages.
Args:
package_name (str): The name of the package.
Returns:
Path
| get_package_path | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def extract_archive(archive_file: Path, destination: Optional[Path] = None):
"""
Extract an archive file. Supports ``.zip`` or ``.tar.gz``.
Args:
archive_file (Path): The file-path to the archive.
destination (Optional[Path]): Optionally provide a destination.
Defaults to the pare... |
Extract an archive file. Supports ``.zip`` or ``.tar.gz``.
Args:
archive_file (Path): The file-path to the archive.
destination (Optional[Path]): Optionally provide a destination.
Defaults to the parent directory of the archive file.
| extract_archive | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def within_directory(directory: Path):
"""
A context-manager for changing the cwd to the given path.
Args:
directory (Path): The directory to change.
"""
here = Path.cwd()
if directory != here:
os.chdir(directory)
try:
yield
finally:
if Path.cwd() != here... |
A context-manager for changing the cwd to the given path.
Args:
directory (Path): The directory to change.
| within_directory | python | ApeWorX/ape | src/ape/utils/os.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/os.py | Apache-2.0 |
def spawn(target, *args, **kwargs):
"""
Spawn a new daemon thread. Borrowed from the ``py-geth`` library.
"""
thread = threading.Thread(
target=target,
args=args,
kwargs=kwargs,
)
thread.daemon = True
thread.start()
return thread |
Spawn a new daemon thread. Borrowed from the ``py-geth`` library.
| spawn | python | ApeWorX/ape | src/ape/utils/process.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/process.py | Apache-2.0 |
def allow_disconnected(fn: Callable):
"""
A decorator that instead of raising :class:`~ape.exceptions.ProviderNotConnectedError`
warns and returns ``None``.
Usage example::
from typing import Optional
from ape.types import SnapshotID
from ape.utils import return_none_when_disco... |
A decorator that instead of raising :class:`~ape.exceptions.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
... | allow_disconnected | python | ApeWorX/ape | src/ape/utils/rpc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/rpc.py | Apache-2.0 |
def 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.
Args:
download_url (str): String to get files to download.
progress_bar_description ... |
Download HTTP content by streaming and returning the bytes.
Progress bar will be displayed in the CLI.
Args:
download_url (str): String to get files to download.
progress_bar_description (str): Downloading word.
Returns:
bytes: Content in bytes to show the progress.
| stream_response | python | ApeWorX/ape | src/ape/utils/rpc.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/rpc.py | Apache-2.0 |
def generate_dev_accounts(
mnemonic: str = DEFAULT_TEST_MNEMONIC,
number_of_accounts: int = DEFAULT_NUMBER_OF_TEST_ACCOUNTS,
hd_path: str = DEFAULT_TEST_HD_PATH,
start_index: int = 0,
) -> list[GeneratedDevAccount]:
"""
Create accounts from the given test mnemonic.
Use these accounts (or the... |
Create accounts from the given test mnemonic.
Use these accounts (or the mnemonic) in chain-genesis
for testing providers.
Args:
mnemonic (str): mnemonic phrase or seed words.
number_of_accounts (int): Number of accounts. Defaults to ``10``.
hd_path(str): Hard Wallets/HD Keys d... | generate_dev_accounts | python | ApeWorX/ape | src/ape/utils/testing.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/testing.py | Apache-2.0 |
def _validate_account_passphrase(passphrase: str) -> str:
"""Make sure given passphrase is valid for account encryption"""
if not passphrase or not isinstance(passphrase, str):
raise AccountsError("Account file encryption passphrase must be provided.")
if len(passphrase) < MIN_PASSPHRASE_LENGTH:
... | Make sure given passphrase is valid for account encryption | _validate_account_passphrase | python | ApeWorX/ape | src/ape/utils/validators.py | https://github.com/ApeWorX/ape/blob/master/src/ape/utils/validators.py | Apache-2.0 |
def set_autosign(self, enabled: bool, passphrase: Optional[str] = None):
"""
Allow this account to automatically sign messages and transactions.
Args:
enabled (bool): ``True`` to enable, ``False`` to disable.
passphrase (Optional[str]): Optionally provide the passphrase.... |
Allow this account to automatically sign messages and transactions.
Args:
enabled (bool): ``True`` to enable, ``False`` to disable.
passphrase (Optional[str]): Optionally provide the passphrase.
If not provided, you will be prompted to enter it.
| set_autosign | python | ApeWorX/ape | src/ape_accounts/accounts.py | https://github.com/ApeWorX/ape/blob/master/src/ape_accounts/accounts.py | Apache-2.0 |
def _write_and_return_account(
alias: str, passphrase: str, account: "LocalAccount"
) -> KeyfileAccount:
"""Write an account to disk and return an Ape KeyfileAccount"""
path = ManagerAccessMixin.account_manager.containers["accounts"].data_folder.joinpath(
f"{alias}.json"
)
path.write_text(js... | Write an account to disk and return an Ape KeyfileAccount | _write_and_return_account | python | ApeWorX/ape | src/ape_accounts/accounts.py | https://github.com/ApeWorX/ape/blob/master/src/ape_accounts/accounts.py | Apache-2.0 |
def generate_account(
alias: str, passphrase: str, hd_path: str = ETHEREUM_DEFAULT_PATH, word_count: int = 12
) -> tuple[KeyfileAccount, str]:
"""
Generate a new account.
Args:
alias (str): The alias name of the account.
passphrase (str): Passphrase used to encrypt the account storage f... |
Generate a new account.
Args:
alias (str): The alias name of the account.
passphrase (str): Passphrase used to encrypt the account storage file.
hd_path (str): The hierarchical deterministic path to use when generating the account.
Defaults to `m/44'/60'/0'/0/0`.
wo... | generate_account | python | ApeWorX/ape | src/ape_accounts/accounts.py | https://github.com/ApeWorX/ape/blob/master/src/ape_accounts/accounts.py | Apache-2.0 |
def import_account_from_mnemonic(
alias: str, passphrase: str, mnemonic: str, hd_path: str = ETHEREUM_DEFAULT_PATH
) -> KeyfileAccount:
"""
Import a new account from a mnemonic seed phrase.
Args:
alias (str): The alias name of the account.
passphrase (str): Passphrase used to encrypt th... |
Import a new account from a mnemonic seed phrase.
Args:
alias (str): The alias name of the account.
passphrase (str): Passphrase used to encrypt the account storage file.
mnemonic (str): List of space-separated words representing the mnemonic seed phrase.
hd_path (str): The hie... | import_account_from_mnemonic | python | ApeWorX/ape | src/ape_accounts/accounts.py | https://github.com/ApeWorX/ape/blob/master/src/ape_accounts/accounts.py | Apache-2.0 |
def import_account_from_private_key(
alias: str, passphrase: str, private_key: str
) -> KeyfileAccount:
"""
Import a new account from a mnemonic seed phrase.
Args:
alias (str): The alias name of the account.
passphrase (str): Passphrase used to encrypt the account storage file.
... |
Import a new account from a mnemonic seed phrase.
Args:
alias (str): The alias name of the account.
passphrase (str): Passphrase used to encrypt the account storage file.
private_key (str): Hex string private key to import.
Returns:
Tuple of AccountAPI and mnemonic for the... | import_account_from_private_key | python | ApeWorX/ape | src/ape_accounts/accounts.py | https://github.com/ApeWorX/ape/blob/master/src/ape_accounts/accounts.py | Apache-2.0 |
def cli():
"""
Command-line helper for managing local accounts. You can unlock local accounts from
scripts or the console using the accounts.load() method.
""" |
Command-line helper for managing local accounts. You can unlock local accounts from
scripts or the console using the accounts.load() method.
| cli | python | ApeWorX/ape | src/ape_accounts/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_accounts/_cli.py | Apache-2.0 |
def show_delegate(account):
"""Show if an existing delegate is authorized for account"""
if contract := account.delegate:
click.echo(f"{account.address} is delegated to {contract.address}")
else:
click.secho(f"{account.address} has no delegate", fg="red") | Show if an existing delegate is authorized for account | show_delegate | python | ApeWorX/ape | src/ape_accounts/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_accounts/_cli.py | Apache-2.0 |
def authorize_delegate(account, receiver, data, gas_limit, contract):
"""Authorize and set delegate for account"""
account.set_delegate(contract, receiver=receiver, data=data, gas_limit=gas_limit)
click.echo(f"{account.address} is now delegated to {contract}") | Authorize and set delegate for account | authorize_delegate | python | ApeWorX/ape | src/ape_accounts/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_accounts/_cli.py | Apache-2.0 |
def _get_database_file(self, ecosystem_name: str, network_name: str) -> Path:
"""
Allows us to figure out what the file *will be*, mostly used for database management.
Args:
ecosystem_name (str): Name of the ecosystem to store data for (ex: ethereum)
network_name (str): ... |
Allows us to figure out what the file *will be*, mostly used for database management.
Args:
ecosystem_name (str): Name of the ecosystem to store data for (ex: ethereum)
network_name (str): name of the network to store data for (ex: mainnet)
Raises:
:class:`... | _get_database_file | python | ApeWorX/ape | src/ape_cache/query.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/query.py | Apache-2.0 |
def init_database(self, ecosystem_name: str, network_name: str):
"""
Initialize the SQLite database for caching of provider data.
Args:
ecosystem_name (str): Name of the ecosystem to store data for (ex: ethereum)
network_name (str): name of the network to store data for ... |
Initialize the SQLite database for caching of provider data.
Args:
ecosystem_name (str): Name of the ecosystem to store data for (ex: ethereum)
network_name (str): name of the network to store data for (ex: mainnet)
Raises:
:class:`~ape.exceptions.QueryEngi... | init_database | python | ApeWorX/ape | src/ape_cache/query.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/query.py | Apache-2.0 |
def purge_database(self, ecosystem_name: str, network_name: str):
"""
Removes the SQLite database file from disk.
Args:
ecosystem_name (str): Name of the ecosystem to store data for (ex: ethereum)
network_name (str): name of the network to store data for (ex: mainnet)
... |
Removes the SQLite database file from disk.
Args:
ecosystem_name (str): Name of the ecosystem to store data for (ex: ethereum)
network_name (str): name of the network to store data for (ex: mainnet)
Raises:
:class:`~ape.exceptions.QueryEngineError`: When th... | purge_database | python | ApeWorX/ape | src/ape_cache/query.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/query.py | Apache-2.0 |
def database_connection(self):
"""
Returns a connection for the currently active network.
**NOTE**: Creates a database if it doesn't exist.
Raises:
:class:`~ape.exceptions.QueryEngineError`: If you are not connected to a provider,
or if the database has not ... |
Returns a connection for the currently active network.
**NOTE**: Creates a database if it doesn't exist.
Raises:
:class:`~ape.exceptions.QueryEngineError`: If you are not connected to a provider,
or if the database has not been initialized.
Returns:
... | database_connection | python | ApeWorX/ape | src/ape_cache/query.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/query.py | Apache-2.0 |
def _estimate_query_clause(self, query: QueryType) -> Select:
"""
A singledispatchmethod that returns a select statement.
Args:
query (QueryType): Choice of query type to perform a
check of the number of rows that match the clause.
Raises:
:class... |
A singledispatchmethod that returns a select statement.
Args:
query (QueryType): Choice of query type to perform a
check of the number of rows that match the clause.
Raises:
:class:`~ape.exceptions.QueryEngineError`: When given an
incomp... | _estimate_query_clause | python | ApeWorX/ape | src/ape_cache/query.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/query.py | Apache-2.0 |
def estimate_query(self, query: QueryType) -> Optional[int]:
"""
Method called by the client to return a query time estimate.
Args:
query (QueryType): Choice of query type to perform a
check of the number of rows that match the clause.
Returns:
O... |
Method called by the client to return a query time estimate.
Args:
query (QueryType): Choice of query type to perform a
check of the number of rows that match the clause.
Returns:
Optional[int]
| estimate_query | python | ApeWorX/ape | src/ape_cache/query.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/query.py | Apache-2.0 |
def perform_query(self, query: QueryType) -> Iterator: # type: ignore
"""
Performs the requested query from cache.
Args:
query (QueryType): Choice of query type to perform a
check of the number of rows that match the clause.
Raises:
:class:`~ape... |
Performs the requested query from cache.
Args:
query (QueryType): Choice of query type to perform a
check of the number of rows that match the clause.
Raises:
:class:`~ape.exceptions.QueryEngineError`: When given an
incompatible QueryTyp... | perform_query | python | ApeWorX/ape | src/ape_cache/query.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/query.py | Apache-2.0 |
def _cache_update_clause(self, query: QueryType) -> Insert:
"""
Update cache database Insert statement.
Args:
query (QueryType): Choice of query type to perform a
check of the number of rows that match the clause.
Raises:
:class:`~ape.exceptions.... |
Update cache database Insert statement.
Args:
query (QueryType): Choice of query type to perform a
check of the number of rows that match the clause.
Raises:
:class:`~ape.exceptions.QueryEngineError`: When given an
incompatible QueryType... | _cache_update_clause | python | ApeWorX/ape | src/ape_cache/query.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/query.py | Apache-2.0 |
def init(ecosystem, network):
"""
Initializes an SQLite database and creates a file to store data
from the provider.
Note that ape cannot store local data in this database. You have to
give an ecosystem name and a network name to initialize the database.
"""
get_engine().init_database(ecos... |
Initializes an SQLite database and creates a file to store data
from the provider.
Note that ape cannot store local data in this database. You have to
give an ecosystem name and a network name to initialize the database.
| init | python | ApeWorX/ape | src/ape_cache/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/_cli.py | Apache-2.0 |
def query(query_str):
"""
Allows for a query of the database from an SQL statement.
Note that without an SQL statement, this method will not return
any data from the caching database.
Also note that an ecosystem name and a network name are required
to make the correct connection to the databas... |
Allows for a query of the database from an SQL statement.
Note that without an SQL statement, this method will not return
any data from the caching database.
Also note that an ecosystem name and a network name are required
to make the correct connection to the database.
| query | python | ApeWorX/ape | src/ape_cache/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/_cli.py | Apache-2.0 |
def purge(ecosystem, network):
"""
Purges data from the selected database instance.
Note that this is a destructive purge, and will remove the database file from disk.
If you want to store data in the caching system, you will have to
re-initiate the database following a purge.
Note that an eco... |
Purges data from the selected database instance.
Note that this is a destructive purge, and will remove the database file from disk.
If you want to store data in the caching system, you will have to
re-initiate the database following a purge.
Note that an ecosystem name and network name are requi... | purge | python | ApeWorX/ape | src/ape_cache/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_cache/_cli.py | Apache-2.0 |
def serialize_exclude(self, exclude, info):
"""
Exclude is put back with the weird r-prefix so we can
go to-and-from.
"""
result: list[str] = []
for excl in exclude:
if isinstance(excl, Pattern):
result.append(f'r"{excl.pattern}"')
... |
Exclude is put back with the weird r-prefix so we can
go to-and-from.
| serialize_exclude | python | ApeWorX/ape | src/ape_compile/config.py | https://github.com/ApeWorX/ape/blob/master/src/ape_compile/config.py | Apache-2.0 |
def cli(
cli_ctx,
project,
file_paths: set[Path],
use_cache: bool,
display_size: bool,
include_dependencies,
excluded_compilers: list[str],
config_override,
):
"""
Compiles the manifest for this project and saves the results
back to the manifest.
Note that ape automatica... |
Compiles the manifest for this project and saves the results
back to the manifest.
Note that ape automatically recompiles any changed contracts each time
a project is loaded. You do not have to manually trigger a recompile.
| cli | python | ApeWorX/ape | src/ape_compile/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_compile/_cli.py | Apache-2.0 |
def ape(self, line: str = ""):
"""
Run Ape CLI commands within an ``ape console`` session.
Usage example::
%ape accounts list
"""
runner = CliRunner()
if "console" in [x.strip("\"' \t\n") for x in shlex.split(line)]:
# Prevent running console wi... |
Run Ape CLI commands within an ``ape console`` session.
Usage example::
%ape accounts list
| ape | python | ApeWorX/ape | src/ape_console/plugin.py | https://github.com/ApeWorX/ape/blob/master/src/ape_console/plugin.py | Apache-2.0 |
def bal(self, line: str = ""):
"""
Show an account balance in human-readable form.
Usage example::
account = accounts.load("me")
%bal account
"""
if not line:
raise ValueError("Missing argument.")
provider = ape.networks.provider
... |
Show an account balance in human-readable form.
Usage example::
account = accounts.load("me")
%bal account
| bal | python | ApeWorX/ape | src/ape_console/plugin.py | https://github.com/ApeWorX/ape/blob/master/src/ape_console/plugin.py | Apache-2.0 |
def cli(cli_ctx, project, code):
"""Opens a console for the local project."""
verbose = cli_ctx.logger.level == logging.DEBUG
return console(project=project, verbose=verbose, code=code) | Opens a console for the local project. | cli | python | ApeWorX/ape | src/ape_console/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_console/_cli.py | Apache-2.0 |
def create_transaction(self, **kwargs) -> "TransactionAPI":
"""
Returns a transaction using the given constructor kwargs.
**NOTE**: This generally should not be called by the user since this API method is used as a
hook for Ecosystems to customize how transactions are created.
... |
Returns a transaction using the given constructor kwargs.
**NOTE**: This generally should not be called by the user since this API method is used as a
hook for Ecosystems to customize how transactions are created.
Returns:
:class:`~ape.api.transactions.TransactionAPI`
... | create_transaction | python | ApeWorX/ape | src/ape_ethereum/ecosystem.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/ecosystem.py | Apache-2.0 |
def _sanitize_web3_url(msg: str) -> str:
"""Sanitize RPC URI from given log string"""
# `auto` used by some providers to figure it out automatically
if "URI: " not in msg or "URI: auto" in msg:
return msg
parts = msg.split("URI: ")
prefix = parts[0].strip()
rest = parts[1].split(" ")
... | Sanitize RPC URI from given log string | _sanitize_web3_url | python | ApeWorX/ape | src/ape_ethereum/provider.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/provider.py | Apache-2.0 |
def assert_web3_provider_uri_env_var_not_set():
"""
Environment variable $WEB3_PROVIDER_URI causes problems
when used with Ape (ignores Ape's networks). Use
this validator to eliminate the concern.
Raises:
:class:`~ape.exceptions.ProviderError`: If environment variable
WEB3_PR... |
Environment variable $WEB3_PROVIDER_URI causes problems
when used with Ape (ignores Ape's networks). Use
this validator to eliminate the concern.
Raises:
:class:`~ape.exceptions.ProviderError`: If environment variable
WEB3_PROVIDER_URI exists in ``os.environ``.
| assert_web3_provider_uri_env_var_not_set | python | ApeWorX/ape | src/ape_ethereum/provider.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/provider.py | Apache-2.0 |
def web3(self) -> Web3:
"""
Access to the ``web3`` object as if you did ``Web3(HTTPProvider(uri))``.
"""
if web3 := self._web3:
return web3
raise ProviderNotConnectedError() |
Access to the ``web3`` object as if you did ``Web3(HTTPProvider(uri))``.
| web3 | python | ApeWorX/ape | src/ape_ethereum/provider.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/provider.py | Apache-2.0 |
def _configured_rpc(self) -> Optional[str]:
"""
First of URI, HTTP_URI, WS_URI, IPC_PATH
found in the provider_settings or config.
"""
# NOTE: Even though this only returns 1 value,
# each configured URI is passed in to web3 and
# will be used as each specifi... |
First of URI, HTTP_URI, WS_URI, IPC_PATH
found in the provider_settings or config.
| _configured_rpc | python | ApeWorX/ape | src/ape_ethereum/provider.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/provider.py | Apache-2.0 |
def _get_connected_rpc(self, validator: Callable[[str], bool]) -> Optional[str]:
"""
The connected HTTP URI. If using providers
like `ape-node`, configure your URI and that will
be returned here instead.
"""
if web3 := self._web3:
if endpoint_uri := getattr(we... |
The connected HTTP URI. If using providers
like `ape-node`, configure your URI and that will
be returned here instead.
| _get_connected_rpc | python | ApeWorX/ape | src/ape_ethereum/provider.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/provider.py | Apache-2.0 |
def call_trace_approach(self) -> Optional[TraceApproach]:
"""
The default tracing approach to use when building up a call-tree.
By default, Ape attempts to use the faster approach. Meaning, if
geth-call-tracer or parity are available, Ape will use one of those
instead of building... |
The default tracing approach to use when building up a call-tree.
By default, Ape attempts to use the faster approach. Meaning, if
geth-call-tracer or parity are available, Ape will use one of those
instead of building a call-trace entirely from struct-logs.
| call_trace_approach | python | ApeWorX/ape | src/ape_ethereum/provider.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/provider.py | Apache-2.0 |
def create_access_list(
self, transaction: TransactionAPI, block_id: Optional["BlockID"] = None
) -> list[AccessList]:
"""
Get the access list for a transaction use ``eth_createAccessList``.
Args:
transaction (:class:`~ape.api.transactions.TransactionAPI`): The
... |
Get the access list for a transaction use ``eth_createAccessList``.
Args:
transaction (:class:`~ape.api.transactions.TransactionAPI`): The
transaction to check.
block_id (:class:`~ape.types.BlockID`): Optionally specify a block
ID. Defaults to using ... | create_access_list | python | ApeWorX/ape | src/ape_ethereum/provider.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/provider.py | Apache-2.0 |
def has_poa_history(self) -> bool:
"""
``True`` if detected any PoA history. If the chain was _ever_ PoA, the special
middleware is needed for web3.py. Provider plugins use this property when
creating Web3 instances.
"""
findings = False
for option in ("earliest",... |
``True`` if detected any PoA history. If the chain was _ever_ PoA, the special
middleware is needed for web3.py. Provider plugins use this property when
creating Web3 instances.
| has_poa_history | python | ApeWorX/ape | src/ape_ethereum/provider.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/provider.py | Apache-2.0 |
def perform_contract_creation_query(
self, query: ContractCreationQuery
) -> Iterator[ContractCreation]:
"""
Find when a contract was deployed using binary search and block tracing.
"""
# skip the search if there is still no code at address at head
if not self.chain_m... |
Find when a contract was deployed using binary search and block tracing.
| perform_contract_creation_query | python | ApeWorX/ape | src/ape_ethereum/query.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/query.py | Apache-2.0 |
def transaction(self) -> dict:
"""
The transaction data (obtained differently on
calls versus transactions).
""" |
The transaction data (obtained differently on
calls versus transactions).
| transaction | python | ApeWorX/ape | src/ape_ethereum/trace.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/trace.py | Apache-2.0 |
def get_calltree(self) -> CallTreeNode:
"""
Get an un-enriched call-tree node.
""" |
Get an un-enriched call-tree node.
| get_calltree | python | ApeWorX/ape | src/ape_ethereum/trace.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/trace.py | Apache-2.0 |
def raw_trace_frames(self) -> Iterator[dict]:
"""
The raw trace ``"structLogs"`` from ``debug_traceTransaction``
for deeper investigation.
"""
if self._frames:
yield from self._frames
else:
for frame in self._stream_struct_logs():
... |
The raw trace ``"structLogs"`` from ``debug_traceTransaction``
for deeper investigation.
| raw_trace_frames | python | ApeWorX/ape | src/ape_ethereum/trace.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/trace.py | Apache-2.0 |
def debug_logs_typed(self) -> list[tuple[Any]]:
"""
Extract messages to console outputted by contracts via print() or console.log() statements
"""
try:
trace = self.trace
# Some providers do not implement this, so skip.
except NotImplementedError:
... |
Extract messages to console outputted by contracts via print() or console.log() statements
| debug_logs_typed | python | ApeWorX/ape | src/ape_ethereum/transactions.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/transactions.py | Apache-2.0 |
def is_console_log(call: "CallTreeNode") -> "TypeGuard[CallTreeNode]":
"""Determine if a call is a standard console.log() call"""
return (
call.address == HexBytes(CONSOLE_ADDRESS)
and to_hex(call.calldata[:4]) in console_contract.identifier_lookup
) | Determine if a call is a standard console.log() call | is_console_log | python | ApeWorX/ape | src/ape_ethereum/_print.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/_print.py | Apache-2.0 |
def is_vyper_print(call: "CallTreeNode") -> "TypeGuard[CallTreeNode]":
"""Determine if a call is a standard Vyper print() call"""
if call.address != HexBytes(CONSOLE_ADDRESS) or call.calldata[:4] != VYPER_PRINT_METHOD_ID:
return False
schema, _ = decode(["string", "bytes"], call.calldata[4:])
t... | Determine if a call is a standard Vyper print() call | is_vyper_print | python | ApeWorX/ape | src/ape_ethereum/_print.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/_print.py | Apache-2.0 |
def console_log(method_abi: MethodABI, calldata: str) -> tuple[Any]:
"""Return logged data for console.log() calls"""
bcalldata = decode_hex(calldata)
data = ape.networks.ethereum.decode_calldata(method_abi, bcalldata)
return tuple(data.values()) | Return logged data for console.log() calls | console_log | python | ApeWorX/ape | src/ape_ethereum/_print.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/_print.py | Apache-2.0 |
def vyper_print(calldata: str) -> tuple[Any]:
"""Return logged data for print() calls"""
schema, payload = decode(["string", "bytes"], HexBytes(calldata))
data = decode(schema.strip("()").split(","), payload)
return tuple(data) | Return logged data for print() calls | vyper_print | python | ApeWorX/ape | src/ape_ethereum/_print.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/_print.py | Apache-2.0 |
def extract_debug_logs(call: "CallTreeNode") -> Iterable[tuple[Any]]:
"""Filter calls to console.log() and print() from a transactions call tree"""
if is_vyper_print(call) and call.calldata is not None:
yield vyper_print(add_0x_prefix(to_hex(call.calldata[4:])))
elif is_console_log(call) and call.c... | Filter calls to console.log() and print() from a transactions call tree | extract_debug_logs | python | ApeWorX/ape | src/ape_ethereum/_print.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/_print.py | Apache-2.0 |
def __init__(
self,
address: "AddressType" = MULTICALL3_ADDRESS,
supported_chains: Optional[list[int]] = None,
) -> None:
"""
Initialize a new Multicall session object. By default, there are no calls to make.
"""
self.address = address
self.supported_c... |
Initialize a new Multicall session object. By default, there are no calls to make.
| __init__ | python | ApeWorX/ape | src/ape_ethereum/multicall/handlers.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/multicall/handlers.py | Apache-2.0 |
def inject(cls) -> ModuleType:
"""
Create the multicall module contract on-chain, so we can use it.
Must use a provider that supports ``debug_setCode``.
Usage example::
from ape_ethereum import multicall
@pytest.fixture(scope="session")
def use_mul... |
Create the multicall module contract on-chain, so we can use it.
Must use a provider that supports ``debug_setCode``.
Usage example::
from ape_ethereum import multicall
@pytest.fixture(scope="session")
def use_multicall():
# NOTE: use this... | inject | python | ApeWorX/ape | src/ape_ethereum/multicall/handlers.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/multicall/handlers.py | Apache-2.0 |
def add(
self,
call: ContractMethodHandler,
*args,
allowFailure: bool = True,
value: int = 0,
) -> "BaseMulticall":
"""
Adds a call to the Multicall session object.
Raises:
:class:`~ape_ethereum.multicall.exceptions.InvalidOption`: If one
... |
Adds a call to the Multicall session object.
Raises:
:class:`~ape_ethereum.multicall.exceptions.InvalidOption`: If one
of the kwarg modifiers is not able to be used.
Args:
call (:class:`~ape_ethereum.multicall.handlers.ContractMethodHandler`):
... | add | python | ApeWorX/ape | src/ape_ethereum/multicall/handlers.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/multicall/handlers.py | Apache-2.0 |
def __call__(self, **txn_kwargs) -> "ReceiptAPI":
"""
Execute the Multicall transaction. The transaction will broadcast again every time
the ``Transaction`` object is called.
Raises:
:class:`UnsupportedChain`: If there is not an instance of Multicall3 deployed
... |
Execute the Multicall transaction. The transaction will broadcast again every time
the ``Transaction`` object is called.
Raises:
:class:`UnsupportedChain`: If there is not an instance of Multicall3 deployed
on the current chain at the expected address.
Args:
... | __call__ | python | ApeWorX/ape | src/ape_ethereum/multicall/handlers.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/multicall/handlers.py | Apache-2.0 |
def as_transaction(self, **txn_kwargs) -> "TransactionAPI":
"""
Encode the Multicall transaction as a ``TransactionAPI`` object, but do not execute it.
Returns:
:class:`~ape.api.transactions.TransactionAPI`
"""
self._validate_calls(**txn_kwargs)
return self.h... |
Encode the Multicall transaction as a ``TransactionAPI`` object, but do not execute it.
Returns:
:class:`~ape.api.transactions.TransactionAPI`
| as_transaction | python | ApeWorX/ape | src/ape_ethereum/multicall/handlers.py | https://github.com/ApeWorX/ape/blob/master/src/ape_ethereum/multicall/handlers.py | Apache-2.0 |
def cli(cli_ctx, github, project_name):
"""
``ape init`` allows the user to create an ape project with
default folders and ape-config.yaml.
"""
if github:
from ape.utils._github import github_client
org, repo = github
github_client.clone_repo(org, repo, Path.cwd())
s... |
``ape init`` allows the user to create an ape project with
default folders and ape-config.yaml.
| cli | python | ApeWorX/ape | src/ape_init/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_init/_cli.py | Apache-2.0 |
def cli():
"""
Command-line helper for managing networks.
""" |
Command-line helper for managing networks.
| cli | python | ApeWorX/ape | src/ape_networks/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_networks/_cli.py | Apache-2.0 |
def _list(cli_ctx, output_format, ecosystem_filter, network_filter, provider_filter, running):
"""
List all the registered ecosystems, networks, and providers.
"""
if running:
# TODO: Honor filter args.
_print_running_networks(cli_ctx)
return
network_data = cli_ctx.network_m... |
List all the registered ecosystems, networks, and providers.
| _list | python | ApeWorX/ape | src/ape_networks/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_networks/_cli.py | Apache-2.0 |
def run(cli_ctx, provider, block_time, background):
"""
Start a subprocess node as if running independently
and stream stdout and stderr.
"""
from ape.api.providers import SubprocessProvider
# Ignore extra loggers, such as web3 loggers.
cli_ctx.logger._extra_loggers = {}
if not isinstan... |
Start a subprocess node as if running independently
and stream stdout and stderr.
| run | python | ApeWorX/ape | src/ape_networks/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_networks/_cli.py | Apache-2.0 |
def create_genesis_data(alloc: Alloc, chain_id: int) -> "GenesisDataTypedDict":
"""
A wrapper around genesis data for py-geth that
fills in more defaults.
"""
return {
"alloc": alloc,
"config": {
"arrowGlacierBlock": 0,
"berlinBlock": 0,
"byzantium... |
A wrapper around genesis data for py-geth that
fills in more defaults.
| create_genesis_data | python | ApeWorX/ape | src/ape_node/provider.py | https://github.com/ApeWorX/ape/blob/master/src/ape_node/provider.py | Apache-2.0 |
def cli():
"""
Command-line helper for managing plugins.
""" |
Command-line helper for managing plugins.
| cli | python | ApeWorX/ape | src/ape_plugins/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_plugins/_cli.py | Apache-2.0 |
def plugins_argument():
"""
An argument that is either the given list of plugins
or plugins loaded from the local config file.
"""
def load_from_file(ctx, file_path: Path) -> list["PluginMetadata"]:
from ape.plugins._utils import PluginMetadata
from ape.utils.misc import load_config... |
An argument that is either the given list of plugins
or plugins loaded from the local config file.
| plugins_argument | python | ApeWorX/ape | src/ape_plugins/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_plugins/_cli.py | Apache-2.0 |
def _install(name, spec, exit_on_fail: bool = True) -> int:
"""
Helper function to install or update a Python package using pip.
Args:
name (str): The package name.
spec (str): Version specifier, e.g., '==1.0.0', '>=1.0.0', etc.
exit_on_fail (bool): Set to ``False`` to not exit on fail.
... |
Helper function to install or update a Python package using pip.
Args:
name (str): The package name.
spec (str): Version specifier, e.g., '==1.0.0', '>=1.0.0', etc.
exit_on_fail (bool): Set to ``False`` to not exit on fail.
Returns:
The process return-code.
| _install | python | ApeWorX/ape | src/ape_plugins/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_plugins/_cli.py | Apache-2.0 |
def version_from_project_package_json(self) -> Optional[str]:
"""
The version from your project's package.json, if exists.
"""
return _get_version_from_package_json(
self.local_project.path, dict_path=("dependencies", self.package_id)
) |
The version from your project's package.json, if exists.
| version_from_project_package_json | python | ApeWorX/ape | src/ape_pm/dependency.py | https://github.com/ApeWorX/ape/blob/master/src/ape_pm/dependency.py | Apache-2.0 |
def uninstall(cli_ctx, name, versions, yes):
"""
Uninstall a package
This command removes a package from the installed packages.
If specific versions are provided, only those versions of the package will be
removed. If no versions are provided, the command will prompt you to choose
versions to... |
Uninstall a package
This command removes a package from the installed packages.
If specific versions are provided, only those versions of the package will be
removed. If no versions are provided, the command will prompt you to choose
versions to remove. You can also choose to remove all versions ... | uninstall | python | ApeWorX/ape | src/ape_pm/_cli.py | https://github.com/ApeWorX/ape/blob/master/src/ape_pm/_cli.py | Apache-2.0 |
def skip_if_plugin_installed(*plugin_names: str):
"""
A simple decorator for skipping a test if a plugin is installed.
**NOTE**: For performance reasons, this method is not very good.
It only works for common ApeWorX supported plugins and is only
meant for assisting testing in Core (NOT a public uti... |
A simple decorator for skipping a test if a plugin is installed.
**NOTE**: For performance reasons, this method is not very good.
It only works for common ApeWorX supported plugins and is only
meant for assisting testing in Core (NOT a public utility).
| skip_if_plugin_installed | python | ApeWorX/ape | tests/conftest.py | https://github.com/ApeWorX/ape/blob/master/tests/conftest.py | Apache-2.0 |
def disable_fork_providers(ethereum):
"""
When ape-hardhat or ape-foundry is installed,
this tricks the test into thinking they are not
(only uses sepolia-fork).
"""
actual = ethereum.sepolia_fork.__dict__.pop("providers", {})
ethereum.sepolia_fork.__dict__["providers"] = {}
yield
if... |
When ape-hardhat or ape-foundry is installed,
this tricks the test into thinking they are not
(only uses sepolia-fork).
| disable_fork_providers | python | ApeWorX/ape | tests/functional/conftest.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/conftest.py | Apache-2.0 |
def mock_fork_provider(mocker, ethereum, mock_sepolia):
"""
A fake provider representing something like ape-foundry
that can fork networks (only uses sepolia-fork).
"""
initial_providers = ethereum.sepolia_fork.__dict__.pop("providers", {})
initial_default = ethereum.sepolia_fork._default_provid... |
A fake provider representing something like ape-foundry
that can fork networks (only uses sepolia-fork).
| mock_fork_provider | python | ApeWorX/ape | tests/functional/conftest.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/conftest.py | Apache-2.0 |
def test_transfer_value_of_0(sender, receiver):
"""
There was a bug where this failed, thinking there was no value.
"""
initial_balance = receiver.balance
sender.transfer(receiver, 0)
assert receiver.balance == initial_balance
# Also show conversion works.
sender.transfer(receiver, "0 w... |
There was a bug where this failed, thinking there was no value.
| test_transfer_value_of_0 | python | ApeWorX/ape | tests/functional/test_accounts.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_accounts.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.