The personal finance app for everyone (by everyone)
Ruby
fix: preserve CoinStats balances when wallet sync data is missing (#2132)
Sure Admin (bot)08bfd4377589
diff --git a/AGENTS.md b/AGENTS.mdindex c5359f025e..399375924e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -63,6 +63,15 @@ Reviewers escalate violations of (2)–(3) to close/rewrite; (1) and (4) are reqIf you need to add a new securities price provider (Tiingo, EODHD, Binance-style crypto, etc.), see [adding-a-securities-provider.md](./docs/llm-guides/adding-a-securities-provider.md) for the full walkthrough — provider class, registry wiring, MIC handling, settings UI, locales, and tests.+## Debug Logging for Provider Syncs++When a provider sync/import path hits a recoverable error or suspicious partial response that support may need to inspect later, prefer `DebugLogEntry.capture(...)` over `Rails.logger.*`.++- Record support-relevant diagnostics in the debug log so they surface in the super-admin-friendly `/settings/debug` UI.+- Include `category`, `level`, `message`, `source`, `provider_key`, and useful structured `metadata`.+- Attach `family` and `account_provider` when available so support can filter and trace the affected connection.+- Reserve raw Rails logging for low-value local noise; anything operators may need should go to the debug log.+## Providers: Pending Transactions and FX Metadata (SimpleFIN/Plaid/Lunchflow)- Pending detectiondiff --git a/CLAUDE.md b/CLAUDE.mdindex 4fc9fcf107..5464699de3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -132,6 +132,12 @@ Sidekiq handles asynchronous tasks:- AI chat responses (`AssistantResponseJob`)- Scheduled maintenance via sidekiq-cron+### Debug Logging for Provider Syncs+- Prefer `DebugLogEntry.capture(...)` over `Rails.logger.*` for provider sync/import failures, partial responses, and other support-relevant diagnostics.+- Record support-relevant incidents in the super-admin `/settings/debug` UI rather than leaving them only in raw application logs.+- Include `category`, `level`, `message`, `source`, `provider_key`, and structured `metadata`.+- Attach `family` and `account_provider` whenever possible so support can filter to the affected provider connection.+### Frontend Architecture- **Hotwire Stack**: Turbo + Stimulus for reactive UI without heavy JavaScript- **ViewComponents**: Reusable UI components in `app/components/`diff --git a/app/models/coinstats_item/importer.rb b/app/models/coinstats_item/importer.rbindex 8c2075daff..2a5f77b32d 100644--- a/app/models/coinstats_item/importer.rb+++ b/app/models/coinstats_item/importer.rb@@ -149,8 +149,17 @@ class CoinstatsItem::Importerresponse = coinstats_provider.get_wallet_balances(wallets_param)response.success? ? response.data : FETCH_FAILEDrescue => e- Rails.logger.warn "CoinstatsItem::Importer - Bulk balance fetch failed: #{e.message}"- FETCH_FAILED+ log_debug_event(+ level: "warn",+ message: "CoinStats bulk balance fetch failed",+ metadata: {+ coinstats_item_id: coinstats_item.id,+ wallets: wallets.map { |wallet| "#{wallet[:blockchain]}:#{wallet[:address]}" },+ error_class: e.class.name,+ error_message: e.message+ }+ )+ nilenddef fetch_portfolio_coins_for_exchange(linked_accounts)@@ -244,15 +253,38 @@ class CoinstatsItem::Importerreturn { success: false, error: "Missing address or blockchain" }end- # Extract balance data for this specific wallet from the bulk response- balance_data = if bulk_balance_data.present?- coinstats_provider.extract_wallet_balance(bulk_balance_data, address, blockchain)+ if bulk_balance_data.nil?+ log_debug_event(+ level: "warn",+ message: "CoinStats wallet balance sync preserved existing snapshot after bulk fetch failure",+ account_provider: coinstats_account.account_provider,+ metadata: {+ coinstats_item_id: coinstats_item.id,+ coinstats_account_id: coinstats_account.id,+ wallet_address: address,+ blockchain: blockchain,+ reason: "bulk_balance_data_missing"+ }+ )+ elsif wallet_missing_from_bulk_balance_data?(bulk_balance_data, address, blockchain)+ log_debug_event(+ level: "warn",+ message: "CoinStats wallet balance sync preserved existing snapshot because wallet was missing from bulk response",+ account_provider: coinstats_account.account_provider,+ metadata: {+ coinstats_item_id: coinstats_item.id,+ coinstats_account_id: coinstats_account.id,+ wallet_address: address,+ blockchain: blockchain,+ reason: "wallet_missing_from_bulk_response"+ }+ )else- []- end+ balance_data = coinstats_provider.extract_wallet_balance(bulk_balance_data, address, blockchain)- # Update the coinstats account with new balance data- coinstats_account.upsert_coinstats_snapshot!(normalize_balance_data(balance_data, coinstats_account))+ # Update the coinstats account with new balance data+ coinstats_account.upsert_coinstats_snapshot!(normalize_balance_data(balance_data, coinstats_account))+ end# Extract and merge transactions from bulk responsetransactions_count = fetch_and_merge_transactions(coinstats_account, address, blockchain, bulk_transactions_data)@@ -260,6 +292,30 @@ class CoinstatsItem::Importer{ success: true, transactions_count: transactions_count }end+ def wallet_missing_from_bulk_balance_data?(bulk_balance_data, address, blockchain)+ return true unless bulk_balance_data.is_a?(Array)++ bulk_balance_data.none? do |entry|+ entry = entry.with_indifferent_access+ entry[:address]&.downcase == address&.downcase &&+ (entry[:connectionId]&.downcase == blockchain&.downcase ||+ entry[:blockchain]&.downcase == blockchain&.downcase)+ end+ end++ def log_debug_event(level:, message:, metadata:, account_provider: nil)+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: level,+ message: message,+ source: self.class.name,+ provider_key: "coinstats",+ family: coinstats_item.family,+ account_provider: account_provider,+ metadata: metadata+ )+ end+def update_exchange_account(coinstats_account, portfolio_coins_data:, portfolio_transactions_data:)portfolio_id = exchange_portfolio_id_for(coinstats_account)balance_data = portfolio_coins_data[portfolio_id]diff --git a/test/models/coinstats_item/importer_test.rb b/test/models/coinstats_item/importer_test.rbindex 823a84945e..a07a7526e2 100644--- a/test/models/coinstats_item/importer_test.rb+++ b/test/models/coinstats_item/importer_test.rb@@ -465,10 +465,6 @@ class CoinstatsItem::ImporterTest < ActiveSupport::TestCase.with(bulk_response, "0xworking", "ethereum").returns([ { coinId: "ethereum", name: "Ethereum", amount: 1.0, price: 2000 } ])- @mock_provider.expects(:extract_wallet_balance)- .with(bulk_response, "0xfailing", "ethereum")- .returns([]) # Empty array for missing wallet-bulk_transactions_response = [{blockchain: "ethereum",@@ -498,6 +494,194 @@ class CoinstatsItem::ImporterTest < ActiveSupport::TestCaseassert_equal 0, result[:accounts_failed]end+ test "multi-wallet import preserves an existing wallet when bulk response omits it" do+ crypto1 = Crypto.create!+ account1 = @family.accounts.create!(+ accountable: crypto1,+ name: "Working Wallet",+ balance: 2000,+ currency: "USD"+ )+ coinstats_account1 = @coinstats_item.coinstats_accounts.create!(+ name: "Working Wallet",+ currency: "USD",+ current_balance: 2000,+ account_id: "ethereum",+ raw_payload: {+ address: "0xworking",+ blockchain: "ethereum",+ coinId: "ethereum",+ amount: 1.0,+ price: 2000,+ balance: 2000+ }+ )+ AccountProvider.create!(account: account1, provider: coinstats_account1)++ crypto2 = Crypto.create!+ account2 = @family.accounts.create!(+ accountable: crypto2,+ name: "DOGE Wallet",+ balance: 100,+ currency: "USD"+ )+ coinstats_account2 = @coinstats_item.coinstats_accounts.create!(+ name: "DOGE Wallet",+ currency: "USD",+ current_balance: 100,+ account_id: "dogecoin",+ raw_payload: {+ address: "Ddoge123",+ blockchain: "dogecoin",+ coinId: "dogecoin",+ amount: 1000,+ price: 0.1,+ balance: 100+ }+ )+ AccountProvider.create!(account: account2, provider: coinstats_account2)++ bulk_response = [+ {+ blockchain: "dogecoin",+ address: "Ddoge123",+ connectionId: "dogecoin",+ balances: [ { coinId: "dogecoin", name: "Dogecoin", amount: 1000, price: 0.1 } ]+ }+ ]++ @mock_provider.expects(:get_wallet_balances)+ .with("ethereum:0xworking,dogecoin:Ddoge123")+ .returns(success_response(bulk_response))++ @mock_provider.expects(:extract_wallet_balance)+ .with(bulk_response, "Ddoge123", "dogecoin")+ .returns([ { coinId: "dogecoin", name: "Dogecoin", amount: 1000, price: 0.1 } ])++ bulk_transactions_response = [+ {+ blockchain: "dogecoin",+ address: "Ddoge123",+ connectionId: "dogecoin",+ transactions: []+ }+ ]++ @mock_provider.expects(:get_wallet_transactions)+ .with("ethereum:0xworking,dogecoin:Ddoge123")+ .returns(success_response(bulk_transactions_response))++ @mock_provider.expects(:extract_wallet_transactions)+ .with(bulk_transactions_response, "0xworking", "ethereum")+ .returns([])++ @mock_provider.expects(:extract_wallet_transactions)+ .with(bulk_transactions_response, "Ddoge123", "dogecoin")+ .returns([])++ assert_difference "DebugLogEntry.count", 1 do+ result = CoinstatsItem::Importer.new(@coinstats_item, coinstats_provider: @mock_provider).import++ assert result[:success]+ end++ coinstats_account1.reload+ coinstats_account2.reload++ assert_equal 2000.0, coinstats_account1.current_balance.to_f, "missing wallet data should not zero an existing wallet"+ assert_equal 100.0, coinstats_account2.current_balance.to_f++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "provider_sync_error", entry.category+ assert_equal "warn", entry.level+ assert_equal "CoinStats wallet balance sync preserved existing snapshot because wallet was missing from bulk response", entry.message+ assert_equal "coinstats", entry.provider_key+ assert_equal @family.id, entry.family_id+ assert_equal coinstats_account1.account_provider.id, entry.account_provider_id+ assert_equal "wallet_missing_from_bulk_response", entry.metadata["reason"]+ assert_equal "0xworking", entry.metadata["wallet_address"]+ end++ test "bulk balance fetch failure preserves all existing wallet balances during import" do+ crypto1 = Crypto.create!+ account1 = @family.accounts.create!(+ accountable: crypto1,+ name: "Ethereum Wallet",+ balance: 2000,+ currency: "USD"+ )+ coinstats_account1 = @coinstats_item.coinstats_accounts.create!(+ name: "Ethereum Wallet",+ currency: "USD",+ current_balance: 2000,+ account_id: "ethereum",+ raw_payload: {+ address: "0xeth123",+ blockchain: "ethereum",+ coinId: "ethereum",+ amount: 1.0,+ price: 2000,+ balance: 2000+ }+ )+ AccountProvider.create!(account: account1, provider: coinstats_account1)++ crypto2 = Crypto.create!+ account2 = @family.accounts.create!(+ accountable: crypto2,+ name: "DOGE Wallet",+ balance: 100,+ currency: "USD"+ )+ coinstats_account2 = @coinstats_item.coinstats_accounts.create!(+ name: "DOGE Wallet",+ currency: "USD",+ current_balance: 100,+ account_id: "dogecoin",+ raw_payload: {+ address: "Ddoge456",+ blockchain: "dogecoin",+ coinId: "dogecoin",+ amount: 1000,+ price: 0.1,+ balance: 100+ }+ )+ AccountProvider.create!(account: account2, provider: coinstats_account2)++ @mock_provider.expects(:get_wallet_balances)+ .with("ethereum:0xeth123,dogecoin:Ddoge456")+ .raises(Provider::Coinstats::Error.new("CoinStats timeout"))++ bulk_transactions_response = []+ @mock_provider.expects(:get_wallet_transactions)+ .with("ethereum:0xeth123,dogecoin:Ddoge456")+ .returns(success_response(bulk_transactions_response))++ assert_difference "DebugLogEntry.count", 3 do+ result = CoinstatsItem::Importer.new(@coinstats_item, coinstats_provider: @mock_provider).import++ assert result[:success]+ end++ coinstats_account1.reload+ coinstats_account2.reload++ assert_equal 2000.0, coinstats_account1.current_balance.to_f+ assert_equal 100.0, coinstats_account2.current_balance.to_f++ entries = DebugLogEntry.order(:created_at).last(3)+ fetch_failure_entry = entries.find { |entry| entry.message == "CoinStats bulk balance fetch failed" }+ assert_not_nil fetch_failure_entry+ assert_equal "provider_sync_error", fetch_failure_entry.category+ assert_equal "coinstats", fetch_failure_entry.provider_key+ assert_equal "CoinStats timeout", fetch_failure_entry.metadata["error_message"]++ preserved_entries = entries.select { |entry| entry.message == "CoinStats wallet balance sync preserved existing snapshot after bulk fetch failure" }+ assert_equal 2, preserved_entries.size+ assert_equal [ "0xeth123", "Ddoge456" ], preserved_entries.map { |entry| entry.metadata["wallet_address"] }.sort+ end+test "uses bulk endpoint for multiple unique wallets and falls back on error" do# Create accounts with two different wallet addressescrypto1 = Crypto.create!