Exth.Transport.Websocket (Exth v0.4.2)

View Source

WebSocket transport implementation for JSON-RPC requests using Fresh.

Implements the Exth.Transport.Transportable protocol for making WebSocket connections to JSON-RPC endpoints. Uses Fresh as the WebSocket client library.

Features

  • Full-duplex communication
  • Automatic connection management
  • Asynchronous message handling
  • Support for both ws:// and wss:// protocols
  • Configurable dispatch callbacks
  • Connection state management

Usage

transport = Transportable.new(
  %Exth.Transport.Websocket{},
  rpc_url: "wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID",
  dispatch_callback: fn response -> handle_response(response) end
)

{:ok, response} = Transportable.call(transport, request)

Configuration

Required options:

  • :rpc_url - The WebSocket endpoint URL (must start with ws:// or wss://)
  • :dispatch_callback - Function to handle incoming messages (arity 1)

Message Flow

  1. Transport is initialized with a dispatch callback
  2. WebSocket connection is established
  3. Outgoing messages are sent through call/2
  4. Incoming messages are handled by the dispatch callback
  5. Connection is maintained for subsequent requests

Error Handling

The transport handles several error cases:

  • Invalid URL format
  • Missing required options
  • Connection failures
  • Message dispatch errors

Best Practices

  • Use wss:// for production environments
  • Implement proper error handling in dispatch callbacks
  • Monitor connection health
  • Handle reconnection scenarios
  • Clean up resources when done

See Exth.Transport.Transportable for protocol details.

Summary

Types

t()

@type t() :: %Exth.Transport.Websocket{
  dispatch_callback: function(),
  name: {:via, module(), {module(), String.t()}}
}

Functions

call(websocket, encoded_request)

@spec call(t(), String.t()) :: :ok

new(opts)

@spec new(keyword()) :: t()