1#!/usr/bin/ruby
2# frozen_string_literal: true
3
4# Usage: bin/process_pending-btc_transactions '{
5# healthchecks_url = "https://hc-ping.com/...",
6# oxr_app_id = "",
7# required_confirmations = 3,
8# notify_using = {
9# jid = "",
10# password = "",
11# target = \(jid: Text) -> "+12266669977@cheogram.com",
12# body = \(jid: Text) -> \(body: Text) -> "/msg ${jid} ${body}",
13# },
14# electrum = env:ELECTRUM_CONFIG,
15# plans = ./plans.dhall,
16# activation_amount = 10000
17# }'
18
19require "bigdecimal"
20require "dhall"
21require "money/bank/open_exchange_rates_bank"
22require "net/http"
23require "nokogiri"
24require "pg"
25require "redis"
26
27require_relative "../lib/blather_notify"
28require_relative "../lib/electrum"
29
30CONFIG =
31 Dhall::Coder
32 .new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
33 .load(ARGV[0], transform_keys: :to_sym)
34
35Net::HTTP.post_form(URI("#{CONFIG[:healthchecks_url]}/start"), {})
36
37REDIS = Redis.new
38ELECTRUM = Electrum.new(**CONFIG[:electrum])
39
40DB = PG.connect(dbname: "jmp")
41DB.type_map_for_results = PG::BasicTypeMapForResults.new(DB)
42DB.type_map_for_queries = PG::BasicTypeMapForQueries.new(DB)
43
44BlatherNotify.start(
45 CONFIG[:notify_using][:jid],
46 CONFIG[:notify_using][:password]
47)
48
49unless (cad_to_usd = REDIS.get("cad_to_usd")&.to_f)
50 oxr = Money::Bank::OpenExchangeRatesBank.new(Money::RatesStore::Memory.new)
51 oxr.app_id = CONFIG.fetch(:oxr_app_id)
52 oxr.update_rates
53 cad_to_usd = oxr.get_rate("CAD", "USD")
54 REDIS.set("cad_to_usd", cad_to_usd, ex: 60*60)
55end
56
57canadianbitcoins = Nokogiri::HTML.parse(
58 Net::HTTP.get(URI("https://www.canadianbitcoins.com"))
59)
60
61bitcoin_row = canadianbitcoins.at("#ticker > table > tbody > tr")
62raise "Bitcoin row has moved" unless bitcoin_row.at("td").text == "Bitcoin"
63
64btc_sell_price = {}
65btc_sell_price[:CAD] = BigDecimal.new(
66 bitcoin_row.at("td:nth-of-type(3)").text.match(/^\$(\d+\.\d+)/)[1]
67)
68btc_sell_price[:USD] = btc_sell_price[:CAD] * cad_to_usd
69
70class Plan
71 def self.for_customer(customer)
72 row = DB.exec_params(<<-SQL, [customer.id]).first
73 SELECT plan_name FROM customer_plans WHERE customer_id=$1 LIMIT 1
74 SQL
75 from_name(customer, row&.[]("plan_name"))
76 end
77
78 def self.pending_for_customer(customer)
79 from_name(
80 customer,
81 REDIS.get("pending_plan_for-#{customer.id}"),
82 klass: Pending
83 )
84 end
85
86 def self.from_name(customer, plan_name, klass: Plan)
87 return unless plan_name
88 plan = CONFIG[:plans].find { |p| p[:name] == plan_name }
89 klass.new(customer, plan) if plan
90 end
91
92 def initialize(customer, plan)
93 @customer = customer
94 @plan = plan
95 end
96
97 def name
98 @plan[:name]
99 end
100
101 def currency
102 @plan[:currency]
103 end
104
105 def bonus_for(fiat_amount, cad_to_usd)
106 bonus = (0.050167 * fiat_amount) - (currency == :CAD ? 1 : cad_to_usd)
107 return bonus.round(4, :floor) if bonus > 0
108 end
109
110 def price
111 BigDecimal.new(@plan[:monthly_price].to_i) * 0.0001
112 end
113
114 def insert(start:, expire:)
115 params = [@customer.id, name, start, expire]
116 DB.exec_params(<<-SQL, params)
117 INSERT INTO plan_log
118 (customer_id, plan_name, starts_at, expires_at)
119 VALUES
120 ($1, $2, $3, $4)
121 SQL
122 end
123
124 def activate_any_pending_plan!; end
125
126 class Pending < Plan
127 def initialize(customer, plan)
128 super
129 @go_until = Date.today >> 1
130 end
131
132 def activation_amount
133 camnt = BigDecimal.new(CONFIG[:activation_amount].to_i) * 0.0001
134 [camnt, price].max
135 end
136
137 def activate_any_pending_plan!
138 if @customer.balance < activation_amount
139 @customer.notify(
140 "Your account could not be activated because your " \
141 "balance of $#{@customer.balance} is less that the " \
142 "required activation amount of $#{activation_amount}. " \
143 "Please buy more credit to have your account activated."
144 )
145 else
146 charge_insert_notify
147 end
148 end
149
150 protected
151
152 def charge_insert_notify
153 @customer.add_transaction(
154 "activate_#{name}_until_#{@go_until}",
155 -price,
156 "Activate pending plan"
157 )
158 insert(start: Date.today, expire: @go_until)
159 REDIS.del("pending_plan_for-#{@customer.id}")
160 @customer.notify("Your account has been activated")
161 end
162 end
163end
164
165class Customer
166 def initialize(customer_id)
167 @customer_id = customer_id
168 end
169
170 def id
171 @customer_id
172 end
173
174 def notify(body)
175 jid = REDIS.get("jmp_customer_jid-#{@customer_id}")
176 raise "No JID for #{customer_id}" unless jid
177 BlatherNotify.say(
178 CONFIG[:notify_using][:target].call(jid),
179 CONFIG[:notify_using][:body].call(jid, body)
180 )
181 end
182
183 def plan
184 Plan.for_customer(self) || pending_plan
185 end
186
187 def pending_plan
188 Plan.pending_for_customer(self)
189 end
190
191 def balance
192 result = DB.exec_params(<<-SQL, [@customer_id]).first&.[]("balance")
193 SELECT balance FROM balances WHERE customer_id=$1
194 SQL
195 result || BigDecimal.new(0)
196 end
197
198 def add_btc_credit(txid, btc_amount, fiat_amount, cad_to_usd)
199 add_transaction(txid, btc_amount, fiat_amount, "Bitcoin payment")
200 if (bonus = plan.bonus_for(fiat_amount, cad_to_usd))
201 add_transaction("bonus_for_#{txid}", bonus, "Bitcoin payment bonus")
202 end
203 notify_btc_credit(txid, btc_amount, fiat_amount, bonus)
204 end
205
206 def notify_btc_credit(txid, btc_amount, fiat_amount, bonus)
207 tx_hash, = txid.split("/", 2)
208 notify([
209 "Your Bitcoin transaction of #{btc_amount.to_s('F')} BTC ",
210 "has been added as $#{'%.4f' % fiat_amount} (#{plan.currency}) ",
211 ("+ $#{'%.4f' % bonus} bonus " if bonus),
212 "to your account.\n(txhash: #{tx_hash})"
213 ].compact.join)
214 end
215
216 def add_transaction(id, amount, note)
217 DB.exec_params(<<-SQL, [@customer_id, id, amount, note])
218 INSERT INTO transactions
219 (customer_id, transaction_id, amount, note)
220 VALUES
221 ($1, $2, $3, $4)
222 ON CONFLICT (transaction_id) DO NOTHING
223 SQL
224 end
225end
226
227REDIS.hgetall("pending_btc_transactions").each do |(txid, customer_id)|
228 tx_hash, address = txid.split("/", 2)
229 transaction = ELECTRUM.gettransaction(tx_hash)
230 next unless transaction.confirmations >= CONFIG[:required_confirmations]
231 btc = transaction.amount_for(address)
232 if btc <= 0
233 warn "Transaction shows as #{btc}, skipping #{txid}"
234 next
235 end
236 DB.transaction do
237 customer = Customer.new(customer_id)
238 if (plan = customer.plan)
239 amount = btc * btc_sell_price.fetch(plan.currency).round(4, :floor)
240 customer.add_btc_credit(txid, btc, amount, cad_to_usd)
241 customer.plan.activate_any_pending_plan!
242 REDIS.hdel("pending_btc_transactions", txid)
243 else
244 warn "No plan for #{customer_id} cannot save #{txid}"
245 end
246 end
247end
248
249Net::HTTP.post_form(URI(CONFIG[:healthchecks_url].to_s), {})