Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(onchain-wallets): call transfers transfers, and drop the address swap (#3153)

buzzromaind7bf401cc7c5
diff --git a/app/controllers/onchain_wallet_items_controller.rb b/app/controllers/onchain_wallet_items_controller.rb
index c349c2f3d0..c5821fcdd4 100644
--- a/app/controllers/onchain_wallet_items_controller.rb
+++ b/app/controllers/onchain_wallet_items_controller.rb
@@ -6,9 +6,9 @@
class OnchainWalletItemsController < ApplicationController
before_action :require_admin!
before_action :set_onchain_wallet_item,
- only: %i[update destroy sync manage review_tokens update_tokens edit_wallet change_address
+ only: %i[update destroy sync manage review_tokens update_tokens
disconnect_wallet disconnect_asset]
- before_action :set_wallet, only: %i[review_tokens update_tokens edit_wallet change_address disconnect_wallet]
+ before_action :set_wallet, only: %i[review_tokens update_tokens disconnect_wallet]
def update
if @onchain_wallet_item.update(onchain_wallet_item_params)
@@ -155,28 +155,7 @@ class OnchainWalletItemsController < ApplicationController
redirect_to_manage(notice: t(".success", created: result.created, removed: result.removed))
end
- def edit_wallet
- end
-
- def change_address
- new_address = Onchain::Chains.canonical_address(@chain, params[:new_address])
-
- unless Onchain::Chains.valid_address?(@chain, new_address)
- return render_edit_wallet(t(".errors.invalid_address"))
- end
-
- if new_address == @address
- return render_edit_wallet(t(".errors.unchanged"))
- end
- if Current.family.onchain_address_linked?(@chain, new_address)
- return render_edit_wallet(t(".errors.already_linked"))
- end
-
- @onchain_wallet_item.change_wallet_address!(chain: @chain, from: @address, to: new_address)
-
- redirect_to_manage(notice: t(".success"))
- end
def disconnect_wallet
removed = @onchain_wallet_item.disconnect_wallet!(chain: @chain, address: @address)
@@ -222,10 +201,6 @@ class OnchainWalletItemsController < ApplicationController
redirect_to manage_onchain_wallet_item_path(@onchain_wallet_item), **flash_message, status: :see_other
end
- def render_edit_wallet(error_message)
- @error_message = error_message
- render :edit_wallet, status: :unprocessable_entity
- end
def onchain_wallet_item_params
permitted = params.require(:onchain_wallet_item).permit(:sync_start_date, :etherscan_api_key)
diff --git a/app/models/onchain_wallet_account/processor.rb b/app/models/onchain_wallet_account/processor.rb
index 6da18fd197..5358411daa 100644
--- a/app/models/onchain_wallet_account/processor.rb
+++ b/app/models/onchain_wallet_account/processor.rb
@@ -7,6 +7,9 @@
# the importer stored on it.
class OnchainWalletAccount::Processor
SOURCE = "onchain_wallet"
+ # The label this processor writes on every movement. Named so the repair
+ # below and the import above cannot drift apart.
+ TRANSFER_LABEL = "Transfer"
attr_reader :onchain_wallet_account
@@ -43,13 +46,15 @@ class OnchainWalletAccount::Processor
def repair_display_only_movements
return 0 unless account
+ relabelled = relabel_legacy_trades
+
candidates = display_only_entries
- return 0 if candidates.empty?
+ return relabelled if candidates.empty?
security = resolve_security
- return 0 if security.nil?
+ return relabelled if security.nil?
- candidates.count { |entry| upgrade_to_trade(entry, security) }
+ relabelled + candidates.count { |entry| upgrade_to_trade(entry, security) }
end
private
@@ -242,11 +247,16 @@ class OnchainWalletAccount::Processor
currency: currency,
date: date,
# Named here because the shared helper says "Buy 0.5 shares of
- # CRYPTO:BTC" — "shares" is not a thing a wallet holds.
- name: trade_name(quantity),
+ # CRYPTO:BTC" — "shares" is not a thing a wallet holds. The wording is
+ # the same one an unpriced movement already carries, so a transfer
+ # does not change its name the day a price turns up for it.
+ name: movement_name(quantity),
external_id: external_id,
source: SOURCE,
- activity_label: quantity.positive? ? "Buy" : "Sell"
+ # A trade is the shape this ledger needs to carry quantity and cost
+ # basis, but the event is a transfer: coins arriving at an address are
+ # not a purchase, and nothing here knows whether they were ever bought.
+ activity_label: TRANSFER_LABEL
)
end
end
@@ -282,6 +292,37 @@ class OnchainWalletAccount::Processor
# The zero-amount, excluded entries this processor writes for unpriced
# movements, identified by the external_id prefix it gave them.
+ # Movements imported before transfers were called transfers still carry a
+ # `Buy` or `Sell` label and a "Buy 0.5 shares of CRYPTO:BTC" name. Nothing
+ # rewrites them on an ordinary sync: `perform_sync` returns early when no
+ # address changed on chain, and the repair above only ever looked at
+ # display-only `Transaction` rows. Left alone they would keep the old
+ # wording for as long as the wallet sits still — which for a cold address
+ # is the whole point of it.
+ #
+ # Scoped to this processor's own external_id prefix and to `source:
+ # SOURCE`, so a trade the user entered by hand is never touched.
+ def relabel_legacy_trades
+ entries = account.entries
+ .where(source: SOURCE, entryable_type: "Trade")
+ .where("external_id LIKE ?", "#{holding_external_id}_%")
+ .includes(:entryable)
+ .to_a
+ return 0 if entries.empty?
+
+ entries.count do |entry|
+ trade = entry.entryable
+ expected_name = movement_name(trade.qty.to_d)
+ next false if trade.investment_activity_label == TRANSFER_LABEL && entry.name == expected_name
+
+ Entry.transaction do
+ trade.update!(investment_activity_label: TRANSFER_LABEL)
+ entry.update!(name: expected_name)
+ end
+ true
+ end
+ end
+
def display_only_entries
account.entries
.where(source: SOURCE, entryable_type: "Transaction", excluded: true, amount: 0)
@@ -311,10 +352,6 @@ class OnchainWalletAccount::Processor
true
end
- def trade_name(quantity)
- translated_name("onchain_wallet_item.trade.#{quantity.positive? ? "buy" : "sell"}", quantity)
- end
-
def movement_name(quantity)
translated_name("onchain_wallet_item.movement.#{quantity.positive? ? "received" : "sent"}", quantity)
end
diff --git a/app/models/onchain_wallet_item.rb b/app/models/onchain_wallet_item.rb
index b915107310..fbe391fcae 100644
--- a/app/models/onchain_wallet_item.rb
+++ b/app/models/onchain_wallet_item.rb
@@ -99,31 +99,6 @@ class OnchainWalletItem < ApplicationRecord
# Moves every tracked asset at an address to a new one, keeping the rows — and
# so the accounts, holdings and entries hanging off them — intact. Recreating
# them would throw away the balance history the user came here for.
- def change_wallet_address!(chain:, from:, to:)
- rows = accounts_for_wallet(chain, from).to_a
- raise ActiveRecord::RecordNotFound, "No tracked assets at that address" if rows.empty?
-
- transaction do
- # The destination can still hold rows left behind by deleted accounts.
- # They track nothing, yet they hold the slot in the partial unique index
- # that the rows moving in need, so they make way. A destination that is
- # genuinely tracked never reaches here — the caller refuses it.
- accounts_for_wallet(chain, to).unlinked.destroy_all
-
- rows.each do |row|
- previous_display_name = row.display_name
- # The digest is cleared so the next sync reprocesses against the new
- # address even if it happens to hold the same amount.
- row.update!(wallet_address: to, content_hash: nil)
-
- account = row.current_account
- account.update!(name: row.display_name) if account && account.name == previous_display_name
- end
- end
-
- sync_later
- rows.size
- end
# Stops tracking every asset at an address. The accounts and their history stay
# behind as manual accounts; only the provider link goes.
diff --git a/app/models/provider/onchain_wallet_adapter.rb b/app/models/provider/onchain_wallet_adapter.rb
index 8c28e036c0..89d65a9f6b 100644
--- a/app/models/provider/onchain_wallet_adapter.rb
+++ b/app/models/provider/onchain_wallet_adapter.rb
@@ -54,4 +54,19 @@ class Provider::OnchainWalletAdapter < Provider::Base
def institution_name
provider_account.chain_label
end
+
+ # Account#logo_url asks its provider adapter for one, and without this a
+ # tracked asset shows no icon at all on the accounts page — there is no
+ # institution behind a wallet, and nothing attaches a file.
+ #
+ # Built from the symbol rather than looked up: the accounts page renders one
+ # of these per account, and a Security lookup each would be a query per row.
+ # Brandfetch answers nil without a client id, which is the same nothing the
+ # page shows today.
+ def logo_url
+ base = Onchain::AssetSymbol.canonical(provider_account.symbol)
+ return nil if base.blank?
+
+ Security.brandfetch_crypto_url(base)
+ end
end
diff --git a/app/models/security.rb b/app/models/security.rb
index ab273b93d9..053997b44e 100644
--- a/app/models/security.rb
+++ b/app/models/security.rb
@@ -20,8 +20,17 @@ class Security < ApplicationRecord
# Builds the Brandfetch crypto URL for a base asset (e.g. "BTC"). Returns
# nil when Brandfetch isn't configured.
+ # The symbol goes into a URL path segment, and it comes from provider data —
+ # an on-chain token can be called anything its deployer chose. A slash, a
+ # question mark or a hash would not merely break the link: they would point
+ # the path elsewhere on the CDN, or push the client id into a fragment where
+ # Brandfetch never sees it. Guarded here rather than at each call site, since
+ # six of them reach this method from four different providers.
+ SAFE_CRYPTO_SYMBOL = /\A[A-Za-z0-9][A-Za-z0-9.\-]{0,31}\z/
+
def self.brandfetch_crypto_url(base_asset)
return nil if base_asset.blank?
+ return nil unless base_asset.to_s.match?(SAFE_CRYPTO_SYMBOL)
return nil unless Setting.brand_fetch_client_id.present?
size = Setting.brand_fetch_logo_size
"https://cdn.brandfetch.io/crypto/#{base_asset}/icon/fallback/lettermark/w/#{size}/h/#{size}?c=#{Setting.brand_fetch_client_id}"
diff --git a/app/views/onchain_wallet_items/_wallet_card.html.erb b/app/views/onchain_wallet_items/_wallet_card.html.erb
index c91fa9d094..6ae5db610c 100644
--- a/app/views/onchain_wallet_items/_wallet_card.html.erb
+++ b/app/views/onchain_wallet_items/_wallet_card.html.erb
@@ -45,17 +45,32 @@
</div>
</div>
- <%# Management lives in the provider settings panel, where linking,
- token review and disconnection already are — this card links to it
- rather than growing a second, partial copy of those controls. %>
+ <%# A menu, like every other provider card on this page, holding the
+ same two actions Kraken's does. Management itself is reached from
+ the provider settings, as it is for every other connection — no
+ card here links to it, and a menu of actions is the wrong place for
+ a navigation link. %>
<% if Current.user&.admin? %>
- <%= render DS::Link.new(
- text: t(".manage"),
- icon: "settings",
- variant: "secondary",
- href: settings_providers_path,
- frame: "_top"
- ) %>
+ <%= render DS::Menu.new(icon_vertical: true, mobile_fullwidth: false, max_width: "280px") do |menu| %>
+ <% unless onchain_wallet_item.syncing? %>
+ <% menu.with_item(
+ variant: "button",
+ text: t(".sync"),
+ icon: "refresh-cw",
+ href: sync_onchain_wallet_item_path(onchain_wallet_item),
+ method: :post
+ ) %>
+ <% end %>
+
+ <% menu.with_item(
+ variant: "button",
+ text: t(".delete"),
+ icon: "trash-2",
+ href: onchain_wallet_item_path(onchain_wallet_item),
+ method: :delete,
+ confirm: CustomConfirm.for_resource_deletion(onchain_wallet_item.institution_display_name, high_severity: true)
+ ) %>
+ <% end %>
<% end %>
</div>
<% end %>
diff --git a/app/views/onchain_wallet_items/edit_wallet.html.erb b/app/views/onchain_wallet_items/edit_wallet.html.erb
deleted file mode 100644
index 48ed3f29d2..0000000000
--- a/app/views/onchain_wallet_items/edit_wallet.html.erb
+++ /dev/null
@@ -1,40 +0,0 @@
-<%= render DS::Dialog.new do |dialog| %>
- <% dialog.with_header(title: t(".title"), subtitle: t(".subtitle", chain: Onchain::Chains.find!(@chain).label)) %>
-
- <% dialog.with_body do %>
- <div class="space-y-4">
- <% if @error_message.present? %>
- <%= render DS::Alert.new(message: @error_message, variant: :error) %>
- <% end %>
-
- <%= render DS::Alert.new(variant: :info, message: t(".history_preserved")) %>
-
- <%= styled_form_with url: change_address_onchain_wallet_item_path(@onchain_wallet_item),
- method: :patch,
- data: { turbo_frame: "modal" },
- class: "space-y-4" do |form| %>
- <%= hidden_field_tag :chain, @chain %>
- <%= hidden_field_tag :address, @address %>
-
- <div>
- <p class="text-sm text-secondary"><%= t(".current_address") %></p>
- <p class="text-sm text-primary break-all"><%= @address %></p>
- </div>
-
- <%= form.text_field :new_address,
- label: t(".new_address_label"),
- placeholder: t(".new_address_placeholder"),
- required: true %>
-
- <div class="flex justify-end gap-2">
- <%= render DS::Link.new(
- text: t(".cancel"),
- variant: "secondary",
- href: manage_onchain_wallet_item_path(@onchain_wallet_item)
- ) %>
- <%= form.submit t(".save") %>
- </div>
- <% end %>
- </div>
- <% end %>
-<% end %>
diff --git a/app/views/onchain_wallet_items/manage.html.erb b/app/views/onchain_wallet_items/manage.html.erb
index 683a6bb782..07c301c2ee 100644
--- a/app/views/onchain_wallet_items/manage.html.erb
+++ b/app/views/onchain_wallet_items/manage.html.erb
@@ -49,11 +49,13 @@
</p>
</div>
+ <%# Icon-only: this repeats once per asset, and a column of
+ labelled buttons is not how this app renders a list. %>
<%= render DS::Button.new(
- text: t(".disconnect_asset"),
- icon: "unlink",
- variant: :outline_destructive,
+ variant: :icon,
size: :sm,
+ icon: "unlink",
+ title: t(".disconnect_asset"),
href: disconnect_asset_onchain_wallet_item_path(@onchain_wallet_item),
method: :delete,
params: { onchain_wallet_account_id: onchain_account.id },
@@ -63,33 +65,29 @@
<% end %>
</ul>
- <div class="flex flex-wrap items-center gap-2">
- <%= render DS::Link.new(
- text: t(".review_tokens"),
- icon: "list-checks",
- variant: "secondary",
- href: review_tokens_onchain_wallet_item_path(@onchain_wallet_item, chain: chain, address: address),
- frame: :modal
- ) %>
+ <%# A menu rather than a row of labelled buttons: these actions
+ repeat for every tracked address, and accounts/_account.html.erb
+ renders its own per-row actions the same way. %>
+ <div class="flex items-center justify-end">
+ <%= render DS::Menu.new(icon_vertical: true, mobile_fullwidth: false, max_width: "280px") do |menu| %>
+ <% menu.with_item(
+ variant: "link",
+ text: t(".review_tokens"),
+ icon: "list-checks",
+ href: review_tokens_onchain_wallet_item_path(@onchain_wallet_item, chain: chain, address: address),
+ data: { turbo_frame: :modal }
+ ) %>
- <%= render DS::Link.new(
- text: t(".change_address"),
- icon: "pencil",
- variant: "secondary",
- href: edit_wallet_onchain_wallet_item_path(@onchain_wallet_item, chain: chain, address: address),
- frame: :modal
- ) %>
-
- <%= render DS::Button.new(
- text: t(".disconnect_wallet"),
- icon: "trash-2",
- variant: :outline_destructive,
- size: :sm,
- href: disconnect_wallet_onchain_wallet_item_path(@onchain_wallet_item),
- method: :delete,
- params: { chain: chain, address: address },
- confirm: t(".disconnect_wallet_confirm")
- ) %>
+ <% menu.with_item(
+ variant: "button",
+ text: t(".disconnect_wallet"),
+ icon: "trash-2",
+ href: disconnect_wallet_onchain_wallet_item_path(@onchain_wallet_item),
+ method: :delete,
+ params: { chain: chain, address: address },
+ confirm: t(".disconnect_wallet_confirm")
+ ) %>
+ <% end %>
</div>
</section>
<% end %>
diff --git a/app/views/onchain_wallet_items/new_wallet.html.erb b/app/views/onchain_wallet_items/new_wallet.html.erb
index 017742cdce..9ced08e763 100644
--- a/app/views/onchain_wallet_items/new_wallet.html.erb
+++ b/app/views/onchain_wallet_items/new_wallet.html.erb
@@ -5,6 +5,18 @@
<div class="space-y-4">
<%= render "onchain_wallet_items/price_provider_warning" %>
+ <%# Shown here rather than as a permanent banner on the settings page:
+ the question it answers — can Sure spend my coins? — is asked at the
+ moment of pasting an address, and a banner one has already read twice
+ stops being read at all. %>
+ <%= render DS::Alert.new(
+ variant: :info,
+ message: safe_join([
+ content_tag(:p, t("settings.providers.onchain_wallet_panel.keyless_title"), class: "font-medium"),
+ content_tag(:p, t("settings.providers.onchain_wallet_panel.keyless_body"), class: "mt-1")
+ ])
+ ) %>
+
<% if @error_message.present? %>
<%= render DS::Alert.new(message: @error_message, variant: :error) %>
<% end %>
diff --git a/app/views/settings/providers/_onchain_wallet_panel.html.erb b/app/views/settings/providers/_onchain_wallet_panel.html.erb
index c3a1c0701e..48c7c7cc5d 100644
--- a/app/views/settings/providers/_onchain_wallet_panel.html.erb
+++ b/app/views/settings/providers/_onchain_wallet_panel.html.erb
@@ -1,26 +1,19 @@
<div id="onchain_wallet-providers-panel" class="space-y-4">
- <% items = local_assigns[:onchain_wallet_items] || @onchain_wallet_items || Current.family.onchain_wallet_items.active.ordered %>
- <%# The one connection every wallet hangs off, so managing and linking always
- act on the same record. %>
+ <%# Every wallet hangs off one connection, and the actions below all act on
+ it. The rows were previously drawn from a separate list, so a family that
+ somehow held two would have been shown both and been able to manage only
+ one — silently, since nothing said which. %>
<% connection = Current.family.onchain_wallet_item %>
<%= render "onchain_wallet_items/price_provider_warning" %>
- <%= render DS::Alert.new(
- variant: :info,
- message: safe_join([
- content_tag(:p, t("settings.providers.onchain_wallet_panel.keyless_title"), class: "font-medium"),
- content_tag(:p, t("settings.providers.onchain_wallet_panel.keyless_body"), class: "mt-1")
- ])
- ) %>
-
<% error_msg = local_assigns[:error_message] || @error_message %>
<% if error_msg.present? %>
<%= render DS::Alert.new(message: error_msg, variant: :error) %>
<% end %>
- <% items.each do |item| %>
- <%= render "onchain_wallet_items/onchain_wallet_item", onchain_wallet_item: item %>
+ <% if connection.present? %>
+ <%= render "onchain_wallet_items/onchain_wallet_item", onchain_wallet_item: connection %>
<% end %>
<div class="flex flex-wrap items-center gap-2">
@@ -45,25 +38,24 @@
<% if connection.present? %>
<%= render DS::Disclosure.new(title: t("settings.providers.onchain_wallet_panel.advanced"), align: :right) do %>
- <% item = connection %>
<div class="pt-2 space-y-3">
<p class="text-sm text-secondary"><%= t("settings.providers.onchain_wallet_panel.etherscan_hint") %></p>
- <%= styled_form_with model: item,
- url: onchain_wallet_item_path(item),
+ <%= styled_form_with model: connection,
+ url: onchain_wallet_item_path(connection),
scope: :onchain_wallet_item,
method: :patch,
data: { turbo: true },
class: "space-y-3" do |form| %>
<%= form.text_field :etherscan_api_key,
label: t("settings.providers.onchain_wallet_panel.etherscan_api_key_label"),
- placeholder: item.etherscan_api_key.present? ? t("settings.providers.onchain_wallet_panel.keep_etherscan_api_key") : t("settings.providers.onchain_wallet_panel.etherscan_api_key_placeholder"),
+ placeholder: connection.etherscan_api_key.present? ? t("settings.providers.onchain_wallet_panel.keep_etherscan_api_key") : t("settings.providers.onchain_wallet_panel.etherscan_api_key_placeholder"),
type: :password,
value: nil %>
<%= form.date_field :sync_start_date,
label: t("settings.providers.onchain_wallet_panel.sync_start_date_label"),
- value: item.sync_start_date&.to_date %>
+ value: connection.sync_start_date&.to_date %>
<p class="text-xs text-secondary"><%= t("settings.providers.onchain_wallet_panel.sync_start_date_hint") %></p>
@@ -77,7 +69,7 @@
icon: "trash-2",
variant: :outline_destructive,
size: :sm,
- href: onchain_wallet_item_path(item),
+ href: onchain_wallet_item_path(connection),
method: :delete,
confirm: t("settings.providers.onchain_wallet_panel.disconnect_all_confirm")
) %>
diff --git a/config/locales/models/onchain_wallet_item/en.yml b/config/locales/models/onchain_wallet_item/en.yml
index 48bb0e843a..6a1eac6299 100644
--- a/config/locales/models/onchain_wallet_item/en.yml
+++ b/config/locales/models/onchain_wallet_item/en.yml
@@ -15,6 +15,3 @@ en:
movement:
received: "Received %{quantity} %{symbol}"
sent: "Sent %{quantity} %{symbol}"
- trade:
- buy: "Buy %{quantity} %{symbol}"
- sell: "Sell %{quantity} %{symbol}"
diff --git a/config/locales/views/onchain_wallet_items/en.yml b/config/locales/views/onchain_wallet_items/en.yml
index 699887ac03..39616dad29 100644
--- a/config/locales/views/onchain_wallet_items/en.yml
+++ b/config/locales/views/onchain_wallet_items/en.yml
@@ -9,27 +9,12 @@ en:
title: Which network?
destroy:
success: Scheduled the self-custody connection for deletion.
- change_address:
- errors:
- already_linked: That address is already tracked on this network.
- invalid_address: That is not a valid address on this network.
- unchanged: That is the address already being tracked.
- success: Address updated. The next sync will read the new address.
disconnect_asset:
success: "Stopped tracking %{symbol}. Its account and history were kept."
disconnect_wallet:
success:
one: Stopped tracking 1 asset at that address.
other: "Stopped tracking %{count} assets at that address."
- edit_wallet:
- cancel: Cancel
- current_address: Currently tracking
- history_preserved: The accounts, holdings and history stay as they are. Only the address being read changes.
- new_address_label: New address
- new_address_placeholder: Paste the corrected address
- save: Update address
- subtitle: "%{chain}"
- title: Change wallet address
enable_crypto_prices:
not_self_hosted: Market data providers are configured by the instance operator on this deployment.
success: Crypto prices are enabled. Wallet values appear after the next sync.
@@ -51,7 +36,6 @@ en:
other: "Tracking %{count} assets from this wallet."
manage:
assets_truncated: "This address holds more tokens than one read surfaces, so only the %{count} most credible are listed. Anything already tracked keeps syncing."
- change_address: Change address
disconnect_asset: Stop tracking
disconnect_asset_confirm: "Stop tracking %{symbol}? Its account and history are kept and stop updating."
disconnect_wallet: Disconnect wallet
@@ -84,11 +68,12 @@ en:
one: 1 address tracked
other: "%{count} addresses tracked"
deletion_in_progress: Removing...
- manage: Manage
+ delete: Remove connection
needs_attention: Needs attention
no_wallets_message: Link an address from the provider settings to see it here.
no_wallets_title: No wallets linked yet
status: Synced %{timestamp} ago
+ sync: Sync now
status_never: Not synced yet
syncing: Syncing...
price_provider_warning:
diff --git a/config/routes.rb b/config/routes.rb
index 51edee89cc..d8e7d7066a 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -141,8 +141,6 @@ Rails.application.routes.draw do
get :manage
get :review_tokens
post :update_tokens
- get :edit_wallet
- patch :change_address
delete :disconnect_wallet
delete :disconnect_asset
end
diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rb
index ff4307e715..7b35a3968a 100644
--- a/test/controllers/accounts_controller_test.rb
+++ b/test/controllers/accounts_controller_test.rb
@@ -34,6 +34,9 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest
# Without this the wallet is invisible here: its accounts carry a provider
# link, so Account.manual excludes them, and no provider section claimed them.
assert_select "##{dom_id(item, :accounts_index)}"
+ # The card carries the same actions menu every other provider card does.
+ assert_select "form[action=?]", sync_onchain_wallet_item_path(item)
+ assert_select "form[action=?]", onchain_wallet_item_path(item)
ensure
unregister_fake_chain!
end
diff --git a/test/controllers/onchain_wallet_items_controller_test.rb b/test/controllers/onchain_wallet_items_controller_test.rb
index 0b551575bb..587938eda3 100644
--- a/test/controllers/onchain_wallet_items_controller_test.rb
+++ b/test/controllers/onchain_wallet_items_controller_test.rb
@@ -21,6 +21,9 @@ class OnchainWalletItemsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
assert_match I18n.t("onchain_wallet_items.new_wallet.bitcoin_single_address_note"), response.body
+ # "Can Sure spend my coins?" is asked while pasting an address, not while
+ # reading a settings page for the third time.
+ assert_match I18n.t("settings.providers.onchain_wallet_panel.keyless_title"), response.body
assert_match I18n.t("onchain_wallet_items.new_wallet.read_only_note"), response.body
end
@@ -28,7 +31,6 @@ class OnchainWalletItemsControllerTest < ActionDispatch::IntegrationTest
get connect_form_settings_providers_path(provider_key: "onchain_wallet")
assert_response :success
- assert_match I18n.t("settings.providers.onchain_wallet_panel.keyless_title"), response.body
assert_select "a[href=?]", new_wallet_onchain_wallet_items_path
end
@@ -428,7 +430,7 @@ class OnchainWalletItemsControllerTest < ActionDispatch::IntegrationTest
assert_response :redirect
end
- test "manage lists every tracked address and offers all four actions" do
+ test "manage lists every tracked address and offers its actions" do
item = create_onchain_wallet_item(family: @family)
native = create_onchain_wallet_account(item: item)
token_asset = create_onchain_wallet_account(item: item, asset: fake_token_asset(symbol: "USDC", contract: "0xusdc"))
@@ -438,10 +440,12 @@ class OnchainWalletItemsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
assert_match OnchainTestHelper::FAKE_ADDRESS, response.body
assert_match I18n.t("onchain_wallet_items.manage.review_tokens"), response.body
- assert_match I18n.t("onchain_wallet_items.manage.change_address"), response.body
assert_match I18n.t("onchain_wallet_items.manage.disconnect_wallet"), response.body
# Per-asset action, for each asset, not just one for the wallet.
assert_select "form[action=?]", disconnect_asset_onchain_wallet_item_path(item), count: 2
+ # The per-address actions live in a menu, as the accounts page renders its
+ # own repeated row actions.
+ assert_select "form[action=?]", disconnect_wallet_onchain_wallet_item_path(item), count: 1
assert_match native.symbol, response.body
assert_match token_asset.symbol, response.body
end
@@ -518,76 +522,6 @@ class OnchainWalletItemsControllerTest < ActionDispatch::IntegrationTest
assert_not OnchainWalletAccount.exists?(gone.id)
end
- test "change_address keeps the rows, their accounts and their history" do
- item = create_onchain_wallet_item(family: @family)
- onchain_account = create_onchain_wallet_account(item: item)
- account = link_onchain_wallet_account!(onchain_account)
- balance = account.balances.create!(date: Date.current, balance: 100, cash_balance: 0, currency: account.currency)
-
- patch change_address_onchain_wallet_item_url(item), params: {
- chain: OnchainTestHelper::FAKE_CHAIN,
- address: OnchainTestHelper::FAKE_ADDRESS,
- new_address: OnchainTestHelper::FAKE_ADDRESS_ALT
- }
-
- assert_redirected_to manage_onchain_wallet_item_path(item)
- onchain_account.reload
- assert_equal OnchainTestHelper::FAKE_ADDRESS_ALT, onchain_account.wallet_address
- assert_equal account, onchain_account.account
- assert Account.exists?(account.id)
- assert account.balances.exists?(balance.id)
- assert_nil onchain_account.content_hash
- end
-
- test "change_address refuses an address that is invalid for the chain" do
- item = create_onchain_wallet_item(family: @family)
- onchain_account = create_onchain_wallet_account(item: item)
-
- patch change_address_onchain_wallet_item_url(item), params: {
- chain: OnchainTestHelper::FAKE_CHAIN,
- address: OnchainTestHelper::FAKE_ADDRESS,
- new_address: "not-an-address"
- }
-
- assert_response :unprocessable_entity
- assert_match I18n.t("onchain_wallet_items.change_address.errors.invalid_address"), response.body
- assert_equal OnchainTestHelper::FAKE_ADDRESS, onchain_account.reload.wallet_address
- end
-
- test "change_address refuses an address already tracked elsewhere" do
- item = create_onchain_wallet_item(family: @family)
- link_onchain_wallet_account!(create_onchain_wallet_account(item: item))
- link_onchain_wallet_account!(create_onchain_wallet_account(item: item, address: OnchainTestHelper::FAKE_ADDRESS_ALT))
-
- patch change_address_onchain_wallet_item_url(item), params: {
- chain: OnchainTestHelper::FAKE_CHAIN,
- address: OnchainTestHelper::FAKE_ADDRESS,
- new_address: OnchainTestHelper::FAKE_ADDRESS_ALT
- }
-
- assert_response :unprocessable_entity
- assert_match I18n.t("onchain_wallet_items.change_address.errors.already_linked"), response.body
- end
-
- test "change_address moves onto an address whose leftover row tracks nothing" do
- item = create_onchain_wallet_item(family: @family)
- link_onchain_wallet_account!(create_onchain_wallet_account(item: item))
- leftover = create_onchain_wallet_account(item: item, address: OnchainTestHelper::FAKE_ADDRESS_ALT)
-
- patch change_address_onchain_wallet_item_url(item), params: {
- chain: OnchainTestHelper::FAKE_CHAIN,
- address: OnchainTestHelper::FAKE_ADDRESS,
- new_address: OnchainTestHelper::FAKE_ADDRESS_ALT
- }
-
- # The destination looks taken but is not: the leftover holds the slot in the
- # unique index without tracking anything, and colliding with it would put a
- # database error in front of the user.
- assert_redirected_to manage_onchain_wallet_item_path(item)
- assert_not OnchainWalletAccount.exists?(leftover.id)
- assert_equal OnchainTestHelper::FAKE_ADDRESS_ALT, item.onchain_wallet_accounts.sole.wallet_address
- end
-
test "disconnect_wallet stops tracking every asset at that address only" do
item = create_onchain_wallet_item(family: @family)
create_onchain_wallet_account(item: item)
diff --git a/test/models/onchain_wallet_account/processor_test.rb b/test/models/onchain_wallet_account/processor_test.rb
index 6f730bcd15..9bbfd12746 100644
--- a/test/models/onchain_wallet_account/processor_test.rb
+++ b/test/models/onchain_wallet_account/processor_test.rb
@@ -87,7 +87,7 @@ class OnchainWalletAccount::ProcessorTest < ActiveSupport::TestCase
assert_equal 0, @account.reload.balance
end
- test "materializes an inbound movement as a Buy trade when that day's price is known" do
+ test "materializes an inbound movement as a priced transfer when that day's price is known" do
date = 3.days.ago.to_date
price_asset_at(date, 50)
store_movements(fake_movement(external_id: "tx1", amount: "1.5", timestamp: date))
@@ -99,14 +99,16 @@ class OnchainWalletAccount::ProcessorTest < ActiveSupport::TestCase
assert_equal BigDecimal("1.5"), entry.entryable.qty
assert_equal 50, entry.entryable.price
assert_equal(-75, entry.amount)
- assert_equal "Buy", entry.entryable.investment_activity_label
+ # A trade is the shape this ledger needs to carry quantity and cost basis,
+ # but coins arriving at an address were not bought here — and the name is
+ # the one the movement already had before a price existed for it, so it does
+ # not change the day one turns up.
+ assert_equal "Transfer", entry.entryable.investment_activity_label
assert_not entry.excluded
- # The shared helper would call this "Buy 1.5 shares of CRYPTO:FAKE"; a wallet
- # does not hold shares.
- assert_equal "Buy 1.5 FAKE", entry.name
+ assert_equal "Received 1.5 FAKE", entry.name
end
- test "materializes an outbound movement as a Sell trade" do
+ test "materializes an outbound movement as a priced transfer out" do
date = 3.days.ago.to_date
price_asset_at(date, 50)
store_movements(fake_movement(external_id: "tx2", amount: "-1", timestamp: date))
@@ -116,8 +118,8 @@ class OnchainWalletAccount::ProcessorTest < ActiveSupport::TestCase
entry = @account.entries.find_by(external_id: "onchain_#{@onchain_account.id}_tx2")
assert_equal(-1, entry.entryable.qty)
assert_equal 50, entry.amount
- assert_equal "Sell", entry.entryable.investment_activity_label
- assert_equal "Sell 1.0 FAKE", entry.name
+ assert_equal "Transfer", entry.entryable.investment_activity_label
+ assert_equal "Sent 1.0 FAKE", entry.name
end
test "materializes a display-only excluded entry when that day's price is unknown" do
@@ -273,7 +275,53 @@ class OnchainWalletAccount::ProcessorTest < ActiveSupport::TestCase
assert_equal "Transaction", onchain_entry("tx1").entryable_type
end
- test "the repair costs one query and no writes when there is nothing to upgrade" do
+ # Movements imported before transfers were called transfers keep their `Buy`
+ # label and their "Buy 1.5 shares of ..." name. Nothing rewrote them: an
+ # ordinary sync returns early when no address changed on chain, and the
+ # repair only ever looked at display-only Transaction rows — so a cold
+ # wallet would show the old wording indefinitely.
+ test "the repair relabels a trade imported before transfers were named" do
+ date = 3.days.ago.to_date
+ price_asset_at(date, 40)
+ store_movements(fake_movement(external_id: "tx1", amount: "1.5", timestamp: date))
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ entry = onchain_entry("tx1")
+ entry.entryable.update!(investment_activity_label: "Buy")
+ entry.update!(name: "Buy 1.5 shares of CRYPTO:FAKE")
+
+ assert_equal 1, OnchainWalletAccount::Processor.new(@onchain_account).repair_display_only_movements
+
+ repaired = onchain_entry("tx1")
+ assert_equal "Transfer", repaired.entryable.investment_activity_label
+ assert_no_match(/shares/, repaired.name)
+ end
+
+ # Idempotent, so a wallet that syncs nightly does not rewrite the same rows
+ # forever — and the "no writes" test above stays honest.
+ test "the repair leaves an already-correct trade alone" do
+ date = 3.days.ago.to_date
+ price_asset_at(date, 40)
+ store_movements(fake_movement(external_id: "tx1", amount: "1.5", timestamp: date))
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ assert_equal 0, OnchainWalletAccount::Processor.new(@onchain_account).repair_display_only_movements
+ end
+
+ # A trade the user entered by hand is not this processor's to rename.
+ test "the repair does not touch a trade it did not import" do
+ manual = @account.entries.create!(
+ name: "Bought some elsewhere", date: 2.days.ago.to_date, amount: -50, currency: "USD",
+ entryable: Trade.new(security: security, qty: 1, price: 50, currency: "USD",
+ investment_activity_label: "Buy")
+ )
+
+ OnchainWalletAccount::Processor.new(@onchain_account).repair_display_only_movements
+
+ assert_equal "Buy", manual.reload.entryable.investment_activity_label
+ assert_equal "Bought some elsewhere", manual.name
+ end
+ test "the repair writes nothing when there is nothing to upgrade" do
price_asset_at(Date.current, 100)
OnchainWalletAccount::Processor.new(@onchain_account).process
diff --git a/test/models/onchain_wallet_account_test.rb b/test/models/onchain_wallet_account_test.rb
index 03a0a50360..f6fd01247f 100644
--- a/test/models/onchain_wallet_account_test.rb
+++ b/test/models/onchain_wallet_account_test.rb
@@ -128,6 +128,23 @@ class OnchainWalletAccountTest < ActiveSupport::TestCase
assert_not OnchainWalletAccount.exists?(onchain_account.id)
end
+ test "a linked account takes its icon from the asset it tracks" do
+ # Saved rather than assumed nil: `Setting` is application-wide, and an
+ # `ensure` that hard-codes nil erases whatever the suite had configured,
+ # leaving every later test's behaviour dependent on run order.
+ previous_client_id = Setting.brand_fetch_client_id
+ Setting.brand_fetch_client_id = "test-client"
+ onchain_account = create_onchain_wallet_account(item: @item)
+ account = accounts(:investment)
+ onchain_account.ensure_account_provider!(account)
+
+ # There is no institution behind a wallet and nothing attaches a file, so
+ # without this the accounts page shows a tracked asset with no icon at all.
+ assert_includes account.reload.logo_url.to_s, "/crypto/#{onchain_account.symbol}/"
+ ensure
+ Setting.brand_fetch_client_id = previous_client_id
+ end
+
test "a native row and token rows coexist for one address" do
create_onchain_wallet_account(item: @item)
create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xaaa"))
diff --git a/test/models/security_test.rb b/test/models/security_test.rb
index e9748361bd..09225eab92 100644
--- a/test/models/security_test.rb
+++ b/test/models/security_test.rb
@@ -101,6 +101,29 @@ class SecurityTest < ActiveSupport::TestCase
)
end
+ # The symbol lands in a URL path segment and comes from provider data — an
+ # on-chain token can be called whatever its deployer chose. These would not
+ # merely break the link: the slash points the path elsewhere on the CDN, and
+ # the hash pushes the client id into a fragment Brandfetch never sees.
+ test "brandfetch_crypto_url refuses a symbol carrying URL delimiters" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+ Setting.stubs(:brand_fetch_logo_size).returns(120)
+
+ [ "BTC/../ETH", "BTC?c=leak", "BTC#frag", "BTC ETH", "..", ".BTC", "BTC%2F" ].each do |symbol|
+ assert_nil Security.brandfetch_crypto_url(symbol), "#{symbol.inspect} reached the URL"
+ end
+ end
+
+ # Real tickers carry dots and dashes — USDC.e before canonicalisation, and
+ # dashed pairs from some providers. The guard must not swallow them.
+ test "brandfetch_crypto_url still accepts the punctuation real tickers use" do
+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
+ Setting.stubs(:brand_fetch_logo_size).returns(120)
+
+ [ "BTC", "USDC.E", "WSTETH", "1INCH", "BTC-B" ].each do |symbol|
+ assert_not_nil Security.brandfetch_crypto_url(symbol), "#{symbol.inspect} was refused"
+ end
+ end
test "brandfetch_crypto_url returns nil when Brandfetch is not configured" do
Setting.stubs(:brand_fetch_client_id).returns(nil)
assert_nil Security.brandfetch_crypto_url("BTC")
diff --git a/test/system/onchain_wallets_test.rb b/test/system/onchain_wallets_test.rb
index 5afc2f387b..b3f27b044e 100644
--- a/test/system/onchain_wallets_test.rb
+++ b/test/system/onchain_wallets_test.rb
@@ -45,11 +45,20 @@ class OnchainWalletsTest < ApplicationSystemTestCase
open_onchain_panel
# The provider panel opens in the drawer frame.
- assert_text I18n.t("settings.providers.onchain_wallet_panel.keyless_title")
assert_text I18n.t("onchain_wallet_items.price_provider_warning.title")
+ # The read-only reassurance is no longer a permanent banner here...
+ assert_no_text I18n.t("settings.providers.onchain_wallet_panel.keyless_title")
+
click_on I18n.t("settings.providers.onchain_wallet_panel.add_wallet")
+ # ...it lives where the address is pasted. Scoped to the modal, because a
+ # page-wide assertion would pass from any frame and prove nothing about
+ # where the banner actually went.
+ within "turbo-frame#modal" do
+ assert_text I18n.t("settings.providers.onchain_wallet_panel.keyless_title")
+ end
+
# The linking modal opens on top of the drawer.
assert_text I18n.t("onchain_wallet_items.new_wallet.title")
assert_text I18n.t("onchain_wallet_items.new_wallet.bitcoin_single_address_note")
@@ -89,7 +98,9 @@ class OnchainWalletsTest < ApplicationSystemTestCase
assert_text I18n.t("onchain_wallet_items.manage.title")
assert_text OnchainTestHelper::FAKE_ADDRESS
- # Review tokens reopens the selection with the address untouched.
+ # The per-address actions live in a menu, as repeated row actions do
+ # everywhere else in this app.
+ find("[aria-haspopup='menu']", match: :first).click
click_on I18n.t("onchain_wallet_items.manage.review_tokens")
assert_text I18n.t("onchain_wallet_items.review_tokens.title")
assert_no_selector "input[name='new_address']"