simple_swap.rb

 1# frozen_string_literal: true
 2
 3require "em-http/middleware/json_response"
 4
 5class SimpleSwap
 6	def initialize(api_key: CONFIG[:simpleswap_api_key])
 7		@api_key = api_key
 8	end
 9
10	def fetch_range(currency)
11		req(
12			:aget, "get_ranges",
13			query: {
14				fixed: "false",
15				currency_from: currency,
16				currency_to: "btc"
17			}
18		).then { |req|
19			{ min: req.response["min"]&.to_d || 0, max: req.response["max"]&.to_d }
20		}
21	end
22
23	def fetch_rate(currency)
24		req(
25			:aget, "get_estimated",
26			query: {
27				fixed: "false",
28				currency_from: currency,
29				currency_to: "btc",
30				amount: 1
31			}
32		).then { |req| req.response.to_d }
33	end
34
35	def fetch_addr(currency, target)
36		req(
37			:apost, "create_exchange",
38			body: {
39				fixed: false,
40				currency_from: currency,
41				currency_to: "btc",
42				amount: 10,
43				address_to: target
44			}.to_json
45		).then(&method(:parse))
46	end
47
48	def parse(req)
49		return req.response["address_from"] if req.response["address_from"]
50
51		raise req.response["message"]
52	end
53
54	def req(m, path, query: {}, body: nil)
55		EM::HttpRequest.new(
56			"https://api.simpleswap.io/#{path}", tls: { verify_peer: true }
57		).tap { |req| req.use(EM::Middleware::JSONResponse) }.public_send(
58			m,
59			head: {
60				"Accept" => "application/json", "Content-Type" => "application/json"
61			},
62			query: query.merge(api_key: @api_key),
63			body: body
64		)
65	end
66end