Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(kraken): a crypto ledger row moves units, not cash (#3875)

Daniel Garcia Sardinaefe34c6ffedb
diff --git a/app/models/kraken_account/ledger_processor.rb b/app/models/kraken_account/ledger_processor.rb
index 096729d525..21de29136a 100644
--- a/app/models/kraken_account/ledger_processor.rb
+++ b/app/models/kraken_account/ledger_processor.rb
@@ -8,13 +8,22 @@
# sub-account transfers (type="transfer") and margin events (type="margin",
# "rollover", "settled") are also skipped.
#
-# Sign convention (Sure): negative = inflow/income, positive = outflow/expense.
-# Deposits and rewards are negative; withdrawals and fees are positive.
+# Fiat entries are cash and become Transactions, with Sure's sign convention:
+# negative = inflow/income, positive = outflow/expense, so deposits and rewards
+# are negative and withdrawals and fees positive.
+#
+# Crypto entries are not cash. They move units, so they become Trades carrying a
+# quantity and the price on the day, with a zero amount -- see
+# process_crypto_ledger_entry.
class KrakenAccount::LedgerProcessor
include KrakenAccount::UsdConverter
- # Ledger types we import as Transaction entries.
- SUPPORTED_TYPES = %w[deposit withdrawal staking earn fee].freeze
+ # Ledger types we import. `spend` and `receive` are the two halves of Kraken's
+ # dust sweep -- "convert small balances" -- and they move units like any other
+ # entry. Left out they were not skipped but dropped, silently, by the guard
+ # below, so a swept position stayed on the books at its pre-sweep quantity
+ # forever.
+ SUPPORTED_TYPES = %w[deposit withdrawal staking earn fee spend receive].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.
@@ -39,13 +48,20 @@ class KrakenAccount::LedgerProcessor
# 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.
# 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.
+ # from one still owed it, and a trade's price_missing flag so one recorded
+ # before its price existed can be priced later -- all without a lookup per
+ # ledger row. The flag lives on the trade, read here by subselect so this
+ # stays one query on entries.
existing = account.entries
.where(source: "kraken")
.where("external_id LIKE 'kraken_ledger_%'")
- .pluck(:external_id, :name, :user_modified)
+ .pluck(:external_id, :name, :user_modified, :entryable_type,
+ Arel.sql("(SELECT trades.extra -> 'kraken' ->> 'price_missing' FROM trades " \
+ "WHERE entries.entryable_type = 'Trade' AND trades.id = entries.entryable_id)"))
@existing_external_ids = existing.map(&:first).to_set
- @existing_principals = existing.to_h { |external_id, name, user_modified| [ external_id, [ name, user_modified ] ] }
+ @existing_principals = existing.to_h { |external_id, *rest| [ external_id, rest ] }
+
+ warm_crypto_prices
raw_ledgers.each do |ledger_id, ledger|
process_ledger_entry(ledger_id, ledger)
@@ -93,11 +109,6 @@ class KrakenAccount::LedgerProcessor
return if type == "earn" && EARN_INTERNAL_SUBTYPES.include?(subtype)
external_id = "kraken_ledger_#{ledger_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
@@ -109,11 +120,39 @@ class KrakenAccount::LedgerProcessor
# 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]
+ base_symbol = normalized[:price_symbol]
+ fiat = fiat?(base_symbol)
+
+ # Already in, and nothing more to add for it. Two exceptions: a split-fee
+ # type, whose second entry may still be owed and is checked once the fee
+ # is known; and a crypto row still in an older shape -- a cash Transaction
+ # from before coin movements were trades, or a trade saved without a
+ # price -- which the sync heals whatever the ledger type.
+ if @existing_external_ids.include?(external_id) && !SPLIT_FEE_TYPES.include?(type)
+ return if fiat || !crypto_row_needs_healing?(external_id)
+ end
- normalized = normalizer.normalize(raw_asset)
- symbol = normalized[:symbol]
+ # A crypto fee is paid in the units themselves, so it only reduces the
+ # quantity; there is no second cash movement to split out.
+ split_fee = fiat && SPLIT_FEE_TYPES.include?(type) && !raw_fee.zero?
+ net = raw_amount - raw_fee
+ abs_impact = split_fee ? raw_amount.abs : net.abs
+
+ # A crypto row has no fee half to owe, so a quantity of nothing -- a
+ # correction row, a movement the fee consumed whole, or a reward below
+ # the eight decimals trades.qty holds -- has nothing to record.
+ unless fiat
+ return if abs_impact.round(8).zero?
+
+ process_crypto_ledger_entry(
+ external_id: external_id, ledger_id: ledger_id, ledger: ledger, type: type,
+ raw_asset: raw_asset, base_symbol: base_symbol, symbol: symbol,
+ qty: abs_impact, outflow: net.negative?, date: date
+ )
+ return
+ end
# 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
@@ -158,6 +197,217 @@ class KrakenAccount::LedgerProcessor
process_ledger_fee(external_id, ledger_id, ledger, raw_fee, symbol, date) if split_fee
end
+ # Crypto moves units, not cash. A staking reward does not put euros in the
+ # account -- it puts coins in it -- and a deposit or withdrawal of coin is a
+ # position change with no cash leg at all. Recorded as a Transaction the
+ # quantity is lost entirely, so Holding::ReverseCalculator has nothing to
+ # reverse and carries today's position backwards through history, while the
+ # cash balance moves by an amount that never existed.
+ #
+ # `amount` is deliberately zero: Balance::BaseCalculator classifies a trade by
+ # its amount regardless of label, so anything else would reintroduce the
+ # phantom cash. The units and their price carry the value instead.
+ def process_crypto_ledger_entry(external_id:, ledger_id:, ledger:, type:, raw_asset:, base_symbol:, symbol:, qty:, outflow:, date:)
+ # A crypto row carries its fee inside the quantity, so once it is in there
+ # is no second half owed. The caller's early return lets deposits and
+ # withdrawals through for the fee a fiat row may still need, which would
+ # otherwise bring this one back every sync -- unless what is in is the old
+ # shape, which a sync should heal rather than keep.
+ legacy = nil
+ legacy_fee = nil
+ if @existing_external_ids.include?(external_id)
+ return reprice_crypto_trade(external_id, base_symbol, date) if unpriced_trade?(external_id)
+
+ legacy = legacy_crypto_transaction(external_id)
+ return if legacy.nil?
+
+ # Before fees stayed inside a coin's quantity, a crypto deposit or
+ # withdrawal with a fee was written as two cash rows. The trade that
+ # replaces the principal already nets the fee, so the fee row would be
+ # left describing money that never moved; it goes with the principal,
+ # under the same rule -- edited or matched into a transfer, it stays.
+ legacy_fee = legacy_crypto_transaction("#{external_id}_fee")
+ end
+
+ # Resolved before anything is removed: a symbol this cannot place must
+ # leave the old row standing rather than take it away and put nothing back.
+ security = resolve_security(base_symbol)
+ return unless security
+
+ price, price_missing = unit_price_on(security, base_symbol, date)
+ # The direction comes from the ledger's own signed figure, not from the
+ # type: a reversed withdrawal arrives, an earn migration leg can leave,
+ # and on a trade a wrong sign moves units the wrong way through every
+ # earlier holding. For a row that moves the way its type says, the two
+ # agree.
+ signed_qty = outflow ? -qty.abs : qty.abs
+
+ Entry.transaction do
+ legacy&.destroy!
+ legacy_fee&.destroy!
+ create_crypto_trade(external_id, ledger_id, ledger, type, raw_asset, symbol, qty, signed_qty, security, price, price_missing, date)
+ end
+
+ @existing_external_ids.delete("#{external_id}_fee") if legacy_fee
+ @existing_external_ids << external_id
+ @existing_principals[external_id] = [ build_name(type, qty, symbol), false, "Trade" ]
+ end
+
+ def create_crypto_trade(external_id, ledger_id, ledger, type, raw_asset, symbol, qty, signed_qty, security, price, price_missing, date)
+ account.entries.create!(
+ date: date,
+ name: build_name(type, qty, symbol),
+ amount: 0,
+ currency: target_currency,
+ external_id: external_id,
+ source: "kraken",
+ entryable: Trade.new(
+ security: security,
+ qty: signed_qty,
+ price: price,
+ currency: target_currency,
+ investment_activity_label: crypto_activity_label(type),
+ extra: build_extra(ledger_id, ledger, raw_asset, price_missing)
+ )
+ )
+ end
+
+ # An account synced before crypto rows became trades holds this row as a
+ # Transaction: a cash movement that never happened, carrying a quantity the
+ # holdings never saw. Replaced on the next sync, so an install does not have
+ # to re-import to be right -- unless somebody has edited the row or matched
+ # it into a transfer, in which case it is theirs and stays. Only a legacy
+ # row costs a query; a Trade is already the new shape and answers from the
+ # preload.
+ def legacy_crypto_transaction(external_id)
+ return nil unless legacy_crypto_candidate?(external_id)
+
+ entry = find_entry(external_id)
+ return nil if entry.nil? || in_transfer?(entry.entryable)
+
+ entry
+ end
+
+ # Answered from the preload; the row itself is only read when it is one.
+ def legacy_crypto_candidate?(external_id)
+ _name, user_modified, entryable_type = @existing_principals[external_id]
+ entryable_type == "Transaction" && !user_modified
+ end
+
+ def unpriced_trade?(external_id)
+ _name, user_modified, entryable_type, price_missing = @existing_principals[external_id]
+ entryable_type == "Trade" && price_missing == "true" && !user_modified
+ end
+
+ def crypto_row_needs_healing?(external_id)
+ unpriced_trade?(external_id) || legacy_crypto_candidate?(external_id)
+ end
+
+ def find_entry(external_id)
+ account.entries.includes(:entryable).find_by(external_id: external_id)
+ end
+
+ # A trade recorded before its price existed carries zero and the flag.
+ # Pricing can fail on one sync and succeed on the next, so it is tried
+ # again here and the trade is completed once a price is found.
+ def reprice_crypto_trade(external_id, base_symbol, date)
+ entry = find_entry(external_id)
+ return if entry.nil?
+
+ price, price_missing = unit_price_on(entry.entryable.security, base_symbol, date)
+ return if price_missing
+
+ trade = entry.entryable
+ extra = trade.extra.deep_dup
+ extra["kraken"]&.delete("price_missing")
+ trade.update!(price: price, extra: extra)
+ @existing_principals[external_id][3] = nil
+ end
+
+ # A transfer records its two legs on its own row; the transaction's own
+ # transfer_id is only set by some paths, so both are checked.
+ def in_transfer?(transaction)
+ return true if transaction.transfer_id.present?
+
+ Transfer.where(inflow_transaction_id: transaction.id).or(Transfer.where(outflow_transaction_id: transaction.id)).exists?
+ end
+
+ # A coin arriving from outside has a cost nothing here knows, so it is a
+ # Transfer and the basis becomes unknown from that date -- the same treatment
+ # an inbound share transfer already gets. A reward is acquired at the market
+ # price on the day, which is both its basis and the income it represents.
+ def crypto_activity_label(type)
+ case type
+ when "deposit", "withdrawal" then Trade::TRANSFER_LABEL
+ when "staking" then "Dividend"
+ when "earn" then "Interest"
+ when "fee" then "Fee"
+ # A dust sweep exchanges one asset for another inside the exchange. Both
+ # halves are internal movements, so neither invents a cost basis.
+ when "spend" then "Sweep Out"
+ when "receive" then "Sweep In"
+ end
+ end
+
+ def fiat?(base_symbol)
+ KrakenAccount::FIAT_CURRENCIES.include?(base_symbol.to_s.upcase)
+ end
+
+ # One bulk request per asset for the span the ledger covers, the same call
+ # MarketDataImporter makes, so that the per-entry lookup below is a
+ # database read. Left to find_or_fetch_price it was one provider request
+ # per entry -- thousands on a first import.
+ def warm_crypto_prices
+ spans = {}
+ raw_ledgers.each_value do |ledger|
+ next unless SUPPORTED_TYPES.include?(ledger["type"].to_s.downcase)
+
+ base_symbol = normalizer.normalize(ledger["asset"].to_s)[:price_symbol]
+ next if base_symbol.blank? || fiat?(base_symbol)
+
+ date = Time.zone.at(ledger["time"].to_d).to_date
+ span = (spans[base_symbol] ||= [ date, date ])
+ span[0] = date if date < span[0]
+ span[1] = date if date > span[1]
+ end
+
+ spans.each do |base_symbol, (from, to)|
+ security = resolve_security(base_symbol)
+ security&.import_provider_prices(start_date: from, end_date: to)
+ rescue StandardError => e
+ Rails.logger.warn "KrakenAccount::LedgerProcessor - could not warm prices for #{base_symbol}: #{e.message}"
+ end
+ end
+
+ def resolve_security(base_symbol)
+ KrakenAccount::SecurityResolver.resolve("CRYPTO:#{base_symbol}", base_symbol)
+ end
+
+ # The price on the day the units moved, not the price today. Falls back to
+ # the balance snapshot's price, which is what the whole processor used to
+ # use, and flags the entry so the staleness is visible in `extra`.
+ def unit_price_on(security, base_symbol, date)
+ price = security.prices.find_by(date: date)
+ if price&.price.present?
+ converted = Money.new(price.price, price.currency).exchange_to(target_currency).amount
+ return [ converted, false ]
+ end
+
+ [ spot_price_fallback(base_symbol, date), true ]
+ rescue StandardError
+ [ spot_price_fallback(base_symbol, date), true ]
+ end
+
+ # The spot price as a last resort. It cannot be allowed to raise: it is
+ # also what the rescue above reaches for, and an exception there would
+ # escape it and lose the ledger row for this sync.
+ def spot_price_fallback(base_symbol, date)
+ fallback, = resolve_amount(1.to_d, base_symbol, date)
+ fallback || 0
+ rescue StandardError
+ 0
+ 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
@@ -298,8 +548,8 @@ class KrakenAccount::LedgerProcessor
# True when the ledger event represents money flowing INTO the account.
def inflow?(type)
case type
- when "deposit", "staking", "earn" then true
- when "withdrawal", "fee" then false
+ when "deposit", "staking", "earn", "receive" then true
+ when "withdrawal", "fee", "spend" then false
else false
end
end
@@ -312,6 +562,8 @@ class KrakenAccount::LedgerProcessor
when "staking" then "Staking reward #{qty} #{symbol}"
when "earn" then "Earn reward #{qty} #{symbol}"
when "fee" then "Fee #{qty} #{symbol}"
+ when "spend" then "Converted #{qty} #{symbol}"
+ when "receive" then "Received #{qty} #{symbol}"
else "#{type.capitalize} #{qty} #{symbol}"
end
end
@@ -323,6 +575,8 @@ class KrakenAccount::LedgerProcessor
when "staking" then "Dividend"
when "earn" then "Interest"
when "fee" then "Fee"
+ when "spend" then "Sweep Out"
+ when "receive" then "Sweep In"
end
end
diff --git a/test/models/kraken_account/ledger_processor_test.rb b/test/models/kraken_account/ledger_processor_test.rb
index c4ec93545d..d62fbe44bd 100644
--- a/test/models/kraken_account/ledger_processor_test.rb
+++ b/test/models/kraken_account/ledger_processor_test.rb
@@ -285,10 +285,13 @@ class KrakenAccount::LedgerProcessorTest < ActiveSupport::TestCase
end
# ---------------------------------------------------------------------------
- # BTC deposit (crypto → family currency conversion)
+ # crypto moves units, not cash
# ---------------------------------------------------------------------------
- test "creates a deposit entry for BTC using stored price" do
+ # A coin deposit is a position change with no cash leg. Recorded as a
+ # Transaction the quantity is lost, so the holdings calculator has nothing to
+ # reverse and the cash balance moves by an amount that never existed.
+ test "a BTC deposit becomes a trade carrying the quantity, not a cash entry" do
set_ledgers(
"LBTC01" => ledger_entry(type: "deposit", asset: "XXBT", amount: "0.10000000", fee: "0.00000000", time: 1_700_000_000)
)
@@ -297,17 +300,251 @@ class KrakenAccount::LedgerProcessorTest < ActiveSupport::TestCase
entry = @account.entries.find_by(external_id: "kraken_ledger_LBTC01", source: "kraken")
assert entry
- assert entry.amount.negative?, "BTC deposit is an inflow — must be negative"
- # 0.1 BTC × $50,000/BTC = $5,000 (family currency = USD, no conversion needed)
- assert_in_delta(-5000.0, entry.amount.to_f, 1.0)
+ assert_equal "Trade", entry.entryable_type
+ assert_equal 0, entry.amount, "a coin movement has no cash leg"
+ assert_in_delta 0.1, entry.entryable.qty.to_f, 1e-8
+ assert_equal "CRYPTO:BTC", entry.entryable.security.ticker
+ # A coin arriving from outside has a cost nothing here knows.
+ assert_equal Trade::TRANSFER_LABEL, entry.entryable.investment_activity_label
assert_match(/Deposit.*BTC/, entry.name)
end
+ test "a zero-quantity crypto row creates no trade" do
+ set_ledgers(
+ # A correction row, a deposit the fee consumed whole, and a staking
+ # reward below the eight decimals the qty column holds.
+ "LZERO1" => ledger_entry(type: "deposit", asset: "XXBT", amount: "0.00000000", fee: "0.00000000", time: 1_700_000_000),
+ "LZERO2" => ledger_entry(type: "deposit", asset: "XXBT", amount: "0.00010000", fee: "0.00010000", time: 1_700_000_100),
+ "LZERO3" => ledger_entry(type: "staking", asset: "DOT", amount: "0.0000000022", fee: "0.0000000006", time: 1_700_000_200)
+ )
+
+ assert_no_difference "@account.entries.count" do
+ process
+ end
+ end
+
+ # Pricing can fail on one sync and succeed on the next. A trade recorded at
+ # zero with the flag is completed once the price on its date exists.
+ test "a crypto trade recorded without a price is priced on a later sync" do
+ set_raw_payload_assets([])
+ set_ledgers(
+ "LBTC20" => ledger_entry(type: "deposit", asset: "XXBT", amount: "0.10000000", fee: "0.00000000", time: 1_700_000_000)
+ )
+ process
+ trade = @account.entries.find_by(external_id: "kraken_ledger_LBTC20", source: "kraken").entryable
+ assert_equal 0, trade.price
+ assert trade.extra.dig("kraken", "price_missing"), "recorded without a price"
+
+ Security::Price.create!(security: trade.security, date: Time.zone.at(1_700_000_000).to_date, price: 40_000, currency: "USD")
+
+ assert_no_difference "@account.entries.count" do
+ process
+ end
+
+ trade.reload
+ assert_in_delta 40_000.0, trade.price.to_f, 0.01
+ assert_nil trade.extra.dig("kraken", "price_missing")
+ end
+
+ # An account synced before this change holds the coin movement as a
+ # Transaction: a cash leg that never existed, and a quantity the holdings never
+ # saw. A plain sync replaces it, so nobody has to re-import to be right.
+ test "a legacy crypto transaction is replaced by the trade on the next sync" do
+ set_ledgers(
+ "LBTC10" => ledger_entry(type: "deposit", asset: "XXBT", amount: "0.10000000", fee: "0.00000000", time: 1_700_000_000)
+ )
+ legacy = @account.entries.create!(
+ date: Time.zone.at(1_700_000_000).to_date, name: "Deposit 0.1 BTC", amount: -4_000, currency: "EUR",
+ external_id: "kraken_ledger_LBTC10", source: "kraken",
+ entryable: Transaction.new(kind: "funds_movement")
+ )
+
+ assert_no_difference "@account.entries.count" do
+ process
+ end
+
+ assert_nil Entry.find_by(id: legacy.id), "the old cash row must be gone"
+ entry = @account.entries.find_by(external_id: "kraken_ledger_LBTC10", source: "kraken")
+ assert_equal "Trade", entry.entryable_type
+ assert_equal 0, entry.amount
+ assert_in_delta 0.1, entry.entryable.qty.to_f, 1e-8
+ end
+
+ # A row somebody has matched into a transfer, or edited, is theirs: it stays
+ # as it is even though it is the old shape.
+ # The early return for rows already in fires before the ledger type is
+ # looked at; a row in an older shape has to get past it whatever its type.
+ test "a legacy crypto staking reward is replaced by the trade too" do
+ set_ledgers(
+ "LSTK10" => ledger_entry(type: "staking", asset: "XXBT", amount: "0.00100000", fee: "0.00000000", time: 1_700_000_000)
+ )
+ legacy = @account.entries.create!(
+ date: Time.zone.at(1_700_000_000).to_date, name: "Staking reward 0.001 BTC", amount: -40, currency: "EUR",
+ external_id: "kraken_ledger_LSTK10", source: "kraken",
+ entryable: Transaction.new(kind: "standard")
+ )
+
+ assert_no_difference "@account.entries.count" do
+ process
+ end
+
+ assert_nil Entry.find_by(id: legacy.id)
+ entry = @account.entries.find_by(external_id: "kraken_ledger_LSTK10", source: "kraken")
+ assert_equal "Trade", entry.entryable_type
+ assert_in_delta 0.001, entry.entryable.qty.to_f, 1e-8
+ end
+
+ test "a staking trade recorded without a price is priced on a later sync too" do
+ set_raw_payload_assets([])
+ set_ledgers(
+ "LSTK20" => ledger_entry(type: "staking", asset: "XXBT", amount: "0.00100000", fee: "0.00000000", time: 1_700_000_000)
+ )
+ process
+ trade = @account.entries.find_by(external_id: "kraken_ledger_LSTK20", source: "kraken").entryable
+ assert trade.extra.dig("kraken", "price_missing")
+
+ Security::Price.create!(security: trade.security, date: Time.zone.at(1_700_000_000).to_date, price: 40_000, currency: "USD")
+ assert_no_difference "@account.entries.count" do
+ process
+ end
+
+ assert_in_delta 40_000.0, trade.reload.price.to_f, 0.01
+ assert_nil trade.extra.dig("kraken", "price_missing")
+ end
+
+ # Before fees stayed inside the quantity, a crypto withdrawal with a fee was
+ # two cash rows. The trade nets the fee, so the fee row must go with the
+ # principal or it is left describing money that never moved.
+ test "healing a legacy crypto withdrawal removes its split fee row as well" do
+ set_ledgers(
+ "LBTC40" => ledger_entry(type: "withdrawal", asset: "XXBT", amount: "-0.10000000", fee: "0.00050000", time: 1_700_000_000)
+ )
+ date = Time.zone.at(1_700_000_000).to_date
+ legacy = @account.entries.create!(
+ date: date, name: "Withdrawal 0.1 BTC", amount: 4_000, currency: "EUR",
+ external_id: "kraken_ledger_LBTC40", source: "kraken", entryable: Transaction.new(kind: "funds_movement")
+ )
+ legacy_fee = @account.entries.create!(
+ date: date, name: "Withdrawal fee 0.0005 BTC", amount: 20, currency: "EUR",
+ external_id: "kraken_ledger_LBTC40_fee", source: "kraken", entryable: Transaction.new(kind: "standard")
+ )
+
+ assert_difference "@account.entries.count", -1 do
+ process
+ end
+
+ assert_nil Entry.find_by(id: legacy.id)
+ assert_nil Entry.find_by(id: legacy_fee.id), "the fee row describes money the trade already accounts for"
+ entry = @account.entries.find_by(external_id: "kraken_ledger_LBTC40", source: "kraken")
+ assert_equal "Trade", entry.entryable_type
+ assert_in_delta(-0.1005, entry.entryable.qty.to_f, 1e-8, "the fee left with the coins")
+
+ # Nothing to heal on the next pass.
+ assert_no_difference "@account.entries.count" do
+ process
+ end
+ end
+
+ test "a legacy crypto transaction in a transfer, or edited, is left alone" do
+ set_ledgers(
+ "LBTC11" => ledger_entry(type: "withdrawal", asset: "XXBT", amount: "-0.05000000", fee: "0.00000000", time: 1_700_000_000),
+ "LBTC12" => ledger_entry(type: "deposit", asset: "XXBT", amount: "0.02000000", fee: "0.00000000", time: 1_700_000_100)
+ )
+ outflow = @account.entries.create!(
+ date: Time.zone.at(1_700_000_000).to_date, name: "Withdrawal 0.05 BTC", amount: 2_000, currency: "EUR",
+ external_id: "kraken_ledger_LBTC11", source: "kraken", entryable: Transaction.new(kind: "funds_movement")
+ )
+ # A transfer needs the other leg on another account of the same family.
+ wallet = @account.family.accounts.create!(name: "Cold wallet", balance: 0, currency: "EUR", accountable: Depository.new)
+ inflow = wallet.entries.create!(
+ date: Time.zone.at(1_700_000_000).to_date, name: "Received 0.05 BTC", amount: -2_000, currency: "EUR",
+ entryable: Transaction.new(kind: "funds_movement")
+ )
+ Transfer.create!(inflow_transaction: inflow.entryable, outflow_transaction: outflow.entryable)
+ edited = @account.entries.create!(
+ date: Time.zone.at(1_700_000_100).to_date, name: "Deposit 0.02 BTC", amount: -800, currency: "EUR",
+ external_id: "kraken_ledger_LBTC12", source: "kraken", user_modified: true,
+ entryable: Transaction.new(kind: "funds_movement")
+ )
+
+ assert_no_difference "@account.entries.count" do
+ process
+ end
+
+ assert_equal "Transaction", outflow.reload.entryable_type
+ assert_equal 2_000, outflow.amount
+ assert_equal "Transaction", edited.reload.entryable_type
+ assert_equal(-800, edited.amount)
+ end
+
+ # The price is the one on the day the units moved, read from the prices
+ # already in the database; the provider is asked once per asset for the
+ # whole span, not once per entry.
+ test "a crypto trade is priced from the stored price on its date" do
+ security = Security.create!(ticker: "CRYPTO:BTC", name: "BTC")
+ Security::Price.create!(security: security, date: Time.zone.at(1_700_000_000).to_date, price: 40_000, currency: "USD")
+ Security.any_instance.expects(:find_or_fetch_price).never
+
+ set_ledgers(
+ "LBTC03" => ledger_entry(type: "staking", asset: "XXBT", amount: "0.00100000", fee: "0.00", time: 1_700_000_000)
+ )
+
+ process
+
+ trade = @account.entries.find_by(external_id: "kraken_ledger_LBTC03", source: "kraken").entryable
+ assert_in_delta 40_000.0, trade.price.to_f, 0.01
+ assert_not trade.extra.dig("kraken", "price_missing")
+ end
+
+ # Kraken's amounts are signed and some rows move against their type's usual
+ # direction; the quantity follows the figure, not the label.
+ test "a crypto row's direction follows the ledger's signed amount, not its type" do
+ set_ledgers(
+ "LREV01" => ledger_entry(type: "withdrawal", asset: "XXBT", amount: "0.05000000", fee: "0.00000000", time: 1_700_000_000),
+ "LMIG01" => ledger_entry(type: "earn", subtype: "migration", asset: "XXBT", amount: "-0.02000000", fee: "0.00000000", time: 1_700_000_100)
+ )
+
+ process
+
+ reversed = @account.entries.find_by(external_id: "kraken_ledger_LREV01", source: "kraken")
+ assert_in_delta 0.05, reversed.entryable.qty.to_f, 1e-8, "a reversed withdrawal brings the coins back"
+ migration = @account.entries.find_by(external_id: "kraken_ledger_LMIG01", source: "kraken")
+ assert_in_delta(-0.02, migration.entryable.qty.to_f, 1e-8, "a migration leg with a negative amount gives units up")
+ end
+
+ test "a BTC withdrawal becomes a trade that gives up units" do
+ set_ledgers(
+ "LBTC02" => ledger_entry(type: "withdrawal", asset: "XXBT", amount: "-0.20000000", fee: "0.00000000", time: 1_700_000_000)
+ )
+
+ process
+
+ entry = @account.entries.find_by(external_id: "kraken_ledger_LBTC02", source: "kraken")
+ assert_equal "Trade", entry.entryable_type
+ assert_equal 0, entry.amount
+ assert_in_delta(-0.2, entry.entryable.qty.to_f, 1e-8)
+ end
+
+ # A fiat deposit still has a cash leg and stays a Transaction.
+ test "a fiat deposit is still a cash entry" do
+ set_ledgers(
+ "LUSD01" => ledger_entry(type: "deposit", asset: "ZUSD", amount: "250.00", fee: "0.00", time: 1_700_000_000)
+ )
+
+ process
+
+ entry = @account.entries.find_by(external_id: "kraken_ledger_LUSD01", source: "kraken")
+ assert_equal "Transaction", entry.entryable_type
+ assert_in_delta(-250.0, entry.amount.to_f, 0.01)
+ end
+
# ---------------------------------------------------------------------------
# staking
# ---------------------------------------------------------------------------
- test "creates a staking reward entry (negative = inflow)" do
+ # A staking reward pays coins, not euros. It is acquired at the market price
+ # on the day, which is both its basis and the income it represents.
+ test "a crypto staking reward becomes a trade that adds units" do
set_ledgers(
"LSTK01" => ledger_entry(type: "staking", asset: "XXBT", amount: "0.00050000", fee: "0.00", time: 1_700_000_000)
)
@@ -318,10 +555,24 @@ class KrakenAccount::LedgerProcessorTest < ActiveSupport::TestCase
entry = @account.entries.find_by(external_id: "kraken_ledger_LSTK01", source: "kraken")
assert entry
- assert entry.amount.negative?, "staking reward is an inflow — must be negative"
+ assert_equal "Trade", entry.entryable_type
+ assert_equal 0, entry.amount
+ assert_in_delta 0.0005, entry.entryable.qty.to_f, 1e-9
assert_match(/Staking reward.*BTC/, entry.name)
assert_equal "Dividend", entry.entryable.investment_activity_label
- assert_equal "standard", entry.entryable.kind
+ end
+
+ test "a fiat staking reward is still a cash entry" do
+ set_ledgers(
+ "LSTK03" => ledger_entry(type: "staking", asset: "ZUSD", amount: "4.00", fee: "0.00", time: 1_700_000_000)
+ )
+
+ process
+
+ entry = @account.entries.find_by(external_id: "kraken_ledger_LSTK03", source: "kraken")
+ assert_equal "Transaction", entry.entryable_type
+ assert_in_delta(-4.0, entry.amount.to_f, 0.01)
+ assert_equal "standard", entry.entryable.kind
end
# ---------------------------------------------------------------------------
@@ -374,6 +625,61 @@ class KrakenAccount::LedgerProcessorTest < ActiveSupport::TestCase
assert_equal "Fee", entry.entryable.investment_activity_label
end
+ # ---------------------------------------------------------------------------
+ # dust sweep
+ # ---------------------------------------------------------------------------
+
+ # "Convert small balances" emits a spend and a receive. Neither type was
+ # listed as supported or as skipped, so both fell through the guard and were
+ # dropped without a trace -- a swept position stayed on the books at its
+ # pre-sweep quantity forever.
+ test "imports both halves of a dust sweep" do
+ set_ledgers(
+ "LSWP01" => ledger_entry(type: "spend", asset: "XXBT", amount: "-0.00010000", fee: "0.00", time: 1_700_000_000),
+ "LSWP02" => ledger_entry(type: "receive", asset: "XXBT", amount: "0.00004000", fee: "0.00", time: 1_700_000_000)
+ )
+
+ assert_difference "@account.entries.count", 2 do
+ process
+ end
+
+ spent = @account.entries.find_by(external_id: "kraken_ledger_LSWP01", source: "kraken")
+ assert_in_delta(-0.0001, spent.entryable.qty.to_f, 1e-9)
+ assert_match(/Converted/, spent.name)
+
+ received = @account.entries.find_by(external_id: "kraken_ledger_LSWP02", source: "kraken")
+ assert_in_delta 0.00004, received.entryable.qty.to_f, 1e-9
+ assert_match(/Received/, received.name)
+ end
+
+ # Both halves stay inside the exchange, so neither invents a cost basis.
+ test "a dust sweep is an internal movement on both sides" do
+ set_ledgers(
+ "LSWP03" => ledger_entry(type: "spend", asset: "XXBT", amount: "-0.00010000", fee: "0.00", time: 1_700_000_000),
+ "LSWP04" => ledger_entry(type: "receive", asset: "XXBT", amount: "0.00004000", fee: "0.00", time: 1_700_000_000)
+ )
+
+ process
+
+ %w[LSWP03 LSWP04].each do |id|
+ trade = @account.entries.find_by(external_id: "kraken_ledger_#{id}", source: "kraken").entryable
+ assert trade.internal_movement?, "#{id} must not create or relieve a cost basis"
+ end
+ end
+
+ # Kraken sweeps into crypto today, but a fiat half must not read as income.
+ test "a fiat half of a sweep is labelled as the internal movement it is" do
+ set_ledgers(
+ "LSWP05" => ledger_entry(type: "receive", asset: "ZUSD", amount: "3.00", fee: "0.00", time: 1_700_000_000)
+ )
+
+ process
+
+ entry = @account.entries.find_by(external_id: "kraken_ledger_LSWP05", source: "kraken")
+ assert_equal "Transaction", entry.entryable_type
+ assert_equal "Sweep In", entry.entryable.investment_activity_label
+ end
+
# ---------------------------------------------------------------------------
# skipped types
# ---------------------------------------------------------------------------