Exth.Rpc (Exth v0.1.1)

View Source

Core module for making JSON-RPC requests to EVM-compatible blockchain nodes.

Provides a simple interface for creating clients, building requests, and handling responses using different transport options.

Quick Start

client = Rpc.new_client(:http, rpc_url: "https://eth-mainnet.example.com")

request = Rpc.request(client, "eth_blockNumber", [])
{:ok, response} = Rpc.send(client, request)

Summary

Functions

Returns the JSON-RPC protocol version used by the client.

Creates a new JSON-RPC client with the specified transport type and options.

Builds a new JSON-RPC request for the given method and parameters.

Sends a JSON-RPC request using the client's configured transport. Supports both single requests and batch requests.

Types

id()

@type id() :: pos_integer()

jsonrpc()

@type jsonrpc() :: String.t()

method()

@type method() :: String.t()

params()

@type params() :: [binary()]

Functions

jsonrpc_version()

@spec jsonrpc_version() :: jsonrpc()

Returns the JSON-RPC protocol version used by the client.

new_client(type, opts)

@spec new_client(
  Exth.Transport.type(),
  keyword()
) :: Exth.Rpc.Client.t()

Creates a new JSON-RPC client with the specified transport type and options.

Transport Types

  • :http - HTTP/HTTPS transport
  • :custom - Custom transport implementation

Options

  • :rpc_url - (Required) The endpoint URL
  • :encoder - Function to encode requests to JSON
  • :decoder - Function to decode JSON responses
  • :headers - Additional HTTP headers (HTTP transport only)
  • :timeout - Request timeout in ms (HTTP transport only)

Examples

client = Rpc.new_client(:http, rpc_url: "https://eth-mainnet.example.com")

request(client, method, params)

@spec request(Exth.Rpc.Client.t(), method(), params()) :: Exth.Rpc.Request.t()

Builds a new JSON-RPC request for the given method and parameters.

The request will automatically:

  • Set the protocol version to "2.0"
  • Generate a unique request ID
  • Format parameters according to the JSON-RPC spec

Examples

request = Rpc.request(client, "eth_blockNumber", [])
request = Rpc.request(client, "eth_getBalance", ["0x742d...", "latest"])

send(client, request)

Sends a JSON-RPC request using the client's configured transport. Supports both single requests and batch requests.

Returns

  • {:ok, response} - Successful single request with decoded response
  • {:ok, responses} - Successful batch request with list of responses
  • {:error, reason} - Request failed with error details (Exception.t() or map())

Examples

# Single request
{:ok, response} = Rpc.send(client, request)

# Batch request
{:ok, responses} = Rpc.send(client, [request1, request2])

# Error handling
{:error, reason} = Rpc.send(client, bad_request)