We’re depending on canadianbitcoins.com to get exchange rates and that doesn’t exist anymore
The following changes since commit 4ccdc72babc1ed5f04537ae45d826c879dc49a8b:
Merge branch ‘migrate-bandwidth-bits-to-oauth’ of secluded.site/jmp-pay at downcase-jids · Tangled (2026-03-25 10:20:56 -0500)
are available in the Git repository at:
mrry.band/jmp-pay at master · Tangled fix-pending-btc-transactions
for you to fetch changes up to 39cc68ee6f70d0d61fc7597999bc5ebf1e0fc716:
Use same exchange calculations as sgx-jmp (2026-10-22 10:03:44 -0400)
Eric Roberts (1):
Use same exchange calculations as sgx-jmp
bin/process_pending_btc_transactions | 37 ++++±------------
lib/btc_sell_prices.rb | 63 +++++++++++++++++++++++++++++++
lib/bull_bitcoin.rb | 73 ++++++++++++++++++++++++++++++++++++
lib/simple_swap.rb | 46 +++++++++++++++++++++++
test/test_btc_sell_prices.rb | 66 ++++++++++++++++++++++++++++++++
5 files changed, 257 insertions(+), 28 deletions(-)
create mode 100644 lib/btc_sell_prices.rb
create mode 100644 lib/bull_bitcoin.rb
create mode 100644 lib/simple_swap.rb
create mode 100644 test/test_btc_sell_prices.rb
diff --git a/bin/process_pending_btc_transactions b/bin/process_pending_btc_transactions
index 79303a6..880d5a5 100755
--- a/bin/process_pending_btc_transactions
+++ b/bin/process_pending_btc_transactions
@@ -4,6 +4,7 @@
# Usage: bin/process_pending-btc_transactions '{
# oxr_app_id = "",
# required_confirmations = 3,
+# simpleswap_api_key = "", -- Required for BCH pricing
# notify_using = {
# jid = "",
# password = "",
@@ -17,14 +18,12 @@
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"
+require_relative "../lib/btc_sell_prices"
require_relative "../lib/pending_transaction_repo"
require_relative "../lib/transaction"
@@ -45,38 +44,20 @@ BlatherNotify.start(
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"))
-)
-
-case CONFIG[:electrum][:currency]
+prices = case CONFIG[:electrum][:currency]
when "btc"
- exchange_row = canadianbitcoins.at("#ticker > table > tbody > tr")
- raise "Bitcoin row has moved" unless exchange_row.at("td").text == "Bitcoin"
+ BTCSellPrices.new(REDIS, CONFIG.fetch(:oxr_app_id))
when "bch"
- exchange_row = canadianbitcoins.at(
- "#ticker > table > tbody > tr:nth-child(2)"
+ BCHSellPrices.new(
+ REDIS, CONFIG.fetch(:oxr_app_id),
+ simple_swap: SimpleSwap.new(api_key: CONFIG.fetch(:simpleswap_api_key))
)
- if exchange_row.at("td").text != "Bitcoin Cash"
- raise "Bitcoin Cash row has moved"
- end
else
raise "Unknown currency #{CONFIG[:electrum][:currency]}"
end
-sell_price = {}
-sell_price[:CAD] = BigDecimal(
- exchange_row.at("td:nth-of-type(4)").text.match(/^\$(\d+\.\d+)/)[1]
-)
-sell_price[:USD] = sell_price[:CAD] * cad_to_usd
+sell_price = { CAD: prices.cad }
+sell_price[:USD] = prices.usd
class Plan
def self.for_customer(customer)
diff --git a/lib/btc_sell_prices.rb b/lib/btc_sell_prices.rb
new file mode 100644
index 0000000..94fdb0c
--- /dev/null
+++ b/lib/btc_sell_prices.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+# Synchronous adaptation of sgx-jmp/lib/btc_sell_prices.rb.
+
+require "money/bank/open_exchange_rates_bank"
+
+require_relative "bull_bitcoin"
+require_relative "simple_swap"
+
+class CryptoSellPrices
+ class PriceError < StandardError; end
+
+ def initialize(redis, oxr_app_id, bull: BullBitcoin.new)
+ @redis = redis
+ @bull = bull
+ @oxr = Money::Bank::OpenExchangeRatesBank.new(
+ Money::RatesStore::Memory.new
+ )
+ @oxr.app_id = oxr_app_id
+ end
+
+ def usd
+ cad * cad_to_usd
+ end
+
+protected
+
+ def cad_to_usd
+ rate = @redis.get("cad_to_usd")
+ return rate.to_f if rate
+
+ @oxr.update_rates
+ orate = @oxr.get_rate("CAD", "USD")
+ @redis.setex("cad_to_usd", 60 * 60, orate)
+ orate
+ end
+end
+
+class BCHSellPrices < CryptoSellPrices
+ def initialize(
+ redis, oxr_app_id,
+ simple_swap:, bull: BullBitcoin.new
+ )
+ super(redis, oxr_app_id, bull: bull)
+ @simple_swap = simple_swap
+ end
+
+ def cad
+ btc_cad = @bull.fetch_btc_cad
+ bch_per_btc = @simple_swap.fetch_rate("btc")
+ unless bch_per_btc&.positive?
+ raise PriceError, "SimpleSwap BTC to BCH rate was not positive"
+ end
+
+ btc_cad / bch_per_btc
+ end
+end
+
+class BTCSellPrices < CryptoSellPrices
+ def cad
+ @bull.fetch_btc_cad
+ end
+end
diff --git a/lib/bull_bitcoin.rb b/lib/bull_bitcoin.rb
new file mode 100644
index 0000000..7be5db6
--- /dev/null
+++ b/lib/bull_bitcoin.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+require "bigdecimal"
+require "json"
+require "net/http"
+
+# Synchronous adaptation of sgx-jmp/lib/bull_bitcoin.rb.
+class BullBitcoin
+ Error = Class.new(StandardError)
+
+ def fetch_btc_cad
+ uri = URI("https://www.bullbitcoin.com/api/price")
+ req = Net::HTTP::Post.new(uri)
+ req["Accept"] = "application/json"
+ req["Content-Type"] = "application/json"
+ req.body = {
+ id: request_id,
+ jsonrpc: "2.0",
+ method: "getUserRate",
+ params: {
+ element: {
+ fromCurrency: "BTC",
+ toCurrency: "CAD"
+ }
+ }
+ }.to_json
+ response = Net::HTTP.start(
+ uri.host, uri.port, use_ssl: true,
+ open_timeout: 10, read_timeout: 10
+ ) { |http| http.request(req) }
+ parse_response(response)
+ end
+
+private
+
+ def request_id
+ "#{(Time.now.to_f * 1000).to_i}-#{rand(100...999)}"
+ end
+
+ def parse_response(http)
+ status = http.code.to_i
+ if status != 200
+ raise Error, "Bull Bitcoin price request failed with HTTP #{status}"
+ end
+
+ el = extract_element(http.body)
+ BigDecimal(el.fetch("userPrice").to_s) / (10**el.fetch("precision"))
+ rescue JSON::ParserError, KeyError => e
+ raise Error, "Bull Bitcoin price response invalid: #{e.message}"
+ end
+
+ def extract_element(response)
+ json = JSON.parse(response)
+ if json["error"]
+ raise Error,
+ "Bull Bitcoin price response error: #{format_error(json['error'])}"
+ end
+
+ el = json.dig("result", "element")
+ return el if el
+
+ raise Error, "Bull Bitcoin price response missing result.element"
+ end
+
+ def format_error(error)
+ if error["message"] == "Validation error" && error["data"].is_a?(Hash)
+ nested = error.dig("data", "apiError", "message")
+ return "#{error['message']}: #{nested}" if nested
+ end
+
+ error["message"]
+ end
+end
diff --git a/lib/simple_swap.rb b/lib/simple_swap.rb
new file mode 100644
index 0000000..3758c8f
--- /dev/null
+++ b/lib/simple_swap.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+require "bigdecimal/util"
+require "json"
+require "net/http"
+
+# Pricing subset of sgx-jmp/lib/simple_swap.rb, using synchronous HTTP.
+class SimpleSwap
+ def initialize(api_key:)
+ @api_key = api_key
+ end
+
+ def fetch_rate(currency)
+ req(
+ :get, "get_estimated",
+ query: {
+ fixed: "false",
+ currency_from: currency,
+ currency_to: "bch",
+ amount: 1
+ }
+ ).to_d
+ end
+
+ def req(m, path, query: {})
+ if !@api_key || @api_key.empty?
+ raise ArgumentError, "simpleswap_api_key is required for BCH pricing"
+ end
+
+ uri = URI("https://api.simpleswap.io/#{path}")
+ uri.query = URI.encode_www_form(query.merge(api_key: @api_key))
+ response = Net::HTTP.start(
+ uri.host, uri.port, use_ssl: true,
+ open_timeout: 10, read_timeout: 10
+ ) do |http|
+ http.public_send(m, uri.request_uri, {
+ "Accept" => "application/json", "Content-Type" => "application/json"
+ })
+ end
+ unless response.is_a?(Net::HTTPSuccess)
+ raise "SimpleSwap price request failed with HTTP #{response.code}"
+ end
+
+ JSON.parse(response.body)
+ end
+end
diff --git a/test/test_btc_sell_prices.rb b/test/test_btc_sell_prices.rb
new file mode 100644
index 0000000..067b913
--- /dev/null
+++ b/test/test_btc_sell_prices.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require "btc_sell_prices"
+
+class BTCSellPricesTest < Minitest::Test
+ def stub_bull(body, status: 200)
+ stub_request(:post, "https://www.bullbitcoin.com/api/price").with(
+ body: hash_including(
+ method: "getUserRate",
+ params: { element: { fromCurrency: "BTC", toCurrency: "CAD" } }
+ )
+ ).to_return(status: status, body: body.to_json)
+ end
+
+ def test_cad
+ stub_bull({ result: { element: { userPrice: 11190811, precision: 2 } } })
+ assert_equal BigDecimal("111908.11"), BTCSellPrices.new(nil, "").cad
+ end
+
+ def test_bch_cad
+ stub_bull({ result: { element: { userPrice: 11190811, precision: 2 } } })
+ stub_request(:get, "https://api.simpleswap.io/get_estimated").with(
+ query: {
+ api_key: "key", fixed: "false", currency_from: "btc",
+ currency_to: "bch", amount: "1"
+ }
+ ).to_return(body: '"200"')
+ prices = BCHSellPrices.new(
+ nil, "", simple_swap: SimpleSwap.new(api_key: "key")
+ )
+ assert_equal BigDecimal("559.54055"), prices.cad
+ end
+
+ def test_rejects_zero_bch_rate
+ bull = Minitest::Mock.new
+ bull.expect(:fetch_btc_cad, BigDecimal("100"))
+ swap = Minitest::Mock.new
+ swap.expect(:fetch_rate, BigDecimal("0"), ["btc"])
+ prices = BCHSellPrices.new(nil, "", bull: bull, simple_swap: swap)
+ assert_raises(CryptoSellPrices::PriceError) { prices.cad }
+ assert_mock bull
+ assert_mock swap
+ end
+
+ def test_usd_uses_cached_conversion
+ bull = Minitest::Mock.new
+ bull.expect(:fetch_btc_cad, BigDecimal("100"))
+ redis = Minitest::Mock.new
+ redis.expect(:get, "0.5", ["cad_to_usd"])
+ assert_equal BigDecimal("50"), BTCSellPrices.new(redis, "", bull: bull).usd
+ assert_mock bull
+ assert_mock redis
+ end
+
+ def test_rpc_error
+ stub_bull({ error: { message: "Unavailable" } })
+ error = assert_raises(BullBitcoin::Error) { BullBitcoin.new.fetch_btc_cad }
+ assert_equal "Bull Bitcoin price response error: Unavailable", error.message
+ end
+
+ def test_http_error
+ stub_bull({}, status: 503)
+ assert_raises(BullBitcoin::Error) { BullBitcoin.new.fetch_btc_cad }
+ end
+end
Added this so we just fetch prices once (prices.usd would fetch cad again and do the conversion)
diff --git a/bin/process_pending_btc_transactions b/bin/process_pending_btc_transactions
index 880d5a5..fab7e77 100755
--- a/bin/process_pending_btc_transactions
+++ b/bin/process_pending_btc_transactions
@@ -56,8 +56,7 @@ else
raise "Unknown currency #{CONFIG[:electrum][:currency]}"
end
-sell_price = { CAD: prices.cad }
-sell_price[:USD] = prices.usd
+sell_price = prices.all
class Plan
def self.for_customer(customer)
diff --git a/lib/btc_sell_prices.rb b/lib/btc_sell_prices.rb
index 94fdb0c..aa99ab7 100644
--- a/lib/btc_sell_prices.rb
+++ b/lib/btc_sell_prices.rb
@@ -23,6 +23,11 @@ class CryptoSellPrices
cad * cad_to_usd
end
+ def all
+ cad_price = cad
+ { CAD: cad_price, USD: cad_price * cad_to_usd }
+ end
+
protected
def cad_to_usd
diff --git a/test/test_btc_sell_prices.rb b/test/test_btc_sell_prices.rb
index 067b913..c3613de 100644
--- a/test/test_btc_sell_prices.rb
+++ b/test/test_btc_sell_prices.rb
@@ -59,6 +59,33 @@ class BTCSellPricesTest < Minitest::Test
assert_equal "Bull Bitcoin price response error: Unavailable", error.message
end
+ def test_all_fetches_btc_quote_once
+ bull = Minitest::Mock.new
+ bull.expect(:fetch_btc_cad, BigDecimal("100"))
+ redis = Minitest::Mock.new
+ redis.expect(:get, "0.5", ["cad_to_usd"])
+ prices = BTCSellPrices.new(redis, "", bull: bull)
+ assert_equal({ CAD: BigDecimal("100"), USD: BigDecimal("50") },
+ prices.all)
+ assert_mock bull
+ assert_mock redis
+ end
+
+ def test_all_fetches_bch_quotes_once
+ bull = Minitest::Mock.new
+ bull.expect(:fetch_btc_cad, BigDecimal("100"))
+ swap = Minitest::Mock.new
+ swap.expect(:fetch_rate, BigDecimal("20"), ["btc"])
+ redis = Minitest::Mock.new
+ redis.expect(:get, "0.5", ["cad_to_usd"])
+ prices = BCHSellPrices.new(redis, "", bull: bull, simple_swap: swap)
+ assert_equal({ CAD: BigDecimal("5"), USD: BigDecimal("2.5") },
+ prices.all)
+ assert_mock bull
+ assert_mock swap
+ assert_mock redis
+ end
+
def test_http_error
stub_bull({}, status: 503)
assert_raises(BullBitcoin::Error) { BullBitcoin.new.fetch_btc_cad }
Um. Why not just make the hash with both items
Ah sure. That’s better anyway
too close to initial implementation which did something similar but less dumb. as you saw I fixed in a follow up