Class: SolanaRpcRuby::ApiClient

Inherits:
Object
  • Object
show all
Defined in:
lib/solana_rpc_ruby/api_client.rb

Overview

ApiClient class serves as a client for solana JSON RPC API.

Constant Summary collapse

OPEN_TIMEOUT =
120
READ_TIMEOUT =
120

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cluster = nil) ⇒ ApiClient

Initialize object with cluster address where requests will be sent.

Parameters:

  • cluster (String) (defaults to: nil)

Raises:

  • (ArgumentError)

21
22
23
24
25
26
# File 'lib/solana_rpc_ruby/api_client.rb', line 21

def initialize(cluster = nil)
  @cluster = cluster || SolanaRpcRuby.cluster

  message = 'Cluster is missing. Please provide default cluster in config or pass it to the client directly.'
  raise ArgumentError, message unless @cluster
end

Instance Attribute Details

#clusterString

Determines which cluster will be used to send requests.

Returns:

  • (String)

12
13
14
# File 'lib/solana_rpc_ruby/api_client.rb', line 12

def cluster
  @cluster
end

#default_headers=(value) ⇒ Hash

Default headers.

Returns:

  • (Hash)

16
17
18
# File 'lib/solana_rpc_ruby/api_client.rb', line 16

def default_headers=(value)
  @default_headers = value
end

Instance Method Details

#call_api(body:, http_method:, params: {}) ⇒ Object

Sends request to the api.

Parameters:

  • body (Hash)
  • http_method (Symbol)
  • params (Hash) (defaults to: {})

Returns:

  • (Object)

    Net::HTTPOK


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/solana_rpc_ruby/api_client.rb', line 35

def call_api(body:, http_method:, params: {})
  uri = URI.parse(@cluster)

  request = Net::HTTP::Post.new(uri, default_headers)
  request.body = body

  Net::HTTP.start(
    uri.host, 
    uri.port, 
    use_ssl: true, 
    open_timeout: OPEN_TIMEOUT,
    read_timeout: READ_TIMEOUT
  ) do |http|
    http.request(request)
  end

rescue Timeout::Error,
       Net::HTTPError,
       Net::HTTPNotFound,
       Net::HTTPClientException,
       Net::HTTPFatalError,
       Net::ReadTimeout,
       Errno::ECONNREFUSED,
       SocketError => e

  fail ApiError.new(error_class: e.class, message: e.message)
rescue StandardError => e
  message = "#{e.class} #{e.message}\n Backtrace: \n #{e.backtrace}"
  fail ApiError.new(error_class: e.class, message: e.message)
end