class Harmony::Api::Client
Attributes
api_version[RW]
configuration[RW]
connection[RW]
headers[RW]
payload[RW]
url[RW]
Public Class Methods
new(network: :mainnet, shard: 0, configuration: ::Harmony::Api.configuration, options: {})
click to toggle source
# File lib/harmony/api/client.rb, line 8 def initialize(network: :mainnet, shard: 0, configuration: ::Harmony::Api.configuration, options: {}) self.configuration = configuration set_url(network, shard) set_defaults set_connection end
Public Instance Methods
log(tag = self.class.name, message)
click to toggle source
# File lib/harmony/api/client.rb, line 82 def log(tag = self.class.name, message) puts "[#{tag}] - #{Time.now}: #{message}" if configuration.verbose end
post(method, params: [])
click to toggle source
# File lib/harmony/api/client.rb, line 51 def post(method, params: []) versioned_method = api_version.eql?(1) ? "hmy_#{method}" : "hmyv#{version}_#{method}" data = payload.merge( method: versioned_method, params: params ) response = connection.post do |request| if headers && !headers.empty? request.headers = connection.headers.merge(headers) end request.body = data if data && !data.empty? end end
response(resp)
click to toggle source
# File lib/harmony/api/client.rb, line 67 def response(resp) if resp.success? resp = resp&.body error = resp&.fetch('error', {}) unless error.empty? raise ::Harmony::Api::Error, "#{error.fetch('message', '')} (#{error.fetch('code', -1)})" end resp&.fetch('result') else raise ::Harmony::Api::Error, "Failed to send request to #{self.url}" end end
set_connection()
click to toggle source
# File lib/harmony/api/client.rb, line 27 def set_connection self.connection = ::Faraday.new(url) do |builder| if configuration.faraday.fetch(:timeout, nil) builder.options[:timeout] = configuration.faraday.fetch(:timeout, nil) end if configuration.faraday.fetch(:open_timeout, nil) builder.options[:open_timeout] = configuration.faraday.fetch(:open_timeout, nil) end builder.headers = headers if headers && !headers.empty? builder.request :json if configuration.verbose builder.response :logger, ::Logger.new(STDOUT), bodies: true end builder.response :json, content_type: /\bjson$/ builder.use ::FaradayMiddleware::FollowRedirects, limit: 10 builder.adapter configuration.faraday.fetch(:adapter, ::Faraday.default_adapter) end end
set_defaults()
click to toggle source
# File lib/harmony/api/client.rb, line 20 def set_defaults self.payload = { jsonrpc: '2.0', id: 1 } end
set_url(network, shard)
click to toggle source
# File lib/harmony/api/client.rb, line 16 def set_url(network, shard) self.url = configuration.networks[network][:url] % shard end