The personal finance app for everyone (by everyone)
Ruby
Fix Coinbase cryptocurrency holding precision (#3456)
jaysbeekaybbc42af52eb6
diff --git a/app/controllers/holdings_controller.rb b/app/controllers/holdings_controller.rbindex a74fa9ab74..c85e7032ff 100644--- a/app/controllers/holdings_controller.rb+++ b/app/controllers/holdings_controller.rb@@ -6,6 +6,7 @@ class HoldingsController < ApplicationControllerdef index@account = accessible_accounts.find(params[:account_id])+ @current_holdings = @account.current_holdings@trade_republic_categories = trade_republic_categories_for(@account)enddiff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rbindex 7cf1aba052..6394521db0 100644--- a/app/helpers/application_helper.rb+++ b/app/helpers/application_helper.rb@@ -257,7 +257,7 @@ module ApplicationHelperabs_qty = qty.absprecision = if exact- 8 # "10.374"+ 18 # Preserve the full stored precision for crypto quantitieselsif abs_qty >= 11 # "10.4"elsif abs_qty >= 0.01diff --git a/app/views/holdings/_holding.html.erb b/app/views/holdings/_holding.html.erbindex 533b2a7a6a..e303fb06b6 100644--- a/app/views/holdings/_holding.html.erb+++ b/app/views/holdings/_holding.html.erb@@ -1,4 +1,4 @@-<%# locals: (holding:) %>+<%# locals: (holding:, crypto:) %><%= turbo_frame_tag dom_id(holding) do %><div class="grid grid-cols-12 items-center text-primary text-sm font-medium p-4">@@ -39,7 +39,7 @@<% else %><%= tag.p "--", class: "text-secondary" %><% end %>- <%= tag.p t(".shares", qty: format_quantity(holding.qty)), class: "font-normal text-secondary privacy-sensitive" %>+ <%= tag.p t(".shares", qty: format_quantity(holding.qty, exact: crypto)), class: "font-normal text-secondary privacy-sensitive" %></div><div class="col-span-2 text-right">diff --git a/app/views/holdings/index.html.erb b/app/views/holdings/index.html.erbindex 88b27b13fe..297f6be5b8 100644--- a/app/views/holdings/index.html.erb+++ b/app/views/holdings/index.html.erb@@ -41,10 +41,11 @@<%= render "shared/ruler" %><% end %>- <% if @account.current_holdings.any? %>- <%= render partial: "holdings/holding",- collection: @account.current_holdings,- spacer_template: "shared/ruler" %>+ <% if @current_holdings.any? %>+ <% @current_holdings.each_with_index do |holding, index| %>+ <%= render "holdings/holding", holding: holding, crypto: @account.crypto? %>+ <%= render "shared/ruler" unless index == @current_holdings.length - 1 %>+ <% end %><% end %></div></div>diff --git a/db/migrate/20260908090000_increase_coinbase_balance_precision.rb b/db/migrate/20260908090000_increase_coinbase_balance_precision.rbnew file mode 100644index 0000000000..a69eeb4a9f--- /dev/null+++ b/db/migrate/20260908090000_increase_coinbase_balance_precision.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true++class IncreaseCoinbaseBalancePrecision < ActiveRecord::Migration[8.1]+ def up+ change_column :coinbase_accounts, :current_balance, :decimal, precision: 34, scale: 18+ change_column :holdings, :qty, :decimal, precision: 34, scale: 18, null: false+ change_column :trades, :qty, :decimal, precision: 34, scale: 18+ end++ def down+ raise ActiveRecord::IrreversibleMigration,+ "Reducing Coinbase balances to four decimal places would discard imported cryptocurrency precision"+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 3d5e057152..388419848e 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -435,7 +435,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_10_130000) dot.uuid "coinbase_item_id", null: falset.datetime "created_at", null: falset.string "currency"- t.decimal "current_balance", precision: 19, scale: 4+ t.decimal "current_balance", precision: 34, scale: 18t.jsonb "institution_metadata"t.string "name"t.string "provider"@@ -916,7 +916,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_10_130000) dot.string "external_id"t.decimal "price", precision: 19, scale: 4, null: falset.uuid "provider_security_id"- t.decimal "qty", precision: 24, scale: 8, null: false+ t.decimal "qty", precision: 34, scale: 18, null: falset.uuid "security_id", null: falset.boolean "security_locked", default: false, null: falset.datetime "updated_at", null: false@@ -2393,7 +2393,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_10_130000) dot.string "investment_activity_label"t.jsonb "locked_attributes", default: {}t.decimal "price", precision: 19, scale: 10- t.decimal "qty", precision: 24, scale: 8+ t.decimal "qty", precision: 34, scale: 18t.uuid "security_id", null: falset.datetime "updated_at", null: falset.index ["extra"], name: "index_trades_on_extra", using: :gindiff --git a/test/controllers/holdings_controller_test.rb b/test/controllers/holdings_controller_test.rbindex 6e88a2a196..f3113fc8c8 100644--- a/test/controllers/holdings_controller_test.rb+++ b/test/controllers/holdings_controller_test.rb@@ -26,6 +26,28 @@ class HoldingsControllerTest < ActionDispatch::IntegrationTestassert_select "##{dom_id(@holding, :shares)}", text: "10.374"end+ test "shows the exact stored quantity for a small crypto holding in the holdings list" do+ account = accounts(:crypto)+ security = Security.create!(+ ticker: "CRYPTO:BTC",+ name: "Bitcoin",+ exchange_operating_mic: "XCBS",+ offline: true+ )+ holding = account.holdings.create!(+ security: security,+ date: Date.current,+ qty: BigDecimal("0.000000000000000148"),+ price: 100_000,+ amount: 14.884,+ currency: "USD"+ )++ get holdings_url(account_id: account.id)++ assert_select "##{dom_id(holding)} p", text: "0.000000000000000148 shares"+ end+test "destroys holding and associated entries" doassert_difference -> { Holding.count } => -1,-> { Entry.count } => -1 dodiff --git a/test/models/coinbase_account/processor_test.rb b/test/models/coinbase_account/processor_test.rbindex 54b87f3b26..75053bff5b 100644--- a/test/models/coinbase_account/processor_test.rb+++ b/test/models/coinbase_account/processor_test.rb@@ -27,6 +27,7 @@ class CoinbaseAccount::ProcessorTest < ActiveSupport::TestCaseaccountable: Crypto.create!(subtype: "exchange"))AccountProvider.create!(account: @account, provider: @coinbase_account)+ @security = Security.create!(ticker: "CRYPTO:BTC", name: "BTC", exchange_operating_mic: "XCBS", offline: true)@coinbase_account.reloadend@@ -49,4 +50,56 @@ class CoinbaseAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal 0.to_d, @account.cash_balanceassert_equal "USD", @account.currencyend++ test "uses the exact Coinbase quantity for a spot-priced holding and account balance" do+ @coinbase_account.update!(current_balance: BigDecimal("0.00014884"), raw_payload: {})+ provider = mock("coinbase provider")+ provider.stubs(:get_spot_price).with("BTC-USD").returns({ "amount" => "66580" })+ CoinbaseItem.any_instance.stubs(:coinbase_provider).returns(provider)+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:resolve_security).returns(@security)++ assert_difference -> { @account.holdings.count }, 1 do+ CoinbaseAccount::Processor.new(@coinbase_account).process+ end++ holding = @account.holdings.find_by!(security: @security, date: Date.current)+ assert_equal BigDecimal("0.00014884"), holding.qty+ assert_equal BigDecimal("9.91"), holding.amount+ assert_equal BigDecimal("9.91"), @account.reload.balance++ assert_no_difference -> { @account.holdings.count } do+ CoinbaseAccount::Processor.new(@coinbase_account).process+ end+ assert_equal BigDecimal("0.00014884"), holding.reload.qty+ end++ test "keeps the exact Coinbase quantity when native balance is available" do+ @coinbase_account.update!(+ current_balance: BigDecimal("0.00014884"),+ raw_payload: { "native_balance" => { "amount" => "9.91", "currency" => "EUR" } }+ )+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:resolve_security).returns(@security)++ CoinbaseAccount::Processor.new(@coinbase_account).process++ holding = @account.holdings.find_by!(security: @security, date: Date.current)+ assert_equal BigDecimal("0.00014884"), holding.qty+ assert_equal BigDecimal("9.91"), holding.amount+ assert_equal BigDecimal("9.91"), @account.reload.balance+ assert_equal "EUR", @account.currency+ end++ test "keeps eighteen-decimal Coinbase quantities" do+ quantity = BigDecimal("0.000000000000000148")+ @coinbase_account.update!(current_balance: quantity, raw_payload: {})+ provider = mock("coinbase provider")+ provider.stubs(:get_spot_price).with("BTC-USD").returns({ "amount" => "66580" })+ CoinbaseItem.any_instance.stubs(:coinbase_provider).returns(provider)+ CoinbaseAccount::HoldingsProcessor.any_instance.stubs(:resolve_security).returns(@security)++ CoinbaseAccount::Processor.new(@coinbase_account).process++ holding = @account.holdings.find_by!(security: @security, date: Date.current)+ assert_equal quantity, holding.qty+ endenddiff --git a/test/models/coinbase_item/importer_test.rb b/test/models/coinbase_item/importer_test.rbnew file mode 100644index 0000000000..854f07b014--- /dev/null+++ b/test/models/coinbase_item/importer_test.rb@@ -0,0 +1,52 @@+# frozen_string_literal: true++require "test_helper"++class CoinbaseItem::ImporterTest < ActiveSupport::TestCase+ setup do+ @item = CoinbaseItem.create!(+ family: families(:dylan_family),+ name: "Coinbase",+ api_key: "key",+ api_secret: "secret"+ )+ end++ 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([])++ CoinbaseItem::Importer.new(@item, coinbase_provider: provider).import++ coinbase_account = @item.coinbase_accounts.find_by!(account_id: "cb_btc_123")+ assert_equal BigDecimal("0.000000000000000148"), coinbase_account.current_balance+ 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+ assert_quantity_precision Trade, "qty", nullable: true+ end++ private++ def btc_account_payload+ {+ "id" => "cb_btc_123",+ "name" => "BTC Wallet",+ "type" => "wallet",+ "status" => "active",+ "balance" => { "amount" => "0.000000000000000148", "currency" => "BTC" },+ "currency" => { "code" => "BTC", "name" => "Bitcoin", "type" => "crypto" }+ }+ end++ def assert_quantity_precision(model, column_name, nullable:)+ column = model.columns_hash.fetch(column_name)++ assert_equal 34, column.precision+ assert_equal 18, column.scale+ assert_equal nullable, column.null+ end+end