Class: Nanook::Rpc

Inherits:
Object
  • Object
show all
Defined in:
lib/nanook/rpc.rb

Overview

The Nanook::Rpc class is responsible for maintaining the connection to the RPC server, calling the RPC and parsing its response into Ruby primitives.

Internally, the Nanook class creates an instance of this class, and it's generally more convenient to interact with the RPC through an instance of #rpc instead of by instantiating this class directly:

nanook = Nanook.new
nanook.rpc(:accounts_create, wallet: wallet_id, count: 2)

Constant Summary collapse

DEFAULT_URI =

Default RPC server and port to connect to.

'http://[::1]:7076'
DEFAULT_TIMEOUT =

Default request timeout in seconds.

60
RPC_CONTROL_DISABLED_ERROR =

Error expected to be returned when the RPC makes a call that requires the `enable_control` setting to be enabled when it is disabled.

'RPC control is disabled'

Instance Method Summary collapse

Constructor Details

#initialize(uri = DEFAULT_URI, timeout: DEFAULT_TIMEOUT) ⇒ Rpc

Returns a new instance of Rpc.



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/nanook/rpc.rb', line 26

def initialize(uri = DEFAULT_URI, timeout: DEFAULT_TIMEOUT)
  @rpc_server = URI(uri)

  unless %w[http https].include?(@rpc_server.scheme)
    raise ArgumentError, "URI must have http or https in it. Was given: #{uri}"
  end

  @http = Net::HTTP.new(@rpc_server.hostname, @rpc_server.port)
  @http.read_timeout = timeout
  @request = Net::HTTP::Post.new(@rpc_server.request_uri, { 'user-agent' => "Ruby nanook gem v#{Nanook::VERSION}" })
  @request.content_type = 'application/json'
end

Instance Method Details

#call(action, params = {}) ⇒ Hash

Calls the RPC server and returns the response.

Parameters:

  • action (Symbol)

    the “action” of the RPC to call. The RPC always expects an “action” param to identify what RPC action is being called.

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

    all other params to pass to the RPC

Returns:

  • (Hash)

    the response from the RPC



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/nanook/rpc.rb', line 55

def call(action, params = {})
  coerce_to = params.delete(:_coerce)
  access_as = params.delete(:_access)

  raw_hash = make_call(action, params)

  check_for_errors!(raw_hash)

  hash = parse_values(raw_hash)

  hash = hash[access_as] if access_as
  hash = coerce_empty_string_to_type(hash, coerce_to) if coerce_to

  hash
end

#testBoolean

Tests the RPC connection. Returns true if connection is successful, otherwise raises an exception.

Returns:

  • (Boolean)

    true if connection is successful

Raises:

  • (Errno::ECONNREFUSED)

    if connection is unsuccessful



44
45
46
47
# File 'lib/nanook/rpc.rb', line 44

def test
  call(:telemetry)
  true
end

#to_sString Also known as: inspect

Returns:

  • (String)


72
73
74
# File 'lib/nanook/rpc.rb', line 72

def to_s
  "#{self.class.name}(host: \"#{@rpc_server}\", timeout: #{@http.read_timeout})"
end