We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
TypeError: Cannot convert None of type <class 'NoneType'> to bytes (in formatting middleware?)
* Version: 5.24.0
* Python: 3.8
* OS: linux
* `pip freeze` output

```
aiohttp==3.8.1
aiosignal==1.2.0
astroid==2.11.5
async-timeout==4.0.2
attrs==21.4.0
base58==2.1.1
bitarray==1.2.2
black==21.12b0
blinker==1.4
boto3==1.23.0
boto3-stubs==1.23.0
botocore==1.26.0
botocore-stubs==1.26.0.post1
CacheControl==0.12.11
cachy==0.3.0
certifi==2021.10.8
cffi==1.15.0
charset-normalizer==2.0.12
cleo==0.8.1
click==8.0.4
clickclick==20.10.2
clikit==0.6.2
common==0.1.0
connexion==2.13.1
crashtest==0.3.1
cryptography==37.0.2
cytoolz==0.11.2
dill==0.3.4
distlib==0.3.4
ecdsa==0.17.0
eth-abi==2.1.1
eth-account==0.5.7
eth-hash==0.3.2
eth-keyfile==0.5.1
eth-keys==0.3.4
eth-rlp==0.2.1
eth-typing==2.3.0
eth-utils==1.10.0
filelock==3.7.0
flasgger==0.9.5
Flask==2.1.2
Flask-Pydantic==0.9.0
frozenlist==1.3.0
hexbytes==0.2.2
html5lib==1.1
idna==3.3
importlib-metadata==4.11.3
importlib-resources==5.6.0
inflection==0.5.1
iniconfig==1.1.1
ipfshttpclient==0.8.0a2
isort==5.10.1
itsdangerous==2.1.2
jeepney==0.8.0
Jinja2==3.1.2
jmespath==1.0.0
jsonschema==3.2.0
keyring==23.5.0
lazy-object-proxy==1.7.1
lockfile==0.12.2
lru-dict==1.1.7
MarkupSafe==2.1.1
mccabe==0.7.0
mistune==2.0.2
msgpack==1.0.3
multiaddr==0.0.9
multidict==6.0.2
mypy==0.910
mypy-extensions==0.4.3
netaddr==0.8.0
openapi-schema-validator==0.2.3
openapi-spec-validator==0.3.1
packaging==20.9
parsimonious==0.8.1
pastel==0.2.1
pathspec==0.9.0
pendulum==2.1.2
pexpect==4.8.0
pip==22.0.4
pkginfo==1.8.2
platformdirs==2.5.2
pluggy==1.0.0
poetry==1.1.13
poetry-core==1.0.8
protobuf==3.20.1
ptyprocess==0.7.0
py==1.11.0
pyasn1==0.4.8
pycparser==2.21
pycryptodome==3.14.1
pydantic==1.9.0
pylev==1.4.0
pylint==2.13.9
pyparsing==3.0.9
pyrsistent==0.16.1
pytest==7.1.2
python-dateutil==2.8.2
python-dotenv==0.19.2
python-jose==3.3.0
pytzdata==2020.1
PyYAML==5.4.1
requests==2.27.1
requests-toolbelt==0.9.1
rlp==2.0.1
rsa==4.8
s3transfer==0.5.2
SecretStorage==3.3.2
sentry-sdk==1.5.12
setuptools==62.1.0
shellingham==1.4.0
six==1.16.0
swagger-ui-bundle==0.0.9
toml==0.10.2
tomli==1.2.3
tomlkit==0.10.2
toolz==0.11.2
types-boto3==1.0.2
types-requests==2.27.25
types-urllib3==1.26.14
typing_extensions==4.2.0
urllib3==1.26.9
varint==1.0.2
virtualenv==20.14.1
web3==5.24.0
webencodings==0.5.1
websockets==9.1
Werkzeug==2.1.2
wheel==0.37.1
wrapt==1.14.1
yarl==1.7.2
zipp==3.8.0
```


