class BcashRubyExplorer::Api

Main class of this library, contains the following public methods: block_full_txs, address_full_txs and tx_info

Public Instance Methods

address_full_txs(address, page = 0) click to toggle source
# File lib/bcash_ruby_explorer/api.rb, line 17
def address_full_txs(address, page = 0)
  query = {
    address: address,
    pageNum: page
  }

  uri = URI('https://explorer.bitcoin.com/api/bch/txs')
  api_http_get(uri, query: query)
end
block_full_txs(hash, page = 0) click to toggle source
# File lib/bcash_ruby_explorer/api.rb, line 7
def block_full_txs(hash, page = 0)
  query = {
    block: hash,
    pageNum: page
  }

  uri = URI('https://explorer.bitcoin.com/api/bch/txs')
  api_http_get(uri, query: query)
end
tx_info(hash) click to toggle source
# File lib/bcash_ruby_explorer/api.rb, line 27
def tx_info(hash)
  uri = URI("https://rest.bitcoin.com/v2/slp/txDetails/#{hash}")
  api_http_get(uri, query: {})
end

Private Instance Methods

api_http_call(http_method, uri, query, json_payload: nil) click to toggle source
# File lib/bcash_ruby_explorer/api.rb, line 34
def api_http_call(http_method, uri, query, json_payload: nil)
  uri.query = URI.encode_www_form(query) unless query.empty?

  # Build the connection
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  # Build the Request
  if http_method == :post
    request = Net::HTTP::Post.new(uri.request_uri)
  elsif http_method == :get
    request = Net::HTTP::Get.new(uri.request_uri)
  elsif http_method == :delete
    request = Net::HTTP::Delete.new(uri.request_uri)
  else
    raise 'Invalid HTTP method'
  end

  unless json_payload.nil?
    request.content_type = 'application/json'
    request.body = json_payload.to_json
  end

  response = http.request(request)
  response_code = response.code.to_i

  # Detect errors/return 204 empty body
  if response_code >= 400
    raise Error.new(uri.to_s + ' Response:' + response.body)
  elsif response_code == 204
    return nil
  end

  # Process the response
  begin
    json_response = JSON.parse(response.body)
    return json_response
  rescue => e
    raise "Unable to parse JSON response #{e.inspect}, #{response.body}"
  end
end
api_http_get(uri, query: {}) click to toggle source
# File lib/bcash_ruby_explorer/api.rb, line 76
def api_http_get(uri, query: {})
  api_http_call(:get, uri, query)
end