DeribitEx.RPC (deribit_ex v0.1.0)
View SourceCore 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
Adds authentication token to parameters if required.
Parameters
params
- The original parameters mapmethod
- The JSON-RPC method stringaccess_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"}
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"}
Generates a standardized error tuple for failed Deribit API operations.
Parameters
reason
- The error reasondetails
- Additional error details
Returns
{:error, map()}
with standardized error structure
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}
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}
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
Gets the timeout value for a request.
Parameters
method
- The JSON-RPC methodoptions
- Request options that may include timeoutstate
- The adapter state which may have default timeouts
Returns
- Timeout value in milliseconds
@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
@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]
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 refreshedfalse
otherwise
Examples
iex> RPC.needs_reauth?(%{"code" => 13010, "message" => "Token expired"})
true
iex> RPC.needs_reauth?(%{"code" => 10001, "message" => "Invalid parameter"})
false
@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"}}
Removes a tracked request from state once processed.
Parameters
state
- The current adapter stateid
- The request ID to remove
Returns
- Updated state with the request removed
Determines if a method requires authentication.
Parameters
method
- The JSON-RPC method string
Returns
true
if authentication is requiredfalse
otherwise
Examples
iex> RPC.requires_auth?("private/get_position")
true
iex> RPC.requires_auth?("public/get_time")
false
Tracks a new request in the state for later matching with response.
Parameters
state
- The current adapter stateid
- The request IDmethod
- The JSON-RPC methodparams
- The request parametersoptions
- Optional request options
Returns
- Updated state with the request tracked