### What was wrong?

on a company project we're getting the following error once every few moons
```
Traceback (most recent call last):
  .... (company code that calls contract.functions.functionName().call())
  File "/usr/local/lib/python3.8/site-packages/web3/contract.py", line 959, in call
    return call_contract_function(
  File "/usr/local/lib/python3.8/site-packages/web3/contract.py", line 1503, in call_contract_function
    return_data = web3.eth.call(
  File "/usr/local/lib/python3.8/site-packages/web3/module.py", line 57, in caller
    result = w3.manager.request_blocking(method_str,
  File "/usr/local/lib/python3.8/site-packages/web3/manager.py", line 186, in request_blocking
    response = self._make_request(method, params)
  File "/usr/local/lib/python3.8/site-packages/web3/manager.py", line 147, in _make_request
    return request_func(method, params)
  File "cytoolz/functoolz.pyx", line 254, in cytoolz.functoolz.curry.__call__
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "/usr/local/lib/python3.8/site-packages/web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "/usr/local/lib/python3.8/site-packages/web3/middleware/gas_price_strategy.py", line 90, in middleware
    return make_request(method, params)
  File "cytoolz/functoolz.pyx", line 254, in cytoolz.functoolz.curry.__call__
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "/usr/local/lib/python3.8/site-packages/web3/middleware/formatting.py", line 74, in apply_formatters
    response = make_request(method, formatted_params)
  File "/usr/local/lib/python3.8/site-packages/web3/middleware/attrdict.py", line 33, in middleware
    response = make_request(method, params)
  File "cytoolz/functoolz.pyx", line 254, in cytoolz.functoolz.curry.__call__
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "/usr/local/lib/python3.8/site-packages/web3/middleware/formatting.py", line 83, in apply_formatters
    formatter(response["result"]),
  File "/usr/local/lib/python3.8/site-packages/hexbytes/main.py", line 23, in __new__
    bytesval = to_bytes(val)
  File "/usr/local/lib/python3.8/site-packages/hexbytes/_utils.py", line 30, in to_bytes
    raise TypeError(f"Cannot convert {val!r} of type {type(val)} to bytes")
TypeError: Cannot convert None of type <class 'NoneType'> to bytes
```

unfortunately we haven't managed to find code to reproduce this issue consistently, it just happens sometimes on a pretty standard `call` that we issue quite often and that almost always succeeds. any pointers would be appreciated !


