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