We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
 cannot import name 'DEFAULT_WEBSOCKET_TIMEOUT'

ImportError: cannot import name 'DEFAULT_WEBSOCKET_TIMEOUT' from 'web3.providers.websocket' (C:\Python310\lib\site-packages\web3\providers\websocket\__init__.py)

any one know what happened?

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `web3/manager.py`
Content:
```
1 import asyncio
2 import json
3 import logging
4 from typing import (
5     TYPE_CHECKING,
6     Any,
7     AsyncGenerator,
8     Callable,
9     List,
10     Optional,
11     Sequence,
12     Tuple,
13     Union,
14     cast,
15 )
16 
17 from eth_utils.toolz import (
18     pipe,
19 )
20 from hexbytes import (
21     HexBytes,
22 )
23 from websockets.exceptions import (
24     ConnectionClosedOK,
25 )
26 
27 from web3._utils.caching import (
28     generate_cache_key,
29 )
30 from web3.datastructures import (
31     NamedElementOnion,
32 )
33 from web3.exceptions import (
34     BadResponseFormat,
35     MethodUnavailable,
36 )
37 from web3.middleware import (
38     abi_middleware,
39     async_attrdict_middleware,
40     async_buffered_gas_estimate_middleware,
41     async_gas_price_strategy_middleware,
42     async_name_to_address_middleware,
43     async_validation_middleware,
44     attrdict_middleware,
45     buffered_gas_estimate_middleware,
46     gas_price_strategy_middleware,
47     name_to_address_middleware,
48     validation_middleware,
49 )
50 from web3.module import (
51     apply_result_formatters,
52 )
53 from web3.providers import (
54     AutoProvider,
55     PersistentConnectionProvider,
56 )
57 from web3.types import (
58     AsyncMiddleware,
59     AsyncMiddlewareOnion,
60     Middleware,
61     MiddlewareOnion,
62     RPCEndpoint,
63     RPCResponse,
64 )
65 
66 if TYPE_CHECKING:
67     from web3 import (  # noqa: F401
68         AsyncWeb3,
69         Web3,
70     )
71     from web3.providers import (  # noqa: F401
72         AsyncBaseProvider,
73         BaseProvider,
74     )
75 
76 
77 NULL_RESPONSES = [None, HexBytes("0x"), "0x"]
78 
79 
80 def apply_error_formatters(
81     error_formatters: Callable[..., Any],
82     response: RPCResponse,
83 ) -> RPCResponse:
84     if error_formatters:
85         formatted_resp = pipe(response, error_formatters)
86         return formatted_resp
87     else:
88         return response
89 
90 
91 def apply_null_result_formatters(
92     null_result_formatters: Callable[..., Any],
93     response: RPCResponse,
94     params: Optional[Any] = None,
95 ) -> RPCResponse:
96     if null_result_formatters:
97         formatted_resp = pipe(params, null_result_formatters)
98         return formatted_resp
99     else:
100         return response
101 
102 
103 class RequestManager:
104     logger = logging.getLogger("web3.RequestManager")
105 
106     middleware_onion: Union[
107         MiddlewareOnion, AsyncMiddlewareOnion, NamedElementOnion[None, None]
108     ]
109 
110     def __init__(
111         self,
112         w3: Union["AsyncWeb3", "Web3"],
113         provider: Optional[Union["BaseProvider", "AsyncBaseProvider"]] = None,
114         middlewares: Optional[
115             Union[
116                 Sequence[Tuple[Middleware, str]], Sequence[Tuple[AsyncMiddleware, str]]
117             ]
118         ] = None,
119     ) -> None:
120         self.w3 = w3
121 
122         if provider is None:
123             self.provider = AutoProvider()
124         else:
125             self.provider = provider
126 
127         if middlewares is None:
128             middlewares = (
129                 self.async_default_middlewares()
130                 if self.provider.is_async
131                 else self.default_middlewares(cast("Web3", w3))
132             )
133 
134         self.middleware_onion = NamedElementOnion(middlewares)
135 
136     w3: Union["AsyncWeb3", "Web3"] = None
137     _provider = None
138 
139     @property
140     def provider(self) -> Union["BaseProvider", "AsyncBaseProvider"]:
141         return self._provider
142 
143     @provider.setter
144     def provider(self, provider: Union["BaseProvider", "AsyncBaseProvider"]) -> None:
145         self._provider = provider
146 
147     @staticmethod
148     def default_middlewares(w3: "Web3") -> List[Tuple[Middleware, str]]:
149         """
150         List the default middlewares for the request manager.
151         Leaving w3 unspecified will prevent the middleware from resolving names.
152         Documentation should remain in sync with these defaults.
153         """
154         return [
155             (gas_price_strategy_middleware, "gas_price_strategy"),
156             (name_to_address_middleware(w3), "name_to_address"),
157             (attrdict_middleware, "attrdict"),
158             (validation_middleware, "validation"),
159             (abi_middleware, "abi"),
160             (buffered_gas_estimate_middleware, "gas_estimate"),
161         ]
162 
163     @staticmethod
164     def async_default_middlewares() -> List[Tuple[AsyncMiddleware, str]]:
165         """
166         List the default async middlewares for the request manager.
167         Documentation should remain in sync with these defaults.
168         """
169         return [
170             (async_gas_price_strategy_middleware, "gas_price_strategy"),
171             (async_name_to_address_middleware, "name_to_address"),
172             (async_attrdict_middleware, "attrdict"),
173             (async_validation_middleware, "validation"),
174             (async_buffered_gas_estimate_middleware, "gas_estimate"),
175         ]
176 
177     #
178     # Provider requests and response
179     #
180     def _make_request(
181         self, method: Union[RPCEndpoint, Callable[..., RPCEndpoint]], params: Any
182     ) -> RPCResponse:
183         provider = cast("BaseProvider", self.provider)
184         request_func = provider.request_func(
185             cast("Web3", self.w3), cast(MiddlewareOnion, self.middleware_onion)
186         )
187         self.logger.debug(f"Making request. Method: {method}")
188         return request_func(method, params)
189 
190     async def _coro_make_request(
191         self, method: Union[RPCEndpoint, Callable[..., RPCEndpoint]], params: Any
192     ) -> RPCResponse:
193         provider = cast("AsyncBaseProvider", self.provider)
194         request_func = await provider.request_func(
195             cast("AsyncWeb3", self.w3),
196             cast(AsyncMiddlewareOnion, self.middleware_onion),
197         )
198         self.logger.debug(f"Making request. Method: {method}")
199         return await request_func(method, params)
200 
201     @staticmethod
202     def formatted_response(
203         response: RPCResponse,
204         params: Any,
205         error_formatters: Optional[Callable[..., Any]] = None,
206         null_result_formatters: Optional[Callable[..., Any]] = None,
207     ) -> Any:
208         if "error" in response:
209             apply_error_formatters(error_formatters, response)
210 
211             # guard against eth-tester case - eth-tester returns a string
212             # with no code, so can't parse what the error is.
213             if isinstance(response["error"], dict):
214                 resp_code = response["error"].get("code")
215                 if resp_code == -32601:
216                     raise MethodUnavailable(response["error"])
217             raise ValueError(response["error"])
218         # NULL_RESPONSES includes None, so return False here as the default
219         # so we don't apply the null_result_formatters if there is no 'result' key
220         elif response.get("result", False) in NULL_RESPONSES:
221             # null_result_formatters raise either a BlockNotFound
222             # or a TransactionNotFound error, depending on the method called
223             apply_null_result_formatters(null_result_formatters, response, params)
224             return response["result"]
225         elif response.get("result") is not None:
226             return response["result"]
227         elif (
228             # eth_subscribe case
229             response.get("params") is not None
230             and response["params"].get("result") is not None
231         ):
232             return response["params"]["result"]
233         else:
234             raise BadResponseFormat(
235                 "The response was in an unexpected format and unable to be parsed. "
236                 f"The raw response is: {response}"
237             )
238 
239     def request_blocking(
240         self,
241         method: Union[RPCEndpoint, Callable[..., RPCEndpoint]],
242         params: Any,
243         error_formatters: Optional[Callable[..., Any]] = None,
244         null_result_formatters: Optional[Callable[..., Any]] = None,
245     ) -> Any:
246         """
247         Make a synchronous request using the provider
248         """
249         response = self._make_request(method, params)
250         return self.formatted_response(
251             response, params, error_formatters, null_result_formatters
252         )
253 
254     async def coro_request(
255         self,
256         method: Union[RPCEndpoint, Callable[..., RPCEndpoint]],
257         params: Any,
258         error_formatters: Optional[Callable[..., Any]] = None,
259         null_result_formatters: Optional[Callable[..., Any]] = None,
260     ) -> Any:
261         """
262         Coroutine for making a request using the provider
263         """
264         response = await self._coro_make_request(method, params)
265         return self.formatted_response(
266             response, params, error_formatters, null_result_formatters
267         )
268 
269     # persistent connection
270     async def ws_send(
271         self,
272         method: Union[RPCEndpoint, Callable[..., RPCEndpoint]],
273         params: Any,
274     ) -> RPCResponse:
275         provider = cast(PersistentConnectionProvider, self._provider)
276         request_func = await provider.request_func(
277             cast("AsyncWeb3", self.w3),
278             cast(AsyncMiddlewareOnion, self.middleware_onion),
279         )
280         self.logger.debug(
281             "Making request to open websocket connection - "
282             f"uri: {provider.endpoint_uri}, method: {method}"
283         )
284         await request_func(method, params)
285         return await asyncio.wait_for(
286             self.ws_recv(),
287             timeout=provider.call_timeout,
288         )
289 
290     async def ws_recv(self) -> Any:
291         return await self._ws_recv_stream().__anext__()
292 
293     def persistent_recv_stream(self) -> "_AsyncPersistentRecvStream":
294         return _AsyncPersistentRecvStream(self)
295 
296     async def _ws_recv_stream(self) -> AsyncGenerator[RPCResponse, None]:
297         if not isinstance(self._provider, PersistentConnectionProvider):
298             raise TypeError(
299                 "Only websocket providers that maintain an open, persistent connection "
300                 "can listen to websocket recv streams."
301             )
302 
303         response = json.loads(
304             await asyncio.wait_for(
305                 self._provider.ws.recv(),
306                 timeout=self._provider.call_timeout,
307             )
308         )
309         request_info = self._provider._get_request_information_for_response(response)
310 
311         if request_info is None:
312             self.logger.debug("No cache key found for response, returning raw response")
313             yield response
314 
315         if request_info.method == "eth_subscribe" and "result" in response.keys():
316             # if response for the initial eth_subscribe request, which returns the
317             # subscription id
318             subscription_id = response["result"]
319             cache_key = generate_cache_key(subscription_id)
320             if cache_key not in self._provider._async_response_processing_cache:
321                 # cache by subscription id in order to process each response for the
322                 # subscription as it comes in
323                 self._provider.logger.debug(
324                     f"Caching eth_subscription info:\n    cache_key={cache_key},\n    "
325                     f"request_info={request_info.__dict__}"
326                 )
327                 self._provider._async_response_processing_cache.cache(
328                     cache_key, request_info
329                 )
330 
331         # pipe response back through middleware response processors
332         if len(request_info.middleware_response_processors) > 0:
333             response = pipe(response, *request_info.middleware_response_processors)
334 
335         (
336             result_formatters,
337             error_formatters,
338             null_formatters,
339         ) = request_info.response_formatters
340         partly_formatted_response = self.formatted_response(
341             response,
342             request_info.params,
343             error_formatters,
344             null_formatters,
345         )
346         yield apply_result_formatters(result_formatters, partly_formatted_response)
347 
348 
349 class _AsyncPersistentRecvStream:
350     """
351     Async generator for receiving responses from a persistent connection. This
352     abstraction is necessary to define the `__aiter__()` method required for
353     use with "async for" loops.
354     """
355 
356     def __init__(self, manager: RequestManager, *args: Any, **kwargs: Any) -> None:
357         self.manager = manager
358         super().__init__(*args, **kwargs)
359 
360     def __aiter__(self) -> AsyncGenerator[RPCResponse, None]:
361         while True:
362             try:
363                 return self.manager._ws_recv_stream()
364             except ConnectionClosedOK:
365                 pass
366
```

