The personal finance app for everyone (by everyone)
Ruby
fix(binance): let go of an asset the wallet no longer holds (#3234)
buzzromain843e91c25799
diff --git a/app/models/binance_account/holdings_processor.rb b/app/models/binance_account/holdings_processor.rbindex 8eaf0e2890..64d1fb2458 100644--- a/app/models/binance_account/holdings_processor.rb+++ b/app/models/binance_account/holdings_processor.rb@@ -16,12 +16,16 @@ class BinanceAccount::HoldingsProcessorendassets = raw_assets- if assets.empty?- Rails.logger.info "BinanceAccount::HoldingsProcessor - no assets in payload"+ if assets.nil?+ # No asset list at all is not an empty wallet, it is a wallet nothing has+ # reported on yet. Cleaning up here would delete holdings on the strength+ # of missing information.+ Rails.logger.info "BinanceAccount::HoldingsProcessor - no asset list in payload"returnendassets.each { |asset| process_asset(asset) }+ cleanup_stale_holdings!(assets)rescue StandardError => eRails.logger.error "BinanceAccount::HoldingsProcessor - error: #{e.message}"nil@@ -39,8 +43,43 @@ class BinanceAccount::HoldingsProcessorbinance_account.current_accountend+ # nil when the payload has never carried an asset list, [] when Binance+ # reported an empty wallet. The two mean different things to the cleanup.def raw_assets- binance_account.raw_payload&.dig("assets") || []+ binance_account.raw_payload&.dig("assets")+ end++ # Binance reports what the wallet holds NOW, so a holding written for today+ # whose asset is no longer in the payload is one that has left the wallet.+ # Nothing removed them before, and the account page reads exactly today's+ # rows — so a coin sold hours ago was still in the portfolio.+ #+ # Keyed on what the PAYLOAD contains, not on what was successfully+ # imported: an asset whose price could not be fetched is skipped above, and+ # deleting it would turn a price outage into a disappeared holding.+ def cleanup_stale_holdings!(assets)+ provider_id = binance_account.account_provider&.id+ return if provider_id.nil?++ keep = assets.filter_map { |asset| external_id_for(asset) }+ scope = account.holdings.where(account_provider_id: provider_id, date: Date.current)+ scope = scope.where.not(external_id: keep) if keep.any?++ removed = scope.delete_all+ Rails.logger.info "BinanceAccount::HoldingsProcessor - removed #{removed} holding(s) no longer in the wallet" if removed.positive?+ end++ def external_id_for(asset)+ symbol = asset["symbol"] || asset[:symbol]+ source = asset["source"] || asset[:source]+ return if symbol.blank?+ return if (asset["total"] || asset[:total]).to_d.zero?++ holding_external_id(symbol, source)+ end++ def holding_external_id(symbol, source)+ "binance_#{symbol}_#{source}_#{Date.current}"enddef process_asset(asset)@@ -76,7 +115,7 @@ class BinanceAccount::HoldingsProcessordate: Date.current,price: price,cost_basis: nil,- external_id: "binance_#{symbol}_#{source}_#{Date.current}",+ external_id: holding_external_id(symbol, source),account_provider_id: binance_account.account_provider&.id,source: "binance",delete_future_holdings: falsediff --git a/app/models/binance_item.rb b/app/models/binance_item.rbindex b482cd5015..7843dfd2e1 100644--- a/app/models/binance_item.rb+++ b/app/models/binance_item.rb@@ -40,6 +40,16 @@ class BinanceItem < ApplicationRecordBinanceItem::Importer.new(self, binance_provider: provider).importrescue StandardError => e+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "error",+ message: "Binance import failed",+ source: self.class.name,+ provider_key: "binance",+ family: family,+ account_provider: binance_accounts.includes(:account_provider).filter_map(&:account_provider).first,+ metadata: { binance_item_id: id, error_class: e.class.name, error: e.message }+ )Rails.logger.error "BinanceItem #{id} - Failed to import: #{e.message}"raiseenddiff --git a/app/models/binance_item/earn_importer.rb b/app/models/binance_item/earn_importer.rbindex a6d761ec3f..111e054e7e 100644--- a/app/models/binance_item/earn_importer.rb+++ b/app/models/binance_item/earn_importer.rb@@ -11,16 +11,34 @@ class BinanceItem::EarnImporterenddef import+ @errors = {}flexible_raw = fetch_flexiblelocked_raw = fetch_locked+ # Both sub-requests rescue to nil, so a double failure came back looking+ # exactly like "no Earn positions". The caller decides from these results+ # whether the wallet is empty, so it has to be told the difference.+ if flexible_raw.nil? && locked_raw.nil?+ return {+ assets: [],+ raw: { "flexible" => nil, "locked" => nil },+ source: "earn",+ error: @errors.values.uniq.join("; ").presence || "simple earn unavailable"+ }+ end++ # One side down does not fail the import, so the caller never records it —+ # and /settings/debug would show nothing at all about an endpoint that has+ # stopped answering, even though positions are being carried because of it.+ record_partial_failure if @errors.any?+assets = merge_earn_assets(parse_flexible(flexible_raw),parse_locked(locked_raw)){- assets: assets,+ assets: restore_unavailable_side(assets, flexible_ok: !flexible_raw.nil?, locked_ok: !locked_raw.nil?),raw: { "flexible" => flexible_raw, "locked" => locked_raw },source: "earn"}@@ -34,6 +52,7 @@ class BinanceItem::EarnImporterdef fetch_flexibleprovider.get_simple_earn_flexiblerescue => e+ @errors["flexible"] = e.messageRails.logger.warn "BinanceItem::EarnImporter #{binance_item.id} - flexible failed: #{e.message}"nilend@@ -41,10 +60,68 @@ class BinanceItem::EarnImporterdef fetch_lockedprovider.get_simple_earn_lockedrescue => e+ @errors["locked"] = e.messageRails.logger.warn "BinanceItem::EarnImporter #{binance_item.id} - locked failed: #{e.message}"nilend+ # One side failing is not the whole source failing, so the caller cannot+ # carry the previous assets the way it does for a dead source — that would+ # discard the side that did answer. But dropping the silent side outright+ # removes live positions: a locked ETH holding would disappear because the+ # flexible call happened to be the one that worked.+ #+ # The two amounts are kept apart on every asset, so the missing side is+ # refilled from what it last reported and the working side stays fresh.+ def restore_unavailable_side(assets, flexible_ok:, locked_ok:)+ return assets if flexible_ok && locked_ok++ previous = previous_earn_assets+ return assets if previous.empty?++ merged = assets.index_by { |asset| asset[:symbol] }++ previous.each do |old|+ symbol = old["symbol"]+ current = merged[symbol]++ free = flexible_ok ? current&.dig(:free).to_d : old["free"].to_d+ locked = locked_ok ? current&.dig(:locked).to_d : old["locked"].to_d+ total = free + locked+ next if total.zero?++ merged[symbol] = {+ symbol: symbol, free: free.to_s("F"), locked: locked.to_s("F"), total: total.to_s("F")+ }+ end++ merged.values+ end++ def record_partial_failure+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: "Binance Simple Earn read only part of its positions",+ source: self.class.name,+ provider_key: "binance",+ family: binance_item.family,+ metadata: {+ binance_item_id: binance_item.id,+ unavailable_endpoints: @errors.keys,+ errors: @errors+ }+ )+ end++ def previous_earn_assets+ Array(+ binance_item.binance_accounts+ .find_by(account_type: "combined")+ &.raw_payload&.dig("assets")+ ).select { |asset| asset["source"] == "earn" }+ end+def parse_flexible(raw)return {} unless raw.is_a?(Hash)diff --git a/app/models/binance_item/importer.rb b/app/models/binance_item/importer.rbindex 1987022d2d..5490a361c2 100644--- a/app/models/binance_item/importer.rb+++ b/app/models/binance_item/importer.rb@@ -2,6 +2,12 @@# Orchestrates all Binance sub-importers and upserts a single combined BinanceAccount.class BinanceItem::Importer+ # Every sub-importer swallows its own error and answers with an empty asset+ # list, so "the wallet is empty" and "nothing could be fetched" arrive here+ # looking identical. Raising on the second keeps the sync honest instead of+ # reporting a successful import of nothing.+ class AllRequestsFailed < StandardError; end+attr_reader :binance_item, :binance_providerdef initialize(binance_item, binance_provider:)@@ -17,9 +23,27 @@ class BinanceItem::Importerearn_result = BinanceItem::EarnImporter.new(binance_item, provider: binance_provider).importfutures_result = BinanceItem::FuturesImporter.new(binance_item, provider: binance_provider).import- all_assets = tagged_assets(spot_result) + tagged_assets(margin_result) + tagged_assets(earn_result) + tagged_assets(futures_result)+ results = [ spot_result, margin_result, earn_result, futures_result ]+ all_assets = results.flat_map { |result| tagged_assets(result) }++ if results.all? { |result| result[:error].present? }+ raise AllRequestsFailed, results.filter_map { |result| result[:error] }.uniq.join("; ")+ end- return { success: true, assets_imported: 0, total_usd: 0 } if all_assets.empty?+ # A source that failed tells us nothing about what it holds, and the+ # holdings processor removes anything missing from this list. Writing only+ # the sources that answered would therefore delete live positions on a+ # transient error or a permission-scoped key. Their last known assets are+ # carried instead: stale until the source answers again, which beats gone.+ all_assets += carried_over_assets(results)++ # An emptied wallet still has to be written down. Returning here left the+ # previous payload in place, and the holdings processor reads that payload —+ # so assets already sold were re-imported as today's holdings on every sync+ # and never went away. Only skipped when there is nothing to correct yet.+ if all_assets.empty? && binance_item.binance_accounts.find_by(account_type: "combined").nil?+ return { success: true, assets_imported: 0, total_usd: 0 }+ endtotal_usd = calculate_total_usd(all_assets)@@ -51,6 +75,50 @@ class BinanceItem::Importerresult[:assets].map { |a| a.merge(source: result[:source]) }end+ def carried_over_assets(results)+ failed = results.select { |result| result[:error].present? }+ return [] if failed.empty?++ # A partial failure returns normally, so it never reaches the rescue in+ # BinanceItem#import_latest_binance_data. Without this the only trace is+ # an application log line, and support has nothing against the connection+ # saying part of the wallet went unread.+ record_partial_failure(failed)++ sources = failed.map { |result| result[:source] }+ previous = binance_item.binance_accounts.find_by(account_type: "combined")&.raw_payload&.dig("assets")+ return [] if previous.blank?++ carried = previous+ .map(&:deep_symbolize_keys)+ .select { |asset| sources.include?(asset[:source]) }++ if carried.any?+ Rails.logger.warn(+ "BinanceItem::Importer #{binance_item.id} - carrying #{carried.size} asset(s) " \+ "from unavailable source(s): #{sources.join(', ')}"+ )+ end++ carried+ end++ def record_partial_failure(failed)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: "Binance import read only part of the wallet",+ source: self.class.name,+ provider_key: "binance",+ family: binance_item.family,+ metadata: {+ binance_item_id: binance_item.id,+ unavailable_sources: failed.map { |result| result[:source] },+ errors: failed.to_h { |result| [ result[:source], result[:error] ] }+ }+ )+ end+def calculate_total_usd(assets)assets.sum do |asset|quantity = asset[:total].to_ddiff --git a/test/models/binance_account/holdings_processor_test.rb b/test/models/binance_account/holdings_processor_test.rbindex 929fccf52f..3b5c3a39ba 100644--- a/test/models/binance_account/holdings_processor_test.rb+++ b/test/models/binance_account/holdings_processor_test.rb@@ -69,4 +69,61 @@ class BinanceAccount::HoldingsProcessorTest < ActiveSupport::TestCaseBinanceAccount::HoldingsProcessor.new(@ba).processend+ # The reported bug. The processor wrote whatever Binance returned and never+ # removed what it stopped returning, so an asset sold between two syncs kept+ # its row for the day — and the account page reads exactly that day.+ test "an asset that has left the wallet stops being held" do+ seed_rate_and_securities++ write_payload([ btc_asset, eth_asset ])+ BinanceAccount::HoldingsProcessor.new(@ba).process+ assert_equal [ "CRYPTO:BTC", "CRYPTO:ETH" ], held_tickers++ # ETH is sold, so Binance stops returning it.+ write_payload([ btc_asset ])+ BinanceAccount::HoldingsProcessor.new(@ba).process++ assert_equal [ "CRYPTO:BTC" ], held_tickers,+ "an asset the wallet no longer holds was still in the portfolio"+ end++ # An emptied wallet is the same question with nothing left to compare+ # against, and the early return on a blank asset list skipped the removal+ # entirely.+ test "emptying the wallet empties the portfolio" do+ seed_rate_and_securities++ write_payload([ btc_asset ])+ BinanceAccount::HoldingsProcessor.new(@ba).process+ assert_equal [ "CRYPTO:BTC" ], held_tickers++ write_payload([])+ BinanceAccount::HoldingsProcessor.new(@ba).process++ assert_empty held_tickers, "the emptied wallet still reported holdings"+ end++ private+ def seed_rate_and_securities+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR",+ date: Date.current, rate: 1.0)+ %w[BTC ETH].each do |symbol|+ Security.find_or_create_by!(ticker: "CRYPTO:#{symbol}") do |s|+ s.name = symbol+ s.exchange_operating_mic = "XBNC"+ end+ end+ BinanceAccount::HoldingsProcessor.any_instance.stubs(:fetch_price).returns(1_000.0)+ end++ def btc_asset = { "symbol" => "BTC", "total" => "0.5", "source" => "spot" }+ def eth_asset = { "symbol" => "ETH", "total" => "2", "source" => "spot" }++ def write_payload(assets)+ @ba.update!(raw_payload: { "assets" => assets })+ end++ def held_tickers+ @account.reload.current_holdings.filter_map { |h| h.security&.ticker }.sort+ endenddiff --git a/test/models/binance_item/earn_importer_test.rb b/test/models/binance_item/earn_importer_test.rbindex c0797ad837..e0b7f35577 100644--- a/test/models/binance_item/earn_importer_test.rb+++ b/test/models/binance_item/earn_importer_test.rb@@ -45,14 +45,103 @@ class BinanceItem::EarnImporterTest < ActiveSupport::TestCaseassert_equal "1.5", result[:assets].first[:total]end- test "returns empty assets when both APIs fail" do- @provider.stubs(:get_simple_earn_flexible).raises(Provider::Binance::ApiError, "error")- @provider.stubs(:get_simple_earn_locked).raises(Provider::Binance::ApiError, "error")+ # Both sub-requests rescue to nil, so a double failure used to be reported as+ # a successful import of no positions — and the caller decides from these+ # results whether the whole wallet is empty.+ test "returns empty assets when both APIs fail, and says they failed" do+ @provider.stubs(:get_simple_earn_flexible).raises(Provider::Binance::ApiError, "flexible down")+ @provider.stubs(:get_simple_earn_locked).raises(Provider::Binance::ApiError, "locked down")result = BinanceItem::EarnImporter.new(@item, provider: @provider).importassert_equal "earn", result[:source]assert_equal [], result[:assets]assert_equal({ "flexible" => nil, "locked" => nil }, result[:raw])+ assert_includes result[:error].to_s, "flexible down"+ assert_includes result[:error].to_s, "locked down"end++ # One side answering is still an answer: an account with only flexible+ # positions must not be reported as a failure.+ test "one side failing is not a failure" do+ @provider.stubs(:get_simple_earn_flexible).returns(+ { "rows" => [ { "asset" => "BTC", "totalAmount" => "1.0" } ] }+ )+ @provider.stubs(:get_simple_earn_locked).raises(Provider::Binance::ApiError, "locked down")++ result = BinanceItem::EarnImporter.new(@item, provider: @provider).import++ assert_nil result[:error]+ assert_equal [ "BTC" ], result[:assets].map { |a| a[:symbol] }+ end++ # ...but it must not cost the silent side its positions. The caller carries a+ # whole source that failed; a half-answering source slips through that, so a+ # locked position would have vanished because the flexible call happened to+ # be the one that worked.+ test "the side that went silent keeps what it last reported" do+ seed_previous_earn(symbol: "ETH", free: "1.0", locked: "3.0")++ @provider.stubs(:get_simple_earn_flexible).returns(+ { "rows" => [ { "asset" => "ETH", "totalAmount" => "2.0" } ] }+ )+ @provider.stubs(:get_simple_earn_locked).raises(Provider::Binance::ApiError, "locked down")++ asset = BinanceItem::EarnImporter.new(@item, provider: @provider).import[:assets].first++ assert_equal "2.0", asset[:free], "the side that answered was not taken fresh"+ assert_equal "3.0", asset[:locked], "the silent side lost its position"+ assert_equal "5.0", asset[:total]+ end++ # The reverse direction, and the case where the silent side is the only one+ # holding the asset at all.+ test "an asset held only on the silent side survives" do+ seed_previous_earn(symbol: "SOL", free: "4.0", locked: "0.0")++ @provider.stubs(:get_simple_earn_flexible).raises(Provider::Binance::ApiError, "flexible down")+ @provider.stubs(:get_simple_earn_locked).returns({ "rows" => [] })++ assets = BinanceItem::EarnImporter.new(@item, provider: @provider).import[:assets]++ assert_equal [ "SOL" ], assets.map { |a| a[:symbol] }+ assert_equal "4.0", assets.first[:total]+ end++ # One side down does not fail the import, so the caller never records it. The+ # endpoint that stopped answering would otherwise be invisible in+ # /settings/debug, while positions are quietly carried because of it.+ test "a side that went silent is recorded against the connection" do+ @provider.stubs(:get_simple_earn_flexible).returns({ "rows" => [] })+ @provider.stubs(:get_simple_earn_locked).raises(Provider::Binance::ApiError, "locked down")++ assert_difference "DebugLogEntry.count", 1 do+ BinanceItem::EarnImporter.new(@item, provider: @provider).import+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "binance", entry.provider_key+ assert_equal [ "locked" ], entry.metadata["unavailable_endpoints"]+ assert_equal "locked down", entry.metadata.dig("errors", "locked")+ end++ test "both sides answering records nothing" do+ @provider.stubs(:get_simple_earn_flexible).returns({ "rows" => [] })+ @provider.stubs(:get_simple_earn_locked).returns({ "rows" => [] })++ assert_no_difference "DebugLogEntry.count" do+ BinanceItem::EarnImporter.new(@item, provider: @provider).import+ end+ end++ private+ def seed_previous_earn(symbol:, free:, locked:)+ @item.binance_accounts.create!(+ name: "Binance", account_type: "combined", currency: "USD", current_balance: 0,+ raw_payload: { "assets" => [+ { "symbol" => symbol, "free" => free, "locked" => locked,+ "total" => (free.to_d + locked.to_d).to_s("F"), "source" => "earn" }+ ] }+ )+ endenddiff --git a/test/models/binance_item/importer_test.rb b/test/models/binance_item/importer_test.rbindex a38bf60a51..88c0b47fa7 100644--- a/test/models/binance_item/importer_test.rb+++ b/test/models/binance_item/importer_test.rb@@ -56,6 +56,98 @@ class BinanceItem::ImporterTest < ActiveSupport::TestCaseendend+ # Each sub-importer swallows its own error and answers with an empty asset+ # list, so a total outage reached the upsert looking exactly like an emptied+ # wallet. It reported success, left the previous payload in place, and the+ # holdings processor re-imported that payload as today's holdings — so an+ # asset already sold came back on every sync.+ test "a total outage is not an empty wallet" do+ stub_failed_result("spot")+ stub_failed_result("margin")+ stub_failed_result("earn")+ stub_failed_result("futures")++ assert_raises BinanceItem::Importer::AllRequestsFailed do+ BinanceItem::Importer.new(@item, binance_provider: @provider).import+ end+ end++ # A source that failed tells us nothing about what it holds. Writing only the+ # sources that answered would hand the holdings processor a list missing every+ # margin position, and it removes what is missing — so a transient error, or a+ # key without margin permission, would delete live positions.+ test "a source that failed keeps its last known assets" do+ stub_margin_result([ { symbol: "ETH", free: "2.0", locked: "0.0", total: "2.0" } ])+ BinanceItem::Importer.new(@item, binance_provider: @provider).import+ assert_equal [ "BTC", "ETH" ], payload_symbols.sort++ stub_failed_result("margin")+ BinanceItem::Importer.new(@item, binance_provider: @provider).import++ assert_equal [ "BTC", "ETH" ], payload_symbols.sort,+ "the unavailable source's positions were dropped"+ assert_equal "margin", payload_assets.find { |a| a["symbol"] == "ETH" }["source"]+ end++ # Carried only while the source is silent: once it answers again, what it says+ # is what stands, including an asset it no longer reports.+ test "a source that answers again overrides what was carried" do+ stub_margin_result([ { symbol: "ETH", free: "2.0", locked: "0.0", total: "2.0" } ])+ BinanceItem::Importer.new(@item, binance_provider: @provider).import++ stub_failed_result("margin")+ BinanceItem::Importer.new(@item, binance_provider: @provider).import+ assert_includes payload_symbols, "ETH"++ stub_margin_result([])+ BinanceItem::Importer.new(@item, binance_provider: @provider).import++ assert_equal [ "BTC" ], payload_symbols, "the carried asset outlived the source coming back"+ end++ # A partial failure returns normally, so it never reaches the rescue that logs+ # a failed import. Support would otherwise have no record that part of the+ # wallet went unread on a sync that reported success.+ test "a source that failed is recorded against the connection" do+ stub_failed_result("margin")++ assert_difference "DebugLogEntry.count", 1 do+ BinanceItem::Importer.new(@item, binance_provider: @provider).import+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "binance", entry.provider_key+ assert_equal [ "margin" ], entry.metadata["unavailable_sources"]+ assert_equal @family, entry.family+ end++ # One call still answering means the picture is trustworthy, even if it is+ # only part of one. Only a complete outage tells us nothing.+ test "a partial outage still records what did answer" do+ stub_failed_result("margin")+ stub_failed_result("earn")+ stub_failed_result("futures")++ BinanceItem::Importer.new(@item, binance_provider: @provider).import++ assert_equal [ "BTC" ], @item.binance_accounts.first.raw_payload["assets"].map { |a| a["symbol"] }+ end++ # The wallet an existing account was built from can legitimately empty out,+ # and that has to be written down: the holdings processor reads this payload,+ # so leaving the old one behind kept the sold assets alive indefinitely.+ test "emptying a wallet is recorded rather than skipped" do+ BinanceItem::Importer.new(@item, binance_provider: @provider).import+ assert_equal [ "BTC" ], @item.binance_accounts.first.raw_payload["assets"].map { |a| a["symbol"] }++ stub_spot_result([])+ BinanceItem::Importer.new(@item, binance_provider: @provider).import++ ba = @item.binance_accounts.first.reload+ assert_empty ba.raw_payload["assets"], "the emptied wallet kept its old asset list"+ assert_equal 0, ba.current_balance.to_d+ end+test "stores source breakdown in raw_payload" doBinanceItem::Importer.new(@item, binance_provider: @provider).import@@ -68,6 +160,22 @@ class BinanceItem::ImporterTest < ActiveSupport::TestCaseprivate+ def payload_assets+ @item.binance_accounts.first.reload.raw_payload["assets"]+ end++ def payload_symbols+ payload_assets.map { |a| a["symbol"] }.uniq+ end++ def stub_failed_result(source)+ klass = { "spot" => BinanceItem::SpotImporter, "margin" => BinanceItem::MarginImporter,+ "earn" => BinanceItem::EarnImporter, "futures" => BinanceItem::FuturesImporter }.fetch(source)+ klass.any_instance.stubs(:import).returns(+ { assets: [], raw: nil, source: source, error: "boom" }+ )+ end+def stub_spot_result(assets)BinanceItem::SpotImporter.any_instance.stubs(:import).returns({ assets: assets, raw: {}, source: "spot" }