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