Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Coinbase: import full transaction history and all activity types, (#4660)

Avalanche Ridings99475ba6feb5
diff --git a/app/models/coinbase_account/processor.rb b/app/models/coinbase_account/processor.rb
index a817534c0b..42f604dc01 100644
--- a/app/models/coinbase_account/processor.rb
+++ b/app/models/coinbase_account/processor.rb
@@ -3,6 +3,69 @@
class CoinbaseAccount::Processor
include CurrencyNormalizable
+ # Maps Coinbase transaction types outside buy/sell to Sure's Trade
+ # activity labels (see Trade::ACTIVITY_LABELS), so an account funded
+ # mostly by staking rewards shows how its balance actually built up
+ # over time instead of a single balance snapshot.
+ #
+ # staking_reward -> Dividend (income, paid in the held asset)
+ # interest -> Interest (exact match)
+ # pro_deposit/pro_withdrawal,
+ # staking_transfer/unstaking_transfer -> Transfer (moved between the user's own
+ # Coinbase/Coinbase Pro/staking sub-accounts;
+ # ownership preserved, no cost basis - see
+ # Trade::TRANSFER_LABEL)
+ # exchange_deposit -> Transfer (same asset, moved to another
+ # exchange the user controls)
+ # asset_migration -> Exchange (security-for-security swap,
+ # e.g. a token rebrand)
+ # exchange_withdrawal -> Transfer (same asset, moved to another
+ # exchange the user controls - the withdrawal
+ # side of exchange_deposit above)
+ # vault_withdrawal -> Transfer (moved out of Coinbase Vault,
+ # another of the user's own sub-accounts)
+ # send -> Transfer (could be a reward relabeled as
+ # "send" - seen in real data - or a genuine
+ # external transfer; no reliable way to tell
+ # from the payload. "Other" would be worse:
+ # Trade::INTERNAL_MOVEMENT_LABELS doesn't
+ # include it, so #internal_movement? would
+ # see a real buy/sell and let it fabricate a
+ # cost-basis event from an ambiguous signal -
+ # exactly what this whole map exists to avoid)
+ #
+ # Deliberately not handled: fiat_deposit/fiat_withdrawal move real cash, not
+ # a crypto asset. CoinbaseAccount models a crypto wallet whose cash_balance
+ # is always zero (see #process_account!), so a fiat movement needs a plain
+ # cash Transaction entry on a different account, not a Trade here; that's
+ # outside what this crypto-focused processor can represent today.
+ ACTIVITY_LABEL_BY_COINBASE_TXN_TYPE = {
+ "staking_reward" => "Dividend",
+ "interest" => "Interest",
+ "pro_deposit" => "Transfer",
+ "pro_withdrawal" => "Transfer",
+ "staking_transfer" => "Transfer",
+ "unstaking_transfer" => "Transfer",
+ "exchange_deposit" => "Transfer",
+ "exchange_withdrawal" => "Transfer",
+ "vault_withdrawal" => "Transfer",
+ "asset_migration" => "Exchange",
+ "send" => "Transfer"
+ }.freeze
+
+ # Dividend/Interest are real income paid in-kind rather than cash, but
+ # InvestmentStatement::Totals reports dividends/interest as -SUM(entries.amount)
+ # (see investment_statement/totals.rb) - zeroing amount for every label here
+ # would make every imported staking reward look like $0 of income. Only the
+ # Transfer/Exchange labels are genuinely cash-neutral (see amount: below).
+ INCOME_LABELS = %w[Dividend Interest].freeze
+
+ # Coinbase's transactions endpoint sometimes describes one real Pro/staking
+ # transfer as two records in the same batch: a generic "send" plus a
+ # specific pro_deposit/pro_withdrawal/etc with the same date+amount+currency.
+ # Used by #shadowed_by_specific_transfer? to de-dupe those.
+ SPECIFIC_TRANSFER_TYPES = %w[pro_deposit pro_withdrawal staking_transfer unstaking_transfer exchange_deposit].freeze
+
attr_reader :coinbase_account
# @param coinbase_account [CoinbaseAccount] Account to process
@@ -146,15 +209,193 @@ class CoinbaseAccount::Processor
report_exception(e, "trades")
end
- # Process a transaction from the /v2/accounts/{id}/transactions endpoint
+ # Process a transaction from the /v2/accounts/{id}/transactions endpoint.
+ # Buy/sell go through the trade-specific path below; every other
+ # completed type (staking_reward, interest, send, pro_deposit/withdrawal,
+ # exchange_deposit, asset_migration, staking/unstaking_transfer) is
+ # imported as a generic activity via #process_other_transaction_type
+ # instead of being silently dropped.
def process_transaction(txn_data)
+ if %w[buy sell].include?(txn_data["type"])
+ process_buy_sell_transaction(txn_data)
+ else
+ process_other_transaction_type(txn_data)
+ end
+ end
+
+ # Handles every non-buy/sell completed transaction type using Coinbase's
+ # own amount sign (positive = received into this wallet, negative = left
+ # it - confirmed against real payloads for every type in
+ # ACTIVITY_LABEL_BY_COINBASE_TXN_TYPE, no from/to parsing needed).
+ def process_other_transaction_type(txn_data)
+ return unless txn_data["status"] == "completed"
+
+ account = coinbase_account.current_account
+ return unless account
+
+ txn_type = txn_data["type"]
+ label = ACTIVITY_LABEL_BY_COINBASE_TXN_TYPE[txn_type]
+ return unless label # unknown type - skip rather than guess
+
+ raw_qty = txn_data.dig("amount", "amount").to_d
+ return if raw_qty.zero?
+
+ # Confirmed against real data: only a minority of "send" entries are
+ # duplicates of a specific-type sibling (most are standalone, e.g. Earn
+ # rewards tagged as "send") - so only skip a "send" when a specific-type
+ # sibling actually matches it. Reconciling an already-imported duplicate
+ # happens from the sibling's own side below, once it's confirmed saved -
+ # never eagerly here: destroying the send before confirming the sibling
+ # actually persists would leave the account with neither entry if the
+ # sibling's own import then failed.
+ return if txn_type == "send" && shadowed_by_specific_transfer?(txn_data)
+
+ security = find_or_create_security(txn_data)
+ return unless security
+
+ external_id = "coinbase_txn_#{txn_data['id']}"
+ if account.entries.exists?(external_id: external_id)
+ reconcile_shadowed_sends(account, txn_data) if SPECIFIC_TRANSFER_TYPES.include?(txn_type)
+ return
+ end
+
+ date = Time.zone.parse(txn_data["created_at"]).to_date
+ qty = raw_qty.abs
+ native_amount = txn_data.dig("native_amount", "amount").to_d.abs
+ price = qty > 0 ? (native_amount / qty).round(8) : 0
+ txn_currency = txn_data.dig("native_amount", "currency") || native_currency
+ received = raw_qty.positive?
+
+ # Transfer/Exchange move an asset the account already owns between its
+ # own sub-ledgers (Trade::INTERNAL_MOVEMENT_LABELS) or swap it for an
+ # equivalent one -- no real purchase or sale, so a real cash amount
+ # would invent a cost basis backed by no actual cash, and since the two
+ # legs of an internal transfer almost never share the same market
+ # price, it'd also leave a phantom, permanent cash drift every time one
+ # round-trips. Dividend/Interest is real income, just paid in-kind
+ # instead of cash -- InvestmentStatement::Totals reports it as
+ # -SUM(entries.amount), so zeroing it here would make every imported
+ # staking reward look like $0 of income. Same sign convention as a Buy:
+ # negative when received, since nothing here was paid for in cash.
+ amount = INCOME_LABELS.include?(label) ? (received ? -native_amount : native_amount) : 0
+
+ notes_parts = []
+ notes_parts << txn_data["description"] if txn_data["description"].present?
+ notes_parts << txn_type.humanize
+ notes = notes_parts.join(" - ").presence
+
+ account.entries.create!(
+ date: date,
+ name: "#{received ? "Received" : "Sent"} #{qty.round(8)} #{security.ticker} (#{txn_type.humanize})",
+ amount: amount,
+ currency: txn_currency,
+ external_id: external_id,
+ source: "coinbase",
+ notes: notes,
+ entryable: Trade.new(
+ security: security,
+ qty: received ? qty : -qty,
+ price: price,
+ currency: txn_currency,
+ investment_activity_label: label
+ )
+ )
+ Rails.logger.info(
+ "CoinbaseAccount::Processor - Created #{txn_type} entry: #{raw_qty} #{security.ticker} @ #{price} #{txn_currency}"
+ )
+ reconcile_shadowed_sends(account, txn_data) if SPECIFIC_TRANSFER_TYPES.include?(txn_type)
+ rescue => e
+ Rails.logger.error "CoinbaseAccount::Processor - Failed to process #{txn_data['type']} transaction #{txn_data['id']}: #{e.message}"
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "Failed to process #{txn_data['type']} transaction #{txn_data['id']}: #{e.message}",
+ source: self.class.name,
+ provider_key: "coinbase",
+ family: coinbase_account.coinbase_item.family,
+ account_provider: coinbase_account.account_provider,
+ metadata: { coinbase_account_id: coinbase_account.id, coinbase_txn_id: txn_data["id"], txn_type: txn_data["type"] }
+ )
+ end
+
+ # True when sibling_a and sibling_b describe the same date+amount+currency
+ # leg - the shape Coinbase uses to double-log one real Pro/staking/vault
+ # transfer as two records in the same batch (see SPECIFIC_TRANSFER_TYPES).
+ # Matches on the *signed* amount, not its absolute value: both records
+ # log the same leg with the same sign, so comparing magnitude alone would
+ # also match an unrelated same-day transaction in the opposite direction
+ # for the same amount and currency, confusing two independent events.
+ def same_transfer_leg?(sibling_a, sibling_b)
+ sibling_a["created_at"].to_s[0, 10] == sibling_b["created_at"].to_s[0, 10] &&
+ sibling_a.dig("amount", "amount").to_d == sibling_b.dig("amount", "amount").to_d &&
+ sibling_a.dig("amount", "currency") == sibling_b.dig("amount", "currency")
+ end
+
+ # True when txn_data (a "send") describes the same transfer as a
+ # specific pro_deposit/pro_withdrawal/staking_transfer/etc sibling in the
+ # same batch. A sibling still pending/failed/canceled can't shadow
+ # anything either -- only a completed one actually happened.
+ def shadowed_by_specific_transfer?(txn_data)
+ siblings = coinbase_account.raw_transactions_payload&.dig("transactions") || []
+
+ siblings.any? do |sibling|
+ next false if sibling["id"] == txn_data["id"]
+ next false unless SPECIFIC_TRANSFER_TYPES.include?(sibling["type"])
+ next false unless sibling["status"] == "completed"
+ same_transfer_leg?(sibling, txn_data)
+ end
+ end
+
+ # The "send" siblings that txn_data (a specific-type transfer whose own
+ # entry has just been confirmed saved, created or already existing)
+ # shadows - the inverse of #shadowed_by_specific_transfer?, used once the
+ # sibling side of the duplicate is itself confirmed, not from the send's
+ # own processing.
+ def shadowed_sends(txn_data)
+ siblings = coinbase_account.raw_transactions_payload&.dig("transactions") || []
+
+ siblings.select do |sibling|
+ sibling["id"] != txn_data["id"] &&
+ sibling["type"] == "send" &&
+ sibling["status"] == "completed" &&
+ same_transfer_leg?(sibling, txn_data)
+ end
+ end
+
+ # Removes any previously-imported "send" entries now shadowed by
+ # txn_data, a specific-transfer sibling whose own entry is confirmed
+ # saved. Deferred to here rather than run eagerly from the send's own
+ # processing: destroying a send before confirming its sibling actually
+ # persists would leave the account with neither entry if the sibling's
+ # own import then failed. A rate-limited partial fetch can import the
+ # send before the sibling is ever reachable in the same batch; once a
+ # later, more complete sync saves the sibling, leaving both would
+ # double-count one real transfer as two entries.
+ def reconcile_shadowed_sends(account, txn_data)
+ shadowed_sends(txn_data).each do |send_txn|
+ external_id = "coinbase_txn_#{send_txn['id']}"
+ shadowed = account.entries.find_by(external_id: external_id)
+ next unless shadowed
+ # A user who excluded or edited this entry made a deliberate choice;
+ # sync-driven reconciliation must not silently override it, same as
+ # every other provider's sync code respects Entry#protected_from_sync?.
+ next if shadowed.protected_from_sync?
+
+ shadowed.destroy!
+ Rails.logger.info(
+ "CoinbaseAccount::Processor - Removed send #{send_txn['id']}, now shadowed by a specific transfer"
+ )
+ end
+ end
+
+ # Buy/sell transaction handling (trade with a cost-basis-relevant price).
+ def process_buy_sell_transaction(txn_data)
return unless txn_data["status"] == "completed"
account = coinbase_account.current_account
return unless account
txn_type = txn_data["type"]
- return unless %w[buy sell].include?(txn_type)
# Get or create the security for this crypto
security = find_or_create_security(txn_data)
diff --git a/app/models/coinbase_item/importer.rb b/app/models/coinbase_item/importer.rb
index 138c942e31..bf8708b879 100644
--- a/app/models/coinbase_item/importer.rb
+++ b/app/models/coinbase_item/importer.rb
@@ -1,6 +1,16 @@
# Imports wallet/account data from Coinbase API.
# Fetches accounts, balances, and transaction history.
class CoinbaseItem::Importer
+ # Coinbase's /v2/accounts/{id}/transactions endpoint returns newest-first,
+ # so a low limit silently drops older history for any wallet with more
+ # lifetime transactions than that (e.g. one funded by frequent staking
+ # rewards) - it's never even fetched, let alone processed by
+ # CoinbaseAccount::Processor. 5000 comfortably covers even a multi-year
+ # daily-staking-reward history without risking an unbounded loop against
+ # Coinbase's API; Provider::Coinbase#get_transactions already paginates up
+ # to whatever limit it's given, following Coinbase's next_uri cursor.
+ FULL_HISTORY_LIMIT = 5000
+
attr_reader :coinbase_item, :coinbase_provider
# @param coinbase_item [CoinbaseItem] Item containing accounts to import
@@ -50,9 +60,7 @@ class CoinbaseItem::Importer
private
def import_account(account_data)
- # Skip accounts with zero balance unless they have transaction history
balance = account_data.dig("balance", "amount").to_d
- return if balance.zero? && account_data.dig("balance", "currency") != "USD"
# Find or create the coinbase_account record
coinbase_account = coinbase_item.coinbase_accounts.find_or_initialize_by(
@@ -80,10 +88,11 @@ class CoinbaseItem::Importer
}
)
- # Fetch transactions for this account if it has a balance
- if balance > 0
- fetch_and_store_transactions(coinbase_account, account_data["id"])
- end
+ # Fetch transactions for every account, regardless of current balance:
+ # a wallet that was fully sold or transferred out still needs its
+ # history imported to reconstruct realized gains, and a balance of
+ # zero here says nothing about whether that history exists.
+ fetch_and_store_transactions(coinbase_account, account_data["id"])
coinbase_account.save!
end
@@ -91,19 +100,58 @@ class CoinbaseItem::Importer
def fetch_and_store_transactions(coinbase_account, account_id)
# Fetch transactions for this account (includes buys, sells, sends, receives)
# This endpoint returns better data than separate buys/sells endpoints
- transactions = coinbase_provider.get_transactions(account_id, limit: 100)
+ transactions = coinbase_provider.get_transactions(account_id, limit: FULL_HISTORY_LIMIT)
+ store_transactions(coinbase_account, transactions)
+ rescue Provider::Coinbase::PartialResultError => e
+ # A rate limit hit a later page after earlier ones already succeeded;
+ # Provider::Coinbase#paginated_get hands back those earlier pages
+ # instead of discarding them. Transactions are newest-first, so a
+ # *shorter* partial fetch can still contain genuinely new transactions
+ # the last stored history doesn't have -- comparing sizes to decide
+ # whether to keep it would silently drop those. Merge by id instead:
+ # every stored transaction is kept, every new one is added, and an id
+ # present in both takes the freshly-fetched version.
+ merged = merge_transactions(coinbase_account, e.partial_results)
+ store_transactions(coinbase_account, merged, truncated: true)
+ record_transactions_incident(coinbase_account, e, account_id, partial: true)
+ rescue Provider::Coinbase::ApiError, Provider::Coinbase::RateLimitError => e
+ # RateLimitError is a sibling of ApiError (both < Provider::Coinbase::Error),
+ # not a subclass, so it has to be listed explicitly here. Without it, a
+ # 429 on this call propagates past coinbase_account.save! below, so this
+ # account's balance update -- already fetched correctly above -- gets
+ # silently skipped for the whole sync along with the transaction fetch.
+ record_transactions_incident(coinbase_account, e, account_id)
+ end
+
+ def merge_transactions(coinbase_account, incoming)
+ stored = coinbase_account.raw_transactions_payload&.dig("transactions") || []
+ by_id = stored.index_by { |txn| txn["id"] }
+ incoming.each { |txn| by_id[txn["id"]] = txn }
+ by_id.values
+ end
- # Store raw transaction data for processing later
+ def store_transactions(coinbase_account, transactions, truncated: false)
coinbase_account.raw_transactions_payload = {
"transactions" => transactions,
- "fetched_at" => Time.current.iso8601
+ "fetched_at" => Time.current.iso8601,
+ "truncated" => truncated
}
Rails.logger.info(
- "CoinbaseItem::Importer - Fetched #{transactions.count} transactions for #{coinbase_account.name}"
+ "CoinbaseItem::Importer - Fetched #{transactions.count} transactions for #{coinbase_account.name}#{" (truncated by a rate limit)" if truncated}"
+ )
+ end
+
+ def record_transactions_incident(coinbase_account, error, account_id, partial: false)
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "#{partial ? "Partial" : "No"} transactions fetched this sync (#{error.class.name.demodulize}) for account #{account_id}: #{error.message}",
+ source: self.class.name,
+ provider_key: "coinbase",
+ family: coinbase_item.family,
+ account_provider: coinbase_account.account_provider,
+ metadata: { coinbase_item_id: coinbase_item.id, account_id: account_id }
)
- rescue Provider::Coinbase::ApiError => e
- # Some accounts may not support transaction endpoints
- Rails.logger.debug "CoinbaseItem::Importer - Could not fetch transactions for account #{account_id}: #{e.message}"
end
end
diff --git a/app/models/provider/coinbase.rb b/app/models/provider/coinbase.rb
index 2ebd3fb4b5..9598856a4a 100644
--- a/app/models/provider/coinbase.rb
+++ b/app/models/provider/coinbase.rb
@@ -7,6 +7,19 @@ class Provider::Coinbase
class RateLimitError < Error; end
class ApiError < Error; end
+ # Raised instead of RateLimitError when a rate limit hits a later page of a
+ # paginated fetch after earlier pages already succeeded -- see
+ # #paginated_get. Carries those earlier pages so a caller can keep them
+ # instead of the fetch as a whole discarding real, already-fetched data.
+ class PartialResultError < Error
+ attr_reader :partial_results
+
+ def initialize(message, partial_results)
+ super(message)
+ @partial_results = partial_results
+ end
+ end
+
# CDP API base URL
API_BASE_URL = "https://api.coinbase.com".freeze
@@ -129,6 +142,14 @@ class Provider::Coinbase
end
results.first(limit)
+ rescue RateLimitError => e
+ # Earlier pages already fetched are real data -- raising RateLimitError
+ # here as before would discard them along with the pages never reached,
+ # forcing every later sync to restart this backfill from page one.
+ # Nothing to preserve on a first-page limit, so that case still raises
+ # RateLimitError exactly as before.
+ raise PartialResultError.new(e.message, results.first(limit)) if results.any?
+ raise
end
# Parses a PEM EC private key, normalizing literal \n sequences to real
diff --git a/test/models/coinbase_account/processor_test.rb b/test/models/coinbase_account/processor_test.rb
index 75053bff5b..70f413b788 100644
--- a/test/models/coinbase_account/processor_test.rb
+++ b/test/models/coinbase_account/processor_test.rb
@@ -102,4 +102,191 @@ class CoinbaseAccount::ProcessorTest < ActiveSupport::TestCase
holding = @account.holdings.find_by!(security: @security, date: Date.current)
assert_equal quantity, holding.qty
end
+
+ test "imports a staking reward with its native value as income, not zero" do
+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)
+ @coinbase_account.update!(raw_transactions_payload: {
+ "transactions" => [
+ coinbase_txn(id: "txn_reward_1", type: "staking_reward", btc_amount: "0.001", native_amount: "66.58")
+ ]
+ })
+
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+
+ entry = @account.entries.find_by!(external_id: "coinbase_txn_txn_reward_1")
+ assert_equal "Dividend", entry.entryable.investment_activity_label
+ assert_equal BigDecimal("-66.58"), entry.amount
+ assert_equal BigDecimal("0.001"), entry.entryable.qty
+ end
+
+ test "maps an ambiguous send to Transfer instead of a cost-basis-affecting Other" do
+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)
+ @coinbase_account.update!(raw_transactions_payload: {
+ "transactions" => [
+ coinbase_txn(id: "txn_send_1", type: "send", btc_amount: "0.01", native_amount: "665.80")
+ ]
+ })
+
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+
+ entry = @account.entries.find_by!(external_id: "coinbase_txn_txn_send_1")
+ assert_equal "Transfer", entry.entryable.investment_activity_label
+ assert entry.entryable.internal_movement?
+ assert_equal 0.to_d, entry.amount
+ end
+
+ test "imports exchange_withdrawal and vault_withdrawal instead of dropping them" do
+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)
+ @coinbase_account.update!(raw_transactions_payload: {
+ "transactions" => [
+ coinbase_txn(id: "txn_ew", type: "exchange_withdrawal", btc_amount: "-0.02", native_amount: "1331.60"),
+ coinbase_txn(id: "txn_vw", type: "vault_withdrawal", btc_amount: "-0.03", native_amount: "1997.40")
+ ]
+ })
+
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_ew")
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_vw")
+ end
+
+ test "does not shadow a send with an opposite-direction transfer of the same magnitude" do
+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)
+ @coinbase_account.update!(raw_transactions_payload: {
+ "transactions" => [
+ coinbase_txn(id: "txn_send_real", type: "send", btc_amount: "0.01", native_amount: "665.80"),
+ coinbase_txn(id: "txn_pro_withdraw", type: "pro_withdrawal", btc_amount: "-0.01", native_amount: "665.80")
+ ]
+ })
+
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_send_real"),
+ "an unrelated same-day transfer in the opposite direction must not shadow a real send"
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_pro_withdraw")
+ end
+
+ test "still shadows a send that duplicates a specific completed transfer in the same direction" do
+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)
+ @coinbase_account.update!(raw_transactions_payload: {
+ "transactions" => [
+ coinbase_txn(id: "txn_send_dup", type: "send", btc_amount: "-0.01", native_amount: "665.80"),
+ coinbase_txn(id: "txn_pro_withdraw_dup", type: "pro_withdrawal", btc_amount: "-0.01", native_amount: "665.80")
+ ]
+ })
+
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+
+ refute @account.entries.exists?(external_id: "coinbase_txn_txn_send_dup")
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_pro_withdraw_dup")
+ end
+
+ test "does not let a pending sibling shadow a completed send" do
+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)
+ @coinbase_account.update!(raw_transactions_payload: {
+ "transactions" => [
+ coinbase_txn(id: "txn_send_pending_sib", type: "send", btc_amount: "-0.01", native_amount: "665.80"),
+ coinbase_txn(id: "txn_pro_pending", type: "pro_withdrawal", btc_amount: "-0.01", native_amount: "665.80", status: "pending")
+ ]
+ })
+
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_send_pending_sib"),
+ "a pending sibling never actually happened, so it can't shadow anything"
+ end
+
+ test "removes a previously-imported send once its matching transfer becomes visible" do
+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)
+ send_txn = coinbase_txn(id: "txn_send_later_shadowed", type: "send", btc_amount: "-0.01", native_amount: "665.80")
+ sibling_txn = coinbase_txn(id: "txn_pro_withdraw_later", type: "pro_withdrawal", btc_amount: "-0.01", native_amount: "665.80")
+
+ # A rate-limited partial fetch (Provider::Coinbase::PartialResultError)
+ # can import this send on one sync before its sibling is ever fetched,
+ # so it isn't shadowed yet.
+ @coinbase_account.update!(raw_transactions_payload: { "transactions" => [ send_txn ] })
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_send_later_shadowed")
+
+ # A later, more complete sync makes the sibling visible. The send is now
+ # shadowed -- its stale duplicate must be removed, leaving only the
+ # sibling's own entry.
+ @coinbase_account.update!(raw_transactions_payload: { "transactions" => [ send_txn, sibling_txn ] })
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+
+ refute @account.entries.exists?(external_id: "coinbase_txn_txn_send_later_shadowed")
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_pro_withdraw_later")
+ end
+
+ test "keeps the send when its matching transfer sibling fails to import" do
+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)
+ send_txn = coinbase_txn(id: "txn_send_keep", type: "send", btc_amount: "-0.01", native_amount: "665.80")
+ # An unparseable created_at fails before the sibling's entry is ever
+ # created, same as any other per-transaction processing failure.
+ broken_sibling = coinbase_txn(
+ id: "txn_pro_withdraw_broken", type: "pro_withdrawal", btc_amount: "-0.01",
+ native_amount: "665.80", created_at: "not-a-real-date"
+ )
+
+ @coinbase_account.update!(raw_transactions_payload: { "transactions" => [ send_txn ] })
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_send_keep")
+
+ @coinbase_account.update!(raw_transactions_payload: { "transactions" => [ send_txn, broken_sibling ] })
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_send_keep"),
+ "the send must survive when its matching sibling fails to import -- otherwise the account has neither entry"
+ refute @account.entries.exists?(external_id: "coinbase_txn_txn_pro_withdraw_broken")
+ end
+
+ test "does not destroy a protected send when its matching transfer becomes visible" do
+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)
+ send_txn = coinbase_txn(id: "txn_send_protected", type: "send", btc_amount: "-0.01", native_amount: "665.80")
+ sibling_txn = coinbase_txn(id: "txn_pro_withdraw_protected", type: "pro_withdrawal", btc_amount: "-0.01", native_amount: "665.80")
+
+ @coinbase_account.update!(raw_transactions_payload: { "transactions" => [ send_txn ] })
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+ # A user's deliberate exclusion must survive sync-driven reconciliation,
+ # same as every other provider's sync code respects protected_from_sync?.
+ @account.entries.find_by!(external_id: "coinbase_txn_txn_send_protected").update!(excluded: true)
+
+ @coinbase_account.update!(raw_transactions_payload: { "transactions" => [ send_txn, sibling_txn ] })
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_send_protected"),
+ "a user-excluded entry must never be silently destroyed by sync reconciliation"
+ assert @account.entries.exists?(external_id: "coinbase_txn_txn_pro_withdraw_protected")
+ end
+
+ test "captures a per-transaction processing failure via DebugLogEntry" do
+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)
+ @coinbase_account.update!(raw_transactions_payload: {
+ "transactions" => [
+ coinbase_txn(id: "txn_bad", type: "staking_reward", btc_amount: "0.001", native_amount: "66.58", created_at: "not-a-real-date")
+ ]
+ })
+
+ assert_difference -> { DebugLogEntry.count }, 1 do
+ CoinbaseAccount::Processor.new(@coinbase_account).process
+ end
+
+ entry = DebugLogEntry.last
+ assert_equal "provider_sync_error", entry.category
+ assert_equal "coinbase", entry.provider_key
+ assert_equal @family, entry.family
+ end
+
+ private
+
+ def coinbase_txn(id:, type:, btc_amount:, native_amount:, created_at: "2026-01-01T00:00:00Z", status: "completed")
+ {
+ "id" => id,
+ "type" => type,
+ "status" => status,
+ "created_at" => created_at,
+ "amount" => { "amount" => btc_amount, "currency" => "BTC" },
+ "native_amount" => { "amount" => native_amount, "currency" => "USD" }
+ }
+ end
end
diff --git a/test/models/coinbase_item/importer_test.rb b/test/models/coinbase_item/importer_test.rb
index 854f07b014..16a31e674d 100644
--- a/test/models/coinbase_item/importer_test.rb
+++ b/test/models/coinbase_item/importer_test.rb
@@ -15,7 +15,7 @@ class CoinbaseItem::ImporterTest < ActiveSupport::TestCase
test "persists an eighteen-decimal Coinbase asset balance after reload" do
provider = mock("coinbase provider")
provider.expects(:get_accounts).returns([ btc_account_payload ])
- provider.expects(:get_transactions).with("cb_btc_123", limit: 100).returns([])
+ provider.expects(:get_transactions).with("cb_btc_123", limit: CoinbaseItem::Importer::FULL_HISTORY_LIMIT).returns([])
CoinbaseItem::Importer.new(@item, coinbase_provider: provider).import
@@ -23,6 +23,129 @@ class CoinbaseItem::ImporterTest < ActiveSupport::TestCase
assert_equal BigDecimal("0.000000000000000148"), coinbase_account.current_balance
end
+ test "still saves the fetched balance when the transactions fetch is rate limited" do
+ provider = mock("coinbase provider")
+ provider.expects(:get_accounts).returns([ btc_account_payload ])
+ # RateLimitError is a sibling of ApiError, not a subclass, so it has to be
+ # rescued explicitly in fetch_and_store_transactions or it propagates past
+ # coinbase_account.save!, silently skipping this account's balance update
+ # for the whole sync even though the balance above was fetched correctly.
+ provider.expects(:get_transactions)
+ .with("cb_btc_123", limit: CoinbaseItem::Importer::FULL_HISTORY_LIMIT)
+ .raises(Provider::Coinbase::RateLimitError, "Rate limit exceeded")
+
+ result = CoinbaseItem::Importer.new(@item, coinbase_provider: provider).import
+ assert result[:success]
+
+ coinbase_account = @item.coinbase_accounts.find_by!(account_id: "cb_btc_123")
+ assert_equal BigDecimal("0.000000000000000148"), coinbase_account.current_balance
+ end
+
+ test "fetches transaction history even for a zero-balance, non-USD wallet" do
+ provider = mock("coinbase provider")
+ provider.expects(:get_accounts).returns([ zero_balance_account_payload ])
+ # A wallet that was fully sold or transferred out reports a zero balance
+ # but still needs its history fetched to reconstruct realized gains --
+ # a zero balance here says nothing about whether that history exists.
+ provider.expects(:get_transactions)
+ .with("cb_eth_zero", limit: CoinbaseItem::Importer::FULL_HISTORY_LIMIT)
+ .returns([ { "id" => "txn_1" } ])
+
+ CoinbaseItem::Importer.new(@item, coinbase_provider: provider).import
+
+ coinbase_account = @item.coinbase_accounts.find_by!(account_id: "cb_eth_zero")
+ assert_equal [ { "id" => "txn_1" } ], coinbase_account.raw_transactions_payload["transactions"]
+ end
+
+ test "stores a rate-limited partial fetch when there is no previous history to merge with" do
+ provider = mock("coinbase provider")
+ provider.expects(:get_accounts).returns([ btc_account_payload ])
+ partial = [ { "id" => "txn_a" }, { "id" => "txn_b" } ]
+ provider.expects(:get_transactions)
+ .with("cb_btc_123", limit: CoinbaseItem::Importer::FULL_HISTORY_LIMIT)
+ .raises(Provider::Coinbase::PartialResultError.new("Rate limit exceeded", partial))
+
+ CoinbaseItem::Importer.new(@item, coinbase_provider: provider).import
+
+ coinbase_account = @item.coinbase_accounts.find_by!(account_id: "cb_btc_123")
+ assert_equal partial, coinbase_account.raw_transactions_payload["transactions"]
+ assert coinbase_account.raw_transactions_payload["truncated"]
+ end
+
+ test "keeps previously-stored transactions a smaller rate-limited fetch didn't reach" do
+ @item.coinbase_accounts.create!(
+ account_id: "cb_btc_123",
+ name: "BTC Wallet",
+ currency: "BTC",
+ current_balance: BigDecimal("0.000000000000000148"),
+ raw_transactions_payload: { "transactions" => [ { "id" => "txn_a" }, { "id" => "txn_b" }, { "id" => "txn_c" } ] }
+ )
+
+ provider = mock("coinbase provider")
+ provider.expects(:get_accounts).returns([ btc_account_payload ])
+ provider.expects(:get_transactions)
+ .with("cb_btc_123", limit: CoinbaseItem::Importer::FULL_HISTORY_LIMIT)
+ .raises(Provider::Coinbase::PartialResultError.new("Rate limit exceeded", [ { "id" => "txn_a" } ]))
+
+ CoinbaseItem::Importer.new(@item, coinbase_provider: provider).import
+
+ coinbase_account = @item.coinbase_accounts.find_by!(account_id: "cb_btc_123")
+ assert_equal 3, coinbase_account.raw_transactions_payload["transactions"].size
+ end
+
+ test "merges new transactions from a rate-limited partial fetch instead of losing them to a size comparison" do
+ @item.coinbase_accounts.create!(
+ account_id: "cb_btc_123",
+ name: "BTC Wallet",
+ currency: "BTC",
+ current_balance: BigDecimal("0.000000000000000148"),
+ raw_transactions_payload: { "transactions" => [ { "id" => "txn_a" }, { "id" => "txn_b" }, { "id" => "txn_c" } ] }
+ )
+
+ provider = mock("coinbase provider")
+ provider.expects(:get_accounts).returns([ btc_account_payload ])
+ # Transactions are newest-first, so a partial fetch that only got through
+ # the first page can be *smaller* than the stored history while still
+ # containing a genuinely new transaction the stored history doesn't have.
+ # Comparing sizes to decide whether to keep it would lose txn_new here.
+ provider.expects(:get_transactions)
+ .with("cb_btc_123", limit: CoinbaseItem::Importer::FULL_HISTORY_LIMIT)
+ .raises(Provider::Coinbase::PartialResultError.new("Rate limit exceeded", [ { "id" => "txn_new" } ]))
+
+ CoinbaseItem::Importer.new(@item, coinbase_provider: provider).import
+
+ coinbase_account = @item.coinbase_accounts.find_by!(account_id: "cb_btc_123")
+ ids = coinbase_account.raw_transactions_payload["transactions"].map { |t| t["id"] }
+ assert_equal %w[txn_a txn_b txn_c txn_new].sort, ids.sort
+ end
+
+ test "includes the linked account_provider in a transactions-fetch DebugLogEntry" do
+ coinbase_account = @item.coinbase_accounts.create!(
+ account_id: "cb_btc_123",
+ name: "BTC Wallet",
+ currency: "BTC",
+ current_balance: 0
+ )
+ account = @item.family.accounts.create!(
+ name: "Coinbase BTC",
+ balance: 0,
+ currency: "USD",
+ accountable: Crypto.create!(subtype: "exchange")
+ )
+ account_provider = AccountProvider.create!(account: account, provider: coinbase_account)
+
+ provider = mock("coinbase provider")
+ provider.expects(:get_accounts).returns([ btc_account_payload ])
+ provider.expects(:get_transactions)
+ .with("cb_btc_123", limit: CoinbaseItem::Importer::FULL_HISTORY_LIMIT)
+ .raises(Provider::Coinbase::RateLimitError, "Rate limit exceeded")
+
+ CoinbaseItem::Importer.new(@item, coinbase_provider: provider).import
+
+ entry = DebugLogEntry.last
+ assert_equal account_provider, entry.account_provider
+ end
+
test "quantity columns preserve sixteen integer and eighteen fractional digits" do
assert_quantity_precision CoinbaseAccount, "current_balance", nullable: true
assert_quantity_precision Holding, "qty", nullable: false
@@ -42,6 +165,17 @@ class CoinbaseItem::ImporterTest < ActiveSupport::TestCase
}
end
+ def zero_balance_account_payload
+ {
+ "id" => "cb_eth_zero",
+ "name" => "ETH Wallet",
+ "type" => "wallet",
+ "status" => "active",
+ "balance" => { "amount" => "0", "currency" => "ETH" },
+ "currency" => { "code" => "ETH", "name" => "Ethereum", "type" => "crypto" }
+ }
+ end
+
def assert_quantity_precision(model, column_name, nullable:)
column = model.columns_hash.fetch(column_name)
diff --git a/test/models/provider/coinbase_test.rb b/test/models/provider/coinbase_test.rb
index 28bc3f197d..1d2a955256 100644
--- a/test/models/provider/coinbase_test.rb
+++ b/test/models/provider/coinbase_test.rb
@@ -142,4 +142,35 @@ class Provider::CoinbaseTest < ActiveSupport::TestCase
refute @provider.send(:ed25519_secret?, @test_key_multiline)
refute @provider.send(:ed25519_secret?, @test_key_single_line)
end
+
+ # --- paginated_get: rate limits mid-pagination ---
+
+ test "paginated_get preserves earlier pages when a later page is rate limited" do
+ stub_request(:get, "https://api.coinbase.com/v2/accounts/acct_1/transactions")
+ .to_return(
+ status: 200,
+ headers: { "Content-Type" => "application/json" },
+ body: {
+ "data" => [ { "id" => "txn_1" } ],
+ "pagination" => { "next_uri" => "/v2/accounts/acct_1/transactions?starting_after=txn_1" }
+ }.to_json
+ )
+ stub_request(:get, "https://api.coinbase.com/v2/accounts/acct_1/transactions?starting_after=txn_1")
+ .to_return(status: 429, headers: { "Content-Type" => "application/json" }, body: { "error" => "rate limited" }.to_json)
+
+ error = assert_raises(Provider::Coinbase::PartialResultError) do
+ @provider.get_transactions("acct_1", limit: 100)
+ end
+
+ assert_equal [ { "id" => "txn_1" } ], error.partial_results
+ end
+
+ test "paginated_get raises a plain RateLimitError when the very first page is rate limited" do
+ stub_request(:get, "https://api.coinbase.com/v2/accounts/acct_1/transactions")
+ .to_return(status: 429, headers: { "Content-Type" => "application/json" }, body: { "error" => "rate limited" }.to_json)
+
+ assert_raises(Provider::Coinbase::RateLimitError) do
+ @provider.get_transactions("acct_1", limit: 100)
+ end
+ end
end