The personal finance app for everyone (by everyone)
Ruby
Import Kraken Earn's allocated/locked balance, not just its payouts (#4651)
Avalanche Ridings1671a7f28f08
diff --git a/app/models/kraken_item/importer.rb b/app/models/kraken_item/importer.rbindex ec9d036a3f..d6f397dd9d 100644--- a/app/models/kraken_item/importer.rb+++ b/app/models/kraken_item/importer.rb@@ -5,6 +5,7 @@ class KrakenItem::ImporterTRADE_PAGE_SIZE = 50MAX_LEDGER_PAGES = 200LEDGER_PAGE_SIZE = 50+ MAX_EARN_PAGES = 50attr_reader :kraken_item, :kraken_provider@@ -20,6 +21,7 @@ class KrakenItem::Importerpair_metadata = kraken_provider.get_asset_pairs || {}balances = kraken_provider.get_extended_balance || {}assets = parse_assets(balances, asset_metadata)+ assets += fetch_and_parse_earn_assets(asset_metadata)trades = fetch_tradesledgers = fetch_ledgers@@ -84,6 +86,227 @@ class KrakenItem::Importerendend+ # Raised to mean "the Earn/Allocations response can't be trusted as a+ # complete snapshot" -- a fetch that failed outright (any page, including+ # a later cursor page after earlier ones succeeded) or a response whose+ # items don't all parse. Either way, #fetch_and_parse_earn_assets carries+ # forward the last known-good values instead of saving an undercount.+ EarnAllocationsUnavailable = Class.new(StandardError)++ # Earn's allocated principal (staking/bonding) lives in a sub-ledger+ # BalanceEx never reports -- see Provider::Kraken#get_earn_allocations.+ # Without this, only Earn's reward payouts (ordinary Ledgers entries,+ # handled in KrakenAccount::LedgerProcessor) were ever visible; the+ # locked balance itself was invisible to holdings.+ #+ # On any failure -- the fetch itself (permission denied, a transient API+ # error on any page) or one malformed item among otherwise-good ones --+ # carries forward the last successful sync's own "earn" assets rather+ # than saving a spot-only or undercounted snapshot. A source that failed+ # tells us nothing about what it holds, and writing only what did answer+ # would delete real principal from the account on a transient error; the+ # carried assets are stale until the next successful sync, which beats+ # gone. Same pattern as BinanceItem::Importer#carried_over_assets.+ def fetch_and_parse_earn_assets(asset_metadata)+ items = fetch_earn_allocations+ parse_earn_assets(items, asset_metadata)+ rescue Provider::Kraken::Error, EarnAllocationsUnavailable, Timeout::Error, SocketError,+ OpenSSL::SSL::SSLError, SystemCallError => e+ # Provider::Kraken::Error covers every classified Kraken error+ # (Permission/Api/RateLimit/Authentication/Nonce/OTPRequired) with one+ # rescue, rather than naming only the three this started with -- a+ # nonce collision or a transient "Invalid signature" on this one call+ # is exactly as recoverable as a rate limit, and none of them should+ # crash the whole sync (including trades/ledgers not yet fetched) over+ # an Earn-specific hiccup. The last four are raw transport failures+ # (HTTParty/Net::HTTP raise these before a response ever reaches+ # Provider::Kraken#handle_response, so they're never classified into a+ # Provider::Kraken::Error) -- same reasoning applies.+ record_earn_unavailable(e)+ carried_over_earn_assets+ end++ def parse_earn_assets(items, asset_metadata)+ normalizer = KrakenAccount::AssetNormalizer.new(asset_metadata)++ items.filter_map do |item|+ raw_asset = item["native_asset"] || item[:native_asset]+ raise "Earn allocation missing native_asset: #{item.inspect}" if raw_asset.blank?++ # Checked before to_d, not after: a missing field or a non-numeric+ # value (both blank? false and to_d 0 for the latter) must raise+ # here rather than silently read as "genuinely zero and filtered" --+ # that's a parse failure, not a real zero balance, and needs to go+ # through the rescue below into the carry-forward path instead of+ # quietly saving an undercounted snapshot.+ raw_balance = item.dig("amount_allocated", "total", "native")+ raise "Earn allocation missing amount_allocated.total.native: #{item.inspect}" if raw_balance.blank?+ # Matches what String#to_d actually parses (leading +, exponent+ # notation included) rather than only the plain decimal shape Kraken+ # happens to use today -- strict enough to still reject real garbage+ # like "N/A", which #to_d would otherwise silently coerce to 0 and+ # let through as "genuinely zero" below.+ unless raw_balance.to_s.match?(/\A[+-]?\d+(\.\d+)?([eE][+-]?\d+)?\z/)+ raise "Earn allocation has a non-numeric amount_allocated.total.native: #{raw_balance.inspect}"+ end++ balance = raw_balance.to_d+ next if balance.zero? # a genuine zero balance, not a parse failure++ parsed = normalizer.normalize(raw_asset)+ # Same canonicalization parse_assets uses: Earn/Allocations' own+ # documented examples show a bare native_asset ("ETH"), but if a+ # bonded/staked allocation is ever reported with a BalanceEx-style+ # wallet-variant suffix (e.g. "DOT28.S"), pricing the raw variant+ # instead of the underlying asset would price it as "missing" and+ # drop the holding entirely, same failure mode canonical_asset+ # already exists to prevent in parse_assets.+ price_usd, price_status = price_for(+ KrakenAccount::SecurityResolver.canonical_asset(parsed[:price_symbol])+ )+ amount_usd = price_usd ? (balance * price_usd).round(2) : 0.to_d++ parsed.merge(+ balance: balance.to_s("F"),+ available: "0", # bonded/pending in Earn, not spendable like a spot balance+ hold_trade: balance.to_s("F"),+ price_usd: price_usd&.to_s("F"),+ amount_usd: amount_usd.to_s("F"),+ price_status: price_status,+ source: "earn"+ )+ end+ rescue StandardError => e+ # One malformed item among otherwise-good ones used to be dropped+ # silently here, letting the importer save the remaining items as a+ # complete snapshot -- silently undercounting current_balance. Raising+ # instead routes it through #fetch_and_parse_earn_assets' carry-forward,+ # same as a fetch failure.+ raise EarnAllocationsUnavailable, "could not parse Earn allocation: #{e.message}"+ end++ def fetch_earn_allocations+ cursor = nil+ all_items_by_id = {}++ MAX_EARN_PAGES.times do+ raw_result = kraken_provider.get_earn_allocations(cursor: cursor)+ # Provider::Kraken#handle_response validates the outer envelope but+ # not the type of "result" itself -- a scalar has no #to_h at all,+ # and a non-pair Array raises TypeError from it, neither of which+ # the rescue below would catch, so this must be checked before #to_h+ # ever runs, not after.+ raise EarnAllocationsUnavailable, "Earn allocation result must be an object" unless raw_result.is_a?(Hash)+ result = raw_result.to_h+ items = result["items"]+ # `|| []` here used to treat a missing "items" key as "genuinely zero+ # Earn assets this sync" -- a malformed response read as a clean+ # empty snapshot, which saves over any previously-carried Earn+ # assets instead of raising into the carry-forward path. A non-Array+ # "items" (e.g. a Hash) would otherwise raise an uncaught TypeError+ # from #concat below, crashing the whole sync instead of degrading+ # gracefully like every other Earn failure here.+ raise EarnAllocationsUnavailable, "Earn allocation items must be an array" unless items.is_a?(Array)++ # Keyed by strategy_id (Kraken's "Unique ID for Earn Strategy" --+ # confirmed against Kraken's own API docs for Earn/Allocations), same+ # dedup #fetch_trades/#fetch_ledgers already do by their own ids.+ # Falls back to the item's own object_id (never equal across two+ # distinct items, even identical-content ones) when strategy_id is+ # missing, so an item lacking the field is never wrongly treated as+ # a duplicate of another one that also lacks it.+ duplicate_count = 0+ items.each do |item|+ key = item["strategy_id"] || item[:strategy_id] || item.object_id+ duplicate_count += 1 if all_items_by_id.key?(key)+ all_items_by_id[key] = item+ end+ if duplicate_count.positive?+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "#{duplicate_count} duplicate Earn allocation id(s) from Kraken ignored",+ source: self.class.name,+ provider_key: "kraken",+ family: kraken_item.family,+ metadata: { kraken_item_id: kraken_item.id }+ )+ end++ cursor = result["next_cursor"].presence+ break if cursor.blank?+ end++ all_items_by_id.values+ end++ # The prior sync's own "earn" assets, for #fetch_and_parse_earn_assets to+ # carry forward when this sync's Earn data can't be trusted. nil/blank+ # whenever there is nothing to fall back on (first sync, or a previous+ # sync that itself had no Earn holdings) -- filter_map above then simply+ # contributes nothing, same as Earn never having been reachable at all.+ def carried_over_earn_assets+ kraken_account = kraken_item.kraken_accounts.find_by(account_id: "combined")+ previous = kraken_account&.raw_payload&.dig("assets")+ return [] if previous.blank?++ carried = previous.map(&:deep_symbolize_keys).select { |asset| asset[:source] == "earn" }++ if carried.any?+ # A carry-forward is exactly the "suspicious partial response" the+ # support-diagnostics convention (docs/llm-guides/providers.md) means+ # by this: record_earn_unavailable above already captures the+ # failure that triggered it, but this is a second, distinct event+ # (how many assets, carried forward or not) that was only ever in+ # Rails.logger -- invisible in /settings/debug.+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "Carrying #{carried.size} Earn asset(s) forward from the last successful sync",+ source: self.class.name,+ provider_key: "kraken",+ family: kraken_item.family,+ account_provider: kraken_account&.account_provider,+ metadata: { kraken_item_id: kraken_item.id }+ )+ end++ carried.map { |asset| reprice_carried_asset(asset) }+ end++ # A carried asset's balance is still real, but its price_usd/amount_usd+ # are frozen at whatever they were the last time Earn actually answered+ # -- every spot asset this sync gets a current price, so that staleness+ # would only compound for as long as Earn keeps failing. Re-fetches a+ # current price for the same price_symbol and recomputes amount_usd from+ # the unchanged balance; when no current price is available, leaves the+ # asset exactly as carried rather than guessing.+ def reprice_carried_asset(asset)+ price_usd, price_status = price_for(+ KrakenAccount::SecurityResolver.canonical_asset(asset[:price_symbol])+ )+ return asset unless price_usd++ balance = asset[:balance].to_d+ asset.merge(+ price_usd: price_usd.to_s("F"),+ amount_usd: (balance * price_usd).round(2).to_s("F"),+ price_status: price_status+ )+ end++ def record_earn_unavailable(error)+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "Earn allocations unavailable this sync (#{error.class.name.demodulize}); carrying forward last known values: #{error.message}",+ source: self.class.name,+ provider_key: "kraken",+ family: kraken_item.family,+ metadata: { kraken_item_id: kraken_item.id }+ )+ end+def price_for(symbol)return [ 1.to_d, "exact" ] if symbol == "USD" || KrakenAccount::STABLECOINS.include?(symbol)diff --git a/app/models/provider/kraken.rb b/app/models/provider/kraken.rbindex 30ef5c1d73..076cbab044 100644--- a/app/models/provider/kraken.rb+++ b/app/models/provider/kraken.rb@@ -68,6 +68,19 @@ class Provider::Krakenprivate_post("Ledgers", params)end+ # Funds bonded/pending in Kraken's Earn program (staking, etc.) live in a+ # separate sub-ledger from the regular spot wallet BalanceEx reads --+ # confirmed against Kraken's own API docs for Earn/Allocations: these+ # amounts are not part of any Balance/BalanceEx response. Without this,+ # only Earn's reward payouts (ordinary Ledgers entries) are ever seen; the+ # allocated principal itself is invisible. cursor/next_cursor paginate.+ def get_earn_allocations(cursor: nil)+ params = { "hide_zero_allocations" => "true" }+ params["cursor"] = cursor if cursor.present?++ private_post("Earn/Allocations", params)+ end+def get_asset_info(asset: nil)params = {}params["asset"] = asset if asset.present?diff --git a/test/models/kraken_item/importer_test.rb b/test/models/kraken_item/importer_test.rbindex 65c69b9418..f476f6a30d 100644--- a/test/models/kraken_item/importer_test.rb+++ b/test/models/kraken_item/importer_test.rb@@ -17,6 +17,7 @@ class KrakenItem::ImporterTest < ActiveSupport::TestCase@provider.stubs(:get_trades_history).returns({ "count" => 0, "trades" => {} })@provider.stubs(:get_ledgers).returns({ "ledger" => {}, "count" => 0 })@provider.stubs(:get_ticker).returns(nil)+ @provider.stubs(:get_earn_allocations).returns({ "items" => [] })endtest "creates a combined kraken account from BalanceEx" do@@ -42,6 +43,445 @@ class KrakenItem::ImporterTest < ActiveSupport::TestCaseassert_equal "0.25", btc["hold_trade"]end+ test "merges Earn allocated balances alongside spot assets" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ # Includes a spot XXBT holding of the *same* asset Earn reports, so this+ # actually exercises what the importer's own comment promises: Earn+ # assets are tagged source: "earn" so they land as a separate holding+ # rather than colliding with a spot balance of the same asset.+ @provider.stubs(:get_extended_balance).returns(+ "XXBT" => { "balance" => "1.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" },+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ {+ "native_asset" => "XXBT",+ "amount_allocated" => { "total" => { "native" => "2.0", "converted" => "100000.0" } }+ }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })++ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ account = @item.kraken_accounts.first+ spot_btc = account.raw_payload["assets"].find { |asset| asset["symbol"] == "BTC" && asset["source"] == "spot" }+ earn_btc = account.raw_payload["assets"].find { |asset| asset["symbol"] == "BTC" && asset["source"] == "earn" }+ assert_not_nil spot_btc, "the spot BTC holding must survive alongside the Earn one, not be overwritten by it"+ assert_equal "1.0", spot_btc["balance"]+ assert_not_nil earn_btc+ assert_equal "2.0", earn_btc["balance"]+ assert_equal "0", earn_btc["available"]+ assert_in_delta 100_000, earn_btc["amount_usd"].to_f, 0.01+ # 1.0 BTC spot + 2.0 BTC Earn, both @ $50,000, plus $50 cash.+ assert_in_delta 150_050, account.current_balance, 0.01+ end++ test "degrades gracefully when Earn Allocations permission is denied" do+ @provider.stubs(:get_asset_info).returns({})+ @provider.stubs(:get_extended_balance).returns({})+ @provider.stubs(:get_earn_allocations).raises(Provider::Kraken::PermissionError, "EGeneral:Permission denied")++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]+ end++ test "degrades gracefully when Earn Allocations is rate limited" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ # RateLimitError is a sibling of ApiError (both < Provider::Kraken::Error),+ # not a subclass, so it must be rescued explicitly here or it propagates+ # out of #import and aborts the whole sync -- including the spot balance+ # that already succeeded -- over a transient, Earn-specific rate limit.+ @provider.stubs(:get_earn_allocations).raises(Provider::Kraken::RateLimitError, "Rate limit exceeded")++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ account = @item.kraken_accounts.first+ assert_in_delta 50.0, account.current_balance, 0.01+ end++ test "degrades gracefully when Earn Allocations times out at the transport level" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ # HTTParty/Net::HTTP raise this before a response ever reaches+ # Provider::Kraken#handle_response, so it's never classified into a+ # Provider::Kraken::Error -- it has to be rescued explicitly here too,+ # same reasoning as RateLimitError above, or a dropped connection on+ # this one call aborts the whole sync.+ @provider.stubs(:get_earn_allocations).raises(Timeout::Error, "execution expired")++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ account = @item.kraken_accounts.first+ assert_in_delta 50.0, account.current_balance, 0.01+ end++ test "carries forward last known Earn assets when the result is not an object" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ # A scalar result has no #to_h at all (NoMethodError); calling #to_h on+ # it must never be reached before this is checked.+ @provider.stubs(:get_earn_allocations).returns("unexpected scalar result")++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ earn_assets = @item.kraken_accounts.first.raw_payload["assets"].select { |asset| asset["source"] == "earn" }+ assert_equal 1, earn_assets.size, "expected the carried-forward snapshot, not a crash"+ assert_equal "BTC", earn_assets.first["symbol"]+ end++ test "carries forward last known Earn assets when a later sync's fetch fails" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ # A transient failure on the next sync -- even one that only shows up on a+ # later cursor page -- must not erase the principal a previous successful+ # sync already saw.+ @provider.stubs(:get_earn_allocations).raises(Provider::Kraken::ApiError, "EGeneral:Internal error")++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ account = @item.kraken_accounts.first+ earn_btc = account.raw_payload["assets"].find { |asset| asset["symbol"] == "BTC" && asset["source"] == "earn" }+ assert_not_nil earn_btc, "expected the previously-seen Earn BTC position to be carried forward"+ assert_equal "2.0", earn_btc["balance"]+ end++ test "reprices a carried-forward Earn asset with a current price instead of the stale one" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ # Earn fails on this sync and must carry the 2.0 BTC balance forward, but+ # BTC's price moved since the last successful Earn sync -- every spot+ # asset gets a current price every sync, so the carried Earn asset must+ # not be the one stale figure left behind.+ @provider.stubs(:get_earn_allocations).raises(Provider::Kraken::ApiError, "EGeneral:Internal error")+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "60000.00" ] })++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ account = @item.kraken_accounts.first+ earn_btc = account.raw_payload["assets"].find { |asset| asset["symbol"] == "BTC" && asset["source"] == "earn" }+ assert_equal "2.0", earn_btc["balance"], "the carried balance itself must be unchanged"+ assert_in_delta 60000.0, earn_btc["price_usd"].to_f, 0.01+ assert_in_delta 120000.0, earn_btc["amount_usd"].to_f, 0.01+ assert_in_delta 120050.0, account.current_balance, 0.01+ end++ test "leaves a carried Earn asset unchanged when no current price is available" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ # Earn fails again, and this time no ticker price is available either+ # (the blanket get_ticker stub from setup returns nil for every pair+ # candidate) -- the carried asset must keep its last known price rather+ # than guessing or zeroing it out.+ @provider.stubs(:get_earn_allocations).raises(Provider::Kraken::ApiError, "EGeneral:Internal error")++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ account = @item.kraken_accounts.first+ earn_btc = account.raw_payload["assets"].find { |asset| asset["symbol"] == "BTC" && asset["source"] == "earn" }+ assert_in_delta 50000.0, earn_btc["price_usd"].to_f, 0.01+ assert_in_delta 100000.0, earn_btc["amount_usd"].to_f, 0.01+ end++ test "carries forward last known Earn assets rather than saving an undercount when one item is malformed" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ # The next sync returns one good item and one with an unexpected shape+ # (amount_allocated is a bare string, not the nested hash #dig expects --+ # confirmed to raise TypeError, not just return nil) -- this must not be+ # saved as a complete-but-undercounted snapshot that silently drops BTC.+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XETH", "amount_allocated" => "unexpected-string-shape" },+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ account = @item.kraken_accounts.first+ earn_assets = account.raw_payload["assets"].select { |asset| asset["source"] == "earn" }+ assert_equal 1, earn_assets.size, "expected the carried-forward snapshot, not a partial new one"+ assert_equal "BTC", earn_assets.first["symbol"]+ end++ test "degrades gracefully when Earn Allocations hits a nonce error, not just permission/API/rate-limit" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ # AuthenticationError/NonceError/OTPRequiredError are siblings of+ # ApiError/PermissionError/RateLimitError under Provider::Kraken::Error,+ # not subclasses of any of those three -- rescuing Provider::Kraken::Error+ # itself is what actually covers all of them in one place.+ @provider.stubs(:get_earn_allocations).raises(Provider::Kraken::NonceError, "EAPI:Invalid nonce")++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ account = @item.kraken_accounts.first+ assert_in_delta 50.0, account.current_balance, 0.01+ end++ test "deduplicates Earn allocations repeated across pages by strategy_id" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ btc_allocation = { "strategy_id" => "ESDQCOL-WTZEU-NU55QF", "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ @provider.expects(:get_earn_allocations).with(cursor: nil).returns(+ "items" => [ btc_allocation ], "next_cursor" => "page2"+ )+ @provider.expects(:get_earn_allocations).with(cursor: "page2").returns(+ "items" => [ btc_allocation ] # same strategy_id repeated on a shifted cursor window+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ account = @item.kraken_accounts.first+ earn_assets = account.raw_payload["assets"].select { |asset| asset["source"] == "earn" }+ assert_equal 1, earn_assets.size, "a repeated allocation must not be double-counted into two holdings"+ assert_in_delta 100_000, earn_assets.first["amount_usd"].to_f, 0.01+ end++ test "logs a carry-forward via DebugLogEntry, not only Rails.logger" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ @provider.stubs(:get_earn_allocations).raises(Provider::Kraken::ApiError, "EGeneral:Internal error")++ assert_difference -> { DebugLogEntry.count }, 2 do # record_earn_unavailable + the carry-forward itself+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ end++ carry_forward_entry = DebugLogEntry.where("message LIKE ?", "Carrying%").last+ assert_not_nil carry_forward_entry, "the carry-forward itself must be visible in /settings/debug, not only Rails.logger"+ assert_equal "provider_sync_error", carry_forward_entry.category+ end++ test "treats a signed or exponent-notation Earn balance as numeric, not garbage" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ # A leading "+" is valid input to String#to_d (so is exponent notation,+ # e.g. "1e-08"); the stricter plain-decimal-only regex this replaced+ # would have rejected this as "non-numeric" and routed it into the+ # carry-forward path despite being a real balance.+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "+2.0" } } } ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ earn_btc = @item.kraken_accounts.first.raw_payload["assets"].find { |asset| asset["source"] == "earn" }+ assert_not_nil earn_btc+ assert_in_delta 100_000, earn_btc["amount_usd"].to_f, 0.01+ end++ test "prices a suffixed Earn allocation as its underlying asset" do+ @provider.stubs(:get_asset_info).returns("DOT28.S" => { "altname" => "DOT28.S" })+ @provider.stubs(:get_extended_balance).returns({})+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [ { "native_asset" => "DOT28.S", "amount_allocated" => { "total" => { "native" => "10.0" } } } ]+ )+ @provider.stubs(:get_ticker).with("DOTUSD").returns("DOTUSD" => { "c" => [ "4.00" ] })++ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ earn_dot = @item.kraken_accounts.first.raw_payload["assets"].find { |asset| asset["source"] == "earn" }+ assert_not_nil earn_dot+ assert_equal "exact", earn_dot["price_status"]+ assert_in_delta 4.0, earn_dot["price_usd"].to_d, 0.001+ assert_in_delta 40.0, earn_dot["amount_usd"].to_d, 0.01+ end++ test "carries forward last known Earn assets when an item is missing native_asset" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ # A missing native_asset used to be dropped via `next` -- normal control+ # flow, not an exception -- so it never reached the carry-forward rescue+ # and silently saved a spot-only snapshot instead.+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [ { "amount_allocated" => { "total" => { "native" => "2.0" } } } ]+ )++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ earn_assets = @item.kraken_accounts.first.raw_payload["assets"].select { |asset| asset["source"] == "earn" }+ assert_equal 1, earn_assets.size, "expected the carried-forward snapshot, not a spot-only one"+ assert_equal "BTC", earn_assets.first["symbol"]+ end++ test "carries forward last known Earn assets when amount_allocated.total.native is non-numeric" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ # "N/A" is not blank, so it used to reach #to_d, which silently coerces+ # non-numeric strings to 0 -- read as a genuine zero balance and+ # filtered out via `next`, the same silent-drop bug as a missing field.+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "N/A" } } } ]+ )++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ earn_assets = @item.kraken_accounts.first.raw_payload["assets"].select { |asset| asset["source"] == "earn" }+ assert_equal 1, earn_assets.size, "expected the carried-forward snapshot, not a spot-only one"+ assert_equal "BTC", earn_assets.first["symbol"]+ end++ test "carries forward last known Earn assets when the response is missing items" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ # A response with no "items" key used to be read via `|| []` as "zero+ # Earn assets this sync" -- a clean, successful-looking empty snapshot+ # that saved over the previously-carried Earn principal instead of+ # raising into the carry-forward path.+ @provider.stubs(:get_earn_allocations).returns({})++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ earn_assets = @item.kraken_accounts.first.raw_payload["assets"].select { |asset| asset["source"] == "earn" }+ assert_equal 1, earn_assets.size, "expected the carried-forward snapshot, not an empty one"+ assert_equal "BTC", earn_assets.first["symbol"]+ end++ test "carries forward last known Earn assets when items is not an array" do+ @provider.stubs(:get_asset_info).returns(asset_metadata)+ @provider.stubs(:get_extended_balance).returns(+ "ZUSD" => { "balance" => "50.0", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }+ )+ @provider.stubs(:get_earn_allocations).returns(+ "items" => [+ { "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } }+ ]+ )+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import++ # "items" as a Hash instead of an Array used to raise an uncaught+ # TypeError from Array#concat, crashing the whole sync -- including the+ # spot balance that had already succeeded -- instead of degrading+ # gracefully like every other Earn-specific failure.+ @provider.stubs(:get_earn_allocations).returns("items" => { "unexpected" => "shape" })++ result = KrakenItem::Importer.new(@item, kraken_provider: @provider).import+ assert result[:success]++ earn_assets = @item.kraken_accounts.first.raw_payload["assets"].select { |asset| asset["source"] == "earn" }+ assert_equal 1, earn_assets.size, "expected the carried-forward snapshot, not a crash"+ assert_equal "BTC", earn_assets.first["symbol"]+ end+test "preserves suffix assets in metadata and marks missing prices" do@provider.stubs(:get_asset_info).returns(asset_metadata)@provider.stubs(:get_extended_balance).returns(diff --git a/test/models/provider/kraken_test.rb b/test/models/provider/kraken_test.rbindex 0ad79c7feb..4f51ce7855 100644--- a/test/models/provider/kraken_test.rb+++ b/test/models/provider/kraken_test.rb@@ -93,6 +93,39 @@ class Provider::KrakenTest < ActiveSupport::TestCase@provider.get_ledgers(start: Time.zone.at(1609459200), type: "deposit", offset: 50)end+ test "get_earn_allocations sends request to Earn/Allocations endpoint" do+ earn_payload = {+ "converted_asset" => "USD",+ "total_allocated" => "100.0",+ "total_rewarded" => "1.0",+ "items" => [+ {+ "native_asset" => "DOT",+ "amount_allocated" => { "total" => { "native" => "10.0", "converted" => "100.0" } },+ "amount_earned" => { "total" => { "native" => "0.1", "converted" => "1.0" } }+ }+ ]+ }+ response = mock_httparty_response(200, { "error" => [], "result" => earn_payload })++ Provider::Kraken.expects(:post)+ .with("/0/private/Earn/Allocations", has_entries(body: includes("hide_zero_allocations=true")))+ .returns(response)++ result = @provider.get_earn_allocations+ assert_equal earn_payload, result+ end++ test "get_earn_allocations forwards cursor param" do+ response = mock_httparty_response(200, { "error" => [], "result" => { "items" => [] } })++ Provider::Kraken.expects(:post)+ .with("/0/private/Earn/Allocations", has_entries(body: includes("cursor=abc123")))+ .returns(response)++ @provider.get_earn_allocations(cursor: "abc123")+ end+test "handle response returns result on success" doresponse = mock_httparty_response(200, { "error" => [], "result" => { "XXBT" => { "balance" => "1.0" } } })