Class: Cryptomarket::Websocket::AuthClient

Inherits:
ClientBase
  • Object
show all
Defined in:
lib/cryptomarket/websocket/auth_client.rb

Overview

A websocket client that authenticates at the moment of connection

Direct Known Subclasses

TradingClient, WalletClient

Instance Method Summary collapse

Methods inherited from ClientBase

#close, #get_callback_for_response, #handle, #handle_good_response, #handle_notification, #handle_response, #on_close, #on_close=, #on_connect, #on_connect=, #on_error, #on_error=, #on_open, #request, #send_subscription, #send_unsubscription, #store_callback_and_send

Constructor Details

#initialize(url:, api_key:, api_secret:, subscription_keys:, window: nil) ⇒ AuthClient

Creates a new client



11
12
13
14
15
16
17
# File 'lib/cryptomarket/websocket/auth_client.rb', line 11

def initialize(url:, api_key:, api_secret:, subscription_keys:, window: nil)
  @api_key = api_key
  @api_secret = api_secret
  @window = window
  super url: url, subscription_keys: subscription_keys
  @authed = false
end

Instance Method Details

#authenticate(callback = nil) ⇒ Object

Authenticates the websocket

api.exchange.cryptomkt.com/#socket-session-authentication

Proc callback

Optional. A Proc to call with the result data. It takes two arguments, err and result.

err is None for successful calls, result is None for calls with error: Proc.new {|err, result| …}



50
51
52
53
54
55
56
57
58
# File 'lib/cryptomarket/websocket/auth_client.rb', line 50

def authenticate(callback = nil)
  timestamp = Time.now.to_i * 1_000
  digest = OpenSSL::Digest.new 'sha256'
  message = timestamp.to_s
  message += @window.to_s unless @window.nil?
  signature = OpenSSL::HMAC.hexdigest digest, @api_secret, message.to_s
  params = build_auth_payload timestamp, signature
  request('login', callback, params)
end

#build_auth_payload(timestamp, signature) ⇒ Object



60
61
62
63
64
65
66
67
68
69
# File 'lib/cryptomarket/websocket/auth_client.rb', line 60

def build_auth_payload(timestamp, signature)
  params = {
    'type' => 'HS256',
    'api_key' => @api_key,
    'timestamp' => timestamp,
    'signature' => signature
  }
  params['window'] = @window unless @window.nil?
  params
end

#connectObject

connects via websocket to the exchange and authenticates it.



24
25
26
27
28
29
30
31
32
# File 'lib/cryptomarket/websocket/auth_client.rb', line 24

def connect
  super
  authenticate(proc { |err, _result|
    raise err unless err.nil?

    @authed = true
  })
  wait_authed
end

#connected?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/cryptomarket/websocket/auth_client.rb', line 19

def connected?
  (super.connected? and @authed)
end

#wait_authedObject



34
35
36
37
38
39
40
41
# File 'lib/cryptomarket/websocket/auth_client.rb', line 34

def wait_authed
  current_try = 0
  max_tries = 60
  while !@authed && (current_try < max_tries)
    current_try += 1
    sleep(1)
  end
end