1#!/usr/bin/ruby
2# frozen_string_literal: true
3
4# Usage: bin/process_pending-btc_transactions '{
5# oxr_app_id = "",
6# required_confirmations = 3,
7# notify_using = {
8# jid = "",
9# password = "",
10# target = \(tel: Text) -> "${tel}@cheogram.com"
11# },
12# electrum = env:ELECTRUM_CONFIG,
13# plans = ./plans.dhall
14# }'
15
16require "bigdecimal"
17require "dhall"
18require "money/bank/open_exchange_rates_bank"
19require "net/http"
20require "nokogiri"
21require "pg"
22require "redis"
23
24require_relative "../lib/blather_notify"
25require_relative "../lib/electrum"
26
27CONFIG =
28 Dhall::Coder
29 .new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
30 .load(ARGV[0], transform_keys: :to_sym)
31
32REDIS = Redis.new
33ELECTRUM = Electrum.new(**CONFIG[:electrum])
34
35DB = PG.connect(dbname: "jmp")
36DB.type_map_for_results = PG::BasicTypeMapForResults.new(DB)
37DB.type_map_for_queries = PG::BasicTypeMapForQueries.new(DB)
38
39BlatherNotify.start(
40 CONFIG[:notify_using][:jid],
41 CONFIG[:notify_using][:password]
42)
43
44unless (cad_to_usd = REDIS.get("cad_to_usd")&.to_f)
45 oxr = Money::Bank::OpenExchangeRatesBank.new(Money::RatesStore::Memory.new)
46 oxr.app_id = CONFIG.fetch(:oxr_app_id)
47 oxr.update_rates
48 cad_to_usd = oxr.get_rate("CAD", "USD")
49 REDIS.set("cad_to_usd", cad_to_usd, ex: 60*60)
50end
51
52canadianbitcoins = Nokogiri::HTML.parse(
53 Net::HTTP.get(URI("https://www.canadianbitcoins.com"))
54)
55
56bitcoin_row = canadianbitcoins.at("#ticker > table > tbody > tr")
57raise "Bitcoin row has moved" unless bitcoin_row.at("td").text == "Bitcoin"
58
59btc_sell_price = {}
60btc_sell_price[:CAD] = BigDecimal.new(
61 bitcoin_row.at("td:nth-of-type(3)").text.match(/^\$(\d+\.\d+)/)[1]
62)
63btc_sell_price[:USD] = btc_sell_price[:CAD] * cad_to_usd
64
65class Plan
66 def self.for_customer(customer_id)
67 row = DB.exec_params(<<-SQL, [customer_id]).first
68 SELECT plan_name FROM customer_plans WHERE customer_id=$1 LIMIT 1
69 SQL
70 return unless row
71 plan = CONFIG[:plans].find { |p| p["plan_name"] = row["plan_name"] }
72 new(plan) if plan
73 end
74
75 def initialize(plan)
76 @plan = plan
77 end
78
79 def currency
80 @plan[:currency]
81 end
82end
83
84class Customer
85 def initialize(customer_id)
86 @customer_id = customer_id
87 end
88
89 def notify(body)
90 jid = REDIS.get("jmp_customer_jid-#{@customer_id}")
91 tel = REDIS.lindex("catapult_cred-#{jid}", 3)
92 BlatherNotify.say(
93 CONFIG[:notify_using][:target].call(tel.to_s),
94 body
95 )
96 end
97
98 def plan
99 Plan.for_customer(@customer_id)
100 end
101
102 def add_btc_credit(txid, fiat_amount)
103 DB.exec_params(<<-SQL, [@customer_id, txid, fiat_amount])
104 INSERT INTO transactions
105 (customer_id, transaction_id, amount, note)
106 VALUES
107 ($1, $2, $3, 'Bitcoin payment')
108 ON CONFLICT (transaction_id) DO NOTHING
109 SQL
110 notify_btc_credit(txid, fiat_amount)
111 end
112
113 def notify_btc_credit(txid, fiat_amount)
114 tx_hash, = txid.split("/", 2)
115 notify(
116 "Your Bitcoin transaction has been added as $#{'%.4f' % fiat_amount} " \
117 "to your account.\n(txhash: #{tx_hash})"
118 )
119 end
120end
121
122REDIS.hgetall("pending_btc_transactions").each do |(txid, customer_id)|
123 tx_hash, address = txid.split("/", 2)
124 transaction = ELECTRUM.gettransaction(tx_hash)
125 next unless transaction.confirmations >= CONFIG[:required_confirmations]
126 btc = transaction.amount_for(address)
127 if btc <= 0
128 warn "Transaction shows as #{btc}, skipping #{txid}"
129 next
130 end
131 DB.transaction do
132 customer = Customer.new(customer_id)
133 plan = customer.plan
134 if plan
135 amount = btc * btc_sell_price.fetch(plan.currency).round(4, :floor)
136 customer.add_btc_credit(txid, amount)
137 else
138 warn "No plan for #{customer_id} cannot save #{txid}"
139 end
140 end
141 REDIS.hdel("pending_btc_transactions", txid)
142end