Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(kraken): only add Earn allocations that BalanceEx doesn't already hold (#4941)

Rudolf Tammekivic9cc6d24c7aa
diff --git a/app/models/kraken_item/importer.rb b/app/models/kraken_item/importer.rb
index d6f397dd9d..9d53563b68 100644
--- a/app/models/kraken_item/importer.rb
+++ b/app/models/kraken_item/importer.rb
@@ -93,11 +93,9 @@ class KrakenItem::Importer
# 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.
+ # Only allocations outside Earn/Strategies (hybrid Earn, e.g. the Bitcoin
+ # vault) are missing from BalanceEx; the rest are already counted there
+ # as ETH.B, auto-earn spot, etc. -- see Provider::Kraken#get_earn_allocations.
#
# On any failure -- the fetch itself (permission denied, a transient API
# error on any page) or one malformed item among otherwise-good ones --
@@ -109,7 +107,10 @@ class KrakenItem::Importer
# 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)
+ return [] if items.empty?
+
+ listed = fetch_earn_strategy_ids
+ parse_earn_assets(items.reject { |item| listed.include?(item["strategy_id"]) }, asset_metadata)
rescue Provider::Kraken::Error, EarnAllocationsUnavailable, Timeout::Error, SocketError,
OpenSSL::SSL::SSLError, SystemCallError => e
# Provider::Kraken::Error covers every classified Kraken error
@@ -185,6 +186,32 @@ class KrakenItem::Importer
raise EarnAllocationsUnavailable, "could not parse Earn allocation: #{e.message}"
end
+ def fetch_earn_strategy_ids
+ cursor = nil
+ ids = Set.new
+ seen_cursors = Set.new
+
+ MAX_EARN_PAGES.times do
+ result = kraken_provider.get_earn_strategies(cursor: cursor)
+ items = result.is_a?(Hash) ? result["items"] : nil
+ raise EarnAllocationsUnavailable, "Earn strategy items must be an array" unless items.is_a?(Array)
+
+ items.each do |item|
+ id = item["id"] if item.is_a?(Hash)
+ raise EarnAllocationsUnavailable, "Earn strategy missing id: #{item.inspect}" if id.blank?
+
+ ids << id
+ end
+ cursor = result["next_cursor"].presence
+ break if cursor.blank?
+ raise EarnAllocationsUnavailable, "Earn strategy cursor repeated" unless seen_cursors.add?(cursor)
+ end
+
+ raise EarnAllocationsUnavailable, "Earn strategy pagination incomplete" if cursor.present?
+
+ ids
+ end
+
def fetch_earn_allocations
cursor = nil
all_items_by_id = {}
diff --git a/app/models/provider/kraken.rb b/app/models/provider/kraken.rb
index 076cbab044..c7a4a77d03 100644
--- a/app/models/provider/kraken.rb
+++ b/app/models/provider/kraken.rb
@@ -68,12 +68,9 @@ class Provider::Kraken
private_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.
+ # Allocations to strategies listed by Earn/Strategies (bonded, flex,
+ # auto-earn) are already in BalanceEx; hybrid Earn such as the Bitcoin
+ # vault is not. cursor/next_cursor paginate.
def get_earn_allocations(cursor: nil)
params = { "hide_zero_allocations" => "true" }
params["cursor"] = cursor if cursor.present?
@@ -81,6 +78,13 @@ class Provider::Kraken
private_post("Earn/Allocations", params)
end
+ def get_earn_strategies(cursor: nil)
+ params = {}
+ params["cursor"] = cursor if cursor.present?
+
+ private_post("Earn/Strategies", 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.rb
index f476f6a30d..a738429401 100644
--- a/test/models/kraken_item/importer_test.rb
+++ b/test/models/kraken_item/importer_test.rb
@@ -18,6 +18,7 @@ class KrakenItem::ImporterTest < ActiveSupport::TestCase
@provider.stubs(:get_ledgers).returns({ "ledger" => {}, "count" => 0 })
@provider.stubs(:get_ticker).returns(nil)
@provider.stubs(:get_earn_allocations).returns({ "items" => [] })
+ @provider.stubs(:get_earn_strategies).returns({ "items" => [] })
end
test "creates a combined kraken account from BalanceEx" do
@@ -43,6 +44,89 @@ class KrakenItem::ImporterTest < ActiveSupport::TestCase
assert_equal "0.25", btc["hold_trade"]
end
+ test "skips Earn allocations already in BalanceEx and keeps hybrid Earn" do
+ @provider.stubs(:get_asset_info).returns(asset_metadata.merge("ETH.B" => { "altname" => "ETH.B" }))
+ @provider.stubs(:get_extended_balance).returns(
+ "ETH.B" => { "balance" => "8.4245", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" },
+ "XETH" => { "balance" => "0.0005", "credit" => "0", "credit_used" => "0", "hold_trade" => "0" }
+ )
+ @provider.stubs(:get_earn_allocations).returns(
+ "items" => [
+ { "strategy_id" => "bonded", "native_asset" => "ETH", "amount_allocated" => { "total" => { "native" => "8.4245" } } },
+ { "strategy_id" => "flex", "native_asset" => "ETH", "amount_allocated" => { "total" => { "native" => "0.0005" } } },
+ { "strategy_id" => "vault", "native_asset" => "BTC", "amount_allocated" => { "total" => { "native" => "0.08" } } }
+ ]
+ )
+ @provider.stubs(:get_earn_strategies).returns("items" => [ { "id" => "bonded" }, { "id" => "flex" } ])
+ @provider.stubs(:get_ticker).with("ETHUSD").returns("XETHZUSD" => { "c" => [ "2000.00" ] })
+ @provider.stubs(:get_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })
+
+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import
+
+ earn = @item.kraken_accounts.first.raw_payload["assets"].select { |asset| asset["source"] == "earn" }
+ assert_equal [ [ "BTC", "0.08" ] ], earn.map { |asset| [ asset["symbol"], asset["balance"] ] }
+ assert_in_delta 20_850, @item.kraken_accounts.first.current_balance, 0.01
+ end
+
+ test "carries forward last known Earn assets when Earn/Strategies 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_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })
+ @provider.stubs(:get_earn_allocations).returns(
+ "items" => [ { "strategy_id" => "vault", "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } } ]
+ )
+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import
+ @provider.stubs(:get_earn_allocations).returns(
+ "items" => [ { "strategy_id" => "vault", "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "3.0" } } } ]
+ )
+
+ @provider.stubs(:get_earn_strategies).raises(Provider::Kraken::ApiError, "EGeneral:Internal error")
+ 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_equal "2.0", earn_btc["balance"]
+ end
+
+ test "carries forward last known Earn assets when Earn/Strategies is incomplete" 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_ticker).with("XBTUSD").returns("XXBTZUSD" => { "c" => [ "50000.00" ] })
+ @provider.stubs(:get_earn_allocations).returns(
+ "items" => [ { "strategy_id" => "vault", "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "2.0" } } } ]
+ )
+ KrakenItem::Importer.new(@item, kraken_provider: @provider).import
+ @provider.stubs(:get_earn_allocations).returns(
+ "items" => [ { "strategy_id" => "vault", "native_asset" => "XXBT", "amount_allocated" => { "total" => { "native" => "3.0" } } } ]
+ )
+
+ [
+ { "items" => [ { "name" => "no id" } ] },
+ { "items" => [ { "id" => "bonded" } ], "next_cursor" => "same" }
+ ].each do |response|
+ @provider.stubs(:get_earn_strategies).returns(response)
+ assert KrakenItem::Importer.new(@item, kraken_provider: @provider).import[:success]
+
+ earn_btc = @item.kraken_accounts.first.raw_payload["assets"].find { |asset| asset["source"] == "earn" }
+ assert_equal "2.0", earn_btc["balance"]
+ end
+ end
+
+ test "does not fetch Earn/Strategies when there are no allocations" 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.expects(:get_earn_strategies).never
+
+ assert KrakenItem::Importer.new(@item, kraken_provider: @provider).import[:success]
+ assert_in_delta 50.0, @item.kraken_accounts.first.current_balance, 0.01
+ 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