The personal finance app for everyone (by everyone)
Ruby
fix(onchain): revalue idle wallets at the latest price (#4067)
PierroMojito585fd4a438d2
diff --git a/app/models/onchain_wallet_account/processor.rb b/app/models/onchain_wallet_account/processor.rbindex 7ee7783ff6..c492bcb4cf 100644--- a/app/models/onchain_wallet_account/processor.rb+++ b/app/models/onchain_wallet_account/processor.rb@@ -22,15 +22,35 @@ class OnchainWalletAccount::Processorsecurity = resolve_securitybackfill_prices(security) if security- price = security ? price_on(security, Date.current) : nil- amount = price ? (quantity * price).round(4) : 0.to_d+ price = price_today(security)+ amount = price ? value_at(price) : 0.to_d- import_holding(security, price, amount) if security- update_balances(amount)+ write_valuation(security, price, amount)materialize_movements(security) if securityreport_zero_valuation(security) if security && price.nil?end+ # Revalues an asset that did not move on chain at the latest stored price.+ # @return [Boolean] whether the value changed+ def revalue+ return false unless account++ security = resolve_security+ price = price_today(security)+ return false if price.nil?++ amount = value_at(price)+ return false if amount == account.balance && currency == account.currency++ # Rolls the write back if the sync cannot be queued; the job itself is+ # enqueued after commit (see ApplicationJob).+ Account.transaction do+ write_valuation(security, price, amount)+ account.sync_later+ end+ true+ end+# Converts movements that were recorded as display-only into trades, once a# price for their date exists.#@@ -53,7 +73,7 @@ class OnchainWalletAccount::Processor# 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.+ # recalculated balances, and an idle wallet may schedule none of its own.account.sync_later if amount_changedcandidates = display_only_entries@@ -78,6 +98,19 @@ class OnchainWalletAccount::Processoronchain_wallet_account.quantity.to_dend+ def price_today(security)+ security ? price_on(security, Date.current) : nil+ end++ def value_at(price)+ (quantity * price).round(4)+ end++ def write_valuation(security, price, amount)+ import_holding(security, price, amount) if security+ update_balances(amount)+ end+def resolve_securityOnchain::SecurityResolver.resolve(symbol: onchain_wallet_account.symbol,diff --git a/app/models/onchain_wallet_item/syncer.rb b/app/models/onchain_wallet_item/syncer.rbindex 90c5bced62..474a745445 100644--- a/app/models/onchain_wallet_item/syncer.rb+++ b/app/models/onchain_wallet_item/syncer.rb@@ -1,8 +1,8 @@# frozen_string_literal: true# Reads every tracked address, then reprocesses only the rows whose on-chain-# state actually changed. An idle wallet costs reads and nothing else: no-# holdings, entries or balances are rewritten, and no account syncs are queued.+# state actually changed. An idle wallet is revalued after the sync, and only+# written when its value changed.class OnchainWalletItem::Syncerinclude SyncStats::Collector@@ -53,13 +53,29 @@ class OnchainWalletItem::Syncer# changed here is the price history, which no chain read can tell us about.def perform_post_synclinked_accounts.each do |onchain_account|- OnchainWalletAccount::Processor.new(onchain_account).repair_display_only_movements- rescue StandardError => e- Rails.logger.warn("OnchainWalletItem::Syncer - movement repair failed for #{onchain_account.id}: #{e.class}")+ processor = OnchainWalletAccount::Processor.new(onchain_account)+ post_sync_step(onchain_account, "movement repair") { processor.repair_display_only_movements }+ post_sync_step(onchain_account, "revaluation") { processor.revalue }endendprivate+ # One asset's failing step must not stop the other step or the other assets.+ def post_sync_step(onchain_account, label)+ yield+ rescue StandardError => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "On-chain wallet #{label} failed: #{e.class}",+ source: self.class.name,+ provider_key: "onchain_wallet",+ family: onchain_wallet_item.family,+ account: onchain_account.current_account,+ metadata: { onchain_wallet_account_id: onchain_account.id, error: e.message }+ )+ end+def linked_accountsonchain_wallet_item.onchain_wallet_accounts.linked.joins(:account).merge(Account.visible)enddiff --git a/test/models/onchain_wallet_account/processor_test.rb b/test/models/onchain_wallet_account/processor_test.rbindex ed71a79428..9bb2ae61f4 100644--- a/test/models/onchain_wallet_account/processor_test.rb+++ b/test/models/onchain_wallet_account/processor_test.rb@@ -457,12 +457,70 @@ class OnchainWalletAccount::ProcessorTest < ActiveSupport::TestCaseendend- test "does nothing when the asset is not linked to an account" do+ test "revalue brings an idle wallet up to the latest price and asks for an account sync" do+ price_asset_at(1.day.ago.to_date, 100)+ OnchainWalletAccount::Processor.new(@onchain_account).process+ assert_equal 200, @account.reload.balance++ price_asset_at(Date.current, 150)++ assert_difference -> { @account.syncs.count }, 1 do+ assert OnchainWalletAccount::Processor.new(@onchain_account).revalue+ end+ assert_equal 300, @account.reload.balance+ assert_equal 0, @account.cash_balance+ assert_equal 300, @onchain_account.reload.current_balance+ assert_equal 300, @account.holdings.find_by!(date: Date.current).amount+ end++ test "revalue writes nothing when the account sync cannot be queued" do+ price_asset_at(1.day.ago.to_date, 100)+ OnchainWalletAccount::Processor.new(@onchain_account).process+ price_asset_at(Date.current, 150)+ Account.any_instance.stubs(:sync_later).raises(ActiveRecord::LockWaitTimeout)++ assert_raises(ActiveRecord::LockWaitTimeout) do+ OnchainWalletAccount::Processor.new(@onchain_account).revalue+ end+ assert_equal 200, @account.reload.balance+ assert_equal 200, @account.holdings.find_by!(date: Date.current).amount+ end++ test "revalue fixes the account currency even when the amount matches" do+ price_asset_at(Date.current, 100)+ OnchainWalletAccount::Processor.new(@onchain_account).process+ @account.update_columns(currency: "EUR")++ assert OnchainWalletAccount::Processor.new(@onchain_account.reload).revalue+ assert_equal @onchain_account.currency, @account.reload.currency+ end++ test "revalue changes nothing when the price has not moved" do+ price_asset_at(Date.current, 100)+ OnchainWalletAccount::Processor.new(@onchain_account).process++ assert_no_difference -> { @account.syncs.count } do+ assert_not OnchainWalletAccount::Processor.new(@onchain_account).revalue+ end+ assert_equal 200, @account.reload.balance+ end++ test "revalue leaves the value alone when no price is known" do+ price_asset_at(Date.current, 100)+ OnchainWalletAccount::Processor.new(@onchain_account).process+ security.prices.delete_all++ assert_not OnchainWalletAccount::Processor.new(@onchain_account).revalue+ assert_equal 200, @account.reload.balance+ end++ test "process and revalue do nothing when the asset is not linked to an account" dounlinked = create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xaaa"))assert_nothing_raised doOnchainWalletAccount::Processor.new(unlinked).processend+ assert_not OnchainWalletAccount::Processor.new(unlinked).revalueendprivatediff --git a/test/models/onchain_wallet_item/syncer_test.rb b/test/models/onchain_wallet_item/syncer_test.rbindex e699ac98a1..b80da405f5 100644--- a/test/models/onchain_wallet_item/syncer_test.rb+++ b/test/models/onchain_wallet_item/syncer_test.rb@@ -97,6 +97,29 @@ class OnchainWalletItem::SyncerTest < ActiveSupport::TestCaseassert_equal "Trade", @account.entries.find_by!(external_id: "onchain_#{@onchain_account.id}_tx1").entryable_typeend+ test "post sync revalues an asset that did not move on chain" do+ stub_wallet(quantity: "2")+ security = Onchain::SecurityResolver.resolve(symbol: @onchain_account.symbol, name: @onchain_account.name)+ Security::Price.create!(security: security, date: 1.day.ago.to_date, price: 100, currency: "USD")+ OnchainWalletItem::Syncer.new(@item).perform_sync(@sync)+ assert_equal 200, @account.reload.balance++ Security::Price.create!(security: security, date: Date.current, price: 150, currency: "USD")+ OnchainWalletItem::Syncer.new(@item).perform_sync(@item.syncs.create!)+ OnchainWalletItem::Syncer.new(@item).perform_post_sync++ assert_equal 300, @account.reload.balance+ end++ test "post sync still revalues when the movement repair fails" do+ OnchainWalletAccount::Processor.any_instance.stubs(:repair_display_only_movements).raises(StandardError)+ OnchainWalletAccount::Processor.any_instance.expects(:revalue).once++ assert_difference "DebugLogEntry.count", 1 do+ OnchainWalletItem::Syncer.new(@item).perform_post_sync+ end+ end+privatedef stub_wallet(quantity: "1", assets: nil)stub_fake_snapshot(