process_pending_btc_transactions

  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 plan_name FROM customer_plans WHERE customer_id=$1 LIMIT 1
 71		SQL
 72		from_name(customer, row&.[]("plan_name"))
 73	end
 74
 75	def self.pending_for_customer(customer)
 76		from_name(
 77			customer,
 78			REDIS.get("pending_plan_for-#{customer.id}"),
 79			klass: Pending
 80		)
 81	end
 82
 83	def self.from_name(customer, plan_name, klass: Plan)
 84		return unless plan_name
 85
 86		plan = CONFIG[:plans].find { |p| p[:name] == plan_name }
 87		klass.new(customer, plan) if plan
 88	end
 89
 90	def initialize(customer, plan)
 91		@customer = customer
 92		@plan = plan
 93	end
 94
 95	def name
 96		@plan[:name]
 97	end
 98
 99	def currency
100		@plan[:currency]
101	end
102
103	def bonus_for(fiat_amount)
104		return BigDecimal(0) if fiat_amount <= 15
105
106		fiat_amount * case fiat_amount
107		when (15..29.99)
108			0.01
109		when (30..139.99)
110			0.03
111		else
112			0.05
113		end
114	end
115
116	def price
117		BigDecimal(@plan[:monthly_price].to_i) * 0.0001
118	end
119
120	def insert(start:, expire:)
121		params = [@customer.id, name, start, expire]
122		DB.exec_params(<<-SQL, params)
123			INSERT INTO plan_log
124				(customer_id, plan_name, date_range)
125			VALUES
126				($1, $2, tsrange($3, $4))
127		SQL
128	end
129
130	def activate_any_pending_plan!; end
131
132	class Pending < Plan
133		def initialize(customer, plan)
134			super
135			@go_until = Date.today >> 1
136		end
137
138		def activation_amount
139			camnt = BigDecimal(CONFIG[:activation_amount].to_i) * 0.0001
140			[camnt, price].max
141		end
142
143		def activate_any_pending_plan!
144			if @customer.balance < activation_amount
145				@customer.notify(
146					"Your account could not be activated because your " \
147					"balance of $#{@customer.balance} is less that the " \
148					"required activation amount of $#{activation_amount}. " \
149					"Please buy more credit to have your account activated."
150				)
151			else
152				charge_insert_notify
153			end
154		end
155
156	protected
157
158		def charge_insert_notify
159			return unless @customer.add_transaction(
160				"activate_#{@customer.id}_#{name}_until_#{@go_until}",
161				-price,
162				"Activate pending plan"
163			)
164
165			insert(start: Date.today, expire: @go_until)
166			REDIS.del("pending_plan_for-#{@customer.id}")
167			notify_approved
168		end
169
170		def notify_approved
171			@customer.notify(
172				"Your JMP account has been approved. To complete " \
173				"your signup, click/tap here: xmpp:cheogram.com " \
174				"and send register jmp.chat to the bot."
175			)
176		end
177	end
178end
179
180class Customer
181	def initialize(customer_id)
182		@customer_id = customer_id
183	end
184
185	def id
186		@customer_id
187	end
188
189	def notify(body)
190		jid = REDIS.get("jmp_customer_jid-#{@customer_id}")
191		raise "No JID for #{customer_id}" unless jid
192
193		BlatherNotify.say(
194			CONFIG[:notify_using][:target].call(jid),
195			CONFIG[:notify_using][:body].call(jid, body)
196		)
197	end
198
199	def plan
200		Plan.for_customer(self) || pending_plan
201	end
202
203	def pending_plan
204		Plan.pending_for_customer(self)
205	end
206
207	def balance
208		result = DB.exec_params(<<-SQL, [@customer_id]).first&.[]("balance")
209			SELECT balance FROM balances WHERE customer_id=$1
210		SQL
211		result || BigDecimal(0)
212	end
213
214	def add_btc_credit(txid, btc_amount, fiat_amount)
215		return unless add_transaction(txid, fiat_amount, "Bitcoin payment")
216
217		if (bonus = plan.bonus_for(fiat_amount)).positive?
218			add_transaction("bonus_for_#{txid}", bonus, "Bitcoin payment bonus")
219		end
220		notify_btc_credit(txid, btc_amount, fiat_amount, bonus)
221	end
222
223	def notify_btc_credit(txid, btc_amount, fiat_amount, bonus)
224		tx_hash, = txid.split("/", 2)
225		notify([
226			"Your Bitcoin transaction of #{btc_amount.to_s('F')} BTC ",
227			"has been added as $#{'%.4f' % fiat_amount} (#{plan.currency}) ",
228			("+ $#{'%.4f' % bonus} bonus " if bonus.positive?),
229			"to your account.\n(txhash: #{tx_hash})"
230		].compact.join)
231	end
232
233	def add_transaction(id, amount, note)
234		args = [@customer_id, id, amount, note]
235		DB.exec_params(<<-SQL, args).cmd_tuples.positive?
236			INSERT INTO transactions
237				(customer_id, transaction_id, amount, note)
238			VALUES
239					($1, $2, $3, $4)
240			ON CONFLICT (transaction_id) DO NOTHING
241		SQL
242	end
243end
244
245done = REDIS.hgetall("pending_btc_transactions").map { |(txid, customer_id)|
246	tx_hash, address = txid.split("/", 2)
247	transaction = ELECTRUM.gettransaction(tx_hash)
248	next unless transaction.confirmations >= CONFIG[:required_confirmations]
249
250	btc = transaction.amount_for(address)
251	if btc <= 0
252		# This is a send, not a receive, do not record it
253		REDIS.hdel("pending_btc_transactions", txid)
254		next
255	end
256	DB.transaction do
257		customer = Customer.new(customer_id)
258		if (plan = customer.plan)
259			amount = btc * btc_sell_price.fetch(plan.currency).round(4, :floor)
260			customer.add_btc_credit(txid, btc, amount)
261			customer.plan.activate_any_pending_plan!
262			REDIS.hdel("pending_btc_transactions", txid)
263			txid
264		else
265			warn "No plan for #{customer_id} cannot save #{txid}"
266		end
267	end
268}
269
270puts done.compact.join("\n")