Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 24 additions & 34 deletions web3/middleware/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
Any,
Callable,
Coroutine,
Literal,
Union,
cast,
)
Expand Down Expand Up @@ -55,46 +54,37 @@ def _apply_response_formatters(
error_formatters: Formatters,
response: RPCResponse,
) -> RPCResponse:
def _format_response(
response_type: Literal["result", "error", "params"],
method_response_formatter: Callable[..., Any],
) -> RPCResponse:
appropriate_response = response[response_type]

if response_type == "params":
appropriate_response = cast(EthSubscriptionParams, response[response_type])
if not isinstance(response, dict):
raise BadResponseFormat(
"Malformed response: expected a valid JSON-RPC response object, got: "
"`{}`".format(response)
)

result_formatter = result_formatters.get(method)
if result_formatter is not None:
result = response.get("result")
if result is not None:
return assoc(response, "result", result_formatter(result))

params = response.get("params")
if params is not None and params.get("result") is not None:
# eth_subscription responses
subscription_params = cast(EthSubscriptionParams, params)
return assoc(
response,
response_type,
"params",
assoc(
response["params"],
params,
"result",
method_response_formatter(appropriate_response["result"]),
result_formatter(subscription_params["result"]),
),
)
else:
return assoc(
response, response_type, method_response_formatter(appropriate_response)
)

if not isinstance(response, dict):
raise BadResponseFormat(
"Malformed response: expected a valid JSON-RPC response object, got: "
"`{}`".format(response)
)
elif response.get("result") is not None and method in result_formatters:
return _format_response("result", result_formatters[method])
elif (
# eth_subscription responses
response.get("params") is not None
and response["params"].get("result") is not None
and method in result_formatters
):
return _format_response("params", result_formatters[method])
elif "error" in response and method in error_formatters:
return _format_response("error", error_formatters[method])
else:
return response
error_formatter = error_formatters.get(method)
if error_formatter is not None and "error" in response:
return assoc(response, "error", error_formatter(response["error"]))

return response


SYNC_FORMATTERS_BUILDER = Callable[["Web3", RPCEndpoint], FormattersDict]
Expand Down