--- 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/middleware/formatting.py`
Content:
```
1 from typing import (
2     TYPE_CHECKING,
3     Any,
4     Callable,
5     Coroutine,
6     Optional,
7 )
8 
9 from eth_utils.toolz import (
10     assoc,
11     merge,
12 )
13 
14 from web3.types import (
15     AsyncMiddleware,
16     AsyncMiddlewareCoroutine,
17     Formatters,
18     FormattersDict,
19     Literal,
20     Middleware,
21     RPCEndpoint,
22     RPCResponse,
23 )
24 
25 if TYPE_CHECKING:
26     from web3 import (  # noqa: F401
27         AsyncWeb3,
28         Web3,
29     )
30 
31 FORMATTER_DEFAULTS: FormattersDict = {
32     "request_formatters": {},
33     "result_formatters": {},
34     "error_formatters": {},
35 }
36 
37 
38 def _apply_response_formatters(
39     method: RPCEndpoint,
40     response: RPCResponse,
41     result_formatters: Formatters,
42     error_formatters: Formatters,
43 ) -> RPCResponse:
44     def _format_response(
45         response_type: Literal["result", "error"],
46         method_response_formatter: Callable[..., Any],
47     ) -> RPCResponse:
48         appropriate_response = response[response_type]
49         return assoc(
50             response, response_type, method_response_formatter(appropriate_response)
51         )
52 
53     if "result" in response and method in result_formatters:
54         return _format_response("result", result_formatters[method])
55     elif "error" in response and method in error_formatters:
56         return _format_response("error", error_formatters[method])
57     else:
58         return response
59 
60 
61 # --- sync -- #
62 
63 
64 def construct_formatting_middleware(
65     request_formatters: Optional[Formatters] = None,
66     result_formatters: Optional[Formatters] = None,
67     error_formatters: Optional[Formatters] = None,
68 ) -> Middleware:
69     def ignore_web3_in_standard_formatters(
70         _w3: "Web3",
71         _method: RPCEndpoint,
72     ) -> FormattersDict:
73         return dict(
74             request_formatters=request_formatters or {},
75             result_formatters=result_formatters or {},
76             error_formatters=error_formatters or {},
77         )
78 
79     return construct_web3_formatting_middleware(ignore_web3_in_standard_formatters)
80 
81 
82 def construct_web3_formatting_middleware(
83     web3_formatters_builder: Callable[["Web3", RPCEndpoint], FormattersDict],
84 ) -> Middleware:
85     def formatter_middleware(
86         make_request: Callable[[RPCEndpoint, Any], Any],
87         w3: "Web3",
88     ) -> Callable[[RPCEndpoint, Any], RPCResponse]:
89         def middleware(method: RPCEndpoint, params: Any) -> RPCResponse:
90             formatters = merge(
91                 FORMATTER_DEFAULTS,
92                 web3_formatters_builder(w3, method),
93             )
94             request_formatters = formatters.pop("request_formatters")
95 
96             if method in request_formatters:
97                 formatter = request_formatters[method]
98                 params = formatter(params)
99             response = make_request(method, params)
100 
101             return _apply_response_formatters(
102                 method=method, response=response, **formatters
103             )
104 
105         return middleware
106 
107     return formatter_middleware
108 
109 
110 # --- async --- #
111 
112 
113 async def async_construct_formatting_middleware(
114     request_formatters: Optional[Formatters] = None,
115     result_formatters: Optional[Formatters] = None,
116     error_formatters: Optional[Formatters] = None,
117 ) -> AsyncMiddleware:
118     async def ignore_web3_in_standard_formatters(
119         _async_w3: "AsyncWeb3",
120         _method: RPCEndpoint,
121     ) -> FormattersDict:
122         return dict(
123             request_formatters=request_formatters or {},
124             result_formatters=result_formatters or {},
125             error_formatters=error_formatters or {},
126         )
127 
128     return await async_construct_web3_formatting_middleware(
129         ignore_web3_in_standard_formatters
130     )
131 
132 
133 async def async_construct_web3_formatting_middleware(
134     async_web3_formatters_builder: Callable[
135         ["AsyncWeb3", RPCEndpoint], Coroutine[Any, Any, FormattersDict]
136     ]
137 ) -> Callable[
138     [Callable[[RPCEndpoint, Any], Any], "AsyncWeb3"],
139     Coroutine[Any, Any, AsyncMiddlewareCoroutine],
140 ]:
141     async def formatter_middleware(
142         make_request: Callable[[RPCEndpoint, Any], Any],
143         w3: "AsyncWeb3",
144     ) -> AsyncMiddlewareCoroutine:
145         async def middleware(method: RPCEndpoint, params: Any) -> RPCResponse:
146             formatters = merge(
147                 FORMATTER_DEFAULTS,
148                 await async_web3_formatters_builder(w3, method),
149             )
150             request_formatters = formatters.pop("request_formatters")
151 
152             if method in request_formatters:
153                 formatter = request_formatters[method]
154                 params = formatter(params)
155             response = await make_request(method, params)
156 
157             return _apply_response_formatters(
158                 method=method, response=response, **formatters
159             )
160 
161         return middleware
162 
163     return formatter_middleware
164
```
--- 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/middleware/formatting.py b/web3/middleware/formatting.py
--- a/web3/middleware/formatting.py
+++ b/web3/middleware/formatting.py
@@ -50,7 +50,11 @@
             response, response_type, method_response_formatter(appropriate_response)
         )
 
-    if "result" in response and method in result_formatters:
+    if (
+        "result" in response
+        and response["result"] is not None
+        and method in result_formatters
+    ):
         return _format_response("result", result_formatters[method])
     elif "error" in response and method in error_formatters:
         return _format_response("error", error_formatters[method])

{"golden_diff": "diff --git a/web3/middleware/formatting.py b/web3/middleware/formatting.py\n--- a/web3/middleware/formatting.py\n+++ b/web3/middleware/formatting.py\n@@ -50,7 +50,11 @@\n             response, response_type, method_response_formatter(appropriate_response)\n         )\n \n-    if \"result\" in response and method in result_formatters:\n+    if (\n+        \"result\" in response\n+        and response[\"result\"] is not None\n+        and method in result_formatters\n+    ):\n         return _format_response(\"result\", result_formatters[method])\n     elif \"error\" in response and method in error_formatters:\n         return _format_response(\"error\", error_formatters[method])\n", "issue": "TypeError: Cannot convert None of type <class 'NoneType'> to bytes (in formatting middleware?)\n* Version: 5.24.0\r\n* Python: 3.8\r\n* OS: linux\r\n* `pip freeze` output\r\n\r\n```\r\naiohttp==3.8.1\r\naiosignal==1.2.0\r\nastroid==2.11.5\r\nasync-timeout==4.0.2\r\nattrs==21.4.0\r\nbase58==2.1.1\r\nbitarray==1.2.2\r\nblack==21.12b0\r\nblinker==1.4\r\nboto3==1.23.0\r\nboto3-stubs==1.23.0\r\nbotocore==1.26.0\r\nbotocore-stubs==1.26.0.post1\r\nCacheControl==0.12.11\r\ncachy==0.3.0\r\ncertifi==2021.10.8\r\ncffi==1.15.0\r\ncharset-normalizer==2.0.12\r\ncleo==0.8.1\r\nclick==8.0.4\r\nclickclick==20.10.2\r\nclikit==0.6.2\r\ncommon==0.1.0\r\nconnexion==2.13.1\r\ncrashtest==0.3.1\r\ncryptography==37.0.2\r\ncytoolz==0.11.2\r\ndill==0.3.4\r\ndistlib==0.3.4\r\necdsa==0.17.0\r\neth-abi==2.1.1\r\neth-account==0.5.7\r\neth-hash==0.3.2\r\neth-keyfile==0.5.1\r\neth-keys==0.3.4\r\neth-rlp==0.2.1\r\neth-typing==2.3.0\r\neth-utils==1.10.0\r\nfilelock==3.7.0\r\nflasgger==0.9.5\r\nFlask==2.1.2\r\nFlask-Pydantic==0.9.0\r\nfrozenlist==1.3.0\r\nhexbytes==0.2.2\r\nhtml5lib==1.1\r\nidna==3.3\r\nimportlib-metadata==4.11.3\r\nimportlib-resources==5.6.0\r\ninflection==0.5.1\r\niniconfig==1.1.1\r\nipfshttpclient==0.8.0a2\r\nisort==5.10.1\r\nitsdangerous==2.1.2\r\njeepney==0.8.0\r\nJinja2==3.1.2\r\njmespath==1.0.0\r\njsonschema==3.2.0\r\nkeyring==23.5.0\r\nlazy-object-proxy==1.7.1\r\nlockfile==0.12.2\r\nlru-dict==1.1.7\r\nMarkupSafe==2.1.1\r\nmccabe==0.7.0\r\nmistune==2.0.2\r\nmsgpack==1.0.3\r\nmultiaddr==0.0.9\r\nmultidict==6.0.2\r\nmypy==0.910\r\nmypy-extensions==0.4.3\r\nnetaddr==0.8.0\r\nopenapi-schema-validator==0.2.3\r\nopenapi-spec-validator==0.3.1\r\npackaging==20.9\r\nparsimonious==0.8.1\r\npastel==0.2.1\r\npathspec==0.9.0\r\npendulum==2.1.2\r\npexpect==4.8.0\r\npip==22.0.4\r\npkginfo==1.8.2\r\nplatformdirs==2.5.2\r\npluggy==1.0.0\r\npoetry==1.1.13\r\npoetry-core==1.0.8\r\nprotobuf==3.20.1\r\nptyprocess==0.7.0\r\npy==1.11.0\r\npyasn1==0.4.8\r\npycparser==2.21\r\npycryptodome==3.14.1\r\npydantic==1.9.0\r\npylev==1.4.0\r\npylint==2.13.9\r\npyparsing==3.0.9\r\npyrsistent==0.16.1\r\npytest==7.1.2\r\npython-dateutil==2.8.2\r\npython-dotenv==0.19.2\r\npython-jose==3.3.0\r\npytzdata==2020.1\r\nPyYAML==5.4.1\r\nrequests==2.27.1\r\nrequests-toolbelt==0.9.1\r\nrlp==2.0.1\r\nrsa==4.8\r\ns3transfer==0.5.2\r\nSecretStorage==3.3.2\r\nsentry-sdk==1.5.12\r\nsetuptools==62.1.0\r\nshellingham==1.4.0\r\nsix==1.16.0\r\nswagger-ui-bundle==0.0.9\r\ntoml==0.10.2\r\ntomli==1.2.3\r\ntomlkit==0.10.2\r\ntoolz==0.11.2\r\ntypes-boto3==1.0.2\r\ntypes-requests==2.27.25\r\ntypes-urllib3==1.26.14\r\ntyping_extensions==4.2.0\r\nurllib3==1.26.9\r\nvarint==1.0.2\r\nvirtualenv==20.14.1\r\nweb3==5.24.0\r\nwebencodings==0.5.1\r\nwebsockets==9.1\r\nWerkzeug==2.1.2\r\nwheel==0.37.1\r\nwrapt==1.14.1\r\nyarl==1.7.2\r\nzipp==3.8.0\r\n```\r\n\r\n\r\n### What was wrong?\r\n\r\non a company project we're getting the following error once every few moons\r\n```\r\nTraceback (most recent call last):\r\n  .... (company code that calls contract.functions.functionName().call())\r\n  File \"/usr/local/lib/python3.8/site-packages/web3/contract.py\", line 959, in call\r\n    return call_contract_function(\r\n  File \"/usr/local/lib/python3.8/site-packages/web3/contract.py\", line 1503, in call_contract_function\r\n    return_data = web3.eth.call(\r\n  File \"/usr/local/lib/python3.8/site-packages/web3/module.py\", line 57, in caller\r\n    result = w3.manager.request_blocking(method_str,\r\n  File \"/usr/local/lib/python3.8/site-packages/web3/manager.py\", line 186, in request_blocking\r\n    response = self._make_request(method, params)\r\n  File \"/usr/local/lib/python3.8/site-packages/web3/manager.py\", line 147, in _make_request\r\n    return request_func(method, params)\r\n  File \"cytoolz/functoolz.pyx\", line 254, in cytoolz.functoolz.curry.__call__\r\n  File \"cytoolz/functoolz.pyx\", line 250, in cytoolz.functoolz.curry.__call__\r\n  File \"/usr/local/lib/python3.8/site-packages/web3/middleware/formatting.py\", line 76, in apply_formatters\r\n    response = make_request(method, params)\r\n  File \"/usr/local/lib/python3.8/site-packages/web3/middleware/gas_price_strategy.py\", line 90, in middleware\r\n    return make_request(method, params)\r\n  File \"cytoolz/functoolz.pyx\", line 254, in cytoolz.functoolz.curry.__call__\r\n  File \"cytoolz/functoolz.pyx\", line 250, in cytoolz.functoolz.curry.__call__\r\n  File \"/usr/local/lib/python3.8/site-packages/web3/middleware/formatting.py\", line 74, in apply_formatters\r\n    response = make_request(method, formatted_params)\r\n  File \"/usr/local/lib/python3.8/site-packages/web3/middleware/attrdict.py\", line 33, in middleware\r\n    response = make_request(method, params)\r\n  File \"cytoolz/functoolz.pyx\", line 254, in cytoolz.functoolz.curry.__call__\r\n  File \"cytoolz/functoolz.pyx\", line 250, in cytoolz.functoolz.curry.__call__\r\n  File \"/usr/local/lib/python3.8/site-packages/web3/middleware/formatting.py\", line 83, in apply_formatters\r\n    formatter(response[\"result\"]),\r\n  File \"/usr/local/lib/python3.8/site-packages/hexbytes/main.py\", line 23, in __new__\r\n    bytesval = to_bytes(val)\r\n  File \"/usr/local/lib/python3.8/site-packages/hexbytes/_utils.py\", line 30, in to_bytes\r\n    raise TypeError(f\"Cannot convert {val!r} of type {type(val)} to bytes\")\r\nTypeError: Cannot convert None of type <class 'NoneType'> to bytes\r\n```\r\n\r\nunfortunately we haven't managed to find code to reproduce this issue consistently, it just happens sometimes on a pretty standard `call` that we issue quite often and that almost always succeeds. any pointers would be appreciated !\r\n\n", "before_files": [{"content": "from typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Coroutine,\n    Optional,\n)\n\nfrom eth_utils.toolz import (\n    assoc,\n    merge,\n)\n\nfrom web3.types import (\n    AsyncMiddleware,\n    AsyncMiddlewareCoroutine,\n    Formatters,\n    FormattersDict,\n    Literal,\n    Middleware,\n    RPCEndpoint,\n    RPCResponse,\n)\n\nif TYPE_CHECKING:\n    from web3 import (  # noqa: F401\n        AsyncWeb3,\n        Web3,\n    )\n\nFORMATTER_DEFAULTS: FormattersDict = {\n    \"request_formatters\": {},\n    \"result_formatters\": {},\n    \"error_formatters\": {},\n}\n\n\ndef _apply_response_formatters(\n    method: RPCEndpoint,\n    response: RPCResponse,\n    result_formatters: Formatters,\n    error_formatters: Formatters,\n) -> RPCResponse:\n    def _format_response(\n        response_type: Literal[\"result\", \"error\"],\n        method_response_formatter: Callable[..., Any],\n    ) -> RPCResponse:\n        appropriate_response = response[response_type]\n        return assoc(\n            response, response_type, method_response_formatter(appropriate_response)\n        )\n\n    if \"result\" in response and method in result_formatters:\n        return _format_response(\"result\", result_formatters[method])\n    elif \"error\" in response and method in error_formatters:\n        return _format_response(\"error\", error_formatters[method])\n    else:\n        return response\n\n\n# --- sync -- #\n\n\ndef construct_formatting_middleware(\n    request_formatters: Optional[Formatters] = None,\n    result_formatters: Optional[Formatters] = None,\n    error_formatters: Optional[Formatters] = None,\n) -> Middleware:\n    def ignore_web3_in_standard_formatters(\n        _w3: \"Web3\",\n        _method: RPCEndpoint,\n    ) -> FormattersDict:\n        return dict(\n            request_formatters=request_formatters or {},\n            result_formatters=result_formatters or {},\n            error_formatters=error_formatters or {},\n        )\n\n    return construct_web3_formatting_middleware(ignore_web3_in_standard_formatters)\n\n\ndef construct_web3_formatting_middleware(\n    web3_formatters_builder: Callable[[\"Web3\", RPCEndpoint], FormattersDict],\n) -> Middleware:\n    def formatter_middleware(\n        make_request: Callable[[RPCEndpoint, Any], Any],\n        w3: \"Web3\",\n    ) -> Callable[[RPCEndpoint, Any], RPCResponse]:\n        def middleware(method: RPCEndpoint, params: Any) -> RPCResponse:\n            formatters = merge(\n                FORMATTER_DEFAULTS,\n                web3_formatters_builder(w3, method),\n            )\n            request_formatters = formatters.pop(\"request_formatters\")\n\n            if method in request_formatters:\n                formatter = request_formatters[method]\n                params = formatter(params)\n            response = make_request(method, params)\n\n            return _apply_response_formatters(\n                method=method, response=response, **formatters\n            )\n\n        return middleware\n\n    return formatter_middleware\n\n\n# --- async --- #\n\n\nasync def async_construct_formatting_middleware(\n    request_formatters: Optional[Formatters] = None,\n    result_formatters: Optional[Formatters] = None,\n    error_formatters: Optional[Formatters] = None,\n) -> AsyncMiddleware:\n    async def ignore_web3_in_standard_formatters(\n        _async_w3: \"AsyncWeb3\",\n        _method: RPCEndpoint,\n    ) -> FormattersDict:\n        return dict(\n            request_formatters=request_formatters or {},\n            result_formatters=result_formatters or {},\n            error_formatters=error_formatters or {},\n        )\n\n    return await async_construct_web3_formatting_middleware(\n        ignore_web3_in_standard_formatters\n    )\n\n\nasync def async_construct_web3_formatting_middleware(\n    async_web3_formatters_builder: Callable[\n        [\"AsyncWeb3\", RPCEndpoint], Coroutine[Any, Any, FormattersDict]\n    ]\n) -> Callable[\n    [Callable[[RPCEndpoint, Any], Any], \"AsyncWeb3\"],\n    Coroutine[Any, Any, AsyncMiddlewareCoroutine],\n]:\n    async def formatter_middleware(\n        make_request: Callable[[RPCEndpoint, Any], Any],\n        w3: \"AsyncWeb3\",\n    ) -> AsyncMiddlewareCoroutine:\n        async def middleware(method: RPCEndpoint, params: Any) -> RPCResponse:\n            formatters = merge(\n                FORMATTER_DEFAULTS,\n                await async_web3_formatters_builder(w3, method),\n            )\n            request_formatters = formatters.pop(\"request_formatters\")\n\n            if method in request_formatters:\n                formatter = request_formatters[method]\n                params = formatter(params)\n            response = await make_request(method, params)\n\n            return _apply_response_formatters(\n                method=method, response=response, **formatters\n            )\n\n        return middleware\n\n    return formatter_middleware\n", "path": "web3/middleware/formatting.py"}], "after_files": [{"content": "from typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Coroutine,\n    Optional,\n)\n\nfrom eth_utils.toolz import (\n    assoc,\n    merge,\n)\n\nfrom web3.types import (\n    AsyncMiddleware,\n    AsyncMiddlewareCoroutine,\n    Formatters,\n    FormattersDict,\n    Literal,\n    Middleware,\n    RPCEndpoint,\n    RPCResponse,\n)\n\nif TYPE_CHECKING:\n    from web3 import (  # noqa: F401\n        AsyncWeb3,\n        Web3,\n    )\n\nFORMATTER_DEFAULTS: FormattersDict = {\n    \"request_formatters\": {},\n    \"result_formatters\": {},\n    \"error_formatters\": {},\n}\n\n\ndef _apply_response_formatters(\n    method: RPCEndpoint,\n    response: RPCResponse,\n    result_formatters: Formatters,\n    error_formatters: Formatters,\n) -> RPCResponse:\n    def _format_response(\n        response_type: Literal[\"result\", \"error\"],\n        method_response_formatter: Callable[..., Any],\n    ) -> RPCResponse:\n        appropriate_response = response[response_type]\n        return assoc(\n            response, response_type, method_response_formatter(appropriate_response)\n        )\n\n    if (\n        \"result\" in response\n        and response[\"result\"] is not None\n        and method in result_formatters\n    ):\n        return _format_response(\"result\", result_formatters[method])\n    elif \"error\" in response and method in error_formatters:\n        return _format_response(\"error\", error_formatters[method])\n    else:\n        return response\n\n\n# --- sync -- #\n\n\ndef construct_formatting_middleware(\n    request_formatters: Optional[Formatters] = None,\n    result_formatters: Optional[Formatters] = None,\n    error_formatters: Optional[Formatters] = None,\n) -> Middleware:\n    def ignore_web3_in_standard_formatters(\n        _w3: \"Web3\",\n        _method: RPCEndpoint,\n    ) -> FormattersDict:\n        return dict(\n            request_formatters=request_formatters or {},\n            result_formatters=result_formatters or {},\n            error_formatters=error_formatters or {},\n        )\n\n    return construct_web3_formatting_middleware(ignore_web3_in_standard_formatters)\n\n\ndef construct_web3_formatting_middleware(\n    web3_formatters_builder: Callable[[\"Web3\", RPCEndpoint], FormattersDict],\n) -> Middleware:\n    def formatter_middleware(\n        make_request: Callable[[RPCEndpoint, Any], Any],\n        w3: \"Web3\",\n    ) -> Callable[[RPCEndpoint, Any], RPCResponse]:\n        def middleware(method: RPCEndpoint, params: Any) -> RPCResponse:\n            formatters = merge(\n                FORMATTER_DEFAULTS,\n                web3_formatters_builder(w3, method),\n            )\n            request_formatters = formatters.pop(\"request_formatters\")\n\n            if method in request_formatters:\n                formatter = request_formatters[method]\n                params = formatter(params)\n            response = make_request(method, params)\n\n            return _apply_response_formatters(\n                method=method, response=response, **formatters\n            )\n\n        return middleware\n\n    return formatter_middleware\n\n\n# --- async --- #\n\n\nasync def async_construct_formatting_middleware(\n    request_formatters: Optional[Formatters] = None,\n    result_formatters: Optional[Formatters] = None,\n    error_formatters: Optional[Formatters] = None,\n) -> AsyncMiddleware:\n    async def ignore_web3_in_standard_formatters(\n        _async_w3: \"AsyncWeb3\",\n        _method: RPCEndpoint,\n    ) -> FormattersDict:\n        return dict(\n            request_formatters=request_formatters or {},\n            result_formatters=result_formatters or {},\n            error_formatters=error_formatters or {},\n        )\n\n    return await async_construct_web3_formatting_middleware(\n        ignore_web3_in_standard_formatters\n    )\n\n\nasync def async_construct_web3_formatting_middleware(\n    async_web3_formatters_builder: Callable[\n        [\"AsyncWeb3\", RPCEndpoint], Coroutine[Any, Any, FormattersDict]\n    ]\n) -> Callable[\n    [Callable[[RPCEndpoint, Any], Any], \"AsyncWeb3\"],\n    Coroutine[Any, Any, AsyncMiddlewareCoroutine],\n]:\n    async def formatter_middleware(\n        make_request: Callable[[RPCEndpoint, Any], Any],\n        w3: \"AsyncWeb3\",\n    ) -> AsyncMiddlewareCoroutine:\n        async def middleware(method: RPCEndpoint, params: Any) -> RPCResponse:\n            formatters = merge(\n                FORMATTER_DEFAULTS,\n                await async_web3_formatters_builder(w3, method),\n            )\n            request_formatters = formatters.pop(\"request_formatters\")\n\n            if method in request_formatters:\n                formatter = request_formatters[method]\n                params = formatter(params)\n            response = await make_request(method, params)\n\n            return _apply_response_formatters(\n                method=method, response=response, **formatters\n            )\n\n        return middleware\n\n    return formatter_middleware\n", "path": "web3/middleware/formatting.py"}]}