Skip to content

Instantly share code, notes, and snippets.

@greenbigfrog
Created January 15, 2018 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greenbigfrog/24c4dbdfbe3e0f971890bb1f22bce1d0 to your computer and use it in GitHub Desktop.
Save greenbigfrog/24c4dbdfbe3e0f971890bb1f22bce1d0 to your computer and use it in GitHub Desktop.
require "http/client"
require "json"
require "uri"
require "./bitcoin_rpc/*"
class BitcoinRpc
getter :client
private getter :headers
def initialize(uri : String, username : String, password : String)
@url = URI.parse(uri)
@headers = HTTP::Headers{"Content-Type" => "application/json"}
@username = username
@password = password
end
macro method_missing(call)
command = {{call.name.id.stringify.gsub /_/, ""}}
{% if call.args.size == 0 %}
rpc_request(command)
{% else %}
rpc_request(command, {{call.args}})
{% end %}
end
private def rpc_request(command, params = [] of String)
body = {
:method => command,
:params => params,
}.to_json
client = HTTP::Client.new(@url)
client.basic_auth(@username, @password)
response = client.post("/", headers: @headers, body: body)
parse_response(response)
end
private def parse_response(response : HTTP::Client::Response)
return {"error" => response.status_message} unless response.success?
payload = JSON.parse(response.body).as_h
return {"error" => payload["error"]} if payload["error"]
payload["result"]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment