The personal finance app for everyone (by everyone)
Ruby
Make on-chain wallet transfers cash-neutral (#3703)
B. McCafferty45ab75ae6a0e
diff --git a/app/models/onchain_wallet_account/processor.rb b/app/models/onchain_wallet_account/processor.rbindex 1fcf6c0907..7ee7783ff6 100644--- a/app/models/onchain_wallet_account/processor.rb+++ b/app/models/onchain_wallet_account/processor.rb@@ -42,19 +42,27 @@ class OnchainWalletAccount::Processor## Reads prices from the database only — no network — so this can run for every# linked asset on every sync.- # @return [Integer] number of entries upgraded+ # @return [Integer] number of entries upgraded or normalizeddef repair_display_only_movementsreturn 0 unless account- relabelled = relabel_legacy_trades+ normalized, amount_changed = normalize_legacy_transfers- candidates = display_only_entries- return relabelled if candidates.empty?+ # Scheduled as soon as the amount is corrected, before the upgrade pass —+ # which can raise (a failed trade write `upgrade_to_trade` is allowed to+ # throw), and the syncer's per-account rescue would otherwise skip this and+ # leave the chart with phantom cash until some unrelated sync ran. Zeroing a+ # legacy amount rewrites history, but only an account sync persists the+ # recalculated balances, and an idle wallet schedules none of its own.+ account.sync_later if amount_changed- security = resolve_security- return relabelled if security.nil?+ candidates = display_only_entries+ upgraded = 0+ if candidates.any? && (security = resolve_security)+ upgraded = candidates.count { |entry| upgrade_to_trade(entry, security) }+ end- relabelled + candidates.count { |entry| upgrade_to_trade(entry, security) }+ normalized + upgradedendprivate@@ -242,8 +250,15 @@ class OnchainWalletAccount::Processorsecurity: security,quantity: quantity,price: price,- # Sure's convention for trades: money leaves the account on a buy.- amount: -(quantity * price).round(4),+ # A transfer moves no cash. A self-custody wallet has no cash side for+ # this leg, so booking one fabricates a balance the account never+ # held: the reverse balance calculator then carries a phantom cash+ # figure across every gap between transfers (a wallet reads negative+ # before its first deposit, a sold-out position stays negative through+ # its zero-holding gap, and a live position's line is roughly double).+ # The value lives in qty/price -- and therefore cost basis -- which is+ # all a transfer needs.+ amount: 0,currency: currency,date: date,# Named here because the shared helper says "Buy 0.5 shares of@@ -291,36 +306,54 @@ class OnchainWalletAccount::Processorend# The zero-amount, excluded entries this processor writes for unpriced- # movements, identified by the external_id prefix it gave them.+ # movements, identified by the external_id prefix it gave them. Also brings+ # already-written transfers back in line with the current ledger shape.+ ## Movements imported before transfers were called transfers still carry a- # `Buy` or `Sell` label and a "Buy 0.5 shares of CRYPTO:BTC" name. Nothing- # rewrites them on an ordinary sync: `perform_sync` returns early when no- # address changed on chain, and the repair above only ever looked at- # display-only `Transaction` rows. Left alone they would keep the old- # wording for as long as the wallet sits still — which for a cold address- # is the whole point of it.+ # `Buy` or `Sell` label and a "Buy 0.5 shares of CRYPTO:BTC" name, and+ # transfers written before they became cash-neutral still carry the old+ # signed cash amount. Nothing rewrites them on an ordinary sync: `perform_sync`+ # returns early when no address changed on chain, and the upgrade above only+ # ever looked at display-only `Transaction` rows. Left alone they would keep+ # the old wording (and the phantom cash) for as long as the wallet sits still+ # — which for a cold address is the whole point of it.## Scoped to this processor's own external_id prefix and to `source:# SOURCE`, so a trade the user entered by hand is never touched.- def relabel_legacy_trades+ # @return [Array(Integer, Boolean)] entries normalized, and whether any+ # amount changed — the part that needs a balance recalculation+ def normalize_legacy_transfersentries = account.entries.where(source: SOURCE, entryable_type: "Trade").where("external_id LIKE ?", "#{holding_external_id}_%").includes(:entryable).to_a- return 0 if entries.empty?+ return [ 0, false ] if entries.empty?++ # Computed independently of the per-entry predicate below, so the+ # `account.sync_later` trigger can't silently stop firing if that+ # predicate is ever relaxed.+ amount_changed = entries.any? { |entry| !entry.amount.zero? }- entries.count do |entry|+ count = entries.count do |entry|trade = entry.entryableexpected_name = movement_name(trade.qty.to_d)- next false if trade.investment_activity_label == TRANSFER_LABEL && entry.name == expected_name+ already_normalized = trade.investment_activity_label == TRANSFER_LABEL &&+ entry.name == expected_name &&+ entry.amount.zero?+ next false if already_normalizedEntry.transaction dotrade.update!(investment_activity_label: TRANSFER_LABEL)- entry.update!(name: expected_name)+ # One write for both entry columns — the name wording and the+ # cash-neutral amount (a pre-fix signed value here is what leaves the+ # phantom cash on a wallet that never moves again).+ entry.update!(name: expected_name, amount: 0)endtrueend++ [ count, amount_changed ]enddef display_only_entriesdiff --git a/test/models/onchain_wallet_account/processor_test.rb b/test/models/onchain_wallet_account/processor_test.rbindex 4bab6fc231..ed71a79428 100644--- a/test/models/onchain_wallet_account/processor_test.rb+++ b/test/models/onchain_wallet_account/processor_test.rb@@ -98,7 +98,9 @@ class OnchainWalletAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal "Trade", entry.entryable_typeassert_equal BigDecimal("1.5"), entry.entryable.qtyassert_equal 50, entry.entryable.price- assert_equal(-75, entry.amount)+ # Cash-neutral: a transfer moves no cash, so booking one here would+ # fabricate a balance the wallet never held (see write_trade).+ assert_equal 0, entry.amount# A trade is the shape this ledger needs to carry quantity and cost basis,# but coins arriving at an address were not bought here — and the name is# the one the movement already had before a price existed for it, so it does@@ -117,7 +119,7 @@ class OnchainWalletAccount::ProcessorTest < ActiveSupport::TestCaseentry = @account.entries.find_by(external_id: "onchain_#{@onchain_account.id}_tx2")assert_equal(-1, entry.entryable.qty)- assert_equal 50, entry.amount+ assert_equal 0, entry.amountassert_equal "Transfer", entry.entryable.investment_activity_labelassert_equal "Sent 1.0 FAKE", entry.nameend@@ -257,7 +259,7 @@ class OnchainWalletAccount::ProcessorTest < ActiveSupport::TestCaseentry = onchain_entry("tx1")assert_equal "Trade", entry.entryable_typeassert_equal BigDecimal("1.5"), entry.entryable.qty- assert_equal(-60, entry.amount)+ assert_equal 0, entry.amountassert_equal 1, @account.entries.where(external_id: entry.external_id).countend@@ -295,10 +297,40 @@ class OnchainWalletAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal entry.external_id, upgraded.external_idassert_equal BigDecimal("1.5"), upgraded.entryable.qtyassert_equal 40, upgraded.entryable.price- assert_equal(-60, upgraded.amount)+ assert_equal 0, upgraded.amountassert_not upgraded.excludedend+ test "the repair zeroes the legacy cash amount on a priced transfer" do+ date = 3.days.ago.to_date+ price_asset_at(date, 50)+ store_movements(fake_movement(external_id: "tx1", amount: "1.5", timestamp: date))+ OnchainWalletAccount::Processor.new(@onchain_account).process++ entry = onchain_entry("tx1")+ assert_equal "Trade", entry.entryable_type+ # A transfer written before transfers became cash-neutral.+ entry.update!(amount: -75)++ # The corrected amount only reaches the chart once an account sync+ # recalculates the balances, so the repair has to ask for one.+ assert_difference -> { @account.syncs.count }, 1 do+ assert_equal 1, OnchainWalletAccount::Processor.new(@onchain_account).repair_display_only_movements+ end+ assert_equal 0, entry.reload.amount+ end++ test "the repair leaves an already normalized transfer alone" do+ date = 3.days.ago.to_date+ price_asset_at(date, 50)+ store_movements(fake_movement(external_id: "tx1", amount: "1.5", timestamp: date))+ OnchainWalletAccount::Processor.new(@onchain_account).process++ assert_no_difference -> { @account.syncs.count } do+ assert_equal 0, OnchainWalletAccount::Processor.new(@onchain_account).repair_display_only_movements+ end+ end+test "the repair leaves a movement alone while its price is still unknown" dostore_movements(fake_movement(external_id: "tx1", amount: "1", timestamp: 3.days.ago.to_date))OnchainWalletAccount::Processor.new(@onchain_account).process