diff --git a/apps/ethereum_jsonrpc/lib/ethereum_jsonrpc/ipc/IPCClient.ex b/apps/ethereum_jsonrpc/lib/ethereum_jsonrpc/ipc.ex similarity index 63% rename from apps/ethereum_jsonrpc/lib/ethereum_jsonrpc/ipc/IPCClient.ex rename to apps/ethereum_jsonrpc/lib/ethereum_jsonrpc/ipc.ex index ecadc47805..1d2d7dcea3 100644 --- a/apps/ethereum_jsonrpc/lib/ethereum_jsonrpc/ipc/IPCClient.ex +++ b/apps/ethereum_jsonrpc/lib/ethereum_jsonrpc/ipc.ex @@ -1,7 +1,9 @@ -defmodule EthereumJSONRPC.HTTP.IPCCLient do +defmodule EthereumJSONRPC.IPC do use GenServer @moduledoc false + # Server + def start_link(state \\ []) do GenServer.start_link(__MODULE__, Keyword.merge(state, socket: nil)) end @@ -55,4 +57,31 @@ defmodule EthereumJSONRPC.HTTP.IPCCLient do {:reply, response, state} end + + # Client + + def json_rpc(pid, payload, _opts) do + with {:ok, response} <- post(pid, payload), + {:ok, decoded_body} <- Jason.decode(response) do + case decoded_body do + %{"error" => error} -> {:error, error} + result = [%{} | _] -> {:ok, format_batch(result)} + result -> {:ok, Map.get(result, "result")} + end + else + {:error, %Jason.DecodeError{data: ""}} -> {:error, :empty_response} + {:error, error} -> {:error, {:invalid_json, error}} + {:error, error} -> {:error, error} + end + end + + defp format_batch(list) do + list + |> Enum.sort(fn %{"id" => id1}, %{"id" => id2} -> + id1 <= id2 + end) + |> Enum.map(fn %{"result" => result} -> + result + end) + end end