Class: Hyperliquid::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/hyperliquid/client.rb

Overview

HTTP client for making requests to Hyperliquid API

Constant Summary collapse

DEFAULT_RETRY_OPTIONS =

Default retry configuration for API requests

{
  max: 2,
  interval: 0.5,
  interval_randomness: 0.5,
  backoff_factor: 2,
  retry_statuses: [429, 502, 503, 504],
  exceptions: [
    Faraday::ConnectionFailed,
    Faraday::TimeoutError
  ]
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, timeout: Constants::DEFAULT_TIMEOUT, retry_enabled: false, explorer_base_url: nil) ⇒ Client

Initialize a new HTTP client

Parameters:

  • base_url (String)

    The base URL for the default API (info/exchange)

  • timeout (Integer) (defaults to: Constants::DEFAULT_TIMEOUT)

    Request timeout in seconds (default: Constants::DEFAULT_TIMEOUT)

  • retry_enabled (Boolean) (defaults to: false)

    Whether to enable retry logic (default: false)

  • explorer_base_url (String, nil) (defaults to: nil)

    Optional base URL for the explorer RPC (used by tx_details / user_details). When nil, calls with target: :explorer raise ConfigurationError.



29
30
31
32
33
34
35
36
# File 'lib/hyperliquid/client.rb', line 29

def initialize(base_url:, timeout: Constants::DEFAULT_TIMEOUT, retry_enabled: false,
               explorer_base_url: nil)
  @retry_enabled = retry_enabled
  @timeout = timeout
  @explorer_base_url = explorer_base_url
  @connection = build_connection(base_url)
  @explorer_connection = nil
end

Instance Method Details

#post(endpoint, body = {}, target: :default) ⇒ Hash, String

Make a POST request to the API

Parameters:

  • endpoint (String)

    The API endpoint to make the request to

  • body (Hash) (defaults to: {})

    The request body as a hash (default: {})

  • target (Symbol) (defaults to: :default)

    Which connection to use; :default (info/exchange) or :explorer (RPC)

Returns:

  • (Hash, String)

    The parsed JSON response or raw response body

Raises:



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/hyperliquid/client.rb', line 52

def post(endpoint, body = {}, target: :default)
  connection = connection_for(target)
  response = connection.post(endpoint) do |req|
    req.headers['Content-Type'] = 'application/json'
    req.body = body.to_json unless body.empty?
  end

  handle_response(response)
rescue Faraday::RetriableResponse => e
  # After retries are exhausted, Faraday throws a RetriableResponse
  # Catch and handle that here to bubble up the actual network error
  handle_response(e.response)
rescue Faraday::ConnectionFailed => e
  raise NetworkError, "Connection failed: #{e.message}"
rescue Faraday::TimeoutError => e
  raise TimeoutError, "Request timed out: #{e.message}"
end