alt_top_up_form.rb

 1# frozen_string_literal: true
 2
 3require_relative "simple_swap"
 4
 5class AltTopUpForm
 6	def self.for(customer)
 7		customer.btc_addresses.then do |addrs|
 8			AltTopUpForm.new(customer, addrs)
 9		end
10	end
11
12	def initialize(customer, btc_addresses)
13		@customer = customer
14		@balance = customer.balance
15		@currency = customer.currency
16		@btc_addresses = btc_addresses
17	end
18
19	def form
20		FormTemplate.render(
21			"alt_top_up",
22			balance: @balance,
23			currency: @currency,
24			btc_addresses: @btc_addresses
25		)
26	end
27
28	def parse(form)
29		action =
30			form.field("http://jabber.org/protocol/commands#actions")&.value.to_s
31		case action
32		when "BTC"
33			BitcoinAddress.new(@customer)
34		when /\A[A-Z]{3}\Z/
35			SimpleSwapAddress.new(@customer, action, @btc_addresses.first)
36		else
37			NoOp.new
38		end
39	end
40
41	class NoOp
42		def action(*); end
43	end
44
45	class BitcoinAddress
46		def initialize(customer)
47			@customer = customer
48		end
49
50		def action(reply)
51			@customer.add_btc_address.then do |addr|
52				reply.command << FormTemplate.render(
53					"alt_top_up/btc",
54					btc_addresses: [addr]
55				)
56			end
57		end
58	end
59
60	class SimpleSwapAddress
61		def initialize(customer, currency, btc_address, simple_swap: SimpleSwap.new)
62			@customer = customer
63			@currency = currency.downcase
64			@btc_address = btc_address
65			@simple_swap = simple_swap
66		end
67
68		def btc_address
69			@btc_address || @customer.add_btc_address
70		end
71
72		def action(reply)
73			EMPromise.resolve(btc_address).then { |btc|
74				@simple_swap.fetch_addr(@currency, btc)
75			}.then do |addr|
76				reply.command << FormTemplate.render(
77					"alt_top_up/simpleswap",
78					addresses: [addr]
79				)
80			end
81		end
82	end
83end