Skip to content

Commit

Permalink
Merge branch 'main' into feat/query/add-timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
fubuloubu authored Sep 27, 2023
2 parents a735406 + 9fa1a93 commit 600eb70
Show file tree
Hide file tree
Showing 77 changed files with 2,007 additions and 1,421 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ repos:
- id: isort

- repo: https://github.com/psf/black
rev: 23.7.0
rev: 23.9.1
hooks:
- id: black
name: black
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[build-system]
requires = ["setuptools>=51.1.1", "wheel", "setuptools_scm[toml]>=5.0"]
requires = ["setuptools>=51.1.1", "wheel", "setuptools_scm[toml]>=5.0,<8"]

[tool.mypy]
exclude = ["build/", "dist/", "docs/", "tests/integration/cli/projects/"]
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ exclude =
docs
build
.eggs
tests/integration/cli/projects
per-file-ignores =
# Need signal handler before imports
src/ape/__init__.py: E402
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"hypothesis-jsonschema==0.19.0", # JSON Schema fuzzer extension
],
"lint": [
"black>=23.7.0,<24", # Auto-formatter and linter
"black>=23.9.1,<24", # Auto-formatter and linter
"mypy>=1.5.1,<2", # Static type analyzer
"types-PyYAML", # Needed due to mypy typeshed
"types-requests", # Needed due to mypy typeshed
Expand Down Expand Up @@ -123,7 +123,7 @@
"web3[tester]>=6.7.0,<7",
# ** Dependencies maintained by ApeWorX **
"eip712>=0.2.1,<0.3",
"ethpm-types>=0.5.5,<0.6",
"ethpm-types>=0.5.6,<0.6",
"evm-trace>=0.1.0a23",
],
entry_points={
Expand Down
3 changes: 1 addition & 2 deletions src/ape/api/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from ape.exceptions import ConversionError
from ape.types import AddressType, ContractCode
from ape.utils import BaseInterface, abstractmethod, cached_property
from ape.utils.abi import _convert_kwargs

if TYPE_CHECKING:
from ape.api.transactions import ReceiptAPI, TransactionAPI
Expand Down Expand Up @@ -167,7 +166,7 @@ def history(self) -> "AccountHistory":
return self.chain_manager.history[self.address]

def as_transaction(self, **kwargs) -> "TransactionAPI":
converted_kwargs = _convert_kwargs(kwargs, self.conversion_manager.convert)
converted_kwargs = self.conversion_manager.convert_method_kwargs(kwargs)
return self.provider.network.ecosystem.create_transaction(
receiver=self.address, **converted_kwargs
)
Expand Down
2 changes: 1 addition & 1 deletion src/ape/api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def update(root: Dict, value_map: Dict):
return cls(**update(default_values, overrides))

def __getattr__(self, attr_name: str) -> Any:
# allow hyphens in plugin config files
# Allow hyphens in plugin config files.
attr_name = attr_name.replace("-", "_")
return super().__getattribute__(attr_name)

Expand Down
91 changes: 39 additions & 52 deletions src/ape/api/networks.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from ape.utils import (
DEFAULT_TRANSACTION_ACCEPTANCE_TIMEOUT,
BaseInterfaceModel,
ExtraModelAttributes,
ManagerAccessMixin,
abstractmethod,
cached_property,
Expand Down Expand Up @@ -115,7 +116,7 @@ def encode_contract_blueprint( # type: ignore[empty-body]
or Starknet's ``Declare`` transaction type.
Args:
contract (``ContractType``): The type of contract to create a blueprint for.
contract_type (``ContractType``): The type of contract to create a blueprint for.
This is the type of contract that will get created by factory contracts.
*args: Calldata, if applicable.
**kwargs: Transaction specifications, such as ``value``.
Expand All @@ -142,9 +143,9 @@ def serialize_transaction(self, transaction: "TransactionAPI") -> bytes:

unsigned_txn = serializable_unsigned_transaction_from_dict(txn_data)
signature = (
self.signature.v, # type: ignore
to_int(self.signature.r), # type: ignore
to_int(self.signature.s), # type: ignore
self.signature.v,
to_int(self.signature.r),
to_int(self.signature.s),
)

signed_txn = encode_transaction(unsigned_txn, signature)
Expand Down Expand Up @@ -221,45 +222,13 @@ def __post_init__(self):
if len(self.networks) == 0:
raise NetworkError("Must define at least one network in ecosystem")

def __getitem__(self, network_name: str) -> "NetworkAPI":
"""
Get a network by name.
Raises:
:class:`~ape.exceptions.NetworkNotFoundError`:
When there is no network with the given name.
Args:
network_name (str): The name of the network to retrieve.
Returns:
:class:`~ape.api.networks.NetworkAPI`
"""
return self.get_network(network_name)

def __getattr__(self, network_name: str) -> "NetworkAPI":
"""
Get a network by name using ``.`` access.
Usage example::
from ape import networks
mainnet = networks.ecosystem.mainnet
Raises:
:class:`~ape.exceptions.NetworkNotFoundError`:
When there is no network with the given name.
Args:
network_name (str): The name of the network to retrieve.
Returns:
:class:`~ape.api.networks.NetworkAPI`
"""
try:
return self.get_network(network_name.replace("_", "-"))
except NetworkNotFoundError:
return self.__getattribute__(network_name)
def __ape_extra_attributes__(self) -> Iterator[ExtraModelAttributes]:
yield ExtraModelAttributes(
name="networks",
attributes=self.networks,
include_getattr=True,
include_getitem=True,
)

def add_network(self, network_name: str, network: "NetworkAPI"):
"""
Expand Down Expand Up @@ -565,9 +534,11 @@ class ProviderContextManager(ManagerAccessMixin):

connected_providers: Dict[str, "ProviderAPI"] = {}
provider_stack: List[str] = []
disconnect_map: Dict[str, bool] = {}

def __init__(self, provider: "ProviderAPI"):
def __init__(self, provider: "ProviderAPI", disconnect_after: bool = False):
self._provider = provider
self._disconnect_after = disconnect_after

@property
def empty(self) -> bool:
Expand All @@ -589,6 +560,7 @@ def push_provider(self):
raise ProviderNotConnectedError()

self.provider_stack.append(provider_id)
self.disconnect_map[provider_id] = self._disconnect_after
if provider_id in self.connected_providers:
# Using already connected instance
if must_connect:
Expand All @@ -609,6 +581,12 @@ def pop_provider(self):

# Clear last provider
exiting_provider_id = self.provider_stack.pop()

# Disconnect the provider in same cases.
if self.disconnect_map[exiting_provider_id]:
if provider := self.network_manager.active_provider:
provider.disconnect()

if not self.provider_stack:
self.network_manager.active_provider = None
return
Expand All @@ -619,8 +597,7 @@ def pop_provider(self):
# Active provider is not changing
return

previous_provider = self.connected_providers[previous_provider_id]
if previous_provider:
if previous_provider := self.connected_providers[previous_provider_id]:
self.network_manager.active_provider = previous_provider

def disconnect_all(self):
Expand Down Expand Up @@ -678,7 +655,7 @@ def create_adhoc_network(cls) -> "NetworkAPI":
return cls(
name="adhoc",
ecosystem=ethereum,
data_folder=data_folder,
data_folder=Path(data_folder),
request_header=request_header,
_default_provider="geth",
)
Expand Down Expand Up @@ -889,6 +866,7 @@ def use_provider(
self,
provider_name: str,
provider_settings: Optional[Dict] = None,
disconnect_after: bool = False,
) -> ProviderContextManager:
"""
Use and connect to a provider in a temporary context. When entering the context, it calls
Expand All @@ -905,6 +883,9 @@ def use_provider(
Args:
provider_name (str): The name of the provider to use.
disconnect_after (bool): Set to ``True`` to force a disconnect after ending
the context. This defaults to ``False`` so you can re-connect to the
same network, such as in a multi-chain testing scenario.
provider_settings (dict, optional): Settings to apply to the provider.
Defaults to ``None``.
Expand All @@ -913,9 +894,8 @@ def use_provider(
"""

settings = provider_settings or {}
return ProviderContextManager(
provider=self.get_provider(provider_name=provider_name, provider_settings=settings),
)
provider = self.get_provider(provider_name=provider_name, provider_settings=settings)
return ProviderContextManager(provider=provider, disconnect_after=disconnect_after)

@property
def default_provider(self) -> Optional[str]:
Expand Down Expand Up @@ -955,7 +935,9 @@ def set_default_provider(self, provider_name: str):
raise NetworkError(f"Provider '{provider_name}' not found in network '{self.choice}'.")

def use_default_provider(
self, provider_settings: Optional[Dict] = None
self,
provider_settings: Optional[Dict] = None,
disconnect_after: bool = False,
) -> ProviderContextManager:
"""
Temporarily connect and use the default provider. When entering the context, it calls
Expand All @@ -973,13 +955,18 @@ def use_default_provider(
Args:
provider_settings (dict, optional): Settings to override the provider.
disconnect_after (bool): Set to ``True`` to force a disconnect after ending
the context. This defaults to ``False`` so you can re-connect to the
same network, such as in a multi-chain testing scenario.
Returns:
:class:`~ape.api.networks.ProviderContextManager`
"""
if self.default_provider:
settings = provider_settings or {}
return self.use_provider(self.default_provider, provider_settings=settings)
return self.use_provider(
self.default_provider, provider_settings=settings, disconnect_after=disconnect_after
)

raise NetworkError(f"No providers for network '{self.name}'.")

Expand Down
Loading

0 comments on commit 600eb70

Please sign in to comment.