Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(kraken): keep a transfer fee out of the movement it is charged on (#3759)

Daniel Garcia Sardina19cc353de419
diff --git a/app/models/kraken_account/ledger_processor.rb b/app/models/kraken_account/ledger_processor.rb
index 74d661caec..096729d525 100644
--- a/app/models/kraken_account/ledger_processor.rb
+++ b/app/models/kraken_account/ledger_processor.rb
@@ -16,6 +16,10 @@ class KrakenAccount::LedgerProcessor
# Ledger types we import as Transaction entries.
SUPPORTED_TYPES = %w[deposit withdrawal staking earn fee].freeze
+ # Types whose fee is charged on top of a movement with an external counterparty,
+ # and so must stay a separate entry for transfer matching to work.
+ SPLIT_FEE_TYPES = %w[deposit withdrawal].freeze
+
# Ledger types we intentionally ignore (handled elsewhere or out of scope).
SKIP_TYPES = %w[trade transfer margin rollover settled adjustment].freeze
@@ -34,11 +38,14 @@ class KrakenAccount::LedgerProcessor
# membership in memory, instead of an EXISTS query per ledger entry (a full
# sync can carry up to ~10k entries — see MAX_LEDGER_PAGES in the importer).
# Scoped to the kraken_ledger_ prefix so trade entries aren't loaded.
- @existing_external_ids = account.entries
- .where(source: "kraken")
- .where("external_id LIKE 'kraken_ledger_%'")
- .pluck(:external_id)
- .to_set
+ # The name comes along so a principal already holding its fee can be told
+ # from one still owed it, without a lookup per ledger row.
+ existing = account.entries
+ .where(source: "kraken")
+ .where("external_id LIKE 'kraken_ledger_%'")
+ .pluck(:external_id, :name, :user_modified)
+ @existing_external_ids = existing.map(&:first).to_set
+ @existing_principals = existing.to_h { |external_id, name, user_modified| [ external_id, [ name, user_modified ] ] }
raw_ledgers.each do |ledger_id, ledger|
process_ledger_entry(ledger_id, ledger)
@@ -86,21 +93,41 @@ class KrakenAccount::LedgerProcessor
return if type == "earn" && EARN_INTERNAL_SUBTYPES.include?(subtype)
external_id = "kraken_ledger_#{ledger_id}"
- return if @existing_external_ids.include?(external_id)
+ # Already in, and nothing more to add for it: skip before any parsing. A
+ # split-fee type is the exception, checked further down once the fee is
+ # known -- its second entry may still be owed.
+ return if @existing_external_ids.include?(external_id) && !SPLIT_FEE_TYPES.include?(type)
raw_asset = ledger["asset"].to_s
raw_amount = ledger["amount"].to_d
raw_fee = ledger["fee"].to_d
date = Time.zone.at(ledger["time"].to_d).to_date
- # Compute the total balance impact: Kraken applies amount - fee to the balance.
- # abs_impact captures the full magnitude of the cash movement for this event.
- abs_impact = (raw_amount - raw_fee).abs
- return if abs_impact.zero?
+ # Kraken applies amount - fee to the balance, and reports the two separately.
+ # Deposits and withdrawals are emitted as two entries so the movement keeps the
+ # figure the counterparty actually sees: a bank records the transfer net of
+ # Kraken's fee, and Transfer requires both legs to sum to zero, so folding the
+ # fee in here makes the entry permanently unmatchable. Other ledger types have
+ # no counterparty to reconcile against and keep the combined figure.
+ split_fee = SPLIT_FEE_TYPES.include?(type) && !raw_fee.zero?
+ abs_impact = split_fee ? raw_amount.abs : (raw_amount - raw_fee).abs
normalized = normalizer.normalize(raw_asset)
symbol = normalized[:symbol]
+ # The principal is in from an earlier pass, or there is none: a correction
+ # row can carry a fee against a zero amount. Either way the fee is checked
+ # on its own external_id, so a later sync can still create the missing
+ # half -- pricing it can fail on one sync and succeed on the next --
+ # without duplicating the one it has.
+ if abs_impact.zero? || @existing_external_ids.include?(external_id)
+ if split_fee && !@existing_external_ids.include?("#{external_id}_fee") &&
+ principal_awaits_fee?(external_id, raw_amount, symbol)
+ process_ledger_fee(external_id, ledger_id, ledger, raw_fee, symbol, date)
+ end
+ return
+ end
+
entry_amount, price_missing = resolve_amount(abs_impact, symbol, date)
return if entry_amount.nil?
@@ -127,6 +154,64 @@ class KrakenAccount::LedgerProcessor
)
@existing_external_ids << external_id
+
+ process_ledger_fee(external_id, ledger_id, ledger, raw_fee, symbol, date) if split_fee
+ end
+
+ # Kraken's fee is always a cost, so it is an outflow whichever way the principal
+ # moved. Its own external_id keeps it idempotent alongside the principal entry.
+ # An entry written before fees were split holds the fee inside it: adding the
+ # fee entry now would charge it twice. Only a principal already standing on
+ # its own is owed one -- which happens when pricing the fee failed on an
+ # earlier sync. The two are told apart by the native quantity the entry was
+ # charged, which its name carries. Not by the stored amount: a crypto row is
+ # converted at the current spot price, so recomputing it later scales the
+ # candidates while the stored figure stays where it was, and after any real
+ # price move nearness decides nothing.
+ def principal_awaits_fee?(external_id, raw_amount, symbol)
+ stored_name, user_modified = @existing_principals[external_id]
+ return true if stored_name.nil? # no principal at all: a correction row carrying only a fee
+ return false if user_modified
+
+ charged = charged_quantity(stored_name, symbol)
+ return false if charged.nil?
+
+ charged == raw_amount.abs.round(8)
+ end
+
+ # The quantity out of "Withdrawal 0.501 BTC", compared as a number so a name
+ # written when the formatting differed -- "500.0" against today's "500" --
+ # still reads. Nil unless the name is one this class built for this symbol,
+ # which leaves a renamed entry alone.
+ def charged_quantity(name, symbol)
+ parts = name.to_s.split(" ")
+ return nil unless parts.length >= 3 && parts.last == symbol
+
+ BigDecimal(parts[-2], exception: false)&.round(8)
+ end
+
+ def process_ledger_fee(principal_external_id, ledger_id, ledger, raw_fee, symbol, date)
+ fee_external_id = "#{principal_external_id}_fee"
+ return if @existing_external_ids.include?(fee_external_id)
+
+ fee_amount, price_missing = resolve_amount(raw_fee.abs, symbol, date)
+ return if fee_amount.nil? || fee_amount.zero?
+
+ account.entries.create!(
+ date: date,
+ name: build_name("fee", raw_fee.abs, symbol),
+ amount: fee_amount.abs,
+ currency: target_currency,
+ external_id: fee_external_id,
+ source: "kraken",
+ entryable: Transaction.new(
+ kind: transaction_kind("fee"),
+ investment_activity_label: activity_label("fee"),
+ extra: build_extra(ledger_id, ledger, ledger["asset"].to_s, price_missing)
+ )
+ )
+
+ @existing_external_ids << fee_external_id
end
# Returns [family_currency_amount, price_missing_bool] or [nil, nil] on hard failure.
diff --git a/test/models/kraken_account/ledger_processor_test.rb b/test/models/kraken_account/ledger_processor_test.rb
index 6268f0d4b3..c4ec93545d 100644
--- a/test/models/kraken_account/ledger_processor_test.rb
+++ b/test/models/kraken_account/ledger_processor_test.rb
@@ -70,20 +70,218 @@ class KrakenAccount::LedgerProcessorTest < ActiveSupport::TestCase
end
# ---------------------------------------------------------------------------
- # fee inclusion in amount
+ # fee handling
# ---------------------------------------------------------------------------
- test "includes the Kraken fee in the total withdrawal amount" do
- # Kraken: balance_change = amount - fee = -500 - 1 = -501 total outflow
+ # A withdrawal has a counterparty. The receiving bank records 500, not 501,
+ # and `Transfer` requires both legs to sum to zero -- so a withdrawal carrying
+ # Kraken's fee can never be matched. The fee becomes its own entry instead;
+ # together the two still move the balance by the 501 Kraken applied.
+ test "a withdrawal fee is charged as its own entry" do
set_ledgers(
"LWIT02" => ledger_entry(type: "withdrawal", asset: "ZUSD", amount: "-500.00", fee: "1.00", time: 1_700_000_000)
)
+ assert_difference "@account.entries.count", 2 do
+ process
+ end
+
+ principal = @account.entries.find_by(external_id: "kraken_ledger_LWIT02", source: "kraken")
+ assert principal
+ assert_in_delta 500.0, principal.amount.to_f, 0.01
+
+ fee = @account.entries.find_by(external_id: "kraken_ledger_LWIT02_fee", source: "kraken")
+ assert fee, "the fee must be its own entry"
+ assert_in_delta 1.0, fee.amount.to_f, 0.01
+ assert_equal "Fee 1 USD", fee.name, "a BigDecimal must not reach the name as 0.1e1"
+ assert_equal "Fee", fee.entryable.investment_activity_label
+ assert_in_delta 501.0, principal.amount.to_f + fee.amount.to_f, 0.01
+ end
+
+ # The fee is a cost whichever way the principal moved, so it is an outflow on
+ # a deposit too.
+ test "a deposit fee is charged as its own outflow" do
+ set_ledgers(
+ "LDEP02" => ledger_entry(type: "deposit", asset: "ZUSD", amount: "1000.00", fee: "2.00", time: 1_700_000_000)
+ )
+
+ assert_difference "@account.entries.count", 2 do
+ process
+ end
+
+ principal = @account.entries.find_by(external_id: "kraken_ledger_LDEP02", source: "kraken")
+ assert_in_delta(-1000.0, principal.amount.to_f, 0.01)
+
+ fee = @account.entries.find_by(external_id: "kraken_ledger_LDEP02_fee", source: "kraken")
+ assert fee
+ assert fee.amount.positive?, "a fee is always an outflow"
+ assert_in_delta 2.0, fee.amount.to_f, 0.01
+ end
+
+ # Only deposits and withdrawals have a counterparty to reconcile against.
+ # Everything else keeps the combined figure.
+ test "a fee on a ledger type with no counterparty stays folded in" do
+ set_ledgers(
+ "LSTK02" => ledger_entry(type: "staking", asset: "ZUSD", amount: "10.00", fee: "1.00", time: 1_700_000_000)
+ )
+
+ assert_difference "@account.entries.count", 1 do
+ process
+ end
+
+ entry = @account.entries.find_by(external_id: "kraken_ledger_LSTK02", source: "kraken")
+ assert_in_delta(-9.0, entry.amount.to_f, 0.01)
+ end
+
+ # Pricing the fee can fail on one sync and succeed on the next. The principal
+ # being present must not stop the fee from being created later.
+ test "a fee missing after an earlier pass is created without duplicating the principal" do
+ @account.entries.create!(
+ date: Time.zone.at(1_700_000_000).to_date, name: "Withdrawal 500.0 USD", amount: 500, currency: "USD",
+ external_id: "kraken_ledger_LWIT05", source: "kraken",
+ entryable: Transaction.new(kind: "funds_movement", investment_activity_label: "Withdrawal")
+ )
+ set_ledgers(
+ "LWIT05" => ledger_entry(type: "withdrawal", asset: "ZUSD", amount: "-500.00", fee: "1.00", time: 1_700_000_000)
+ )
+
+ assert_difference "@account.entries.count", 1 do
+ process
+ end
+
+ assert_equal 1, @account.entries.where(external_id: "kraken_ledger_LWIT05").count
+ fee = @account.entries.find_by(external_id: "kraken_ledger_LWIT05_fee", source: "kraken")
+ assert fee
+ assert_in_delta 1.0, fee.amount.to_f, 0.01
+ end
+
+ # A correction row can carry a fee against a zero principal. Before the fee
+ # was split out the combined figure kept it; now the fee is its own entry and
+ # a zero principal must not swallow it.
+ test "a fee-only ledger row still produces its fee entry" do
+ set_ledgers(
+ "LWIT06" => ledger_entry(type: "withdrawal", asset: "ZUSD", amount: "0.00", fee: "0.50", time: 1_700_000_000)
+ )
+
+ assert_difference "@account.entries.count", 1 do
+ process
+ end
+
+ assert_nil @account.entries.find_by(external_id: "kraken_ledger_LWIT06"), "no principal for a zero amount"
+ fee = @account.entries.find_by(external_id: "kraken_ledger_LWIT06_fee", source: "kraken")
+ assert fee
+ assert_in_delta 0.5, fee.amount.to_f, 0.01
+ end
+
+ # An account synced before fees were split carries the fee inside the
+ # withdrawal. An ordinary sync reaches it long before the re-import this
+ # change asks for, and must not charge the fee a second time.
+ test "a principal written with its fee inside it is left alone" do
+ set_ledgers(
+ "LWIT07" => ledger_entry(type: "withdrawal", asset: "ZUSD", amount: "-500.00", fee: "1.00", time: 1_700_000_000)
+ )
+ legacy = @account.entries.create!(
+ date: Time.zone.at(1_700_000_000).to_date,
+ name: "Withdrawal 501 USD",
+ amount: 501,
+ currency: "USD",
+ external_id: "kraken_ledger_LWIT07",
+ source: "kraken",
+ entryable: Transaction.new
+ )
+
+ assert_no_difference "@account.entries.count" do
+ process
+ end
+
+ assert_nil @account.entries.find_by(external_id: "kraken_ledger_LWIT07_fee")
+ assert_equal 501, legacy.reload.amount
+ end
+
+ # The other reason a principal can stand alone: pricing the fee failed on an
+ # earlier sync. That one is still owed its other half.
+ test "a principal written without its fee still gets one" do
+ set_ledgers(
+ "LWIT08" => ledger_entry(type: "withdrawal", asset: "ZUSD", amount: "-500.00", fee: "1.00", time: 1_700_000_000)
+ )
+ @account.entries.create!(
+ date: Time.zone.at(1_700_000_000).to_date,
+ name: "Withdrawal 500 USD",
+ amount: 500,
+ currency: "USD",
+ external_id: "kraken_ledger_LWIT08",
+ source: "kraken",
+ entryable: Transaction.new
+ )
+
+ assert_difference "@account.entries.count", 1 do
+ process
+ end
+
+ fee = @account.entries.find_by(external_id: "kraken_ledger_LWIT08_fee", source: "kraken")
+ assert fee
+ assert_in_delta 1.0, fee.amount.to_f, 0.01
+ end
+
+ # A crypto principal is converted at the current spot price, so the stored
+ # figure and anything recomputed later drift apart as the price moves. The
+ # native quantity does not, which is why the classification reads that.
+ test "a crypto principal written with its fee inside it survives a price move" do
+ set_raw_payload_assets([ { "symbol" => "BTC", "price_usd" => "50000.00" } ])
+ set_ledgers(
+ "LWBTC1" => ledger_entry(type: "withdrawal", asset: "XXBT", amount: "-0.50000000", fee: "0.00100000", time: 1_700_000_000)
+ )
+ # As the old code wrote it: one entry for 0.501 BTC, priced at 50,000.
+ @account.entries.create!(
+ date: Time.zone.at(1_700_000_000).to_date,
+ name: "Withdrawal 0.501 BTC",
+ amount: 25_050,
+ currency: "USD",
+ external_id: "kraken_ledger_LWBTC1",
+ source: "kraken",
+ entryable: Transaction.new
+ )
+
+ # Upwards: the stored figure now sits nearer the fee-less candidate than the
+ # fee-inclusive one, which is what a comparison of converted amounts reads
+ # as "still owed its fee".
+ set_raw_payload_assets([ { "symbol" => "BTC", "price_usd" => "60000.00" } ])
+
+ assert_no_difference "@account.entries.count" do
+ process
+ end
+
+ assert_nil @account.entries.find_by(external_id: "kraken_ledger_LWBTC1_fee")
+ end
+
+ # The legacy check must not cost a query per ledger row: the principal
+ # amounts are loaded with the external ids, in the same bulk read.
+ test "the legacy-principal check does not scale entries queries with ledger count" do
+ set_ledgers(
+ "LWQ1" => ledger_entry(type: "withdrawal", asset: "ZUSD", amount: "-100.00", fee: "1.00", time: 1_700_000_000),
+ "LWQ2" => ledger_entry(type: "withdrawal", asset: "ZUSD", amount: "-200.00", fee: "1.00", time: 1_700_000_100),
+ "LWQ3" => ledger_entry(type: "withdrawal", asset: "ZUSD", amount: "-300.00", fee: "1.00", time: 1_700_000_200)
+ )
+
process
+ queries = capture_sql_queries { process }
+ entries_selects = queries.count { |q| q.match?(/from "entries"/i) }
+ assert_equal 1, entries_selects,
+ "second pass should still issue exactly one bulk read, not one per split-fee row"
+ end
- entry = @account.entries.find_by(external_id: "kraken_ledger_LWIT02", source: "kraken")
- assert entry
- assert_in_delta 501.0, entry.amount.to_f, 0.01
+ test "a split fee entry is not duplicated on reprocessing" do
+ set_ledgers(
+ "LWIT03" => ledger_entry(type: "withdrawal", asset: "ZUSD", amount: "-500.00", fee: "1.00", time: 1_700_000_000)
+ )
+
+ assert_difference "@account.entries.count", 2 do
+ process
+ end
+
+ assert_no_difference "@account.entries.count" do
+ process
+ end
end
# ---------------------------------------------------------------------------