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