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: "bch"
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: "bch",
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: "bch",
42 amount: currency.downcase == "xmr" ? 0.1 : 0.01,
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 if req.response["error"].to_s =~ /does not fall within the range/
52 raise "Network fees are too high, try again later."
53 end
54
55 raise req.response["message"] || req.response["error"] || "Error"
56 end
57
58 def req(m, path, query: {}, body: nil)
59 EM::HttpRequest.new(
60 "https://api.simpleswap.io/#{path}", tls: { verify_peer: true }
61 ).tap { |req| req.use(EM::Middleware::JSONResponse) }.public_send(
62 m,
63 head: {
64 "Accept" => "application/json", "Content-Type" => "application/json"
65 },
66 query: query.merge(api_key: @api_key),
67 body: body
68 )
69 end
70end