-
Notifications
You must be signed in to change notification settings - Fork 7
/
client.rb
87 lines (76 loc) · 2.37 KB
/
client.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
require 'memoist'
require 'faraday'
require 'better-faraday'
module Dogecoin
class Client
Error = Class.new(StandardError)
class ConnectionError < Error; end
class ResponseError < Error
def initialize(code, msg)
@code = code
@msg = msg
end
def message
"#{@msg} (#{@code})"
end
end
extend Memoist
def initialize(endpoint)
@json_rpc_endpoint = URI.parse(endpoint)
end
def json_rpc(method, params = [])
response = connection.post \
'/',
{ jsonrpc: '1.0', method: method, params: params }.to_json,
{ 'Accept' => 'application/json',
'Content-Type' => 'application/json' }
response.assert_2xx!
response = JSON.parse(response.body)
response['error'].tap { |e| raise ResponseError.new(e['code'], e['message']) if e }
response.fetch('result')
rescue => e
if e.is_a?(Error)
raise e
elsif e.is_a?(Faraday::Error)
raise ConnectionError, e
else
raise Error, e
end
end
def json_rpc_for_withdrawal(method, address, amount)
response = connection.post \
'/',
{ jsonrpc: '1.0', method: method, params: [
address,
amount.to_f,
# '', REMOVED! because protocol dosent support this para
# '', REMOVED! because protocol dosent support this para
# options[:subtract_fee].to_s == 'true' # subtract fee from transaction amount.
]}.to_json,
{ 'Accept' => 'application/json',
'Content-Type' => 'application/json' }
response.assert_2xx!
response = JSON.parse(response.body)
response['error'].tap { |e| raise ResponseError.new(e['code'], e['message']) if e }
response.fetch('result')
rescue => e
if e.is_a?(Error)
raise e
elsif e.is_a?(Faraday::Error)
raise ConnectionError, e
else
raise Error, e
end
end
private
def connection
Faraday.new(@json_rpc_endpoint).tap do |connection|
unless @json_rpc_endpoint.user.blank?
connection.basic_auth(@json_rpc_endpoint.user,
@json_rpc_endpoint.password)
end
end
end
memoize :connection
end
end