The personal finance app for everyone (by everyone)
Ruby
fix(crypto): open an exchange account at zero, dated before its history, in the family currency (#3789)
Daniel Garcia Sardina9b429ee4971e
diff --git a/app/models/account.rb b/app/models/account.rbindex 1ca887acfb..1a5ab35dc9 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -358,9 +358,7 @@ class Account < ApplicationRecordenddef create_from_binance_account(binance_account)- account = create_from_crypto_exchange_account(binance_account, family: binance_account.binance_item.family)- account.set_opening_anchor_balance(balance: 0)- account+ create_from_crypto_exchange_account(binance_account, family: binance_account.binance_item.family)enddef create_from_ibkr_account(ibkr_account)@@ -467,12 +465,26 @@ class Account < ApplicationRecordprivatedef create_from_crypto_exchange_account(provider_account, family:)+ # The provider record carries the exchange's *reporting* currency -- Kraken+ # quotes everything in USD -- which says nothing about what the user+ # values the account in. The account's own currency is the one its+ # balance and holdings are shown in, so it is the family's; entries keep+ # whatever currency they were made in and convert at display, as on+ # every other account.+ provider_currency = provider_account.currency.presence || family.currency+ balance = (provider_account.current_balance || 0).to_d+ # With no rate the figure cannot be stated in the family currency, and+ # relabelling it would be wrong by the whole rate. Zero is honest: the+ # first sync writes the converted balance minutes later, and the+ # opening anchor is zeroed below regardless.+ balance = convert_provider_balance(balance, from: provider_currency, to: family.currency) || 0+attributes = {family: family,name: provider_account.name,- balance: (provider_account.current_balance || 0).to_d,+ balance: balance,cash_balance: 0,- currency: provider_account.currency.presence || family.currency,+ currency: family.currency,accountable_type: "Crypto",accountable_attributes: {subtype: "exchange",@@ -480,7 +492,38 @@ class Account < ApplicationRecord}}- create_and_sync(attributes, skip_initial_sync: true)+ # An exchange account's ledger is imported from inception, so it opens at+ # zero. Without this it inherits create_and_sync's default: an opening+ # balance equal to what the account is worth *today*, dated two years ago+ # -- so an exchange older than that imports its whole history on top of+ # its present value, and every entry before the anchor sits ahead of its+ # own opening balance.+ #+ # Through the manager, not set_opening_anchor_balance: that queues a+ # sync, which is what skip_initial_sync below just declined. Running+ # before the provider link exists, it would see one zero anchor and no+ # entries and write that zero over the balance set here.+ #+ # Both in one transaction: creation commits on its own, so a failure+ # while zeroing the anchor would otherwise leave an account behind+ # carrying today's balance as its opening one, and the retry would+ # create a second.+ account = nil+ transaction do+ account = create_and_sync(attributes, skip_initial_sync: true)+ result = Account::OpeningBalanceManager.new(account).set_opening_balance(balance: 0)+ raise result.error if result.error+ end++ account+ end++ def convert_provider_balance(amount, from:, to:)+ return amount if from == to || amount.zero?++ Money.new(amount, from).exchange_to(to).amount+ rescue Money::ConversionError+ nilenddef build_simplefin_accountable_attributes(simplefin_account, account_type, subtype)diff --git a/app/models/account/anchorable.rb b/app/models/account/anchorable.rbindex 1f60534636..ac288970ae 100644--- a/app/models/account/anchorable.rb+++ b/app/models/account/anchorable.rb@@ -27,6 +27,33 @@ module Account::Anchorableopening_balance_manager.has_opening_anchor?end+ # An account whose history a provider imports gets its opening anchor before+ # any of that history exists, so it is dated by default -- two years back.+ # Once the entries are in, an anchor that is not before the oldest of them+ # sits in the middle of the series: the reverse calculator pins the balance+ # there and every earlier day is derived from it, running the flows the+ # wrong way. Called after an import, this moves the anchor to the day before+ # the first entry and keeps its balance. Uses the manager directly so it does+ # not queue a sync of its own; the caller's sync follows anyway.+ # Only the zero anchor an exchange account is bootstrapped with is moved: an+ # anchor with a balance is one somebody entered, on a manual account linked+ # to the exchange later, and it means "this much, on this day".+ def ensure_opening_anchor_precedes_entries+ return unless has_opening_anchor? && opening_anchor_balance.zero?++ # Every entry but the anchor itself, which is how the manager decides+ # whether a date is early enough. Skipping valuations wholesale instead+ # would pick a date it then rejects, leaving the anchor where it was.+ anchor_entry_id = valuations.opening_anchor.first&.entry&.id+ oldest = entries.where.not(id: anchor_entry_id).minimum(:date)+ return if oldest.nil? || opening_anchor_date < oldest++ result = opening_balance_manager.set_opening_balance(balance: opening_anchor_balance, date: oldest.prev_day)+ raise result.error if result.error++ result+ end+def history_start_dateif linked? && balance_type == :investmentBalance::LinkedInvestmentSeriesNormalizer.supported_history_start_date(self)diff --git a/app/models/binance_account/processor.rb b/app/models/binance_account/processor.rbindex 5e67dbaf75..52b26fdc10 100644--- a/app/models/binance_account/processor.rb+++ b/app/models/binance_account/processor.rb@@ -46,6 +46,10 @@ class BinanceAccount::Processorendfetch_and_process_trades++ # The account was created, and anchored, before any of this history+ # existed. Now that it does, the anchor has to precede it.+ binance_account.current_account.ensure_opening_anchor_precedes_entriesendprivatediff --git a/app/models/coinspot_account/processor.rb b/app/models/coinspot_account/processor.rbindex 9dec080105..7b386b491d 100644--- a/app/models/coinspot_account/processor.rb+++ b/app/models/coinspot_account/processor.rb@@ -47,6 +47,10 @@ class CoinspotAccount::Processorfailures.concat(process_fiat_deposits)failures.concat(process_fiat_withdrawals)+ # The account was created, and anchored, before any of this history+ # existed. Now that it does, the anchor has to precede it.+ account.ensure_opening_anchor_precedes_entries+{ success: failures.empty?, failures: failures }enddiff --git a/app/models/kraken_account/processor.rb b/app/models/kraken_account/processor.rbindex 2e3c5bd81b..fd8382a205 100644--- a/app/models/kraken_account/processor.rb+++ b/app/models/kraken_account/processor.rb@@ -16,6 +16,10 @@ class KrakenAccount::Processorprocess_account!process_tradesKrakenAccount::LedgerProcessor.new(kraken_account).process++ # The account was created, and anchored, before any of this history+ # existed. Now that it does, the anchor has to precede it.+ kraken_account.current_account.ensure_opening_anchor_precedes_entriesendprivatediff --git a/app/views/kraken_items/setup_accounts.html.erb b/app/views/kraken_items/setup_accounts.html.erbindex 5b757f492c..a425fd8103 100644--- a/app/views/kraken_items/setup_accounts.html.erb+++ b/app/views/kraken_items/setup_accounts.html.erb@@ -60,11 +60,21 @@<p class="font-medium text-primary truncate"><%= kraken_account.name %></p><p class="text-xs text-secondary"><%= kraken_account.account_type %></p></div>+ <%# Kraken reports in USD. Show the figure in the currency the account+ will actually be created in, which is the one every other number+ on the screen is in. With no rate the account opens at zero+ (Account.convert_provider_balance), so that is what is shown:+ the reported figure would promise a balance the account will+ not have. %>+ <% reported = Money.new(kraken_account.current_balance || 0, kraken_account.currency)+ display = begin+ reported.exchange_to(Current.family.currency)+ rescue Money::ConversionError+ Money.new(0, Current.family.currency)+ end %><div class="text-right flex-shrink-0">- <p class="text-sm font-medium text-primary">- <%= number_with_delimiter(kraken_account.current_balance || 0, delimiter: ",") %>- </p>- <p class="text-xs text-secondary"><%= kraken_account.currency %></p>+ <p class="text-sm font-medium text-primary"><%= format_money(display) %></p>+ <p class="text-xs text-secondary"><%= display.currency.iso_code %></p></div></label><% end %>diff --git a/test/controllers/kraken_items_controller_test.rb b/test/controllers/kraken_items_controller_test.rbindex b740e9d338..a84b4f1758 100644--- a/test/controllers/kraken_items_controller_test.rb+++ b/test/controllers/kraken_items_controller_test.rb@@ -291,6 +291,44 @@ class KrakenItemsControllerTest < ActionDispatch::IntegrationTestassert_includes @response.body, %(value="#{@second_item.id}")end+ # The figure on the setup screen is what the user checks the import against,+ # so it has to be in the currency the account will be created in -- the family+ # currency -- not the one Kraken happens to report in.+ test "setup accounts shows the balance in the family currency" do+ ensure_tailwind_build+ @family.update!(currency: "EUR")+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.9)+ @second_item.kraken_accounts.create!(+ name: "Kraken", account_id: "combined", account_type: "combined",+ currency: "USD", current_balance: 1_000+ )++ get setup_accounts_kraken_item_url(@second_item)++ assert_response :success+ assert_includes @response.body, "€900.00"+ assert_includes @response.body, "EUR"+ end++ # With no rate the account opens at zero, so the screen says zero: showing the+ # reported figure would promise a balance the account will not have.+ test "setup accounts shows zero when the balance cannot be converted" do+ ensure_tailwind_build+ @family.update!(currency: "EUR")+ ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)+ @second_item.kraken_accounts.create!(+ name: "Kraken", account_id: "combined", account_type: "combined",+ currency: "USD", current_balance: 1_000+ )++ get setup_accounts_kraken_item_url(@second_item)++ assert_response :success+ # The balance cell itself: other accounts on the page carry figures of their own.+ assert_match %r{text-primary">€0\.00<}, @response.body+ assert_no_match %r{text-primary">\$1,000\.00<}, @response.body+ end+test "cannot access another family's kraken item" doother_item = KrakenItem.create!(family: families(:empty),diff --git a/test/models/account/crypto_exchange_creation_test.rb b/test/models/account/crypto_exchange_creation_test.rbnew file mode 100644index 0000000000..64ee942d99--- /dev/null+++ b/test/models/account/crypto_exchange_creation_test.rb@@ -0,0 +1,117 @@+# frozen_string_literal: true++require "test_helper"++# Covers the Account factory shared by every crypto-exchange integration:+# `create_from_crypto_exchange_account`, reached through Kraken, Binance and+# CoinSpot.+class Account::CryptoExchangeCreationTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @family.update!(currency: "USD")+ end++ # `create_and_sync` anchors a new account at the balance it was created with,+ # dated in the past. That is right for an account whose history the user will+ # type in, and wrong for an exchange: the processors import its ledger from+ # inception, so every imported entry lands on top of an opening balance equal+ # to what the account is worth today. On an exchange older than the default+ # anchor date the whole history is inflated by the present value.+ test "a Kraken exchange account opens at zero, not at its current value" do+ account = Account.create_from_kraken_account(kraken_account(current_balance: 1_000))++ assert account.has_opening_anchor?+ assert_equal 0, account.opening_anchor_balance+ assert_equal 1_000, account.balance+ end++ test "a Binance exchange account opens at zero, not at its current value" do+ account = Account.create_from_binance_account(binance_account(current_balance: 2_500))++ assert account.has_opening_anchor?+ assert_equal 0, account.opening_anchor_balance+ assert_equal 2_500, account.balance+ end++ # Kraken reports every balance in USD regardless of what the user trades in,+ # but the processors denominate the account's entries and holdings in the+ # family currency. Inheriting the exchange's currency labelled the account+ # USD and then filled it with EUR figures.+ test "an exchange account is created in the family currency, with the balance converted" do+ @family.update!(currency: "EUR")+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.9)++ account = Account.create_from_kraken_account(kraken_account(current_balance: 1_000, currency: "USD"))++ assert_equal "EUR", account.currency+ assert_equal 900, account.balance+ end++ test "a Binance exchange account is created in the family currency" do+ @family.update!(currency: "EUR")+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.9)++ account = Account.create_from_binance_account(binance_account(current_balance: 2_000, currency: "USD"))++ assert_equal "EUR", account.currency+ assert_equal 1_800, account.balance+ end++ test "a CoinSpot exchange account is created in the family currency" do+ @family.update!(currency: "USD")+ ExchangeRate.create!(from_currency: "AUD", to_currency: "USD", date: Date.current, rate: 0.65)++ account = Account.create_from_coinspot_account(coinspot_account(current_balance: 1_000, currency: "AUD"))++ assert_equal "USD", account.currency+ assert_equal 650, account.balance+ end++ # Relabelling 1,000 USD as 1,000 EUR would be wrong by the whole rate. The+ # first sync writes the converted balance; until then zero is the honest figure.+ test "an exchange account starts at zero when no rate is available" do+ @family.update!(currency: "EUR")+ # Stubbed rather than left absent: with no stored rate the lookup still+ # asks the provider, and a rate coming back would make this pass by luck.+ ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)++ account = Account.create_from_kraken_account(kraken_account(current_balance: 1_000, currency: "USD"))++ assert_equal "EUR", account.currency+ assert_equal 0, account.balance+ end++ private++ def kraken_account(current_balance:, currency: "USD")+ item = KrakenItem.create!(family: @family, name: "Kraken", api_key: "k", api_secret: "s")+ item.kraken_accounts.create!(+ name: "Kraken",+ account_id: "combined",+ account_type: "combined",+ currency: currency,+ current_balance: current_balance+ )+ end++ def coinspot_account(current_balance:, currency: "AUD")+ item = CoinspotItem.create!(family: @family, name: "CoinSpot", api_key: "c", api_secret: "s")+ item.coinspot_accounts.create!(+ name: "CoinSpot",+ account_id: "combined",+ account_type: "combined",+ currency: currency,+ current_balance: current_balance+ )+ end++ def binance_account(current_balance:, currency: "USD")+ item = BinanceItem.create!(family: @family, name: "Binance", api_key: "b", api_secret: "s")+ item.binance_accounts.create!(+ name: "Binance",+ account_type: "combined",+ currency: currency,+ current_balance: current_balance+ )+ end+enddiff --git a/test/models/binance_account/processor_test.rb b/test/models/binance_account/processor_test.rbindex 2747fa586b..71b4d4db34 100644--- a/test/models/binance_account/processor_test.rb+++ b/test/models/binance_account/processor_test.rb@@ -270,4 +270,25 @@ class BinanceAccount::ProcessorTest < ActiveSupport::TestCaseBinanceAccount::Processor.new(@ba).processendend++ # Binance opens at zero through the same shared path as Kraken, so it needs+ # the same repair: history older than the anchor leaves the account starting+ # after entries it is supposed to precede.+ test "moves the opening anchor before the first entry" do+ Account::OpeningBalanceManager.new(@account).set_opening_balance(balance: 0, date: 2.years.ago.to_date)+ @account.entries.create!(+ date: 3.years.ago.to_date,+ name: "Old trade",+ amount: 10,+ currency: "EUR",+ entryable: Transaction.new+ )++ BinanceAccount::Processor.new(@ba).process++ # A fresh instance: the manager memoises the anchor it last read.+ account = Account.find(@account.id)+ assert_equal 3.years.ago.to_date.prev_day, account.opening_anchor_date+ assert_equal 0, account.opening_anchor_balance+ endenddiff --git a/test/models/coinspot_account/processor_test.rb b/test/models/coinspot_account/processor_test.rbindex 7bafd4d4db..b0479f4b20 100644--- a/test/models/coinspot_account/processor_test.rb+++ b/test/models/coinspot_account/processor_test.rb@@ -346,6 +346,21 @@ class CoinspotAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal "CoinspotAccount::Processor::UnknownOrderTypeError", result[:failures].first[:error_class]end+ # CoinSpot opens at zero through the same shared path as Kraken, so it needs+ # the same repair: history older than the anchor leaves the account starting+ # after entries it is supposed to precede.+ test "moves the opening anchor before the first imported entry" do+ Account::OpeningBalanceManager.new(@account).set_opening_balance(balance: 0, date: Date.new(2026, 6, 1))++ CoinspotAccount::Processor.new(@coinspot_account).process++ # A fresh instance: the manager memoises the anchor it last read.+ account = Account.find(@account.id)+ oldest = account.entries.where.not(entryable_type: "Valuation").minimum(:date)+ assert_equal oldest.prev_day, account.opening_anchor_date+ assert_equal 0, account.opening_anchor_balance+ end+privatedef order_payload(id, coin, amount, audtotal, rate, fee)diff --git a/test/models/kraken_account/processor_test.rb b/test/models/kraken_account/processor_test.rbindex 44fe052597..2b38526d5f 100644--- a/test/models/kraken_account/processor_test.rb+++ b/test/models/kraken_account/processor_test.rb@@ -105,6 +105,78 @@ class KrakenAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal "USD", @account.currencyend+ # The account is created, and anchored two years back, before any history+ # is imported. A ledger older than that then starts before its own opening+ # balance, and the reverse calculator pins the balance to the anchor and+ # derives every earlier day from it with the flows running the wrong way.+ test "moves the opening anchor before the first imported entry" do+ old_trade = trade_payload("buy", "0.001", "50.00", "0.10").merge("time" => 3.years.ago.to_f)+ kraken_account = @item.kraken_accounts.create!(+ name: "Kraken (old)", account_id: "old", account_type: "combined", currency: "USD", current_balance: 50,+ raw_payload: @kraken_account.raw_payload,+ raw_transactions_payload: { "trades" => { "old_tx" => old_trade } }+ )+ account = Account.create_from_kraken_account(kraken_account)+ AccountProvider.create!(account: account, provider: kraken_account)+ assert_equal 2.years.ago.to_date, account.opening_anchor_date++ KrakenAccount::Processor.new(kraken_account).process++ # A fresh instance: the manager memoises the anchor it last read.+ account = Account.find(account.id)+ assert account.entries.exists?(external_id: "kraken_trade_old_tx"), "the old trade must have been imported"+ assert_equal 3.years.ago.to_date.prev_day, account.opening_anchor_date+ assert_equal 0, account.opening_anchor_balance+ end++ # A reconciliation older than the first trade is still an entry, so the date+ # the anchor moves to has to clear it too -- the manager validates against+ # every entry, not just the ones that are not valuations.+ test "moves the opening anchor before an older valuation too" do+ old_trade = trade_payload("buy", "0.001", "50.00", "0.10").merge("time" => 3.years.ago.to_f)+ kraken_account = @item.kraken_accounts.create!(+ name: "Kraken (valuation)", account_id: "val", account_type: "combined", currency: "USD", current_balance: 50,+ raw_payload: @kraken_account.raw_payload,+ raw_transactions_payload: { "trades" => { "old_tx" => old_trade } }+ )+ account = Account.create_from_kraken_account(kraken_account)+ AccountProvider.create!(account: account, provider: kraken_account)+ account.entries.create!(+ date: 4.years.ago.to_date,+ name: "Balance update",+ amount: 0,+ currency: account.currency,+ entryable: Valuation.new(kind: "reconciliation")+ )++ KrakenAccount::Processor.new(kraken_account).process++ # A fresh instance: the manager memoises the anchor it last read.+ account = Account.find(account.id)+ assert_equal 4.years.ago.to_date.prev_day, account.opening_anchor_date+ assert_equal 0, account.opening_anchor_balance+ end++ # A manual account linked to the exchange later may carry an anchor somebody+ # entered: "this much, on this day". Moving it would change what it says.+ test "leaves an opening anchor with a balance where it is" do+ old_trade = trade_payload("buy", "0.001", "50.00", "0.10").merge("time" => 3.years.ago.to_f)+ kraken_account = @item.kraken_accounts.create!(+ name: "Kraken (linked)", account_id: "linked", account_type: "combined", currency: "USD", current_balance: 50,+ raw_payload: @kraken_account.raw_payload,+ raw_transactions_payload: { "trades" => { "old_tx" => old_trade } }+ )+ account = Account.create_from_kraken_account(kraken_account)+ AccountProvider.create!(account: account, provider: kraken_account)+ account.set_opening_anchor_balance(balance: 250, date: 2.years.ago.to_date)++ KrakenAccount::Processor.new(kraken_account).process++ account = Account.find(account.id)+ assert_equal 2.years.ago.to_date, account.opening_anchor_date+ assert_equal 250, account.opening_anchor_balance+ end+privatedef trade_payload(type, volume, cost, fee)