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 sources(self) -> SourceManager: # type: ignore[override] """ All the sources in the project. """ return SourceManager( self.path, lambda: self.contracts_folder, exclude_globs=self.exclusions )
All the sources in the project.
sources
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def isolate_in_tempdir(self, **config_override) -> Iterator["LocalProject"]: """ Clone this project to a temporary directory and return its project.vers_settings["outputSelection"] """ sources = dict(self.sources.items()) if self.in_tempdir: # Already in a tempdir. if config_override: self.reconfigure(**config_override) self.manifest.sources = sources yield self else: with super().isolate_in_tempdir(**config_override) as project: # Add sources to manifest memory, in case they are missing. project.manifest.sources = sources yield project
Clone this project to a temporary directory and return its project.vers_settings["outputSelection"]
isolate_in_tempdir
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def load_manifest(self) -> PackageManifest: """ Load a publish-able manifest. Returns: ethpm_types.PackageManifest """ if not self.manifest_path.is_file(): return PackageManifest() try: manifest = _load_manifest(self.manifest_path) except Exception as err: logger.error(f"__local__.json manifest corrupted! Re-building.\nFull error: {err}.") self.manifest_path.unlink(missing_ok=True) manifest = PackageManifest() self._manifest = manifest return manifest
Load a publish-able manifest. Returns: ethpm_types.PackageManifest
load_manifest
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def extract_manifest(self) -> PackageManifest: """ Get a finalized manifest for publishing. Returns: PackageManifest """ sources = dict(self.sources) contract_types = { n: c.contract_type for n, c in self.load_contracts().items() if c.contract_type.source_id in sources } # Add any remaining data to the manifest here. self.update_manifest( contract_types=contract_types, dependencies=self.dependencies.uri_map, deployments=self.deployments.instance_map, meta=self.meta, name=self.name, sources=sources, version=self.version, ) return self.manifest
Get a finalized manifest for publishing. Returns: PackageManifest
extract_manifest
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def chdir(self, path: Optional[Path] = None): """ Change the local project to the new path. Args: path (Path): The path of the new project. If not given, defaults to the project's path. """ return ChangeDirectory( self.path, path or self.path, on_push=self._handle_path_changed, on_pop=self._handle_path_restored, )
Change the local project to the new path. Args: path (Path): The path of the new project. If not given, defaults to the project's path.
chdir
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def reload_config(self): """ Reload the local ape-config.yaml file. This is useful if the file was modified in the active python session. """ self._clear_cached_config() _ = self.config
Reload the local ape-config.yaml file. This is useful if the file was modified in the active python session.
reload_config
python
ApeWorX/ape
src/ape/managers/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/project.py
Apache-2.0
def engines(self) -> dict[str, QueryAPI]: """ A dict of all :class:`~ape.api.query.QueryAPI` instances across all installed plugins. Returns: dict[str, :class:`~ape.api.query.QueryAPI`] """ engines: dict[str, QueryAPI] = {"__default__": DefaultQueryProvider()} for plugin_name, engine_class in self.plugin_manager.query_engines: engine_name = clean_plugin_name(plugin_name) engines[engine_name] = engine_class() # type: ignore return engines
A dict of all :class:`~ape.api.query.QueryAPI` instances across all installed plugins. Returns: dict[str, :class:`~ape.api.query.QueryAPI`]
engines
python
ApeWorX/ape
src/ape/managers/query.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/query.py
Apache-2.0
def query( self, query: QueryType, engine_to_use: Optional[str] = None, ) -> Iterator[BaseInterfaceModel]: """ Args: query (``QueryType``): The type of query to execute engine_to_use (Optional[str]): Short-circuit selection logic using a specific engine. Defaults is set by performance-based selection logic. Raises: :class:`~ape.exceptions.QueryEngineError`: When given an invalid or inaccessible ``engine_to_use`` value. Returns: Iterator[``BaseInterfaceModel``] """ if engine_to_use: if engine_to_use not in self.engines: raise QueryEngineError( f"Query engine `{engine_to_use}` not found. " f"Did you mean {' or '.join(self._suggest_engines(engine_to_use))}?" ) sel_engine = self.engines[engine_to_use] est_time = sel_engine.estimate_query(query) else: # Get heuristics from all the query engines to perform this query estimates = map(lambda qe: (qe, qe.estimate_query(query)), self.engines.values()) # Ignore query engines that can't perform this query valid_estimates = filter(lambda qe: qe[1] is not None, estimates) try: # Find the "best" engine to perform the query # NOTE: Sorted by fastest time heuristic sel_engine, est_time = min(valid_estimates, key=lambda qe: qe[1]) # type: ignore except ValueError as e: raise QueryEngineError("No query engines are available.") from e # Go fetch the result from the engine sel_engine_name = getattr(type(sel_engine), "__name__", None) query_type_name = getattr(type(query), "__name__", None) if not sel_engine_name: logger.error("Engine type unknown") if not query_type_name: logger.error("Query type unknown") if sel_engine_name and query_type_name: logger.debug(f"{sel_engine_name}: {query_type_name}({query})") start_time = time.time_ns() result = sel_engine.perform_query(query) exec_time = (time.time_ns() - start_time) // 1000 if sel_engine_name and query_type_name: logger.debug( f"{sel_engine_name}: {query_type_name}" f" executed in {exec_time} ms (expected: {est_time} ms)" ) # Update any caches for engine in self.engines.values(): if not isinstance(engine, sel_engine.__class__): result, cache_data = tee(result) try: engine.update_cache(query, cache_data) except QueryEngineError as err: logger.error(str(err)) return result
Args: query (``QueryType``): The type of query to execute engine_to_use (Optional[str]): Short-circuit selection logic using a specific engine. Defaults is set by performance-based selection logic. Raises: :class:`~ape.exceptions.QueryEngineError`: When given an invalid or inaccessible ``engine_to_use`` value. Returns: Iterator[``BaseInterfaceModel``]
query
python
ApeWorX/ape
src/ape/managers/query.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/query.py
Apache-2.0
def __setitem__( self, address: AddressType, item: Union[ContractType, ProxyInfoAPI, ContractCreation] ): """ Cache the given contract type. Contracts are cached in memory per session. In live networks, contracts also get cached to disk at ``.ape/{ecosystem_name}/{network_name}/contract_types/{address}.json`` for faster look-up next time. Args: address (AddressType): The on-chain address of the contract. item (ContractType | ProxyInfoAPI | ContractCreation): The contract's type, proxy info, or creation metadata. """ # Note: Can't cache blueprints this way. address = self.provider.network.ecosystem.decode_address(int(address, 16)) if isinstance(item, ContractType): self.cache_contract_type(address, item) elif isinstance(item, ProxyInfoAPI): self.cache_proxy_info(address, item) elif isinstance(item, ContractCreation): self.cache_contract_creation(address, item) elif contract_type := getattr(item, "contract_type", None): self.cache_contract_type(address, contract_type) else: raise TypeError(item)
Cache the given contract type. Contracts are cached in memory per session. In live networks, contracts also get cached to disk at ``.ape/{ecosystem_name}/{network_name}/contract_types/{address}.json`` for faster look-up next time. Args: address (AddressType): The on-chain address of the contract. item (ContractType | ProxyInfoAPI | ContractCreation): The contract's type, proxy info, or creation metadata.
__setitem__
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def cache_contract_type( self, address: AddressType, contract_type: ContractType, ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ): """ Cache a contract type at the given address for the given network. If not connected, you must provider both ``ecosystem_key:`` and ``network_key::``. Args: address (AddressType): The address key. contract_type (ContractType): The contract type to cache. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | None): The network key. Defaults to the connected network's name. """ # Get the cache in a way that doesn't require an active connection. cache = self._get_data_cache( "contract_types", ContractType, ecosystem_key=ecosystem_key, network_key=network_key ) cache[address] = contract_type # NOTE: The txn_hash is not included when caching this way. if name := contract_type.name: self.deployments.cache_deployment( address, name, ecosystem_key=ecosystem_key, network_key=network_key )
Cache a contract type at the given address for the given network. If not connected, you must provider both ``ecosystem_key:`` and ``network_key::``. Args: address (AddressType): The address key. contract_type (ContractType): The contract type to cache. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | None): The network key. Defaults to the connected network's name.
cache_contract_type
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def cache_contract_creation( self, address: AddressType, contract_creation: ContractCreation, ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ): """ Cache a contract creation object. Args: address (AddressType): The address of the contract. contract_creation (ContractCreation): The object to cache. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | None): The network key. Defaults to the connected network's name. """ # Get the cache in a way that doesn't require an active connection. cache = self._get_data_cache( "contract_creation", ContractCreation, ecosystem_key=ecosystem_key, network_key=network_key, ) cache[address] = contract_creation
Cache a contract creation object. Args: address (AddressType): The address of the contract. contract_creation (ContractCreation): The object to cache. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | None): The network key. Defaults to the connected network's name.
cache_contract_creation
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def __delitem__(self, address: AddressType): """ Delete a cached contract. If using a live network, it will also delete the file-cache for the contract. Args: address (AddressType): The address to remove from the cache. """ del self.contract_types[address] self._delete_proxy(address) del self.contract_creations[address]
Delete a cached contract. If using a live network, it will also delete the file-cache for the contract. Args: address (AddressType): The address to remove from the cache.
__delitem__
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def use_temporary_caches(self): """ Create temporary context where there are no cached items. Useful for testing. """ caches = self._caches self._caches = {} with self.deployments.use_temporary_cache(): yield self._caches = caches
Create temporary context where there are no cached items. Useful for testing.
use_temporary_caches
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def cache_deployment( self, contract_instance: ContractInstance, proxy_info: Optional[ProxyInfoAPI] = None, detect_proxy: bool = True, ): """ Cache the given contract instance's type and deployment information. Args: contract_instance (:class:`~ape.contracts.base.ContractInstance`): The contract to cache. proxy_info (Optional[ProxyInfoAPI]): Pass in the proxy info, if it is known, to avoid the potentially expensive look-up. detect_proxy (bool): Set to ``False`` to avoid detecting if the contract is a proxy. """ address = contract_instance.address contract_type = contract_instance.contract_type # may be a proxy # Cache contract type in memory before proxy check, # in case it is needed somewhere. It may get overridden. self.contract_types.memory[address] = contract_type if proxy_info: # Was given proxy info. self._cache_proxy_contract(address, proxy_info, contract_type, contract_instance) elif detect_proxy: # Proxy info was not provided. Use the connected ecosystem to figure it out. if proxy_info := self.provider.network.ecosystem.get_proxy_info(address): # The user is caching a deployment of a proxy with the target already set. self._cache_proxy_contract(address, proxy_info, contract_type, contract_instance) else: # Cache as normal. self.contract_types[address] = contract_type else: # Cache as normal; do not do expensive proxy detection. self.contract_types[address] = contract_type # Cache the deployment now. txn_hash = contract_instance.txn_hash if contract_name := contract_type.name: self.deployments.cache_deployment(address, contract_name, transaction_hash=txn_hash) return contract_type
Cache the given contract instance's type and deployment information. Args: contract_instance (:class:`~ape.contracts.base.ContractInstance`): The contract to cache. proxy_info (Optional[ProxyInfoAPI]): Pass in the proxy info, if it is known, to avoid the potentially expensive look-up. detect_proxy (bool): Set to ``False`` to avoid detecting if the contract is a proxy.
cache_deployment
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def get_creation_metadata(self, address: AddressType) -> Optional[ContractCreation]: """ Get contract creation metadata containing txn_hash, deployer, factory, block. Args: address (AddressType): The address of the contract. Returns: Optional[:class:`~ape.api.query.ContractCreation`] """ if creation := self.contract_creations[address]: return creation # Query and cache. query = ContractCreationQuery(columns=["*"], contract=address) get_creation = self.query_manager.query(query) try: if not (creation := next(get_creation, None)): # type: ignore[arg-type] return None except ApeException: return None self.contract_creations[address] = creation return creation
Get contract creation metadata containing txn_hash, deployer, factory, block. Args: address (AddressType): The address of the contract. Returns: Optional[:class:`~ape.api.query.ContractCreation`]
get_creation_metadata
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def get_multiple( self, addresses: Collection[AddressType], concurrency: Optional[int] = None ) -> dict[AddressType, ContractType]: """ Get contract types for all given addresses. Args: addresses (list[AddressType): A list of addresses to get contract types for. concurrency (Optional[int]): The number of threads to use. Defaults to ``min(4, len(addresses))``. Returns: dict[AddressType, ContractType]: A mapping of addresses to their respective contract types. """ if not addresses: logger.warning("No addresses provided.") return {} def get_contract_type(addr: AddressType): addr = self.conversion_manager.convert(addr, AddressType) ct = self.get(addr) if not ct: logger.warning(f"Failed to locate contract at '{addr}'.") return addr, None else: return addr, ct converted_addresses: list[AddressType] = [] for address in converted_addresses: if not self.conversion_manager.is_type(address, AddressType): converted_address = self.conversion_manager.convert(address, AddressType) converted_addresses.append(converted_address) else: converted_addresses.append(address) contract_types = {} default_max_threads = 4 max_threads = ( concurrency if concurrency is not None else min(len(addresses), default_max_threads) or default_max_threads ) with ThreadPoolExecutor(max_workers=max_threads) as pool: for address, contract_type in pool.map(get_contract_type, addresses): if contract_type is None: continue contract_types[address] = contract_type return contract_types
Get contract types for all given addresses. Args: addresses (list[AddressType): A list of addresses to get contract types for. concurrency (Optional[int]): The number of threads to use. Defaults to ``min(4, len(addresses))``. Returns: dict[AddressType, ContractType]: A mapping of addresses to their respective contract types.
get_multiple
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def get( self, address: AddressType, default: Optional[ContractType] = None, fetch_from_explorer: bool = True, proxy_info: Optional[ProxyInfoAPI] = None, detect_proxy: bool = True, ) -> Optional[ContractType]: """ Get a contract type by address. If the contract is cached, it will return the contract from the cache. Otherwise, if on a live network, it fetches it from the :class:`~ape.api.explorers.ExplorerAPI`. Args: address (AddressType): The address of the contract. default (Optional[ContractType]): A default contract when none is found. Defaults to ``None``. fetch_from_explorer (bool): Set to ``False`` to avoid fetching from an explorer. Defaults to ``True``. Only fetches if it needs to (uses disk & memory caching otherwise). proxy_info (Optional[ProxyInfoAPI]): Pass in the proxy info, if it is known, to avoid the potentially expensive look-up. detect_proxy (bool): Set to ``False`` to avoid detecting if it is a proxy. Returns: Optional[ContractType]: The contract type if it was able to get one, otherwise the default parameter. """ try: address_key: AddressType = self.conversion_manager.convert(address, AddressType) except ConversionError: if not address.startswith("0x"): # Still raise conversion errors for ENS and such. raise # In this case, it at least _looked_ like an address. return None if contract_type := self.contract_types[address_key]: # The ContractType was previously cached. if default and default != contract_type: # The given default ContractType is different than the cached one. # Merge the two and cache the merged result. combined_contract_type = _merge_contract_types(contract_type, default) self.contract_types[address_key] = combined_contract_type return combined_contract_type return contract_type # Contract is not cached yet. Check broader sources, such as an explorer. if not proxy_info and detect_proxy: # Proxy info not provided. Attempt to detect. if not (proxy_info := self.proxy_infos[address_key]): if proxy_info := self.provider.network.ecosystem.get_proxy_info(address_key): self.proxy_infos[address_key] = proxy_info if proxy_info: if proxy_contract_type := self._get_proxy_contract_type( address_key, proxy_info, fetch_from_explorer=fetch_from_explorer, default=default, ): # `proxy_contract_type` is one of the following: # 1. A ContractType with the combined proxy and implementation ABIs # 2. Implementation-only ABI ContractType (like forwarder proxies) # 3. Proxy only ABI (e.g. unverified implementation ContractType) return proxy_contract_type # Also gets cached to disk for faster lookup next time. if fetch_from_explorer: contract_type = self._get_contract_type_from_explorer(address_key) # Cache locally for faster in-session look-up. if contract_type: self.contract_types[address_key] = contract_type elif default: self.contract_types[address_key] = default return default return contract_type
Get a contract type by address. If the contract is cached, it will return the contract from the cache. Otherwise, if on a live network, it fetches it from the :class:`~ape.api.explorers.ExplorerAPI`. Args: address (AddressType): The address of the contract. default (Optional[ContractType]): A default contract when none is found. Defaults to ``None``. fetch_from_explorer (bool): Set to ``False`` to avoid fetching from an explorer. Defaults to ``True``. Only fetches if it needs to (uses disk & memory caching otherwise). proxy_info (Optional[ProxyInfoAPI]): Pass in the proxy info, if it is known, to avoid the potentially expensive look-up. detect_proxy (bool): Set to ``False`` to avoid detecting if it is a proxy. Returns: Optional[ContractType]: The contract type if it was able to get one, otherwise the default parameter.
get
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def _get_proxy_contract_type( self, address: AddressType, proxy_info: ProxyInfoAPI, fetch_from_explorer: bool = True, default: Optional[ContractType] = None, ) -> Optional[ContractType]: """ Combines the discoverable ABIs from the proxy contract and its implementation. """ implementation_contract_type = self._get_contract_type( proxy_info.target, fetch_from_explorer=fetch_from_explorer, default=default, ) proxy_contract_type = self._get_contract_type( address, fetch_from_explorer=fetch_from_explorer ) if proxy_contract_type is not None and implementation_contract_type is not None: combined_contract = _get_combined_contract_type( proxy_contract_type, proxy_info, implementation_contract_type ) self.contract_types[address] = combined_contract return combined_contract elif implementation_contract_type is not None: contract_type_to_cache = implementation_contract_type self.contract_types[address] = implementation_contract_type return contract_type_to_cache elif proxy_contract_type is not None: # In this case, the implementation ContactType was not discovered. # However, we were able to discover the ContractType of the proxy. # Proceed with caching the proxy; the user can update the type later # when the implementation is discoverable. self.contract_types[address] = proxy_contract_type return proxy_contract_type logger.warning(f"Unable to determine the ContractType for the proxy at '{address}'.") return None
Combines the discoverable ABIs from the proxy contract and its implementation.
_get_proxy_contract_type
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def _get_contract_type( self, address: AddressType, fetch_from_explorer: bool = True, default: Optional[ContractType] = None, ) -> Optional[ContractType]: """ Get the _exact_ ContractType for a given address. For proxy contracts, returns the proxy ABIs if there are any and not the implementation ABIs. """ if contract_type := self.contract_types[address]: return contract_type elif fetch_from_explorer: return self._get_contract_type_from_explorer(address) return default
Get the _exact_ ContractType for a given address. For proxy contracts, returns the proxy ABIs if there are any and not the implementation ABIs.
_get_contract_type
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def instance_at( self, address: Union[str, AddressType], contract_type: Optional[ContractType] = None, txn_hash: Optional[Union[str, "HexBytes"]] = None, abi: Optional[Union[list[ABI], dict, str, Path]] = None, fetch_from_explorer: bool = True, proxy_info: Optional[ProxyInfoAPI] = None, detect_proxy: bool = True, ) -> ContractInstance: """ Get a contract at the given address. If the contract type of the contract is known, either from a local deploy or a :class:`~ape.api.explorers.ExplorerAPI`, it will use that contract type. You can also provide the contract type from which it will cache and use next time. Raises: TypeError: When passing an invalid type for the `contract_type` arguments (expects `ContractType`). :class:`~ape.exceptions.ContractNotFoundError`: When the contract type is not found. Args: address (Union[str, AddressType]): The address of the plugin. If you are using the ENS plugin, you can also provide an ENS domain name. contract_type (Optional[``ContractType``]): Optionally provide the contract type in case it is not already known. txn_hash (Optional[Union[str, HexBytes]]): The hash of the transaction responsible for deploying the contract, if known. Useful for publishing. Defaults to ``None``. abi (Optional[Union[list[ABI], dict, str, Path]]): Use an ABI str, dict, path, or ethpm models to create a contract instance class. fetch_from_explorer (bool): Set to ``False`` to avoid fetching from the explorer. Defaults to ``True``. Won't fetch unless it needs to (uses disk & memory caching first). proxy_info (Optional[ProxyInfoAPI]): Pass in the proxy info, if it is known, to avoid the potentially expensive look-up. detect_proxy (bool): Set to ``False`` to avoid detecting if the contract is a proxy. Returns: :class:`~ape.contracts.base.ContractInstance` """ if contract_type and not isinstance(contract_type, ContractType): prefix = f"Expected type '{ContractType.__name__}' for argument 'contract_type'" try: suffix = f"; Given '{type(contract_type).__name__}'." except Exception: suffix = "." raise TypeError(f"{prefix}{suffix}") try: contract_address = self.conversion_manager.convert(address, AddressType) except ConversionError: # Attempt as str. raise ValueError(f"Unknown address value '{address}'.") try: # Always attempt to get an existing contract type to update caches contract_type = self.get( contract_address, default=contract_type, fetch_from_explorer=fetch_from_explorer, proxy_info=proxy_info, detect_proxy=detect_proxy, ) except Exception as err: if contract_type or abi: # If a default contract type was provided, don't error and use it. logger.error(str(err)) else: raise # Current exception if abi: # if the ABI is a str then convert it to a JSON dictionary. if isinstance(abi, Path) or ( isinstance(abi, str) and "{" not in abi and Path(abi).is_file() ): # Handle both absolute and relative paths abi_path = Path(abi) if not abi_path.is_absolute(): abi_path = self.local_project.path / abi try: abi = json.loads(abi_path.read_text()) except Exception as err: if contract_type: # If a default contract type was provided, don't error and use it. logger.error(str(err)) else: raise # Current exception elif isinstance(abi, str): # JSON str try: abi = json.loads(abi) except Exception as err: if contract_type: # If a default contract type was provided, don't error and use it. logger.error(str(err)) else: raise # Current exception # If the ABI was a str, it should be a list now. if isinstance(abi, list): contract_type = ContractType(abi=abi) # Ensure we cache the contract-types from ABI! self[contract_address] = contract_type else: raise TypeError( f"Invalid ABI type '{type(abi)}', expecting str, list[ABI] or a JSON file." ) if not contract_type: raise ContractNotFoundError( contract_address, self.provider.network.explorer is not None, self.provider.network_choice, ) if not txn_hash: # Check for txn_hash in deployments. contract_name = getattr(contract_type, "name", f"{contract_type}") or "" deployments = self.deployments[contract_name] for deployment in deployments[::-1]: if deployment.address == contract_address and deployment.transaction_hash: txn_hash = deployment.transaction_hash break return ContractInstance(contract_address, contract_type, txn_hash=txn_hash)
Get a contract at the given address. If the contract type of the contract is known, either from a local deploy or a :class:`~ape.api.explorers.ExplorerAPI`, it will use that contract type. You can also provide the contract type from which it will cache and use next time. Raises: TypeError: When passing an invalid type for the `contract_type` arguments (expects `ContractType`). :class:`~ape.exceptions.ContractNotFoundError`: When the contract type is not found. Args: address (Union[str, AddressType]): The address of the plugin. If you are using the ENS plugin, you can also provide an ENS domain name. contract_type (Optional[``ContractType``]): Optionally provide the contract type in case it is not already known. txn_hash (Optional[Union[str, HexBytes]]): The hash of the transaction responsible for deploying the contract, if known. Useful for publishing. Defaults to ``None``. abi (Optional[Union[list[ABI], dict, str, Path]]): Use an ABI str, dict, path, or ethpm models to create a contract instance class. fetch_from_explorer (bool): Set to ``False`` to avoid fetching from the explorer. Defaults to ``True``. Won't fetch unless it needs to (uses disk & memory caching first). proxy_info (Optional[ProxyInfoAPI]): Pass in the proxy info, if it is known, to avoid the potentially expensive look-up. detect_proxy (bool): Set to ``False`` to avoid detecting if the contract is a proxy. Returns: :class:`~ape.contracts.base.ContractInstance`
instance_at
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def instance_from_receipt( cls, receipt: "ReceiptAPI", contract_type: ContractType ) -> ContractInstance: """ A convenience method for creating instances from receipts. Args: receipt (:class:`~ape.api.transactions.ReceiptAPI`): The receipt. contract_type (ContractType): The deployed contract type. Returns: :class:`~ape.contracts.base.ContractInstance` """ # NOTE: Mostly just needed this method to avoid a local import. return ContractInstance.from_receipt(receipt, contract_type)
A convenience method for creating instances from receipts. Args: receipt (:class:`~ape.api.transactions.ReceiptAPI`): The receipt. contract_type (ContractType): The deployed contract type. Returns: :class:`~ape.contracts.base.ContractInstance`
instance_from_receipt
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def get_deployments(self, contract_container: ContractContainer) -> list[ContractInstance]: """ Retrieves previous deployments of a contract container or contract type. Locally deployed contracts are saved for the duration of the script and read from ``_local_deployments_mapping``, while those deployed on a live network are written to disk in ``deployments_map.json``. Args: contract_container (:class:`~ape.contracts.ContractContainer`): The ``ContractContainer`` with deployments. Returns: list[:class:`~ape.contracts.ContractInstance`]: Returns a list of contracts that have been deployed. """ contract_type = contract_container.contract_type if not (contract_name := contract_type.name or ""): return [] config_deployments = self._get_config_deployments(contract_name) if not (deployments := [*config_deployments, *self.deployments[contract_name]]): return [] instances: list[ContractInstance] = [] for deployment in deployments: instance = ContractInstance( deployment.address, contract_type, txn_hash=deployment.transaction_hash ) instances.append(instance) return instances
Retrieves previous deployments of a contract container or contract type. Locally deployed contracts are saved for the duration of the script and read from ``_local_deployments_mapping``, while those deployed on a live network are written to disk in ``deployments_map.json``. Args: contract_container (:class:`~ape.contracts.ContractContainer`): The ``ContractContainer`` with deployments. Returns: list[:class:`~ape.contracts.ContractInstance`]: Returns a list of contracts that have been deployed.
get_deployments
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def clear_local_caches(self): """ Reset local caches to a blank state. """ if self.network_manager.connected: for cache in ( self.contract_types, self.proxy_infos, self.contract_creations, self.blueprints, ): cache.memory = {} self.deployments.clear_local()
Reset local caches to a blank state.
clear_local_caches
python
ApeWorX/ape
src/ape/managers/_contractscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_contractscache.py
Apache-2.0
def get_deployments( self, contract_name: str, ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ) -> list[Deployment]: """ Get the deployments of the given contract on the currently connected network. Args: contract_name (str): The name of the deployed contract. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | None): The network key. Defaults to the connected network's name. Returns: list[Deployment] """ if not self.network_manager.connected and (not ecosystem_key or not network_key): # Allows it to work when not connected (testing?) return [] ecosystem_name = ecosystem_key or self.provider.network.ecosystem.name network_name = network_key or self.provider.network.name.replace("-fork", "") return ( self._all_deployments.ecosystems.get(ecosystem_name, {}) .get(network_name, {}) .get(contract_name, []) )
Get the deployments of the given contract on the currently connected network. Args: contract_name (str): The name of the deployed contract. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | None): The network key. Defaults to the connected network's name. Returns: list[Deployment]
get_deployments
python
ApeWorX/ape
src/ape/managers/_deploymentscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_deploymentscache.py
Apache-2.0
def cache_deployment( self, address: AddressType, contract_name: str, transaction_hash: Optional[str] = None, ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ): """ Update the deployments cache with a new contract. Args: address (AddressType): The address of the contract. contract_name (str): The name of the contract type. transaction_hash (Optional[str]): Optionally, the transaction has associated with the deployment transaction. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | None): The network key. Defaults to the connected network's name. """ deployments = [ *self.get_deployments(contract_name), Deployment(address=address, transaction_hash=transaction_hash), ] self._set_deployments( contract_name, deployments, ecosystem_key=ecosystem_key, network_key=network_key, )
Update the deployments cache with a new contract. Args: address (AddressType): The address of the contract. contract_name (str): The name of the contract type. transaction_hash (Optional[str]): Optionally, the transaction has associated with the deployment transaction. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | None): The network key. Defaults to the connected network's name.
cache_deployment
python
ApeWorX/ape
src/ape/managers/_deploymentscache.py
https://github.com/ApeWorX/ape/blob/master/src/ape/managers/_deploymentscache.py
Apache-2.0
def account_types( # type: ignore[empty-body] self, ) -> tuple[type["AccountContainerAPI"], type["AccountAPI"]]: """ A hook for returning a tuple of an account container and an account type. Each account-base plugin defines and returns their own types here. Usage example:: @plugins.register(plugins.AccountPlugin) def account_types(): return AccountContainer, KeyfileAccount Returns: tuple[type[:class:`~ape.api.accounts.AccountContainerAPI`], type[:class:`~ape.api.accounts.AccountAPI`]] """
A hook for returning a tuple of an account container and an account type. Each account-base plugin defines and returns their own types here. Usage example:: @plugins.register(plugins.AccountPlugin) def account_types(): return AccountContainer, KeyfileAccount Returns: tuple[type[:class:`~ape.api.accounts.AccountContainerAPI`], type[:class:`~ape.api.accounts.AccountAPI`]]
account_types
python
ApeWorX/ape
src/ape/plugins/account.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/account.py
Apache-2.0
def register_compiler( # type: ignore[empty-body] self, ) -> tuple[tuple[str], type["CompilerAPI"]]: """ A hook for returning the set of file extensions the plugin handles and the compiler class that can be used to compile them. Usage example:: @plugins.register(plugins.CompilerPlugin) def register_compiler(): return (".json",), InterfaceCompiler Returns: tuple[tuple[str], type[:class:`~ape.api.CompilerAPI`]] """
A hook for returning the set of file extensions the plugin handles and the compiler class that can be used to compile them. Usage example:: @plugins.register(plugins.CompilerPlugin) def register_compiler(): return (".json",), InterfaceCompiler Returns: tuple[tuple[str], type[:class:`~ape.api.CompilerAPI`]]
register_compiler
python
ApeWorX/ape
src/ape/plugins/compiler.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/compiler.py
Apache-2.0
def config_class(self) -> type["PluginConfig"]: # type: ignore[empty-body] """ A hook that returns a :class:`~ape.api.config.PluginConfig` parser class that can be used to deconstruct the user config options for this plugins. **NOTE**: If none are specified, all injected :class:`ape.api.config.PluginConfig`'s are empty. Usage example:: @plugins.register(plugins.Config) def config_class(): return MyPluginConfig Returns: type[:class:`~ape.api.config.PluginConfig`] """
A hook that returns a :class:`~ape.api.config.PluginConfig` parser class that can be used to deconstruct the user config options for this plugins. **NOTE**: If none are specified, all injected :class:`ape.api.config.PluginConfig`'s are empty. Usage example:: @plugins.register(plugins.Config) def config_class(): return MyPluginConfig Returns: type[:class:`~ape.api.config.PluginConfig`]
config_class
python
ApeWorX/ape
src/ape/plugins/config.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/config.py
Apache-2.0
def converters(self) -> Iterator[tuple[str, type["ConverterAPI"]]]: # type: ignore[empty-body] """ A hook that returns an iterator of tuples of a string ABI type and a ``ConverterAPI`` subclass. Usage example:: @plugins.register(plugins.ConversionPlugin) def converters(): yield int, MweiConversions Returns: Iterator[tuple[str, type[:class:`~ape.api.convert.ConverterAPI`]]] """
A hook that returns an iterator of tuples of a string ABI type and a ``ConverterAPI`` subclass. Usage example:: @plugins.register(plugins.ConversionPlugin) def converters(): yield int, MweiConversions Returns: Iterator[tuple[str, type[:class:`~ape.api.convert.ConverterAPI`]]]
converters
python
ApeWorX/ape
src/ape/plugins/converter.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/converter.py
Apache-2.0
def ecosystems(self) -> Iterator[type["EcosystemAPI"]]: # type: ignore[empty-body] """ A hook that must return an iterator of :class:`ape.api.networks.EcosystemAPI` subclasses. Usage example:: @plugins.register(plugins.EcosystemPlugin) def ecosystems(): yield Ethereum Returns: Iterator[type[:class:`~ape.api.networks.EcosystemAPI`]] """
A hook that must return an iterator of :class:`ape.api.networks.EcosystemAPI` subclasses. Usage example:: @plugins.register(plugins.EcosystemPlugin) def ecosystems(): yield Ethereum Returns: Iterator[type[:class:`~ape.api.networks.EcosystemAPI`]]
ecosystems
python
ApeWorX/ape
src/ape/plugins/network.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/network.py
Apache-2.0
def networks(self) -> Iterator[tuple[str, str, type["NetworkAPI"]]]: # type: ignore[empty-body] """ A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network name * a :class:`ape.api.networks.NetworkAPI` subclass Usage example:: @plugins.register(plugins.NetworkPlugin) def networks(): yield "ethereum", "ShibaChain", ShibaNetwork Returns: Iterator[tuple[str, str, type[:class:`~ape.api.networks.NetworkAPI`]]] """
A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network name * a :class:`ape.api.networks.NetworkAPI` subclass Usage example:: @plugins.register(plugins.NetworkPlugin) def networks(): yield "ethereum", "ShibaChain", ShibaNetwork Returns: Iterator[tuple[str, str, type[:class:`~ape.api.networks.NetworkAPI`]]]
networks
python
ApeWorX/ape
src/ape/plugins/network.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/network.py
Apache-2.0
def providers( # type: ignore[empty-body] self, ) -> Iterator[tuple[str, str, type["ProviderAPI"]]]: """ A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network it works with (which must be valid network in the ecosystem) * a :class:`ape.api.providers.ProviderAPI` subclass Usage example:: @plugins.register(plugins.ProviderPlugin) def providers(): yield "ethereum", "local", MyProvider Returns: Iterator[tuple[str, str, type[:class:`~ape.api.providers.ProviderAPI`]]] """
A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network it works with (which must be valid network in the ecosystem) * a :class:`ape.api.providers.ProviderAPI` subclass Usage example:: @plugins.register(plugins.ProviderPlugin) def providers(): yield "ethereum", "local", MyProvider Returns: Iterator[tuple[str, str, type[:class:`~ape.api.providers.ProviderAPI`]]]
providers
python
ApeWorX/ape
src/ape/plugins/network.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/network.py
Apache-2.0
def explorers( # type: ignore[empty-body] self, ) -> Iterator[tuple[str, str, type["ExplorerAPI"]]]: """ A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network it works with (which must be valid network in the ecosystem) * a :class:`~ape.api.explorers.ExplorerAPI` subclass Usage example:: @plugins.register(plugins.ExplorerPlugin) def explorers(): yield "ethereum", "mainnet", MyBlockExplorer Returns: Iterator[tuple[str, str, type[:class:`ape.api.explorers.ExplorerAPI`]]] """
A hook that must return an iterator of tuples of: * the target ecosystem plugin's name * the network it works with (which must be valid network in the ecosystem) * a :class:`~ape.api.explorers.ExplorerAPI` subclass Usage example:: @plugins.register(plugins.ExplorerPlugin) def explorers(): yield "ethereum", "mainnet", MyBlockExplorer Returns: Iterator[tuple[str, str, type[:class:`ape.api.explorers.ExplorerAPI`]]]
explorers
python
ApeWorX/ape
src/ape/plugins/network.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/network.py
Apache-2.0
def projects(self) -> Iterator[type["ProjectAPI"]]: # type: ignore[empty-body] """ A hook that returns a :class:`~ape.api.projects.ProjectAPI` subclass type. Returns: type[:class:`~ape.api.projects.ProjectAPI`] """
A hook that returns a :class:`~ape.api.projects.ProjectAPI` subclass type. Returns: type[:class:`~ape.api.projects.ProjectAPI`]
projects
python
ApeWorX/ape
src/ape/plugins/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/project.py
Apache-2.0
def dependencies(self) -> dict[str, type["DependencyAPI"]]: # type: ignore[empty-body] """ A hook that returns a :class:`~ape.api.projects.DependencyAPI` mapped to its ``ape-config.yaml`` file dependencies special key. For example, when configuring GitHub dependencies, you set the ``github`` key in the ``dependencies:`` block of your ``ape-config.yaml`` file and it will automatically use this ``DependencyAPI`` implementation. Returns: type[:class:`~ape.api.projects.DependencyAPI`] """
A hook that returns a :class:`~ape.api.projects.DependencyAPI` mapped to its ``ape-config.yaml`` file dependencies special key. For example, when configuring GitHub dependencies, you set the ``github`` key in the ``dependencies:`` block of your ``ape-config.yaml`` file and it will automatically use this ``DependencyAPI`` implementation. Returns: type[:class:`~ape.api.projects.DependencyAPI`]
dependencies
python
ApeWorX/ape
src/ape/plugins/project.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/project.py
Apache-2.0
def query_engines(self) -> Iterator[type["QueryAPI"]]: # type: ignore[empty-body] """ A hook that returns an iterator of types of a ``QueryAPI`` subclasses Usage example:: @plugins.register(plugins.QueryPlugin) def query_engines(): yield PostgresEngine Returns: Iterator[type[:class:`~ape.api.query.QueryAPI`]] """
A hook that returns an iterator of types of a ``QueryAPI`` subclasses Usage example:: @plugins.register(plugins.QueryPlugin) def query_engines(): yield PostgresEngine Returns: Iterator[type[:class:`~ape.api.query.QueryAPI`]]
query_engines
python
ApeWorX/ape
src/ape/plugins/query.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/query.py
Apache-2.0
def install_str(self) -> str: """ The strings you pass to ``pip`` to make the install request, such as ``ape-trezor==0.4.0``. """ if self.version and self.version.startswith("git+"): # If the version is a remote, you do `pip install git+http://github...` return self.version # `pip install ape-plugin` # `pip install ape-plugin==version`. # `pip install "ape-plugin>=0.6,<0.7"` version = self.version if version: if not any(x in version for x in ("=", "<", ">")): version = f"=={version}" # Validate we are not attempting to install a plugin # that would change the core-Ape version. if ape_version.would_get_downgraded(version): raise PluginVersionError( "install", "Doing so will downgrade Ape's version.", "Downgrade Ape first." ) elif not version: # When not specifying the version, use a default one that # won't dramatically change Ape's version. version = ape_version.version_range return f"{self.package_name}{version}" if version else self.package_name
The strings you pass to ``pip`` to make the install request, such as ``ape-trezor==0.4.0``.
install_str
python
ApeWorX/ape
src/ape/plugins/_utils.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/_utils.py
Apache-2.0
def can_install(self) -> bool: """ ``True`` if the plugin is available and the requested version differs from the installed one. **NOTE**: Is always ``True`` when the plugin is not installed. """ requesting_different_version = ( self.version is not None and self.version != self.current_version ) return not self.is_installed or requesting_different_version
``True`` if the plugin is available and the requested version differs from the installed one. **NOTE**: Is always ``True`` when the plugin is not installed.
can_install
python
ApeWorX/ape
src/ape/plugins/_utils.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/_utils.py
Apache-2.0
def prepare_package_manager_args( self, verb: str, python_location: Optional[str] = None, extra_args: Optional[Iterable[str]] = None, ) -> list[str]: """ Build command arguments for pip or uv package managers. Usage: args = prepare_package_manager_args("install", "/path/to/python", ["--user"]) """ extra_args = list(extra_args) if extra_args else [] command = list(self.pip_command) if command[0] == "uv": return ( [*command, verb, "--python", python_location] + extra_args if python_location else [*command, verb, *extra_args] ) return ( [*command, "--python", python_location, verb] + extra_args if python_location else [*command, verb, *extra_args] )
Build command arguments for pip or uv package managers. Usage: args = prepare_package_manager_args("install", "/path/to/python", ["--user"])
prepare_package_manager_args
python
ApeWorX/ape
src/ape/plugins/_utils.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/_utils.py
Apache-2.0
def register(plugin_type: type[PluginType], **hookimpl_kwargs) -> Callable: """ Register your plugin to ape. You must call this decorator to get your plugins included in ape's plugin ecosystem. Usage example:: @plugins.register(plugins.AccountPlugin) # 'register()' example def account_types(): return AccountContainer, KeyfileAccount Args: plugin_type (type[:class:`~ape.plugins.pluggy_patch.PluginType`]): The plugin type to register. hookimpl_kwargs: Return-values required by the plugin type. Returns: Callable """ # NOTE: we are basically checking that `plugin_type` # is one of the parent classes of `Plugins` if not issubclass(AllPluginHooks, plugin_type): raise PluginError("Not a valid plugin type to register.") def check_hook(plugin_type, hookimpl_kwargs, fn): fn = hookimpl(fn, **hookimpl_kwargs) if not hasattr(plugin_type, fn.__name__): hooks = get_hooks(plugin_type) raise PluginError( f"Registered function `{fn.__name__}` is not" f" a valid hook for {plugin_type.__name__}, must be one of:" f" {hooks}." ) return fn # NOTE: Get around issue with using `plugin_type` raw in `check_hook` return functools.partial(check_hook, plugin_type, hookimpl_kwargs)
Register your plugin to ape. You must call this decorator to get your plugins included in ape's plugin ecosystem. Usage example:: @plugins.register(plugins.AccountPlugin) # 'register()' example def account_types(): return AccountContainer, KeyfileAccount Args: plugin_type (type[:class:`~ape.plugins.pluggy_patch.PluginType`]): The plugin type to register. hookimpl_kwargs: Return-values required by the plugin type. Returns: Callable
register
python
ApeWorX/ape
src/ape/plugins/__init__.py
https://github.com/ApeWorX/ape/blob/master/src/ape/plugins/__init__.py
Apache-2.0
def gas_exclusions(self) -> list["ContractFunctionPath"]: """ The combination of both CLI values and config values. """ from ape.types.trace import ContractFunctionPath cli_value = self.pytest_config.getoption("--gas-exclude") exclusions = ( [ContractFunctionPath.from_str(item) for item in cli_value.split(",")] if cli_value else [] ) paths = _get_config_exclusions(self.ape_test_config.gas) exclusions.extend(paths) return exclusions
The combination of both CLI values and config values.
gas_exclusions
python
ApeWorX/ape
src/ape/pytest/config.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/config.py
Apache-2.0
def _check_dev_message(self, exception: ContractLogicError): """ Attempts to extract a dev-message from the contract source code by inspecting what instruction(s) led to a transaction revert. Raises: AssertionError: When the trace or source can not be retrieved, the dev message cannot be found, or the found dev message does not match the expected dev message. """ try: dev_message = exception.dev_message except ValueError as err: raise AssertionError(str(err)) from err if dev_message is None: err_message = "Could not find the source of the revert." # Attempt to show source traceback so the user can see the real failure. if (info := self.revert_info) and (ex := info.value): if tb := ex.source_traceback: err_message = f"{err_message}\n{tb}" raise AssertionError(err_message) if not ( (self.dev_message.match(dev_message) is not None) if isinstance(self.dev_message, re.Pattern) else (dev_message == self.dev_message) ): assertion_error_message = ( self.dev_message.pattern if isinstance(self.dev_message, re.Pattern) else self.dev_message ) assertion_error_prefix = f"Expected dev revert message '{assertion_error_message}'" raise AssertionError(f"{assertion_error_prefix} but got '{dev_message}'.")
Attempts to extract a dev-message from the contract source code by inspecting what instruction(s) led to a transaction revert. Raises: AssertionError: When the trace or source can not be retrieved, the dev message cannot be found, or the found dev message does not match the expected dev message.
_check_dev_message
python
ApeWorX/ape
src/ape/pytest/contextmanagers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/contextmanagers.py
Apache-2.0
def _check_expected_message(self, exception: ContractLogicError): """ Compares the revert message given by the exception to the expected message. Raises: AssertionError: When the exception message is ``None`` or if the message does not match the expected message. """ actual = exception.revert_message assertion_error_message = ( self.expected_message.pattern if isinstance(self.expected_message, re.Pattern) else self.expected_message ) assertion_error_prefix = f"Expected revert message '{assertion_error_message}'" message_matches = ( (self.expected_message.match(actual) is not None) if isinstance(self.expected_message, re.Pattern) else (actual == self.expected_message) ) if not message_matches: if actual == TransactionError.DEFAULT_MESSAGE: # The transaction failed without a revert message # but the user is expecting one. raise AssertionError(f"{assertion_error_prefix} but there was none.") raise AssertionError(f"{assertion_error_prefix} but got '{actual}'.")
Compares the revert message given by the exception to the expected message. Raises: AssertionError: When the exception message is ``None`` or if the message does not match the expected message.
_check_expected_message
python
ApeWorX/ape
src/ape/pytest/contextmanagers.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/contextmanagers.py
Apache-2.0
def cover( self, traceback: "SourceTraceback", contract: Optional[str] = None, function: Optional[str] = None, ): """ Track the coverage from the given source traceback. Args: traceback (:class:`~ape.types.trace.SourceTraceback`): The class instance containing all the information regarding sources covered for a particular transaction. contract (Optional[str]): Optionally provide the contract's name. This is needed when incrementing function hits that don't have any statements, such as auto-getters. function (Optional[str]): Optionally include function's full name to ensure its hit count is bumped, even when there are not statements found. This is the only way to bump hit counts for auto-getters. """ if not self.data: return last_path: Optional[Path] = None last_pcs: set[int] = set() last_call: Optional[str] = None main_fn = None if (contract and not function) or (function and not contract): raise ValueError("Must provide both function and contract if supplying one of them.") elif contract and function: # Make sure it is the actual source. source_path = traceback[0].source_path if len(traceback) > 0 else None for project in self.data.report.projects: for src in project.sources: # NOTE: We will allow this check to skip if there is no source is the # traceback. This helps increment methods that are missing from the source map. path = self._project.path / src.source_id if source_path is not None and path != source_path: continue # Source containing the auto-getter found. for con in src.contracts: if con.name != contract: continue # Contract containing the auto-getter found. for fn in con.functions: if fn.full_name != function: continue # Auto-getter found. main_fn = fn count_at_start = main_fn.hit_count if main_fn else None for control_flow in traceback: if not control_flow.source_path or not control_flow.pcs: continue new_pcs, new_funcs = self._cover( control_flow, last_path=last_path, last_pcs=last_pcs, last_call=last_call ) if new_pcs: last_path = control_flow.source_path last_pcs = new_pcs if new_funcs: last_call = new_funcs[-1] if count_at_start is not None and main_fn and main_fn.hit_count == count_at_start: # If we get here, the control flow had no statements in it but yet # we were given contract and function information. This happens # for auto-getters where there are no source-map entries but the function # is still called. Thus, we need to bump the hit count for the auto-getter. main_fn.hit_count += 1
Track the coverage from the given source traceback. Args: traceback (:class:`~ape.types.trace.SourceTraceback`): The class instance containing all the information regarding sources covered for a particular transaction. contract (Optional[str]): Optionally provide the contract's name. This is needed when incrementing function hits that don't have any statements, such as auto-getters. function (Optional[str]): Optionally include function's full name to ensure its hit count is bumped, even when there are not statements found. This is the only way to bump hit counts for auto-getters.
cover
python
ApeWorX/ape
src/ape/pytest/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/coverage.py
Apache-2.0
def hit_function(self, contract_source: "ContractSource", method: "MethodABI"): """ Another way to increment a function's hit count. Providers may not offer a way to trace calls but this method is available to still increment function hit counts. Args: contract_source (``ContractSource``): A contract with a known source file. method (``MethodABI``): The method called. """ if not self.data: return for project in self.data.report.projects: for src in project.sources: if src.source_id != contract_source.source_id: continue for contract in src.contracts: if contract.name != contract_source.contract_type.name: continue for function in contract.functions: if function.full_name != method.selector: continue function.hit_count += 1 return
Another way to increment a function's hit count. Providers may not offer a way to trace calls but this method is available to still increment function hit counts. Args: contract_source (``ContractSource``): A contract with a known source file. method (``MethodABI``): The method called.
hit_function
python
ApeWorX/ape
src/ape/pytest/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/coverage.py
Apache-2.0
def names(self) -> list[str]: """ Outputs in correct order for item.fixturenames. Also, injects isolation fixtures if needed. """ result = [] for scope, ls in self.items(): # NOTE: For function scoped, we always add the isolation fixture. if not ls and scope is not Scope.FUNCTION: continue result.append(scope.isolation_fixturename) result.extend(ls) return result
Outputs in correct order for item.fixturenames. Also, injects isolation fixtures if needed.
names
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def get_info(self, name: str) -> list: """ Get fixture info. Args: name (str): Returns: list of info """ if name not in self._arg2fixturedefs: return [] return self._arg2fixturedefs[name]
Get fixture info. Args: name (str): Returns: list of info
get_info
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def is_iterating(self, name: str) -> bool: """ True when is a non-function scoped parametrized fixture that hasn't fully iterated. """ if name not in self.parametrized: return False elif not (info_ls := self.get_info(name)): return False for info in info_ls: if not info.params: continue if not info.cached_result: return True # First iteration elif len(info.cached_result) < 2: continue # ? last_param_ran = info.cached_result[1] last_param = info.params[-1] if last_param_ran != last_param: return True # Is iterating. return False
True when is a non-function scoped parametrized fixture that hasn't fully iterated.
is_iterating
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def isolation(self, scope: Scope) -> Iterator[None]: """ Isolation logic used to implement isolation fixtures for each pytest scope. When tracing support is available, will also assist in capturing receipts. """ self.set_snapshot(scope) if self._track_transactions: did_yield = False try: with self.receipt_capture: yield did_yield = True except BlockNotFoundError: if not did_yield: # Prevent double yielding. yield else: yield self.restore(scope)
Isolation logic used to implement isolation fixtures for each pytest scope. When tracing support is available, will also assist in capturing receipts.
isolation
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def _exclude_from_gas_report( self, contract_name: str, method_name: Optional[str] = None ) -> bool: """ Helper method to determine if a certain contract / method combination should be excluded from the gas report. """ for exclusion in self.config_wrapper.gas_exclusions: # Default to looking at all contracts contract_pattern = exclusion.contract_name if not fnmatch(contract_name, contract_pattern) or not method_name: continue method_pattern = exclusion.method_name if not method_pattern or fnmatch(method_name, method_pattern): return True return False
Helper method to determine if a certain contract / method combination should be excluded from the gas report.
_exclude_from_gas_report
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def fixture(chain_isolation: Optional[bool], **kwargs): """ A thin-wrapper around ``@pytest.fixture`` with extra capabilities. Set ``chain_isolation`` to ``False`` to signal to Ape that this fixture's cached result is the same regardless of block number and it does not need to be invalidated during times or pytest-scoped based chain rebasing. Usage example:: import ape from ape_tokens import tokens @ape.fixture(scope="session", chain_isolation=False, params=("WETH", "DAI", "BAT")) def token_addresses(request): return tokens[request].address """ def decorator(fixture_function): if chain_isolation is not None: name = kwargs.get("name", fixture_function.__name__) FixtureManager._stateful_fixtures_cache[name] = chain_isolation return pytest.fixture(fixture_function, **kwargs) return decorator
A thin-wrapper around ``@pytest.fixture`` with extra capabilities. Set ``chain_isolation`` to ``False`` to signal to Ape that this fixture's cached result is the same regardless of block number and it does not need to be invalidated during times or pytest-scoped based chain rebasing. Usage example:: import ape from ape_tokens import tokens @ape.fixture(scope="session", chain_isolation=False, params=("WETH", "DAI", "BAT")) def token_addresses(request): return tokens[request].address
fixture
python
ApeWorX/ape
src/ape/pytest/fixtures.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/fixtures.py
Apache-2.0
def pytest_exception_interact(self, report, call): """ A ``-I`` option triggers when an exception is raised which can be interactively handled. Outputs the full ``repr`` of the failed test and opens an interactive shell using the same console as the ``ape console`` command. """ # Find the last traceback frame within the active project tb_frames: PytestTraceback = call.excinfo.traceback base = self.local_project.path.as_posix() if self.config_wrapper.show_internal: relevant_tb = list(tb_frames) else: relevant_tb = [ f for f in tb_frames if Path(f.path).as_posix().startswith(base) or Path(f.path).name.startswith("test_") ] if relevant_tb: call.excinfo.traceback = PytestTraceback(relevant_tb) # Only show locals if not digging into the framework's traceback. # Else, it gets way too noisy. show_locals = not self.config_wrapper.show_internal try: here = Path.cwd() except FileNotFoundError: pass # In a temp-folder, most likely. else: report.longrepr = call.excinfo.getrepr( funcargs=True, abspath=here, showlocals=show_locals, style="short", tbfilter=False, truncate_locals=True, chain=False, ) if self.config_wrapper.interactive and report.failed: from ape_console._cli import console traceback = call.excinfo.traceback[-1] # Suspend capsys to ignore our own output. capman = self.config_wrapper.get_pytest_plugin("capturemanager") if capman: capman.suspend_global_capture(in_=True) # Show the exception info before launching the interactive session. click.echo() rich_print(str(report.longrepr)) click.echo() # get global namespace globals_dict = traceback.frame.f_globals # filter python internals and pytest internals globals_dict = { k: v for k, v in globals_dict.items() if not k.startswith("__") and not k.startswith("@") } # filter fixtures globals_dict = { k: v for k, v in globals_dict.items() if not hasattr(v, "_pytestfixturefunction") } # get local namespace locals_dict = traceback.locals locals_dict = {k: v for k, v in locals_dict.items() if not k.startswith("@")} click.echo("Starting interactive mode. Type `exit` to halt current test.") namespace = {"_callinfo": call, **globals_dict, **locals_dict} console(extra_locals=namespace, project=self.local_project, embed=True) if capman: capman.resume_global_capture() if type(call.excinfo.value) in (SystemExit, KeyboardInterrupt): # This will show the rest of Ape Test output as if the # tests had stopped here. pytest.exit("`ape test` exited.")
A ``-I`` option triggers when an exception is raised which can be interactively handled. Outputs the full ``repr`` of the failed test and opens an interactive shell using the same console as the ``ape console`` command.
pytest_exception_interact
python
ApeWorX/ape
src/ape/pytest/runners.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/runners.py
Apache-2.0
def pytest_runtest_setup(self, item): """ By default insert isolation fixtures into each test cases list of fixtures prior to actually executing the test case. https://docs.pytest.org/en/6.2.x/reference.html#pytest.hookspec.pytest_runtest_setup """ if ( not self.config_wrapper.isolation # doctests don't have fixturenames or (hasattr(pytest, "DoctestItem") and isinstance(item, pytest.DoctestItem)) or "_function_isolation" in item.fixturenames # prevent double injection ): # isolation is disabled via cmdline option or running doc-tests. return if self.config_wrapper.isolation: self._setup_isolation(item)
By default insert isolation fixtures into each test cases list of fixtures prior to actually executing the test case. https://docs.pytest.org/en/6.2.x/reference.html#pytest.hookspec.pytest_runtest_setup
pytest_runtest_setup
python
ApeWorX/ape
src/ape/pytest/runners.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/runners.py
Apache-2.0
def pytest_sessionstart(self): """ Called after the `Session` object has been created and before performing collection and entering the run test loop. Removes `PytestAssertRewriteWarning` warnings from the terminalreporter. This prevents warnings that "the `ape` library was already imported and so related assertions cannot be rewritten". The warning is not relevant for end users who are performing tests with ape. """ reporter = self.config_wrapper.get_pytest_plugin("terminalreporter") if not reporter: return warnings = reporter.stats.pop("warnings", []) warnings = [i for i in warnings if "PytestAssertRewriteWarning" not in i.message] if warnings and not self.config_wrapper.disable_warnings: reporter.stats["warnings"] = warnings
Called after the `Session` object has been created and before performing collection and entering the run test loop. Removes `PytestAssertRewriteWarning` warnings from the terminalreporter. This prevents warnings that "the `ape` library was already imported and so related assertions cannot be rewritten". The warning is not relevant for end users who are performing tests with ape.
pytest_sessionstart
python
ApeWorX/ape
src/ape/pytest/runners.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/runners.py
Apache-2.0
def pytest_collection_finish(self, session): """ Called after collection has been performed and modified. """ outcome = yield # Only start provider if collected tests. if not outcome.get_result() and session.items: self._connect()
Called after collection has been performed and modified.
pytest_collection_finish
python
ApeWorX/ape
src/ape/pytest/runners.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/runners.py
Apache-2.0
def pytest_terminal_summary(self, terminalreporter): """ Add a section to terminal summary reporting. When ``--gas`` is active, outputs the gas profile report. """ if self.config_wrapper.track_gas: self._show_gas_report(terminalreporter) if self.config_wrapper.track_coverage: self._show_coverage_report(terminalreporter)
Add a section to terminal summary reporting. When ``--gas`` is active, outputs the gas profile report.
pytest_terminal_summary
python
ApeWorX/ape
src/ape/pytest/runners.py
https://github.com/ApeWorX/ape/blob/master/src/ape/pytest/runners.py
Apache-2.0
def line_rate(self) -> float: """ The number of lines hit divided by number of lines. """ if not self.statements: # If there are no statements, rely on fn hit count only. return 1.0 if self.hit_count > 0 else 0.0 # This function has hittable statements. return self.lines_covered / self.lines_valid if self.lines_valid > 0 else 0
The number of lines hit divided by number of lines.
line_rate
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def profile_statement( self, pc: int, location: Optional[SourceLocation] = None, tag: Optional[str] = None ): """ Initialize a statement in the coverage profile with a hit count starting at zero. This statement is ready to accumulate hits as tests execute. Args: pc (int): The program counter of the statement. location (Optional[ethpm_types.source.SourceStatement]): The location of the statement, if it exists. tag (Optional[str]): Optionally provide more information about the statements being hit. This is useful for builtin statements that may be missing context otherwise. """ for statement in self.statements: if not location or ( location and statement.location and statement.location[0] != location[0] ): # Starts on a different line. continue # Already tracking this location. statement.pcs.add(pc) if not statement.tag: statement.tag = tag return if location: # Adding a source-statement for the first time. coverage_statement = CoverageStatement(location=location, pcs={pc}, tag=tag) else: # Adding a virtual statement. coverage_statement = CoverageStatement(pcs={pc}, tag=tag) if coverage_statement is not None: self.statements.append(coverage_statement)
Initialize a statement in the coverage profile with a hit count starting at zero. This statement is ready to accumulate hits as tests execute. Args: pc (int): The program counter of the statement. location (Optional[ethpm_types.source.SourceStatement]): The location of the statement, if it exists. tag (Optional[str]): Optionally provide more information about the statements being hit. This is useful for builtin statements that may be missing context otherwise.
profile_statement
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def include(self, contract_name: str) -> ContractCoverage: """ Ensure a contract is included in the report. """ for contract in self.contracts: if contract.name == contract_name: return contract # Include the contract. contract_cov = ContractCoverage(name=contract_name) self.contracts.append(contract_cov) return contract_cov
Ensure a contract is included in the report.
include
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def get_xml(self) -> str: """ The coverage XML report as a string. The XML coverage data schema is meant to be compatible with codecov.io. Thus, some of coverage is modified slightly, and some of the naming conventions (based on 90s Java) won't be super relevant to smart-contract projects. """ # See _DTD_URL to learn more about the schema. xml_out = self._get_xml() return xml_out.toprettyxml(indent=" ")
The coverage XML report as a string. The XML coverage data schema is meant to be compatible with codecov.io. Thus, some of coverage is modified slightly, and some of the naming conventions (based on 90s Java) won't be super relevant to smart-contract projects.
get_xml
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def get_html(self, verbose: bool = False) -> str: """ The coverage HTML report as a string. """ html = self._get_html(verbose=verbose) html_str = tostring(html, encoding="utf8", method="html").decode() return _HTMLPrettfier().prettify(html_str)
The coverage HTML report as a string.
get_html
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def prettify(self, html_str: str) -> str: """ This is a custom method not part of the HTMLParser spec that ingests a coverage HTML str, handles the formatting, returns it, and resets this formatter's instance, so that the operation is more functional. """ self.feed(html_str) result = self.prettified_html self.reset() self.indent = 0 self.prettified_html = "<!DOCTYPE html>\n" return result
This is a custom method not part of the HTMLParser spec that ingests a coverage HTML str, handles the formatting, returns it, and resets this formatter's instance, so that the operation is more functional.
prettify
python
ApeWorX/ape
src/ape/types/coverage.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/coverage.py
Apache-2.0
def from_event( cls, event: Union[EventABI, "ContractEvent"], search_topics: Optional[dict[str, Any]] = None, addresses: Optional[list[AddressType]] = None, start_block=None, stop_block=None, ): """ Construct a log filter from an event topic query. """ abi = getattr(event, "abi", event) topic_filter = encode_topics(abi, search_topics or {}) return cls( addresses=addresses or [], events=[abi], topic_filter=topic_filter, start_block=start_block, stop_block=stop_block, )
Construct a log filter from an event topic query.
from_event
python
ApeWorX/ape
src/ape/types/events.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/events.py
Apache-2.0
def __eq__(self, other: Any) -> bool: """ Check for equality between this instance and another ContractLog instance. If the other object is not an instance of ContractLog, this method returns NotImplemented. This triggers the Python interpreter to call the __eq__ method on the other object (i.e., y.__eq__(x)) if it is defined, allowing for a custom comparison. This behavior is leveraged by the MockContractLog class to handle custom comparison logic between ContractLog and MockContractLog instances. Args: other (Any): The object to compare with this instance. Returns: bool: True if the two instances are equal, False otherwise. """ if not isinstance(other, ContractLog): return NotImplemented # call __eq__ on parent class return super().__eq__(other)
Check for equality between this instance and another ContractLog instance. If the other object is not an instance of ContractLog, this method returns NotImplemented. This triggers the Python interpreter to call the __eq__ method on the other object (i.e., y.__eq__(x)) if it is defined, allowing for a custom comparison. This behavior is leveraged by the MockContractLog class to handle custom comparison logic between ContractLog and MockContractLog instances. Args: other (Any): The object to compare with this instance. Returns: bool: True if the two instances are equal, False otherwise.
__eq__
python
ApeWorX/ape
src/ape/types/events.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/events.py
Apache-2.0
def begin_lineno(self) -> Optional[int]: """ The first line number in the sequence. """ stmts = self.source_statements return stmts[0].begin_lineno if stmts else None
The first line number in the sequence.
begin_lineno
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def ws_begin_lineno(self) -> Optional[int]: """ The first line number in the sequence, including whitespace. """ stmts = self.source_statements return stmts[0].ws_begin_lineno if stmts else None
The first line number in the sequence, including whitespace.
ws_begin_lineno
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def line_numbers(self) -> list[int]: """ The list of all line numbers as part of this node. """ if self.begin_lineno is None: return [] elif self.end_lineno is None: return [self.begin_lineno] return list(range(self.begin_lineno, self.end_lineno + 1))
The list of all line numbers as part of this node.
line_numbers
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def extend( self, location: "SourceLocation", pcs: Optional[set[int]] = None, ws_start: Optional[int] = None, ): """ Extend this node's content with other content that follows it directly. Raises: ValueError: When there is a gap in content. Args: location (SourceLocation): The location of the content, in the form (lineno, col_offset, end_lineno, end_coloffset). pcs (Optional[set[int]]): The PC values of the statements. ws_start (Optional[int]): Optionally provide a white-space starting point to back-fill. """ pcs = pcs or set() if ws_start is not None and ws_start > location[0]: # No new lines. return function = self.closure if not isinstance(function, Function): # No source code supported for closure type. return # NOTE: Use non-ws prepending location to fetch AST nodes. asts = function.get_content_asts(location) if not asts: return location = ( (ws_start, location[1], location[2], location[3]) if ws_start is not None else location ) content = function.get_content(location) start = ( max(location[0], self.end_lineno + 1) if self.end_lineno is not None else location[0] ) end = location[0] + len(content) - 1 if end < start: # No new lines. return elif start - end > 1: raise ValueError( "Cannot extend when gap in lines > 1. " "If because of whitespace lines, must include it the given content." ) content_start = len(content) - (end - start) - 1 new_lines = {no: ln.rstrip() for no, ln in content.items() if no >= content_start} if new_lines: # Add the next statement in this sequence. content = Content(root=new_lines) statement = SourceStatement(asts=asts, content=content, pcs=pcs) self.statements.append(statement) else: # Add ASTs to latest statement. self.source_statements[-1].asts.extend(asts) for pc in pcs: self.source_statements[-1].pcs.add(pc)
Extend this node's content with other content that follows it directly. Raises: ValueError: When there is a gap in content. Args: location (SourceLocation): The location of the content, in the form (lineno, col_offset, end_lineno, end_coloffset). pcs (Optional[set[int]]): The PC values of the statements. ws_start (Optional[int]): Optionally provide a white-space starting point to back-fill.
extend
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def format(self, use_arrow: bool = True) -> str: """ Format this trace node into a string presentable to the user. """ # NOTE: Only show last 2 statements. relevant_stmts = self.statements[-2:] content = "" end_lineno = self.content.end_lineno for stmt in relevant_stmts: for lineno, line in getattr(stmt, "content", {}).items(): if not content and not line.strip(): # Prevent starting on whitespace. continue if content: # Add newline to carry over from last. content = f"{content.rstrip()}\n" space = " " if lineno < end_lineno or not use_arrow else " --> " content = f"{content}{space}{lineno} {line}" return content
Format this trace node into a string presentable to the user.
format
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def next_statement(self) -> Optional[SourceStatement]: """ Returns the next statement that _would_ execute if the program were to progress to the next line. """ # Check for more statements that _could_ execute. if not self.source_statements: return None last_stmt = self.source_statements[-1] function = self.closure if not isinstance(function, Function): return None rest_asts = [a for a in function.ast.children if a.lineno > last_stmt.end_lineno] if not rest_asts: # At the end of a function. return None # Filter out to only the ASTs for the next statement. next_stmt_start = min(rest_asts, key=lambda x: x.lineno).lineno next_stmt_asts = [a for a in rest_asts if a.lineno == next_stmt_start] content_dict = {} for ast in next_stmt_asts: sub_content = function.get_content(ast.line_numbers) content_dict = {**sub_content.root} if not content_dict: return None sorted_dict = {k: content_dict[k] for k in sorted(content_dict)} content = Content(root=sorted_dict) return SourceStatement(asts=next_stmt_asts, content=content)
Returns the next statement that _would_ execute if the program were to progress to the next line.
next_statement
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def extend(self, __iterable) -> None: """ Append all the control flows from the given traceback to this one. """ if not isinstance(__iterable, SourceTraceback): raise TypeError("Can only extend another traceback object.") self.root.extend(__iterable.root)
Append all the control flows from the given traceback to this one.
extend
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def format(self) -> str: """ Get a formatted traceback string for displaying to users. """ if not len(self.root): # No calls. return "" header = "Traceback (most recent call last)" indent = " " last_depth = None segments: list[str] = [] for control_flow in reversed(self.root): if last_depth is None or control_flow.depth == last_depth - 1: if control_flow.depth == 0 and len(segments) >= 1: # Ignore 0-layer segments if source code was hit continue last_depth = control_flow.depth content_str = control_flow.format() if not content_str.strip(): continue segment = f"{indent}{control_flow.source_header}\n{control_flow.format()}" # Try to include next statement for display purposes. next_stmt = control_flow.next_statement if next_stmt: if ( next_stmt.begin_lineno is not None and control_flow.end_lineno is not None and next_stmt.begin_lineno > control_flow.end_lineno + 1 ): # Include whitespace. for ws_no in range(control_flow.end_lineno + 1, next_stmt.begin_lineno): function = control_flow.closure if not isinstance(function, Function): continue ws = function.content[ws_no] segment = f"{segment}\n {ws_no} {ws}".rstrip() for no, line in next_stmt.content.items(): segment = f"{segment}\n {no} {line}".rstrip() segments.append(segment) builder = "" for idx, segment in enumerate(reversed(segments)): builder = f"{builder}\n{segment}" if idx < len(segments) - 1: builder = f"{builder}\n" return f"{header}{builder}"
Get a formatted traceback string for displaying to users.
format
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def add_jump( self, location: "SourceLocation", function: Function, depth: int, pcs: Optional[set[int]] = None, source_path: Optional[Path] = None, ): """ Add an execution sequence from a jump. Args: location (``SourceLocation``): The location to add. function (``Function``): The function executing. source_path (Optional[``Path``]): The path of the source file. depth (int): The depth of the function call in the call tree. pcs (Optional[set[int]]): The program counter values. source_path (Optional[``Path``]): The path of the source file. """ asts = function.get_content_asts(location) content = function.get_content(location) if not asts or not content: return pcs = pcs or set() Statement.model_rebuild() ControlFlow.model_rebuild() self._add(asts, content, pcs, function, depth, source_path=source_path)
Add an execution sequence from a jump. Args: location (``SourceLocation``): The location to add. function (``Function``): The function executing. source_path (Optional[``Path``]): The path of the source file. depth (int): The depth of the function call in the call tree. pcs (Optional[set[int]]): The program counter values. source_path (Optional[``Path``]): The path of the source file.
add_jump
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def extend_last(self, location: "SourceLocation", pcs: Optional[set[int]] = None): """ Extend the last node with more content. Args: location (``SourceLocation``): The location of the new content. pcs (Optional[set[int]]): The PC values to add on. """ if not self.last: raise ValueError( "`progress()` should only be called when " "there is at least 1 ongoing execution trail." ) start = ( 1 if self.last is not None and self.last.end_lineno is None else self.last.end_lineno + 1 ) self.last.extend(location, pcs=pcs, ws_start=start)
Extend the last node with more content. Args: location (``SourceLocation``): The location of the new content. pcs (Optional[set[int]]): The PC values to add on.
extend_last
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def add_builtin_jump( self, name: str, _type: str, full_name: Optional[str] = None, source_path: Optional[Path] = None, pcs: Optional[set[int]] = None, ): """ A convenience method for appending a control flow that happened from an internal compiler built-in code. See the ape-vyper plugin for a usage example. Args: name (str): The name of the compiler built-in. _type (str): A str describing the type of check. full_name (Optional[str]): A full-name ID. source_path (Optional[Path]): The source file related, if there is one. pcs (Optional[set[int]]): Program counter values mapping to this check. """ pcs = pcs or set() closure = Closure(name=name, full_name=full_name or name) depth = self.last.depth - 1 if self.last else 0 statement = Statement(type=_type, pcs=pcs) flow = ControlFlow( closure=closure, depth=depth, statements=[statement], source_path=source_path ) self.append(flow)
A convenience method for appending a control flow that happened from an internal compiler built-in code. See the ape-vyper plugin for a usage example. Args: name (str): The name of the compiler built-in. _type (str): A str describing the type of check. full_name (Optional[str]): A full-name ID. source_path (Optional[Path]): The source file related, if there is one. pcs (Optional[set[int]]): Program counter values mapping to this check.
add_builtin_jump
python
ApeWorX/ape
src/ape/types/trace.py
https://github.com/ApeWorX/ape/blob/master/src/ape/types/trace.py
Apache-2.0
def read_data_from_stream(self, stream): """ Override to pad the value instead of raising an error. """ data_byte_size: int = self.data_byte_size # type: ignore data = stream.read(data_byte_size) if len(data) != data_byte_size: # Pad the value (instead of raising InsufficientBytesError). data = validate_bytes_size(data, 32) return data
Override to pad the value instead of raising an error.
read_data_from_stream
python
ApeWorX/ape
src/ape/utils/abi.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/abi.py
Apache-2.0
def is_struct(outputs: Union[ABIType, Sequence[ABIType]]) -> bool: """ Returns ``True`` if the given output is a struct. """ outputs_seq = outputs if isinstance(outputs, (tuple, list)) else [outputs] return ( len(outputs_seq) == 1 and "[" not in outputs_seq[0].type and outputs_seq[0].components not in (None, []) and all(c.name != "" for c in outputs_seq[0].components or []) )
Returns ``True`` if the given output is a struct.
is_struct
python
ApeWorX/ape
src/ape/utils/abi.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/abi.py
Apache-2.0
def create_struct(name: str, types: Sequence[ABIType], output_values: Sequence) -> Any: """ Create a dataclass representing an ABI struct that can be used as inputs or outputs. The struct properties can be accessed via ``.`` notation, as keys in a dictionary, or numeric tuple access. **NOTE**: This method assumes you already know the values to give to the struct properties. Args: name (str): The name of the struct. types (list[ABIType]: The types of values in the struct. output_values (list[Any]): The struct property values. Returns: Any: The struct dataclass. """ def get_item(struct, key) -> Any: # NOTE: Allow struct to function as a tuple and dict as well struct_values = tuple(getattr(struct, field) for field in struct.__dataclass_fields__) if isinstance(key, str): return dict(zip(struct.__dataclass_fields__, struct_values))[key] return struct_values[key] def set_item(struct, key, value): if isinstance(key, str): setattr(struct, key, value) else: struct_values = tuple(getattr(struct, field) for field in struct.__dataclass_fields__) field_to_set = struct_values[key] setattr(struct, field_to_set, value) def contains(struct, key): return key in struct.__dataclass_fields__ def is_equal(struct, other) -> bool: if not hasattr(other, "__len__"): return NotImplemented _len = len(other) if _len != len(struct): return False if hasattr(other, "items"): # Struct or dictionary. for key, value in other.items(): if key not in struct: # Different object. return False if struct[key] != value: # Mismatched properties. return False # Both objects represent the same struct. return True elif isinstance(other, (list, tuple)): # Allows comparing structs with sequence types. # NOTE: The order of the expected sequence matters! for itm1, itm2 in zip(struct.values(), other): if itm1 != itm2: return False return True else: return NotImplemented def length(struct) -> int: return len(struct.__dataclass_fields__) def items(struct) -> list[tuple]: return [(k, struct[k]) for k, v in struct.__dataclass_fields__.items()] def values(struct) -> list[Any]: return [x[1] for x in struct.items()] def reduce(struct) -> tuple: return (create_struct, (name, types, output_values)) # NOTE: Should never be "_{i}", but mypy complains and we need a unique value properties = [m.name or f"_{i}" for i, m in enumerate(types)] methods = { "__eq__": is_equal, "__getitem__": get_item, "__setitem__": set_item, "__contains__": contains, "__len__": length, "__reduce__": reduce, "items": items, "values": values, } if conflicts := [p for p in properties if p in methods]: conflicts_str = ", ".join(conflicts) logger.debug( "The following methods are unavailable on the struct " f"due to having the same name as a field: {conflicts_str}" ) for conflict in conflicts: del methods[conflict] struct_def = make_dataclass( name, properties, namespace=methods, bases=(Struct,), # We set a base class for subclass checking elsewhere. ) return struct_def(*output_values)
Create a dataclass representing an ABI struct that can be used as inputs or outputs. The struct properties can be accessed via ``.`` notation, as keys in a dictionary, or numeric tuple access. **NOTE**: This method assumes you already know the values to give to the struct properties. Args: name (str): The name of the struct. types (list[ABIType]: The types of values in the struct. output_values (list[Any]): The struct property values. Returns: Any: The struct dataclass.
create_struct
python
ApeWorX/ape
src/ape/utils/abi.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/abi.py
Apache-2.0
def encode_topics(abi: EventABI, topics: Optional[dict[str, Any]] = None) -> list[HexStr]: """ Encode the given topics using the given ABI. Useful for searching logs. Args: abi (EventABI): The event. topics (dict[str, Any] } None): Topic inputs to encode. Returns: list[str]: Encoded topics. """ topics = topics or {} values = {} unnamed_iter = 0 topic_inputs = {} for abi_input in abi.inputs: if not abi_input.indexed: continue if name := abi_input.name: topic_inputs[name] = abi_input else: topic_inputs[f"_{unnamed_iter}"] = abi_input for input_name, input_value in topics.items(): if input_name not in topic_inputs: # Was trying to use data or is not part of search. continue input_type = topic_inputs[input_name].type if input_type == "address": convert = ManagerAccessMixin.conversion_manager.convert if isinstance(input_value, (list, tuple)): adjusted_value = [] for addr in input_value: if isinstance(addr, str): adjusted_value.append(convert(addr)) else: from ape.types import AddressType adjusted_value.append(convert(addr, AddressType)) input_value = adjusted_value elif not isinstance(input_value, str): from ape.types import AddressType input_value = convert(input_value, AddressType) values[input_name] = input_value return abi.encode_topics(values) # type: ignore
Encode the given topics using the given ABI. Useful for searching logs. Args: abi (EventABI): The event. topics (dict[str, Any] } None): Topic inputs to encode. Returns: list[str]: Encoded topics.
encode_topics
python
ApeWorX/ape
src/ape/utils/abi.py
https://github.com/ApeWorX/ape/blob/master/src/ape/utils/abi.py
Apache-2.0
def provider(cls) -> "ProviderAPI": """ The current active provider if connected to one. Raises: :class:`~ape.exceptions.ProviderNotConnectedError`: When there is no active provider at runtime. Returns: :class:`~ape.api.providers.ProviderAPI` """ if provider := cls.network_manager.active_provider: return provider raise ProviderNotConnectedError()
The current active provider if connected to one. Raises: :class:`~ape.exceptions.ProviderNotConnectedError`: When there is no active provider at runtime. Returns: :class:`~ape.api.providers.ProviderAPI`
provider
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(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: return res if alt := _get_alt(name): res = self._get(alt) if res is not None: return res return None
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 {}) if isinstance(self, RootBaseModel) else {} if name in private_attrs: _recursion_checker.reset(name) return private_attrs[name] return get_attribute_with_extras(self, name)
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.startswith("_")]
**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.loads(json_str) return {}
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 of class with a .json suffix. **kwargs: Extra kwargs to pass to ``.model_dump_json()``. """ path = self._get_path(path=path) json_str = self.model_dump_json(**kwargs) path.unlink(missing_ok=True) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json_str)
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 kwargs to pass to ``.model_dump_json()``.
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 = cls._model_read_file(path) model = cls.model_validate(data, **kwargs) model._path = path return model
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 package_names: if pkg_name is None or name == pkg_name: distros.append(dist) return distros
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_parts = iter([x.strip(" ,") for x in pragma_str.split(" ")]) def _to_spec(item: str) -> str: item = item.replace("^", "~=") if item and item[0].isnumeric(): return f"=={item}" elif item and len(item) >= 2 and item[0] == "=" and item[1] != "=": return f"={item}" return item pragma_parts_fixed = [] builder = "" for sub_part in pragma_parts: parts_to_handle: list[str] = [] if "," in sub_part: sub_sub_parts = [x.strip() for x in sub_part.split(",")] if len(sub_sub_parts) > 2: # Very rare case. raise ValueError(f"Cannot handle pragma '{pragma_str}'.") if next_part := next(pragma_parts, None): parts_to_handle.extend((sub_sub_parts[0], f"{sub_sub_parts[-1]}{next_part}")) else: # Very rare case. raise ValueError(f"Cannot handle pragma '{pragma_str}'.") else: parts_to_handle.append(sub_part) for part in parts_to_handle: if not any(c.isnumeric() for c in part): # Handle pragma with spaces between constraint and values # like `>= 0.6.0`. builder += part continue elif builder: spec = _to_spec(f"{builder}{part}") builder = "" else: spec = _to_spec(part) pragma_parts_fixed.append(spec) try: return SpecifierSet(",".join(pragma_parts_fixed)) except ValueError as err: logger.error(str(err)) return None
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__ # NOTE: In case where don't pass a module name if not isinstance(obj, str) and hasattr(obj, "__name__"): obj = obj.__name__ elif not isinstance(obj, str): try: str_value = f"{obj}" except Exception: str_value = "<obj>" logger.warning(f"Type issue: Unknown if properly handled {str_value}") # Treat as no version found. return "" # Reduce module string to base package # NOTE: Assumed that string input is module name e.g. `__name__` pkg_name = obj.partition(".")[0] # NOTE: In case the distribution and package name differ dists = _get_distributions(pkg_name) if dists: pkg_name = dists[0].metadata["Name"] try: return str(version_metadata(pkg_name)) except PackageNotFoundError: # NOTE: Must handle empty string result here return ""
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 (str): path to filesystem to find. expand_envars (bool): ``True`` the variables in path are able to expand to show full path. must_exist (bool): ``True`` will be set if the configuration file exist and is able to be load. Returns: dict: Configured settings parsed from a config file. """ if path.is_file(): contents = path.read_text() if expand_envars: contents = expand_environment_variables(contents) if path.name == "pyproject.toml": pyproject_toml = tomllib.loads(contents) config = pyproject_toml.get("tool", {}).get("ape", {}) # Utilize [project] for some settings. if project_settings := pyproject_toml.get("project"): if "name" not in config and "name" in project_settings: config["name"] = project_settings["name"] elif path.suffix in (".json",): config = json.loads(contents) elif path.suffix in (".yml", ".yaml"): config = yaml.safe_load(contents) else: raise TypeError(f"Cannot parse '{path.suffix}' files!") return config or {} elif must_exist: raise OSError(f"{path} does not exist!") else: return {}
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 variables in path are able to expand to show full path. must_exist (bool): ``True`` will be set if the configuration file exist and is able to be load. Returns: dict: Configured settings parsed from a config file.
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 estimate gas. Returns: str: An error message explaining that the gas failed and that the transaction will likely revert. """ txn_error_text = str(tx_error) if txn_error_text.endswith("."): # Strip period from initial error so it looks better. txn_error_text = txn_error_text[:-1] return ( f"Gas estimation failed: '{txn_error_text}'. This transaction will likely revert. " "If you wish to broadcast, you must set the gas limit manually." )
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 that the gas failed and that the transaction will likely revert.
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: root (dict): Nested keys to form arguments. Returns: dict, optional: The final value if it exists else ``None`` if the tree ends at any point. """ current_value: Any = root for arg in args: if not hasattr(current_value, "get"): return None current_value = current_value.get(arg) return current_value
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: dict, optional: The final value if it exists else ``None`` if the tree ends at any point.
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. extra_spaces (int): Optionally append extra spacing. Defaults to ``0``. space_character (str): The character to use in the padding. Defaults to ``" "``. Returns: list[str]: A list of equal-length strings with padded spaces. """ if not str_list: return [] longest_item = len(max(str_list, key=len)) spaced_items = [] for value in str_list: spacing = (longest_item - len(value) + extra_spaces) * space_character spaced_items.append(f"{value}{spacing}") return spaced_items
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 padding. Defaults to ``" "``. Returns: list[str]: A list of equal-length strings with padded spaces.
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): return int.from_bytes(value, "big") raise ValueError(f"cannot convert {value!r} to int")
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. Returns: (Any): The value that results in awaiting the coroutine. Else, ``item`` if ``item`` is not a coroutine. If given multiple coroutines, returns the result from ``asyncio.gather``. """ items = list(item) if not items: return None elif not isinstance(items[0], Coroutine): # Method was marked `async` but didn't return a coroutine. # This happens in some `web3.py` methods. return items if len(items) > 1 else items[0] # Run all coroutines async. task = gather(*items, return_exceptions=True) if len(items) > 1 else items[0] loop = asyncio.get_event_loop() result = loop.run_until_complete(task) return result
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 in awaiting the coroutine. Else, ``item`` if ``item`` is not a coroutine. If given multiple coroutines, returns the result from ``asyncio.gather``.
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) < 10 except Exception: return False
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", ""): return sum(int(x) for x in addr) == 0 else: # "0x" counts as zero. return True except Exception: return False
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[key], value, depth + 1) else: mapping[key] = value return mapping
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 args and isinstance(args[0], type): return fn(*args, **kwargs) else: return fn(*args, **kwargs) except Exception as err: logger.error(str(err)) if default: return default return wrapped return wrapper
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