Path: `web3/providers/websocket/__init__.py`
Content:
```
1 from .websocket import (  # noqa: F401
2     WebsocketProvider,
3 )
4 from .websocket_v2 import (  # noqa: F401
5     WebsocketProviderV2,
6 )
7
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/web3/manager.py b/web3/manager.py
--- a/web3/manager.py
+++ b/web3/manager.py
@@ -312,38 +312,40 @@
             self.logger.debug("No cache key found for response, returning raw response")
             yield response
 
-        if request_info.method == "eth_subscribe" and "result" in response.keys():
-            # if response for the initial eth_subscribe request, which returns the
-            # subscription id
-            subscription_id = response["result"]
-            cache_key = generate_cache_key(subscription_id)
-            if cache_key not in self._provider._async_response_processing_cache:
-                # cache by subscription id in order to process each response for the
-                # subscription as it comes in
-                self._provider.logger.debug(
-                    f"Caching eth_subscription info:\n    cache_key={cache_key},\n    "
-                    f"request_info={request_info.__dict__}"
-                )
-                self._provider._async_response_processing_cache.cache(
-                    cache_key, request_info
-                )
-
-        # pipe response back through middleware response processors
-        if len(request_info.middleware_response_processors) > 0:
-            response = pipe(response, *request_info.middleware_response_processors)
-
-        (
-            result_formatters,
-            error_formatters,
-            null_formatters,
-        ) = request_info.response_formatters
-        partly_formatted_response = self.formatted_response(
-            response,
-            request_info.params,
-            error_formatters,
-            null_formatters,
-        )
-        yield apply_result_formatters(result_formatters, partly_formatted_response)
+        else:
+            if request_info.method == "eth_subscribe" and "result" in response.keys():
+                # if response for the initial eth_subscribe request, which returns the
+                # subscription id
+                subscription_id = response["result"]
+                cache_key = generate_cache_key(subscription_id)
+                if cache_key not in self._provider._async_response_processing_cache:
+                    # cache by subscription id in order to process each response for the
+                    # subscription as it comes in
+                    self._provider.logger.debug(
+                        f"Caching eth_subscription info:\n    "
+                        f"cache_key={cache_key},\n    "
+                        f"request_info={request_info.__dict__}"
+                    )
+                    self._provider._async_response_processing_cache.cache(
+                        cache_key, request_info
+                    )
+
+            # pipe response back through middleware response processors
+            if len(request_info.middleware_response_processors) > 0:
+                response = pipe(response, *request_info.middleware_response_processors)
+
+            (
+                result_formatters,
+                error_formatters,
+                null_formatters,
+            ) = request_info.response_formatters
+            partly_formatted_response = self.formatted_response(
+                response,
+                request_info.params,
+                error_formatters,
+                null_formatters,
+            )
+            yield apply_result_formatters(result_formatters, partly_formatted_response)
 
 
 class _AsyncPersistentRecvStream:
diff --git a/web3/providers/websocket/__init__.py b/web3/providers/websocket/__init__.py
--- a/web3/providers/websocket/__init__.py
+++ b/web3/providers/websocket/__init__.py
@@ -1,4 +1,6 @@
 from .websocket import (  # noqa: F401
+    DEFAULT_WEBSOCKET_TIMEOUT,
+    RESTRICTED_WEBSOCKET_KWARGS,
     WebsocketProvider,
 )
 from .websocket_v2 import (  # noqa: F401

{"golden_diff": "diff --git a/web3/manager.py b/web3/manager.py\n--- a/web3/manager.py\n+++ b/web3/manager.py\n@@ -312,38 +312,40 @@\n             self.logger.debug(\"No cache key found for response, returning raw response\")\n             yield response\n \n-        if request_info.method == \"eth_subscribe\" and \"result\" in response.keys():\n-            # if response for the initial eth_subscribe request, which returns the\n-            # subscription id\n-            subscription_id = response[\"result\"]\n-            cache_key = generate_cache_key(subscription_id)\n-            if cache_key not in self._provider._async_response_processing_cache:\n-                # cache by subscription id in order to process each response for the\n-                # subscription as it comes in\n-                self._provider.logger.debug(\n-                    f\"Caching eth_subscription info:\\n    cache_key={cache_key},\\n    \"\n-                    f\"request_info={request_info.__dict__}\"\n-                )\n-                self._provider._async_response_processing_cache.cache(\n-                    cache_key, request_info\n-                )\n-\n-        # pipe response back through middleware response processors\n-        if len(request_info.middleware_response_processors) > 0:\n-            response = pipe(response, *request_info.middleware_response_processors)\n-\n-        (\n-            result_formatters,\n-            error_formatters,\n-            null_formatters,\n-        ) = request_info.response_formatters\n-        partly_formatted_response = self.formatted_response(\n-            response,\n-            request_info.params,\n-            error_formatters,\n-            null_formatters,\n-        )\n-        yield apply_result_formatters(result_formatters, partly_formatted_response)\n+        else:\n+            if request_info.method == \"eth_subscribe\" and \"result\" in response.keys():\n+                # if response for the initial eth_subscribe request, which returns the\n+                # subscription id\n+                subscription_id = response[\"result\"]\n+                cache_key = generate_cache_key(subscription_id)\n+                if cache_key not in self._provider._async_response_processing_cache:\n+                    # cache by subscription id in order to process each response for the\n+                    # subscription as it comes in\n+                    self._provider.logger.debug(\n+                        f\"Caching eth_subscription info:\\n    \"\n+                        f\"cache_key={cache_key},\\n    \"\n+                        f\"request_info={request_info.__dict__}\"\n+                    )\n+                    self._provider._async_response_processing_cache.cache(\n+                        cache_key, request_info\n+                    )\n+\n+            # pipe response back through middleware response processors\n+            if len(request_info.middleware_response_processors) > 0:\n+                response = pipe(response, *request_info.middleware_response_processors)\n+\n+            (\n+                result_formatters,\n+                error_formatters,\n+                null_formatters,\n+            ) = request_info.response_formatters\n+            partly_formatted_response = self.formatted_response(\n+                response,\n+                request_info.params,\n+                error_formatters,\n+                null_formatters,\n+            )\n+            yield apply_result_formatters(result_formatters, partly_formatted_response)\n \n \n class _AsyncPersistentRecvStream:\ndiff --git a/web3/providers/websocket/__init__.py b/web3/providers/websocket/__init__.py\n--- a/web3/providers/websocket/__init__.py\n+++ b/web3/providers/websocket/__init__.py\n@@ -1,4 +1,6 @@\n from .websocket import (  # noqa: F401\n+    DEFAULT_WEBSOCKET_TIMEOUT,\n+    RESTRICTED_WEBSOCKET_KWARGS,\n     WebsocketProvider,\n )\n from .websocket_v2 import (  # noqa: F401\n", "issue": " cannot import name 'DEFAULT_WEBSOCKET_TIMEOUT'\n\r\nImportError: cannot import name 'DEFAULT_WEBSOCKET_TIMEOUT' from 'web3.providers.websocket' (C:\\Python310\\lib\\site-packages\\web3\\providers\\websocket\\__init__.py)\r\n\r\nany one know what happened?\n", "before_files": [{"content": "import asyncio\nimport json\nimport logging\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    AsyncGenerator,\n    Callable,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n    cast,\n)\n\nfrom eth_utils.toolz import (\n    pipe,\n)\nfrom hexbytes import (\n    HexBytes,\n)\nfrom websockets.exceptions import (\n    ConnectionClosedOK,\n)\n\nfrom web3._utils.caching import (\n    generate_cache_key,\n)\nfrom web3.datastructures import (\n    NamedElementOnion,\n)\nfrom web3.exceptions import (\n    BadResponseFormat,\n    MethodUnavailable,\n)\nfrom web3.middleware import (\n    abi_middleware,\n    async_attrdict_middleware,\n    async_buffered_gas_estimate_middleware,\n    async_gas_price_strategy_middleware,\n    async_name_to_address_middleware,\n    async_validation_middleware,\n    attrdict_middleware,\n    buffered_gas_estimate_middleware,\n    gas_price_strategy_middleware,\n    name_to_address_middleware,\n    validation_middleware,\n)\nfrom web3.module import (\n    apply_result_formatters,\n)\nfrom web3.providers import (\n    AutoProvider,\n    PersistentConnectionProvider,\n)\nfrom web3.types import (\n    AsyncMiddleware,\n    AsyncMiddlewareOnion,\n    Middleware,\n    MiddlewareOnion,\n    RPCEndpoint,\n    RPCResponse,\n)\n\nif TYPE_CHECKING:\n    from web3 import (  # noqa: F401\n        AsyncWeb3,\n        Web3,\n    )\n    from web3.providers import (  # noqa: F401\n        AsyncBaseProvider,\n        BaseProvider,\n    )\n\n\nNULL_RESPONSES = [None, HexBytes(\"0x\"), \"0x\"]\n\n\ndef apply_error_formatters(\n    error_formatters: Callable[..., Any],\n    response: RPCResponse,\n) -> RPCResponse:\n    if error_formatters:\n        formatted_resp = pipe(response, error_formatters)\n        return formatted_resp\n    else:\n        return response\n\n\ndef apply_null_result_formatters(\n    null_result_formatters: Callable[..., Any],\n    response: RPCResponse,\n    params: Optional[Any] = None,\n) -> RPCResponse:\n    if null_result_formatters:\n        formatted_resp = pipe(params, null_result_formatters)\n        return formatted_resp\n    else:\n        return response\n\n\nclass RequestManager:\n    logger = logging.getLogger(\"web3.RequestManager\")\n\n    middleware_onion: Union[\n        MiddlewareOnion, AsyncMiddlewareOnion, NamedElementOnion[None, None]\n    ]\n\n    def __init__(\n        self,\n        w3: Union[\"AsyncWeb3\", \"Web3\"],\n        provider: Optional[Union[\"BaseProvider\", \"AsyncBaseProvider\"]] = None,\n        middlewares: Optional[\n            Union[\n                Sequence[Tuple[Middleware, str]], Sequence[Tuple[AsyncMiddleware, str]]\n            ]\n        ] = None,\n    ) -> None:\n        self.w3 = w3\n\n        if provider is None:\n            self.provider = AutoProvider()\n        else:\n            self.provider = provider\n\n        if middlewares is None:\n            middlewares = (\n                self.async_default_middlewares()\n                if self.provider.is_async\n                else self.default_middlewares(cast(\"Web3\", w3))\n            )\n\n        self.middleware_onion = NamedElementOnion(middlewares)\n\n    w3: Union[\"AsyncWeb3\", \"Web3\"] = None\n    _provider = None\n\n    @property\n    def provider(self) -> Union[\"BaseProvider\", \"AsyncBaseProvider\"]:\n        return self._provider\n\n    @provider.setter\n    def provider(self, provider: Union[\"BaseProvider\", \"AsyncBaseProvider\"]) -> None:\n        self._provider = provider\n\n    @staticmethod\n    def default_middlewares(w3: \"Web3\") -> List[Tuple[Middleware, str]]:\n        \"\"\"\n        List the default middlewares for the request manager.\n        Leaving w3 unspecified will prevent the middleware from resolving names.\n        Documentation should remain in sync with these defaults.\n        \"\"\"\n        return [\n            (gas_price_strategy_middleware, \"gas_price_strategy\"),\n            (name_to_address_middleware(w3), \"name_to_address\"),\n            (attrdict_middleware, \"attrdict\"),\n            (validation_middleware, \"validation\"),\n            (abi_middleware, \"abi\"),\n            (buffered_gas_estimate_middleware, \"gas_estimate\"),\n        ]\n\n    @staticmethod\n    def async_default_middlewares() -> List[Tuple[AsyncMiddleware, str]]:\n        \"\"\"\n        List the default async middlewares for the request manager.\n        Documentation should remain in sync with these defaults.\n        \"\"\"\n        return [\n            (async_gas_price_strategy_middleware, \"gas_price_strategy\"),\n            (async_name_to_address_middleware, \"name_to_address\"),\n            (async_attrdict_middleware, \"attrdict\"),\n            (async_validation_middleware, \"validation\"),\n            (async_buffered_gas_estimate_middleware, \"gas_estimate\"),\n        ]\n\n    #\n    # Provider requests and response\n    #\n    def _make_request(\n        self, method: Union[RPCEndpoint, Callable[..., RPCEndpoint]], params: Any\n    ) -> RPCResponse:\n        provider = cast(\"BaseProvider\", self.provider)\n        request_func = provider.request_func(\n            cast(\"Web3\", self.w3), cast(MiddlewareOnion, self.middleware_onion)\n        )\n        self.logger.debug(f\"Making request. Method: {method}\")\n        return request_func(method, params)\n\n    async def _coro_make_request(\n        self, method: Union[RPCEndpoint, Callable[..., RPCEndpoint]], params: Any\n    ) -> RPCResponse:\n        provider = cast(\"AsyncBaseProvider\", self.provider)\n        request_func = await provider.request_func(\n            cast(\"AsyncWeb3\", self.w3),\n            cast(AsyncMiddlewareOnion, self.middleware_onion),\n        )\n        self.logger.debug(f\"Making request. Method: {method}\")\n        return await request_func(method, params)\n\n    @staticmethod\n    def formatted_response(\n        response: RPCResponse,\n        params: Any,\n        error_formatters: Optional[Callable[..., Any]] = None,\n        null_result_formatters: Optional[Callable[..., Any]] = None,\n    ) -> Any:\n        if \"error\" in response:\n            apply_error_formatters(error_formatters, response)\n\n            # guard against eth-tester case - eth-tester returns a string\n            # with no code, so can't parse what the error is.\n            if isinstance(response[\"error\"], dict):\n                resp_code = response[\"error\"].get(\"code\")\n                if resp_code == -32601:\n                    raise MethodUnavailable(response[\"error\"])\n            raise ValueError(response[\"error\"])\n        # NULL_RESPONSES includes None, so return False here as the default\n        # so we don't apply the null_result_formatters if there is no 'result' key\n        elif response.get(\"result\", False) in NULL_RESPONSES:\n            # null_result_formatters raise either a BlockNotFound\n            # or a TransactionNotFound error, depending on the method called\n            apply_null_result_formatters(null_result_formatters, response, params)\n            return response[\"result\"]\n        elif response.get(\"result\") is not None:\n            return response[\"result\"]\n        elif (\n            # eth_subscribe case\n            response.get(\"params\") is not None\n            and response[\"params\"].get(\"result\") is not None\n        ):\n            return response[\"params\"][\"result\"]\n        else:\n            raise BadResponseFormat(\n                \"The response was in an unexpected format and unable to be parsed. \"\n                f\"The raw response is: {response}\"\n            )\n\n    def request_blocking(\n        self,\n        method: Union[RPCEndpoint, Callable[..., RPCEndpoint]],\n        params: Any,\n        error_formatters: Optional[Callable[..., Any]] = None,\n        null_result_formatters: Optional[Callable[..., Any]] = None,\n    ) -> Any:\n        \"\"\"\n        Make a synchronous request using the provider\n        \"\"\"\n        response = self._make_request(method, params)\n        return self.formatted_response(\n            response, params, error_formatters, null_result_formatters\n        )\n\n    async def coro_request(\n        self,\n        method: Union[RPCEndpoint, Callable[..., RPCEndpoint]],\n        params: Any,\n        error_formatters: Optional[Callable[..., Any]] = None,\n        null_result_formatters: Optional[Callable[..., Any]] = None,\n    ) -> Any:\n        \"\"\"\n        Coroutine for making a request using the provider\n        \"\"\"\n        response = await self._coro_make_request(method, params)\n        return self.formatted_response(\n            response, params, error_formatters, null_result_formatters\n        )\n\n    # persistent connection\n    async def ws_send(\n        self,\n        method: Union[RPCEndpoint, Callable[..., RPCEndpoint]],\n        params: Any,\n    ) -> RPCResponse:\n        provider = cast(PersistentConnectionProvider, self._provider)\n        request_func = await provider.request_func(\n            cast(\"AsyncWeb3\", self.w3),\n            cast(AsyncMiddlewareOnion, self.middleware_onion),\n        )\n        self.logger.debug(\n            \"Making request to open websocket connection - \"\n            f\"uri: {provider.endpoint_uri}, method: {method}\"\n        )\n        await request_func(method, params)\n        return await asyncio.wait_for(\n            self.ws_recv(),\n            timeout=provider.call_timeout,\n        )\n\n    async def ws_recv(self) -> Any:\n        return await self._ws_recv_stream().__anext__()\n\n    def persistent_recv_stream(self) -> \"_AsyncPersistentRecvStream\":\n        return _AsyncPersistentRecvStream(self)\n\n    async def _ws_recv_stream(self) -> AsyncGenerator[RPCResponse, None]:\n        if not isinstance(self._provider, PersistentConnectionProvider):\n            raise TypeError(\n                \"Only websocket providers that maintain an open, persistent connection \"\n                \"can listen to websocket recv streams.\"\n            )\n\n        response = json.loads(\n            await asyncio.wait_for(\n                self._provider.ws.recv(),\n                timeout=self._provider.call_timeout,\n            )\n        )\n        request_info = self._provider._get_request_information_for_response(response)\n\n        if request_info is None:\n            self.logger.debug(\"No cache key found for response, returning raw response\")\n            yield response\n\n        if request_info.method == \"eth_subscribe\" and \"result\" in response.keys():\n            # if response for the initial eth_subscribe request, which returns the\n            # subscription id\n            subscription_id = response[\"result\"]\n            cache_key = generate_cache_key(subscription_id)\n            if cache_key not in self._provider._async_response_processing_cache:\n                # cache by subscription id in order to process each response for the\n                # subscription as it comes in\n                self._provider.logger.debug(\n                    f\"Caching eth_subscription info:\\n    cache_key={cache_key},\\n    \"\n                    f\"request_info={request_info.__dict__}\"\n                )\n                self._provider._async_response_processing_cache.cache(\n                    cache_key, request_info\n                )\n\n        # pipe response back through middleware response processors\n        if len(request_info.middleware_response_processors) > 0:\n            response = pipe(response, *request_info.middleware_response_processors)\n\n        (\n            result_formatters,\n            error_formatters,\n            null_formatters,\n        ) = request_info.response_formatters\n        partly_formatted_response = self.formatted_response(\n            response,\n            request_info.params,\n            error_formatters,\n            null_formatters,\n        )\n        yield apply_result_formatters(result_formatters, partly_formatted_response)\n\n\nclass _AsyncPersistentRecvStream:\n    \"\"\"\n    Async generator for receiving responses from a persistent connection. This\n    abstraction is necessary to define the `__aiter__()` method required for\n    use with \"async for\" loops.\n    \"\"\"\n\n    def __init__(self, manager: RequestManager, *args: Any, **kwargs: Any) -> None:\n        self.manager = manager\n        super().__init__(*args, **kwargs)\n\n    def __aiter__(self) -> AsyncGenerator[RPCResponse, None]:\n        while True:\n            try:\n                return self.manager._ws_recv_stream()\n            except ConnectionClosedOK:\n                pass\n", "path": "web3/manager.py"}, {"content": "from .websocket import (  # noqa: F401\n    WebsocketProvider,\n)\nfrom .websocket_v2 import (  # noqa: F401\n    WebsocketProviderV2,\n)\n", "path": "web3/providers/websocket/__init__.py"}], "after_files": [{"content": "import asyncio\nimport json\nimport logging\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    AsyncGenerator,\n    Callable,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n    cast,\n)\n\nfrom eth_utils.toolz import (\n    pipe,\n)\nfrom hexbytes import (\n    HexBytes,\n)\nfrom websockets.exceptions import (\n    ConnectionClosedOK,\n)\n\nfrom web3._utils.caching import (\n    generate_cache_key,\n)\nfrom web3.datastructures import (\n    NamedElementOnion,\n)\nfrom web3.exceptions import (\n    BadResponseFormat,\n    MethodUnavailable,\n)\nfrom web3.middleware import (\n    abi_middleware,\n    async_attrdict_middleware,\n    async_buffered_gas_estimate_middleware,\n    async_gas_price_strategy_middleware,\n    async_name_to_address_middleware,\n    async_validation_middleware,\n    attrdict_middleware,\n    buffered_gas_estimate_middleware,\n    gas_price_strategy_middleware,\n    name_to_address_middleware,\n    validation_middleware,\n)\nfrom web3.module import (\n    apply_result_formatters,\n)\nfrom web3.providers import (\n    AutoProvider,\n    PersistentConnectionProvider,\n)\nfrom web3.types import (\n    AsyncMiddleware,\n    AsyncMiddlewareOnion,\n    Middleware,\n    MiddlewareOnion,\n    RPCEndpoint,\n    RPCResponse,\n)\n\nif TYPE_CHECKING:\n    from web3 import (  # noqa: F401\n        AsyncWeb3,\n        Web3,\n    )\n    from web3.providers import (  # noqa: F401\n        AsyncBaseProvider,\n        BaseProvider,\n    )\n\n\nNULL_RESPONSES = [None, HexBytes(\"0x\"), \"0x\"]\n\n\ndef apply_error_formatters(\n    error_formatters: Callable[..., Any],\n    response: RPCResponse,\n) -> RPCResponse:\n    if error_formatters:\n        formatted_resp = pipe(response, error_formatters)\n        return formatted_resp\n    else:\n        return response\n\n\ndef apply_null_result_formatters(\n    null_result_formatters: Callable[..., Any],\n    response: RPCResponse,\n    params: Optional[Any] = None,\n) -> RPCResponse:\n    if null_result_formatters:\n        formatted_resp = pipe(params, null_result_formatters)\n        return formatted_resp\n    else:\n        return response\n\n\nclass RequestManager:\n    logger = logging.getLogger(\"web3.RequestManager\")\n\n    middleware_onion: Union[\n        MiddlewareOnion, AsyncMiddlewareOnion, NamedElementOnion[None, None]\n    ]\n\n    def __init__(\n        self,\n        w3: Union[\"AsyncWeb3\", \"Web3\"],\n        provider: Optional[Union[\"BaseProvider\", \"AsyncBaseProvider\"]] = None,\n        middlewares: Optional[\n            Union[\n                Sequence[Tuple[Middleware, str]], Sequence[Tuple[AsyncMiddleware, str]]\n            ]\n        ] = None,\n    ) -> None:\n        self.w3 = w3\n\n        if provider is None:\n            self.provider = AutoProvider()\n        else:\n            self.provider = provider\n\n        if middlewares is None:\n            middlewares = (\n                self.async_default_middlewares()\n                if self.provider.is_async\n                else self.default_middlewares(cast(\"Web3\", w3))\n            )\n\n        self.middleware_onion = NamedElementOnion(middlewares)\n\n    w3: Union[\"AsyncWeb3\", \"Web3\"] = None\n    _provider = None\n\n    @property\n    def provider(self) -> Union[\"BaseProvider\", \"AsyncBaseProvider\"]:\n        return self._provider\n\n    @provider.setter\n    def provider(self, provider: Union[\"BaseProvider\", \"AsyncBaseProvider\"]) -> None:\n        self._provider = provider\n\n    @staticmethod\n    def default_middlewares(w3: \"Web3\") -> List[Tuple[Middleware, str]]:\n        \"\"\"\n        List the default middlewares for the request manager.\n        Leaving w3 unspecified will prevent the middleware from resolving names.\n        Documentation should remain in sync with these defaults.\n        \"\"\"\n        return [\n            (gas_price_strategy_middleware, \"gas_price_strategy\"),\n            (name_to_address_middleware(w3), \"name_to_address\"),\n            (attrdict_middleware, \"attrdict\"),\n            (validation_middleware, \"validation\"),\n            (abi_middleware, \"abi\"),\n            (buffered_gas_estimate_middleware, \"gas_estimate\"),\n        ]\n\n    @staticmethod\n    def async_default_middlewares() -> List[Tuple[AsyncMiddleware, str]]:\n        \"\"\"\n        List the default async middlewares for the request manager.\n        Documentation should remain in sync with these defaults.\n        \"\"\"\n        return [\n            (async_gas_price_strategy_middleware, \"gas_price_strategy\"),\n            (async_name_to_address_middleware, \"name_to_address\"),\n            (async_attrdict_middleware, \"attrdict\"),\n            (async_validation_middleware, \"validation\"),\n            (async_buffered_gas_estimate_middleware, \"gas_estimate\"),\n        ]\n\n    #\n    # Provider requests and response\n    #\n    def _make_request(\n        self, method: Union[RPCEndpoint, Callable[..., RPCEndpoint]], params: Any\n    ) -> RPCResponse:\n        provider = cast(\"BaseProvider\", self.provider)\n        request_func = provider.request_func(\n            cast(\"Web3\", self.w3), cast(MiddlewareOnion, self.middleware_onion)\n        )\n        self.logger.debug(f\"Making request. Method: {method}\")\n        return request_func(method, params)\n\n    async def _coro_make_request(\n        self, method: Union[RPCEndpoint, Callable[..., RPCEndpoint]], params: Any\n    ) -> RPCResponse:\n        provider = cast(\"AsyncBaseProvider\", self.provider)\n        request_func = await provider.request_func(\n            cast(\"AsyncWeb3\", self.w3),\n            cast(AsyncMiddlewareOnion, self.middleware_onion),\n        )\n        self.logger.debug(f\"Making request. Method: {method}\")\n        return await request_func(method, params)\n\n    @staticmethod\n    def formatted_response(\n        response: RPCResponse,\n        params: Any,\n        error_formatters: Optional[Callable[..., Any]] = None,\n        null_result_formatters: Optional[Callable[..., Any]] = None,\n    ) -> Any:\n        if \"error\" in response:\n            apply_error_formatters(error_formatters, response)\n\n            # guard against eth-tester case - eth-tester returns a string\n            # with no code, so can't parse what the error is.\n            if isinstance(response[\"error\"], dict):\n                resp_code = response[\"error\"].get(\"code\")\n                if resp_code == -32601:\n                    raise MethodUnavailable(response[\"error\"])\n            raise ValueError(response[\"error\"])\n        # NULL_RESPONSES includes None, so return False here as the default\n        # so we don't apply the null_result_formatters if there is no 'result' key\n        elif response.get(\"result\", False) in NULL_RESPONSES:\n            # null_result_formatters raise either a BlockNotFound\n            # or a TransactionNotFound error, depending on the method called\n            apply_null_result_formatters(null_result_formatters, response, params)\n            return response[\"result\"]\n        elif response.get(\"result\") is not None:\n            return response[\"result\"]\n        elif (\n            # eth_subscribe case\n            response.get(\"params\") is not None\n            and response[\"params\"].get(\"result\") is not None\n        ):\n            return response[\"params\"][\"result\"]\n        else:\n            raise BadResponseFormat(\n                \"The response was in an unexpected format and unable to be parsed. \"\n                f\"The raw response is: {response}\"\n            )\n\n    def request_blocking(\n        self,\n        method: Union[RPCEndpoint, Callable[..., RPCEndpoint]],\n        params: Any,\n        error_formatters: Optional[Callable[..., Any]] = None,\n        null_result_formatters: Optional[Callable[..., Any]] = None,\n    ) -> Any:\n        \"\"\"\n        Make a synchronous request using the provider\n        \"\"\"\n        response = self._make_request(method, params)\n        return self.formatted_response(\n            response, params, error_formatters, null_result_formatters\n        )\n\n    async def coro_request(\n        self,\n        method: Union[RPCEndpoint, Callable[..., RPCEndpoint]],\n        params: Any,\n        error_formatters: Optional[Callable[..., Any]] = None,\n        null_result_formatters: Optional[Callable[..., Any]] = None,\n    ) -> Any:\n        \"\"\"\n        Coroutine for making a request using the provider\n        \"\"\"\n        response = await self._coro_make_request(method, params)\n        return self.formatted_response(\n            response, params, error_formatters, null_result_formatters\n        )\n\n    # persistent connection\n    async def ws_send(\n        self,\n        method: Union[RPCEndpoint, Callable[..., RPCEndpoint]],\n        params: Any,\n    ) -> RPCResponse:\n        provider = cast(PersistentConnectionProvider, self._provider)\n        request_func = await provider.request_func(\n            cast(\"AsyncWeb3\", self.w3),\n            cast(AsyncMiddlewareOnion, self.middleware_onion),\n        )\n        self.logger.debug(\n            \"Making request to open websocket connection - \"\n            f\"uri: {provider.endpoint_uri}, method: {method}\"\n        )\n        await request_func(method, params)\n        return await asyncio.wait_for(\n            self.ws_recv(),\n            timeout=provider.call_timeout,\n        )\n\n    async def ws_recv(self) -> Any:\n        return await self._ws_recv_stream().__anext__()\n\n    def persistent_recv_stream(self) -> \"_AsyncPersistentRecvStream\":\n        return _AsyncPersistentRecvStream(self)\n\n    async def _ws_recv_stream(self) -> AsyncGenerator[RPCResponse, None]:\n        if not isinstance(self._provider, PersistentConnectionProvider):\n            raise TypeError(\n                \"Only websocket providers that maintain an open, persistent connection \"\n                \"can listen to websocket recv streams.\"\n            )\n\n        response = json.loads(\n            await asyncio.wait_for(\n                self._provider.ws.recv(),\n                timeout=self._provider.call_timeout,\n            )\n        )\n        request_info = self._provider._get_request_information_for_response(response)\n\n        if request_info is None:\n            self.logger.debug(\"No cache key found for response, returning raw response\")\n            yield response\n\n        else:\n            if request_info.method == \"eth_subscribe\" and \"result\" in response.keys():\n                # if response for the initial eth_subscribe request, which returns the\n                # subscription id\n                subscription_id = response[\"result\"]\n                cache_key = generate_cache_key(subscription_id)\n                if cache_key not in self._provider._async_response_processing_cache:\n                    # cache by subscription id in order to process each response for the\n                    # subscription as it comes in\n                    self._provider.logger.debug(\n                        f\"Caching eth_subscription info:\\n    \"\n                        f\"cache_key={cache_key},\\n    \"\n                        f\"request_info={request_info.__dict__}\"\n                    )\n                    self._provider._async_response_processing_cache.cache(\n                        cache_key, request_info\n                    )\n\n            # pipe response back through middleware response processors\n            if len(request_info.middleware_response_processors) > 0:\n                response = pipe(response, *request_info.middleware_response_processors)\n\n            (\n                result_formatters,\n                error_formatters,\n                null_formatters,\n            ) = request_info.response_formatters\n            partly_formatted_response = self.formatted_response(\n                response,\n                request_info.params,\n                error_formatters,\n                null_formatters,\n            )\n            yield apply_result_formatters(result_formatters, partly_formatted_response)\n\n\nclass _AsyncPersistentRecvStream:\n    \"\"\"\n    Async generator for receiving responses from a persistent connection. This\n    abstraction is necessary to define the `__aiter__()` method required for\n    use with \"async for\" loops.\n    \"\"\"\n\n    def __init__(self, manager: RequestManager, *args: Any, **kwargs: Any) -> None:\n        self.manager = manager\n        super().__init__(*args, **kwargs)\n\n    def __aiter__(self) -> AsyncGenerator[RPCResponse, None]:\n        while True:\n            try:\n                return self.manager._ws_recv_stream()\n            except ConnectionClosedOK:\n                pass\n", "path": "web3/manager.py"}, {"content": "from .websocket import (  # noqa: F401\n    DEFAULT_WEBSOCKET_TIMEOUT,\n    RESTRICTED_WEBSOCKET_KWARGS,\n    WebsocketProvider,\n)\nfrom .websocket_v2 import (  # noqa: F401\n    WebsocketProviderV2,\n)\n", "path": "web3/providers/websocket/__init__.py"}]}