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 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 get_deployment_address(self, address: AddressType, nonce: int) -> AddressType:
"""
Calculate the deployment address of a contract before it is deployed.
This is useful if the address is an argument to another contract's deployment
and you have not yet deployed the first contract yet.... |
Calculate the deployment address of a contract before it is deployed.
This is useful if the address is an argument to another contract's deployment
and you have not yet deployed the first contract yet.
| get_deployment_address | 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 |
def test_transfer_mixed_up_sender_and_value(sender, receiver):
"""
Testing the case where the user mixes up the argument order,
it should show a nicer error than it was previously, as this is
a common and easy mistake.
"""
expected = (
r"Cannot use integer-type for the `receiver` "
... |
Testing the case where the user mixes up the argument order,
it should show a nicer error than it was previously, as this is
a common and easy mistake.
| test_transfer_mixed_up_sender_and_value | python | ApeWorX/ape | tests/functional/test_accounts.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_accounts.py | Apache-2.0 |
def test_deploy_instance(owner, vyper_contract_instance):
"""
Tests against a confusing scenario where you would get a SignatureError when
trying to deploy a ContractInstance because Ape would attempt to create a tx
by calling the contract's default handler.
"""
expected = (
r"contract ... |
Tests against a confusing scenario where you would get a SignatureError when
trying to deploy a ContractInstance because Ape would attempt to create a tx
by calling the contract's default handler.
| test_deploy_instance | python | ApeWorX/ape | tests/functional/test_accounts.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_accounts.py | Apache-2.0 |
def test_deploy_no_deployment_bytecode(owner, bytecode):
"""
https://github.com/ApeWorX/ape/issues/1904
"""
expected = (
r"Cannot deploy: contract 'Apes' has no deployment-bytecode\. "
r"Are you attempting to deploy an interface\?"
)
contract_type = ContractType.model_validate(
... | ERROR: type should be string, got "\n https://github.com/ApeWorX/ape/issues/1904\n " | test_deploy_no_deployment_bytecode | python | ApeWorX/ape | tests/functional/test_accounts.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_accounts.py | Apache-2.0 |
def test_unlock_and_reload(runner, account_manager, keyfile_account, message):
"""
Tests against a condition where reloading after unlocking
would not honor unlocked state.
"""
keyfile_account.unlock(passphrase=PASSPHRASE)
reloaded_account = account_manager.load(keyfile_account.alias)
# y: ... |
Tests against a condition where reloading after unlocking
would not honor unlocked state.
| test_unlock_and_reload | python | ApeWorX/ape | tests/functional/test_accounts.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_accounts.py | Apache-2.0 |
def test_repr(account_manager):
"""
NOTE: __repr__ should be simple and fast!
Previously, we showed the repr of all the accounts.
That was a bad idea, as that can be very unnecessarily slow.
Hence, this test exists to ensure care is taken.
"""
actual = repr(account_manager)
assert ... |
NOTE: __repr__ should be simple and fast!
Previously, we showed the repr of all the accounts.
That was a bad idea, as that can be very unnecessarily slow.
Hence, this test exists to ensure care is taken.
| test_repr | python | ApeWorX/ape | tests/functional/test_accounts.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_accounts.py | Apache-2.0 |
def test_ipython_integration_defaults(manager, fn_name):
"""
Test default behavior for IPython integration methods.
The base-manager short-circuits to NotImplementedError to avoid
dealing with any custom `__getattr__` logic entirely. This prevents
side-effects such as unnecessary compiling in the Pr... |
Test default behavior for IPython integration methods.
The base-manager short-circuits to NotImplementedError to avoid
dealing with any custom `__getattr__` logic entirely. This prevents
side-effects such as unnecessary compiling in the ProjectManager.
| test_ipython_integration_defaults | python | ApeWorX/ape | tests/functional/test_base_manager.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_base_manager.py | Apache-2.0 |
def test_model_validate_web3_block():
"""
Show we have good compatibility with web3.py native types.
"""
data = BlockData(number=123, timestamp=123, gasLimit=123, gasUsed=100) # type: ignore
actual = Block.model_validate(data)
assert actual.number == 123 |
Show we have good compatibility with web3.py native types.
| test_model_validate_web3_block | python | ApeWorX/ape | tests/functional/test_block.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_block.py | Apache-2.0 |
def test_snapshot_and_restore_switched_chains(networks, chain):
"""
Ensuring things work as expected when we switch chains after snapshotting
and before restoring.
"""
snapshot = chain.snapshot()
# Switch chains.
with networks.ethereum.local.use_provider(
"test", provider_settings={"... |
Ensuring things work as expected when we switch chains after snapshotting
and before restoring.
| test_snapshot_and_restore_switched_chains | python | ApeWorX/ape | tests/functional/test_chain.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_chain.py | Apache-2.0 |
def test_network_option_with_other_option(runner):
"""
To prove can use the `@network_option` with other options
in the same command (was issue during production where could not!).
"""
# Scenario: Using network_option but not using the value in the command callback.
# (Potentially handling ind... |
To prove can use the `@network_option` with other options
in the same command (was issue during production where could not!).
| test_network_option_with_other_option | python | ApeWorX/ape | tests/functional/test_cli.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_cli.py | Apache-2.0 |
def test_account_option_uses_single_account_as_default(runner, one_account):
"""
When there is only 1 test account, that is the default
when no option is given.
"""
@click.command()
@account_option(account_type=[one_account])
def cmd(account):
_expected = get_expected_account_str(ac... |
When there is only 1 test account, that is the default
when no option is given.
| test_account_option_uses_single_account_as_default | python | ApeWorX/ape | tests/functional/test_cli.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_cli.py | Apache-2.0 |
def test_prompt_choice(runner, opt):
"""
This demonstrates how to use ``PromptChoice``,
as it is a little confusing, requiring a callback.
"""
def choice_callback(ctx, param, value):
return param.type.select()
choice = PromptChoice(["foo", "bar"])
assert hasattr(choice, "name")
... |
This demonstrates how to use ``PromptChoice``,
as it is a little confusing, requiring a callback.
| test_prompt_choice | python | ApeWorX/ape | tests/functional/test_cli.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_cli.py | Apache-2.0 |
def test_account_prompt_name():
"""
It is very important for this class to have the `name` attribute,
even though it is not used. That is because some click internals
expect this property to exist, and we skip the super() constructor.
"""
option = AccountAliasPromptChoice()
assert option.nam... |
It is very important for this class to have the `name` attribute,
even though it is not used. That is because some click internals
expect this property to exist, and we skip the super() constructor.
| test_account_prompt_name | python | ApeWorX/ape | tests/functional/test_cli.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_cli.py | Apache-2.0 |
def test_contract_file_paths_argument_given_directory_and_file(
project_with_contract, runner, contracts_paths_cmd
):
"""
Tests against a bug where if given a directory AND a file together,
only the directory resolved and the file was lost.
"""
pm = project_with_contract
src_stem = next(x fo... |
Tests against a bug where if given a directory AND a file together,
only the directory resolved and the file was lost.
| test_contract_file_paths_argument_given_directory_and_file | python | ApeWorX/ape | tests/functional/test_cli.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_cli.py | Apache-2.0 |
def test_connected_provider_command_use_custom_options(runner):
"""
Ensure custom options work when using `ConnectedProviderCommand`.
(There was an issue during development where we could not).
"""
# Scenario: Custom option and using network object.
@click.command(cls=ConnectedProviderCommand)
... |
Ensure custom options work when using `ConnectedProviderCommand`.
(There was an issue during development where we could not).
| test_connected_provider_command_use_custom_options | python | ApeWorX/ape | tests/functional/test_cli.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_cli.py | Apache-2.0 |
def test_flatten_contract(compilers, project_with_contract):
"""
Positive tests exist in compiler plugins that implement this behavior.b
"""
source_id = project_with_contract.ApeContract0.contract_type.source_id
path = project_with_contract.contracts_folder / source_id
with pytest.raises(APINot... |
Positive tests exist in compiler plugins that implement this behavior.b
| test_flatten_contract | python | ApeWorX/ape | tests/functional/test_compilers.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_compilers.py | Apache-2.0 |
def test_compile(compilers, project_with_contract, factory):
"""
Testing both stringified paths and path-object paths.
"""
path = next(iter(project_with_contract.sources.paths))
actual = compilers.compile((factory(path),), project=project_with_contract)
contract_name = path.stem
assert contr... |
Testing both stringified paths and path-object paths.
| test_compile | python | ApeWorX/ape | tests/functional/test_compilers.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_compilers.py | Apache-2.0 |
def test_compile_multiple_errors(
mock_compiler, make_mock_compiler, compilers, project_with_contract
):
"""
Simulating getting errors from multiple compilers.
We should get all the errors.
"""
second_mock_compiler = make_mock_compiler("mock2")
new_contract_0 = project_with_contract.path / f... |
Simulating getting errors from multiple compilers.
We should get all the errors.
| test_compile_multiple_errors | python | ApeWorX/ape | tests/functional/test_compilers.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_compilers.py | Apache-2.0 |
def test_compile_in_project_where_source_id_matches_local_project(project, compilers):
"""
Tests against a bug where if you had two projects with the same source IDs but
different content, it always compiled the local project's source.
"""
new_abi = {
"inputs": [],
"name": "retrieve"... |
Tests against a bug where if you had two projects with the same source IDs but
different content, it always compiled the local project's source.
| test_compile_in_project_where_source_id_matches_local_project | python | ApeWorX/ape | tests/functional/test_compilers.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_compilers.py | Apache-2.0 |
def test_config_exclude_regex_serialize():
"""
Show we can to-and-fro with exclude regexes.
"""
raw_value = 'r"FooBar"'
cfg = Config(exclude=[raw_value])
excl = [x for x in cfg.exclude if isinstance(x, Pattern)]
assert len(excl) == 1
assert excl[0].pattern == "FooBar"
# NOTE: Use jso... |
Show we can to-and-fro with exclude regexes.
| test_config_exclude_regex_serialize | python | ApeWorX/ape | tests/functional/test_compilers.py | https://github.com/ApeWorX/ape/blob/master/tests/functional/test_compilers.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.