|
21 | 21 | from ethpm_types import MethodABI |
22 | 22 | from pydantic import Field, computed_field, field_serializer, model_validator |
23 | 23 |
|
24 | | -from ape.api.networks import NetworkAPI |
| 24 | +from ape.api.networks import NetworkAPI, ProviderContextManager |
25 | 25 | from ape.api.query import BlockTransactionQuery |
26 | 26 | from ape.api.transactions import ReceiptAPI, TransactionAPI |
27 | 27 | from ape.exceptions import ( |
@@ -311,6 +311,38 @@ def disconnect(self): |
311 | 311 | Disconnect from a provider, such as tear-down a process or quit an HTTP session. |
312 | 312 | """ |
313 | 313 |
|
| 314 | + def connection( |
| 315 | + self, |
| 316 | + disconnect_after: bool = False, |
| 317 | + disconnect_on_exit: bool = True, |
| 318 | + ) -> ProviderContextManager: |
| 319 | + """ |
| 320 | + Use this provider in a temporary context. Connects on enter and disconnects |
| 321 | + on exit. Equivalent to :meth:`~ape.managers.networks.NetworkManager.parse_network_choice` |
| 322 | + but for a provider instance that has already been resolved. |
| 323 | +
|
| 324 | + Usage example:: |
| 325 | +
|
| 326 | + provider = networks.ethereum.mainnet.get_provider("infura") |
| 327 | + with provider.connection(): |
| 328 | + ... |
| 329 | +
|
| 330 | + Args: |
| 331 | + disconnect_after (bool): Set to ``True`` to force a disconnect after ending |
| 332 | + the context. Defaults to ``False`` so the connection can be reused, such |
| 333 | + as in a multi-chain scenario. |
| 334 | + disconnect_on_exit (bool): Whether to disconnect on the exit of the python |
| 335 | + session. Defaults to ``True``. |
| 336 | +
|
| 337 | + Returns: |
| 338 | + :class:`~ape.api.networks.ProviderContextManager` |
| 339 | + """ |
| 340 | + return ProviderContextManager( |
| 341 | + provider=self, |
| 342 | + disconnect_after=disconnect_after, |
| 343 | + disconnect_on_exit=disconnect_on_exit, |
| 344 | + ) |
| 345 | + |
314 | 346 | @property |
315 | 347 | def ipc_path(self) -> Path | None: |
316 | 348 | """ |
|
0 commit comments