Skip to content

Commit ca56e00

Browse files
committed
feat: eth client to get block by number
1 parent 39e4018 commit ca56e00

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
defmodule Explorer.EthClient do
2+
require Logger
3+
@rpc_url System.get_env("RPC_URL")
4+
5+
def get_block_by_number(block_number) do
6+
eth_send("eth_getBlockByNumber", [block_number, false])
7+
end
8+
9+
def eth_send(method, params, id \\ 1) do
10+
headers = [{"Content-Type", "application/json"}]
11+
body = Jason.encode!(%{jsonrpc: "2.0", method: method, params: params, id: id})
12+
request = Finch.build(:post, @rpc_url, headers, body)
13+
response = Finch.request(request, Explorer.Finch, [])
14+
15+
case response do
16+
{:ok, %Finch.Response{status: 200, body: body}} ->
17+
case Jason.decode(body) do
18+
{:ok, %{error: error} = _} -> {:error, error.message}
19+
{:ok, body} -> {:ok, Map.get(body, "result")}
20+
{:error, _} -> {:error, :invalid_json}
21+
end
22+
23+
{:ok, %Finch.Response{status: status}} ->
24+
{:error, status}
25+
26+
{:error, reason} ->
27+
{:error, reason}
28+
end
29+
end
30+
end

0 commit comments

Comments
 (0)