DeribitEx.RPC (deribit_ex v0.1.0)

View Source

Core JSON-RPC handling for Deribit WebSocket API.

This module provides infrastructure for:

  • Generating standard JSON-RPC requests
  • Parsing JSON-RPC responses
  • Handling error responses consistently
  • Tracking request IDs
  • Managing timeouts and retries
  • Extracting metadata from responses

This module is used by the Adapter and Client to ensure consistent RPC handling and error management.

Summary

Functions

Adds authentication token to parameters if required.

Classifies an error based on its error code.

Generates a standardized error tuple for failed Deribit API operations.

Extracts response metadata from a JSON-RPC response.

Generates a standard JSON-RPC 2.0 request payload.

Creates a reference for the timeout process that will be canceled when the request is completed.

Gets the timeout value for a request.

Classifies an RPC method as public, private, or unknown.

Converts a timestamp from microseconds to DateTime.

Checks if an error requires connection re-authentication.

Parses a JSON-RPC response based on its structure.

Removes a tracked request from state once processed.

Determines if a method requires authentication.

Tracks a new request in the state for later matching with response.

Functions

add_auth_params(params, method, access_token)

@spec add_auth_params(map(), String.t(), String.t() | nil) :: map()

Adds authentication token to parameters if required.

Parameters

  • params - The original parameters map
  • method - The JSON-RPC method string
  • access_token - The current access token (or nil if not authenticated)

Returns

  • Updated parameters map with access_token if required
  • Original parameters map if not required or token not available

Examples

iex> RPC.add_auth_params(%{}, "private/get_position", "token123")
%{"access_token" => "token123"}

iex> RPC.add_auth_params(%{instrument: "BTC-PERPETUAL"}, "public/get_time", "token123")
%{instrument: "BTC-PERPETUAL"}

classify_error(arg1)

@spec classify_error(map()) :: {atom(), atom(), String.t()} | :unknown

Classifies an error based on its error code.

Parameters

  • error - The error map from the response

Returns

  • {category, reason, message} tuple with error classification
  • :unknown for unrecognized error codes

Examples

iex> RPC.classify_error(%{"code" => 13010, "message" => "Token expired"})
{:auth, :token_expired, "Token expired"}

iex> RPC.classify_error(%{"code" => 99999, "message" => "Unknown error"})
{:unknown, :unknown_code, "Unknown error"}

error(reason, details \\ nil)

@spec error(atom() | String.t(), map() | nil) :: {:error, map()}

Generates a standardized error tuple for failed Deribit API operations.

Parameters

  • reason - The error reason
  • details - Additional error details

Returns

  • {:error, map()} with standardized error structure

extract_metadata(response)

@spec extract_metadata(map()) :: map()

Extracts response metadata from a JSON-RPC response.

This is useful for handling data from notification responses like subscriptions.

Parameters

  • response - The JSON-RPC response or notification (map)

Returns

  • Map with extracted metadata (if any)
  • Empty map if no metadata is found

Examples

iex> RPC.extract_metadata(%{"jsonrpc" => "2.0", "method" => "subscription", "params" => %{"channel" => "trades.BTC-PERPETUAL.raw"}})
%{channel: "trades.BTC-PERPETUAL.raw", type: :subscription}

generate_request(method, params, id \\ nil)

@spec generate_request(String.t(), map(), integer() | nil) :: {:ok, map(), integer()}

Generates a standard JSON-RPC 2.0 request payload.

Parameters

  • method - The JSON-RPC method to call (e.g., "public/auth")
  • params - The parameters to pass to the method (map)
  • id - Optional request ID (defaults to a unique integer)

Returns

  • {:ok, request_payload, request_id} - The JSON-RPC request and its ID

Examples

iex> RPC.generate_request("public/get_time", %{})
{:ok, %{"jsonrpc" => "2.0", "id" => 123, "method" => "public/get_time", "params" => %{}}, 123}

generate_timeout_reference(request_id)

@spec generate_timeout_reference(integer()) :: reference()

Creates a reference for the timeout process that will be canceled when the request is completed.

Parameters

  • request_id - The JSON-RPC request ID

Returns

  • Timer reference

get_timeout(method, options, state)

@spec get_timeout(String.t(), map() | nil, map()) :: integer()

Gets the timeout value for a request.

Parameters

  • method - The JSON-RPC method
  • options - Request options that may include timeout
  • state - The adapter state which may have default timeouts

Returns

  • Timeout value in milliseconds

method_type(arg1)

@spec method_type(String.t()) :: :public | :private | :unknown

Classifies an RPC method as public, private, or unknown.

This is used for properly handling authentication requirements.

Parameters

  • method - The JSON-RPC method string

Returns

  • :public for public methods
  • :private for private methods
  • :unknown for unclassified methods

Examples

iex> RPC.method_type("public/auth")
:public

iex> RPC.method_type("private/get_position")
:private

microseconds_to_datetime(timestamp_us)

@spec microseconds_to_datetime(integer()) :: DateTime.t()

Converts a timestamp from microseconds to DateTime.

Deribit often provides timestamps in microseconds since epoch.

Parameters

  • timestamp_us - Timestamp in microseconds

Returns

  • DateTime struct representing the timestamp

Examples

iex> RPC.microseconds_to_datetime(1609459200000000)
~U[2021-01-01 00:00:00Z]

needs_reauth?(arg1)

@spec needs_reauth?(map()) :: boolean()

Checks if an error requires connection re-authentication.

Used to determine if authentication needs to be refreshed based on specific Deribit error codes.

Parameters

  • error - The error map from the response

Returns

  • true if authentication needs to be refreshed
  • false otherwise

Examples

iex> RPC.needs_reauth?(%{"code" => 13010, "message" => "Token expired"})
true

iex> RPC.needs_reauth?(%{"code" => 10001, "message" => "Invalid parameter"})
false

parse_response(response)

@spec parse_response(map()) ::
  {:ok, any()} | {:error, any()} | {:error, {:invalid_response, map()}}

Parses a JSON-RPC response based on its structure.

Parameters

  • response - The JSON-RPC response (map)

Returns

  • {:ok, result} - For successful responses with a result field
  • {:error, error} - For error responses
  • {:error, {:invalid_response, response}} - For invalid or unexpected responses

Examples

iex> RPC.parse_response(%{"jsonrpc" => "2.0", "id" => 123, "result" => "success"})
{:ok, "success"}

iex> RPC.parse_response(%{"jsonrpc" => "2.0", "id" => 123, "error" => %{"code" => 10001, "message" => "Error"}})
{:error, %{"code" => 10001, "message" => "Error"}}

remove_tracked_request(state, id)

@spec remove_tracked_request(map(), integer()) :: map()

Removes a tracked request from state once processed.

Parameters

  • state - The current adapter state
  • id - The request ID to remove

Returns

  • Updated state with the request removed

requires_auth?(method)

@spec requires_auth?(String.t()) :: boolean()

Determines if a method requires authentication.

Parameters

  • method - The JSON-RPC method string

Returns

  • true if authentication is required
  • false otherwise

Examples

iex> RPC.requires_auth?("private/get_position")
true

iex> RPC.requires_auth?("public/get_time")
false

track_request(state, id, method, params, options \\ nil)

@spec track_request(map(), integer(), String.t(), map(), map() | nil) :: map()

Tracks a new request in the state for later matching with response.

Parameters

  • state - The current adapter state
  • id - The request ID
  • method - The JSON-RPC method
  • params - The request parameters
  • options - Optional request options

Returns

  • Updated state with the request tracked