Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Track self-custody wallets natively: Bitcoin, EVM and Solana (#3081)

buzzromain735b62d9c776
diff --git a/app/controllers/onchain_wallet_items_controller.rb b/app/controllers/onchain_wallet_items_controller.rb
new file mode 100644
index 0000000000..c349c2f3d0
--- /dev/null
+++ b/app/controllers/onchain_wallet_items_controller.rb
@@ -0,0 +1,319 @@
+# frozen_string_literal: true
+
+# Self-custody wallet connections. Chain-agnostic throughout: a chain is a
+# registry key that arrives as a parameter, gets validated against the registry,
+# and is never branched on.
+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
+ disconnect_wallet disconnect_asset]
+ before_action :set_wallet, only: %i[review_tokens update_tokens edit_wallet change_address disconnect_wallet]
+
+ def update
+ if @onchain_wallet_item.update(onchain_wallet_item_params)
+ render_panel_success(t(".success"))
+ else
+ render_panel_error(@onchain_wallet_item.errors.full_messages.join(", "))
+ end
+ end
+
+ def destroy
+ @onchain_wallet_item.destroy_later
+ redirect_to settings_providers_path, notice: t(".success"), status: :see_other
+ end
+
+ def sync
+ @onchain_wallet_item.sync_later unless @onchain_wallet_item.syncing?
+
+ respond_to do |format|
+ format.html { redirect_back_or_to settings_providers_path }
+ format.json { head :ok }
+ end
+ end
+
+ # Turns the "no crypto prices configured" warning into one click. Without a
+ # crypto-capable market data provider every on-chain holding is valued at zero,
+ # which reads as a broken sync; making the user go and find the setting is how
+ # that becomes a support ticket instead of a fix.
+ def enable_crypto_prices
+ unless self_hosted?
+ return redirect_back_or_to settings_providers_path, alert: t(".not_self_hosted")
+ end
+
+ Onchain::SecurityResolver.enable_price_provider!
+
+ redirect_back_or_to settings_providers_path, notice: t(".success")
+ end
+
+ # Step 1: paste an address.
+ def new_wallet
+ @address = nil
+ end
+
+ # Step 2: work out the chain if it wasn't given, then show what is there.
+ def preview_wallet
+ @address = normalized_address
+ return render_new_wallet(t(".errors.address_required")) if @address.blank?
+
+ @chain = requested_chain
+ if @chain.blank?
+ detection = OnchainWalletItem::ChainDetector.new(preview_item, @address).detect
+ return render_new_wallet(t(".errors.unrecognized_address")) if detection.unrecognized?
+
+ if detection.ambiguous?
+ @detection = detection
+ return render :choose_chain
+ end
+
+ @chain = detection.chain
+ end
+
+ # Only now can the address be put in its canonical form: what counts as the
+ # same address is a per-chain question, and the duplicate check has to run on
+ # the canonical form or two spellings become two wallets.
+ @address = Onchain::Chains.canonical_address(@chain, @address)
+
+ return render_new_wallet(t(".errors.already_linked")) if Current.family.onchain_address_linked?(@chain, @address)
+
+ snapshot = fetch_snapshot(@chain, @address)
+ return render_new_wallet(@provider_error) if snapshot.nil?
+
+ @assets_truncated = snapshot.assets_truncated?
+ @review = OnchainWalletItem::TokenReview.new(snapshot: snapshot)
+ render :token_review
+ end
+
+ # Step 3: track the assets that were ticked.
+ def link_wallet
+ @address = normalized_address
+ @chain = requested_chain
+ return render_new_wallet(t(".errors.unrecognized_address")) if @chain.blank? || @address.blank?
+
+ @address = Onchain::Chains.canonical_address(@chain, @address)
+ return render_new_wallet(t(".errors.already_linked")) if Current.family.onchain_address_linked?(@chain, @address)
+
+ snapshot = fetch_snapshot(@chain, @address)
+ return render_new_wallet(@provider_error) if snapshot.nil?
+
+ # The connection is created only now. Reading the address needs none, so a
+ # failed read must not leave an empty one behind — the same reason previewing
+ # uses an unsaved one.
+ result = OnchainWalletItem::WalletLinker
+ .new(Current.family.onchain_wallet_item!, chain: @chain, address: @address)
+ .link(snapshot: snapshot, selected_keys: params[:assets])
+
+ unless result.success?
+ @assets_truncated = snapshot.assets_truncated?
+ @review = OnchainWalletItem::TokenReview.new(snapshot: snapshot)
+ # Telling someone who ticked three assets to "pick at least one" sends them
+ # back to tick the same three.
+ flash.now[:alert] = if result.errors.any?
+ t(".errors.none_tracked", assets: result.errors.to_sentence)
+ else
+ t(".errors.nothing_selected")
+ end
+ return render :token_review, status: :unprocessable_entity
+ end
+
+ flash[:alert] = t(".errors.some_failed", assets: result.errors.to_sentence) if result.errors.any?
+ redirect_to accounts_path, notice: t(".success", count: result.created), status: :see_other
+ end
+
+ # Everything a linked wallet can have done to it, in one place.
+ def manage
+ end
+
+ # The token screen again, with the address left alone. Without this the only
+ # way to stop tracking one asset would be to change the address.
+ def review_tokens
+ snapshot = fetch_snapshot(@chain, @address)
+ return redirect_to_manage(alert: @provider_error) if snapshot.nil?
+
+ @assets_truncated = snapshot.assets_truncated?
+ @review = review_for(snapshot)
+ end
+
+ def update_tokens
+ snapshot = fetch_snapshot(@chain, @address)
+ return redirect_to_manage(alert: @provider_error) if snapshot.nil?
+
+ result = wallet_linker.revise(snapshot: snapshot, selected_keys: params[:assets])
+
+ unless result.changed?
+ @assets_truncated = snapshot.assets_truncated?
+ @review = review_for(snapshot)
+ flash.now[:alert] = if result.errors.any?
+ t(".errors.none_tracked", assets: result.errors.to_sentence)
+ else
+ t(".errors.no_changes")
+ end
+ return render :review_tokens, status: :unprocessable_entity
+ end
+
+ flash[:alert] = t(".errors.some_failed", assets: result.errors.to_sentence) if result.errors.any?
+ 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)
+
+ redirect_to_manage(notice: t(".success", count: removed))
+ end
+
+ def disconnect_asset
+ onchain_account = @onchain_wallet_item.onchain_wallet_accounts.find(params[:onchain_wallet_account_id])
+ onchain_account.destroy!
+
+ redirect_to_manage(notice: t(".success", symbol: onchain_account.symbol))
+ end
+
+ private
+ def set_onchain_wallet_item
+ @onchain_wallet_item = Current.family.onchain_wallet_items.find(params[:id])
+ end
+
+ # A wallet is a (chain, address) couple, and only one this connection already
+ # tracks: every management action is scoped through the family's own item.
+ def set_wallet
+ @chain = requested_chain
+ @address = normalized_address
+
+ return if @chain.present? && @onchain_wallet_item.tracks_address?(@chain, @address)
+
+ redirect_to_manage(alert: t("onchain_wallet_items.errors.wallet_not_found"))
+ end
+
+ def wallet_linker
+ OnchainWalletItem::WalletLinker.new(@onchain_wallet_item, chain: @chain, address: @address)
+ end
+
+ def review_for(snapshot)
+ OnchainWalletItem::TokenReview.new(
+ snapshot: snapshot,
+ tracked_accounts: @onchain_wallet_item.accounts_for_wallet(@chain, @address).to_a
+ )
+ end
+
+ def redirect_to_manage(flash_message)
+ 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)
+ # Blank means "leave the stored key alone", not "clear it".
+ permitted.delete(:etherscan_api_key) if permitted[:etherscan_api_key].blank?
+ permitted
+ end
+
+ # Reading an address needs no saved connection, so previewing one never
+ # leaves an empty item behind for an abandoned flow.
+ def preview_item
+ @preview_item ||= Current.family.onchain_wallet_item ||
+ Current.family.onchain_wallet_items.new(name: I18n.t("onchain.institution_name"))
+ end
+
+ def normalized_address
+ params[:address].to_s.strip
+ end
+
+ # Only a chain the registry knows can get through.
+ def requested_chain
+ chain = params[:chain].to_s.strip
+ Onchain::Chains.exists?(chain) ? chain : nil
+ end
+
+ # Expected data-source failures become a localized message. Anything else is
+ # a bug: the user gets a generic message and the details go to the debug log,
+ # never into the response.
+ def fetch_snapshot(chain, address)
+ OnchainWalletItem::Importer.new(preview_item).fetch_snapshot(chain: chain, address: address)
+ rescue Onchain::Chains::RateLimitedError
+ @provider_error = t("onchain_wallet_items.errors.rate_limited")
+ nil
+ rescue Onchain::Chains::UnreachableError
+ @provider_error = t("onchain_wallet_items.errors.chain_unreachable")
+ nil
+ rescue Onchain::Chains::Error
+ @provider_error = t("onchain_wallet_items.errors.unrecognized_address")
+ nil
+ rescue StandardError => e
+ capture_unexpected(e, chain: chain)
+ @provider_error = t("onchain_wallet_items.errors.unexpected")
+ nil
+ end
+
+ def capture_unexpected(error, chain:)
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Unexpected on-chain wallet failure: #{error.class}",
+ source: self.class.name,
+ provider_key: "onchain_wallet",
+ family: Current.family,
+ metadata: { chain: chain, error: error.message }
+ )
+ end
+
+ def render_new_wallet(error_message, status: :unprocessable_entity)
+ @error_message = error_message
+ render :new_wallet, status: status
+ end
+
+ def render_panel_success(message)
+ if turbo_frame_request?
+ flash.now[:notice] = message
+ @onchain_wallet_items = Current.family.onchain_wallet_items.active.ordered
+ render turbo_stream: [
+ turbo_stream.update(
+ "onchain_wallet-providers-panel",
+ partial: "settings/providers/onchain_wallet_panel",
+ locals: { onchain_wallet_items: @onchain_wallet_items }
+ ),
+ *flash_notification_stream_items
+ ]
+ else
+ redirect_to settings_providers_path, notice: message, status: :see_other
+ end
+ end
+
+ def render_panel_error(message)
+ if turbo_frame_request?
+ render turbo_stream: turbo_stream.update(
+ "onchain_wallet-providers-panel",
+ partial: "settings/providers/onchain_wallet_panel",
+ locals: { error_message: message }
+ ), status: :unprocessable_entity
+ else
+ redirect_to settings_providers_path, alert: message, status: :see_other
+ end
+ end
+end
diff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rb
index a3f968834f..631c2ef69b 100644
--- a/app/controllers/settings/providers_controller.rb
+++ b/app/controllers/settings/providers_controller.rb
@@ -195,6 +195,7 @@ class Settings::ProvidersController < ApplicationController
{ key: "coinbase", title: "Coinbase", turbo_id: "coinbase", partial: "coinbase_panel" },
{ key: "binance", title: "Binance", turbo_id: "binance", partial: "binance_panel" },
{ key: "kraken", title: "Kraken", turbo_id: "kraken", partial: "kraken_panel" },
+ { key: "onchain_wallet", title: "On-chain wallets", turbo_id: "onchain_wallet", partial: "onchain_wallet_panel" },
{ key: "snaptrade", title: "SnapTrade", turbo_id: "snaptrade", partial: "snaptrade_panel", auto_open: "manage" },
{ key: "ibkr", title: "Interactive Brokers", turbo_id: "ibkr", partial: "ibkr_panel" },
{ key: "trading212", title: "Trading 212", turbo_id: "trading212", partial: "trading212_panel" },
@@ -220,6 +221,7 @@ class Settings::ProvidersController < ApplicationController
"coinbase" => "CoinbaseItem",
"binance" => "BinanceItem",
"kraken" => "KrakenItem",
+ "onchain_wallet" => "OnchainWalletItem",
"snaptrade" => "SnaptradeItem",
"questrade" => "QuestradeItem",
"ibkr" => "IbkrItem",
@@ -256,6 +258,8 @@ class Settings::ProvidersController < ApplicationController
@binance_items = Current.family.binance_items.active.ordered
when "kraken"
@kraken_items = Current.family.kraken_items.active.ordered
+ when "onchain_wallet"
+ @onchain_wallet_items = Current.family.onchain_wallet_items.active.ordered
when "snaptrade"
@snaptrade_items = Current.family.snaptrade_items.includes(:snaptrade_accounts).ordered
when "ibkr"
@@ -299,6 +303,7 @@ class Settings::ProvidersController < ApplicationController
@indexa_capital_items = Current.family.indexa_capital_items.ordered.select(:id)
@binance_items = Current.family.binance_items.active.ordered
@kraken_items = Current.family.kraken_items.active.ordered
+ @onchain_wallet_items = Current.family.onchain_wallet_items.active.ordered
@questrade_items = Current.family.questrade_items.active.ordered.select(:id)
@provider_sync_health = compute_provider_sync_health(family_panel_items)
@@ -330,6 +335,7 @@ class Settings::ProvidersController < ApplicationController
"coinbase" => @coinbase_items,
"binance" => @binance_items,
"kraken" => @kraken_items,
+ "onchain_wallet" => @onchain_wallet_items,
"snaptrade" => @snaptrade_items,
"questrade" => @questrade_items,
"ibkr" => @ibkr_items,
diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rb
index 4744ba041a..2dadf0f46f 100644
--- a/app/helpers/settings_helper.rb
+++ b/app/helpers/settings_helper.rb
@@ -93,6 +93,9 @@ module SettingsHelper
when "kraken"
return { status: :off } unless @kraken_items&.any?
sync_based_summary(key)
+ when "onchain_wallet"
+ return { status: :off } unless @onchain_wallet_items&.any?
+ sync_based_summary(key)
when "snaptrade"
configured_item = @snaptrade_items&.find(&:oauth_configured?)
return { status: :off } unless configured_item
diff --git a/app/models/account.rb b/app/models/account.rb
index e2bb0c0bb5..3cbba8a715 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -374,6 +374,29 @@ class Account < ApplicationRecord
create_from_crypto_exchange_account(kraken_account, family: kraken_account.kraken_item.family)
end
+ # Self-custody assets are wallets, not exchanges: no trade entry by hand,
+ # and no cash side. The balance is written by the provider sync, which is
+ # the only thing that knows what the chain says.
+ def create_from_onchain_wallet_account(onchain_wallet_account)
+ family = onchain_wallet_account.onchain_wallet_item.family
+
+ create_and_sync(
+ {
+ family: family,
+ name: onchain_wallet_account.display_name,
+ balance: 0,
+ cash_balance: 0,
+ currency: onchain_wallet_account.currency.presence || family.currency,
+ accountable_type: "Crypto",
+ accountable_attributes: {
+ subtype: "wallet",
+ tax_treatment: "taxable"
+ }
+ },
+ skip_initial_sync: true
+ )
+ end
+
private
def create_from_crypto_exchange_account(provider_account, family:)
diff --git a/app/models/family.rb b/app/models/family.rb
index 97aa264d56..cecc8a9de7 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -7,6 +7,7 @@ class Family < ApplicationRecord
include Trading212Connectable
include QuestradeConnectable
include RedbarkConnectable
+ include OnchainWalletConnectable
DATE_FORMATS = [
[ "MM-DD-YYYY", "%m-%d-%Y" ],
diff --git a/app/models/family/financial_data_reset.rb b/app/models/family/financial_data_reset.rb
index 10ef3257de..b52c8e3786 100644
--- a/app/models/family/financial_data_reset.rb
+++ b/app/models/family/financial_data_reset.rb
@@ -52,6 +52,7 @@ class Family::FinancialDataReset
lunchflow_items
redbark_items
mercury_items
+ onchain_wallet_items
plaid_items
simplefin_items
snaptrade_items
diff --git a/app/models/family/onchain_wallet_connectable.rb b/app/models/family/onchain_wallet_connectable.rb
new file mode 100644
index 0000000000..a378cd0f91
--- /dev/null
+++ b/app/models/family/onchain_wallet_connectable.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module Family::OnchainWalletConnectable
+ extend ActiveSupport::Concern
+
+ included do
+ has_many :onchain_wallet_items, dependent: :destroy
+ end
+
+ def can_connect_onchain_wallet?
+ true
+ end
+
+ # A family needs only one self-custody connection; every address it tracks
+ # hangs off the same item.
+ def onchain_wallet_item
+ onchain_wallet_items.active.ordered.last
+ end
+
+ def onchain_wallet_item!
+ onchain_wallet_item || create_onchain_wallet_item!
+ end
+
+ def create_onchain_wallet_item!
+ onchain_wallet_items.create!(name: I18n.t("onchain.institution_name")).tap do |item|
+ item.set_onchain_institution_defaults!
+ end
+ end
+
+ def has_onchain_wallets?
+ onchain_wallet_items.active.joins(:onchain_wallet_accounts).exists?
+ end
+
+ # True when an address is already tracked on this chain anywhere in the
+ # family, which is what makes re-linking it a duplicate.
+ def onchain_address_linked?(chain, address)
+ OnchainWalletAccount
+ .where(onchain_wallet_item: onchain_wallet_items.active)
+ .for_wallet(chain, address)
+ .exists?
+ end
+end
diff --git a/app/models/onchain/asset.rb b/app/models/onchain/asset.rb
new file mode 100644
index 0000000000..3bdd86c7fa
--- /dev/null
+++ b/app/models/onchain/asset.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+# One asset held by an address on a chain, normalised so that nothing
+# downstream of a chain adapter needs to know which chain produced it.
+#
+# `kind` is the asset identity model, not the chain: "native" assets are
+# identified by their address alone, token kinds ("erc20", "spl") by their
+# contract/mint. It is what the partial unique indexes on
+# onchain_wallet_accounts key off.
+module Onchain
+ Asset = Data.define(:kind, :symbol, :name, :decimals, :quantity, :contract, :notable) do
+ # `notable` means the data source treats this as a real asset the holder
+ # probably cares about: a priced holding worth more than dust on an EVM
+ # indexer, a place on Solana's verified token list. Anyone can mint a token
+ # with a plausible three-letter symbol, so the symbol itself says nothing —
+ # this is what separates an asset from an airdrop.
+ def initialize(kind:, symbol:, name:, decimals:, quantity:, contract:, notable: false)
+ super
+ end
+
+ def self.native(symbol:, name:, decimals:, quantity:)
+ new(
+ kind: Onchain::Chains::NATIVE_KIND,
+ symbol: symbol,
+ name: name,
+ decimals: decimals,
+ quantity: quantity,
+ contract: nil,
+ notable: true
+ )
+ end
+
+ def self.token(kind:, symbol:, name:, decimals:, quantity:, contract:, notable: false)
+ new(
+ kind: kind,
+ symbol: symbol,
+ name: name,
+ decimals: decimals,
+ quantity: quantity,
+ contract: contract,
+ notable: notable
+ )
+ end
+
+ def notable?
+ notable == true
+ end
+
+ def native?
+ kind == Onchain::Chains::NATIVE_KIND
+ end
+
+ # The identity form of the contract, folded to lower case only for the kinds
+ # where case carries no meaning. See
+ # Onchain::Chains::CASE_INSENSITIVE_CONTRACT_KINDS.
+ def contract_key
+ value = contract.presence
+ return nil if value.nil?
+
+ Onchain::Chains.contract_case_sensitive?(kind) ? value : value.downcase
+ end
+ end
+end
diff --git a/app/models/onchain/asset_budget.rb b/app/models/onchain/asset_budget.rb
new file mode 100644
index 0000000000..967822c740
--- /dev/null
+++ b/app/models/onchain/asset_budget.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+# How many tokens one address may surface in a single read.
+#
+# Real addresses are airdrop dumping grounds: a well-known Ethereum address
+# holds nearly 8,000 ERC-20 tokens, and a comparable Solana one nearly 3,000
+# token accounts. Unbounded, that means a review screen with thousands of rows
+# nobody can use, and — on Solana, where names are looked up in batches — dozens
+# of extra requests per sync.
+#
+# The bound is on what is *surfaced*, not on what is held: the native asset is
+# never affected, and anything already tracked keeps syncing.
+module Onchain
+ module AssetBudget
+ DEFAULT_TOKENS = 200
+ MAX_TOKENS = 5_000
+
+ class << self
+ def tokens
+ configured = ENV["ONCHAIN_MAX_TOKENS_PER_ADDRESS"].to_i
+ return DEFAULT_TOKENS unless configured.positive?
+
+ configured.clamp(1, MAX_TOKENS)
+ end
+ end
+ end
+end
diff --git a/app/models/onchain/asset_symbol.rb b/app/models/onchain/asset_symbol.rb
new file mode 100644
index 0000000000..c4bb282660
--- /dev/null
+++ b/app/models/onchain/asset_symbol.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+# Normalises an on-chain token symbol to the asset a price provider knows.
+#
+# The same dollar is called USDC on Ethereum, USDC.e on Arbitrum and USDbC on
+# Base; the same ether is ETH natively and WETH once wrapped. Left alone, each
+# variant becomes its own Security: one of them gets priced and the others sit
+# at zero, and a portfolio holding "the same" asset on two chains reports two
+# different values.
+class Onchain::AssetSymbol
+ # Bridged or wrapped forms that are redeemable 1:1 for the canonical asset, so
+ # pricing them as the canonical asset is exact rather than an approximation.
+ ALIASES = {
+ "USDT0" => "USDT", # LayerZero-bridged USDT
+ "USDBC" => "USDC", # Base's bridged USDC
+ "AXLUSDC" => "USDC", # Axelar-bridged USDC
+ "WETH" => "ETH",
+ "WSOL" => "SOL",
+ "WPOL" => "POL",
+ "WMATIC" => "POL", # MATIC was renamed POL
+ "WXDAI" => "XDAI"
+ }.freeze
+
+ # Bridge markers appended by Avalanche and Arbitrum: USDC.e, BTC.b
+ BRIDGE_SUFFIX = /\.(?:E|B)\z/
+
+ def self.canonical(symbol)
+ normalized = symbol.to_s.strip.upcase
+ return normalized if normalized.empty?
+
+ normalized = normalized.sub(BRIDGE_SUFFIX, "")
+ ALIASES.fetch(normalized, normalized)
+ end
+end
diff --git a/app/models/onchain/bitcoin_adapter.rb b/app/models/onchain/bitcoin_adapter.rb
new file mode 100644
index 0000000000..b804c90558
--- /dev/null
+++ b/app/models/onchain/bitcoin_adapter.rb
@@ -0,0 +1,124 @@
+# frozen_string_literal: true
+
+# Bitcoin, read from a single address.
+#
+# Bitcoin has no account balances: an address owns unspent outputs, so the
+# balance is everything ever paid to it minus everything spent from it. Mempool
+# totals are included, because a spend that is broadcast but unconfirmed has
+# already left the wallet as far as the owner is concerned.
+#
+# Single address only, by design. A Bitcoin wallet is normally an HD wallet: one
+# extended key (xpub/ypub/zpub) derives thousands of addresses and change is
+# sent to derived ones, so tracking a single address under-reports the balance
+# of such a wallet. Supporting extended keys needs either BIP32 derivation — a
+# new dependency this codebase does not want — or a backend that indexes
+# descriptors. The linking UI states this limit rather than burying it in docs.
+class Onchain::BitcoinAdapter
+ include Onchain::ChainAdapter
+
+ SATS_PER_BTC = 100_000_000.to_d
+
+ # P2PKH ("1…") and P2SH ("3…"), Base58Check: no 0, O, I or l.
+ BASE58_PATTERN = /\A[13][1-9A-HJ-NP-Za-km-z]{25,39}\z/
+ # Bech32 (P2WPKH/P2WSH, "bc1q…") and Bech32m (Taproot, "bc1p…"). The bech32
+ # character set excludes 1, b, i and o after the separator.
+ BECH32_PATTERN = /\Abc1[ac-hj-np-z02-9]{11,87}\z/i
+
+ def initialize(credentials: {})
+ @credentials = credentials
+ end
+
+ def valid_address?(address)
+ candidate = address.to_s.strip
+ BASE58_PATTERN.match?(candidate) || BECH32_PATTERN.match?(candidate)
+ end
+
+ # Bech32 is case-insensitive and canonically lowercase — and the API reports it
+ # that way, so an uppercase input would otherwise match no output and silently
+ # produce zero movements. Base58 is case-sensitive and must be left alone.
+ def canonical_address(address)
+ candidate = address.to_s.strip
+ BECH32_PATTERN.match?(candidate) ? candidate.downcase : candidate
+ end
+
+ def fetch_snapshot(address)
+ raise Onchain::Chains::Error, "Invalid Bitcoin address" unless valid_address?(address)
+
+ wrap_provider_errors do
+ summary = provider.get_address(address)
+
+ movements = best_effort_movements { movements_for(address) }
+
+ Onchain::Snapshot.new(
+ assets: [ definition.native_asset(quantity: balance_from(summary)) ],
+ movements: movements || [],
+ history_truncated: movements.nil? || provider.truncated
+ )
+ end
+ end
+
+ def provider_error_classes
+ [ Provider::MempoolSpace::RateLimitError, Provider::MempoolSpace::Error ]
+ end
+
+ private
+ attr_reader :credentials
+
+ def definition
+ Onchain::Chains.find!(Onchain::Chains::BITCOIN)
+ end
+
+ def provider
+ @provider ||= Provider::MempoolSpace.new(max_pages: Onchain::HistoryBudget.pages)
+ end
+
+ # Confirmed plus mempool: funded minus spent.
+ def balance_from(summary)
+ sats = %w[chain_stats mempool_stats].sum do |scope|
+ stats = summary.to_h.fetch(scope, {}).to_h
+ stats.fetch("funded_txo_sum", 0).to_d - stats.fetch("spent_txo_sum", 0).to_d
+ end
+
+ sats / SATS_PER_BTC
+ end
+
+ def movements_for(address)
+ provider.get_address_transactions(address).filter_map do |transaction|
+ amount = net_amount(transaction, address)
+ next if amount.zero?
+
+ Onchain::Movement.new(
+ external_id: transaction["txid"],
+ symbol: definition.native.symbol,
+ contract: nil,
+ amount: amount,
+ timestamp: transaction_date(transaction)
+ )
+ end
+ end
+
+ # What the address gained or lost in this transaction: outputs paid to it
+ # minus the inputs it funded. A transaction that only moves coins between
+ # the address and itself nets to zero and is dropped.
+ def net_amount(transaction, address)
+ received = Array(transaction["vout"]).sum { |output| value_for(output, address) }
+ sent = Array(transaction["vin"]).sum { |input| value_for(input["prevout"], address) }
+
+ (received - sent) / SATS_PER_BTC
+ end
+
+ def value_for(output, address)
+ return 0.to_d unless output.is_a?(Hash)
+ return 0.to_d unless output["scriptpubkey_address"].to_s == address.to_s
+
+ output["value"].to_d
+ end
+
+ # Unconfirmed transactions have no block time; they happened now.
+ def transaction_date(transaction)
+ block_time = transaction.dig("status", "block_time")
+ return Date.current if block_time.blank?
+
+ Time.zone.at(block_time.to_i).to_date
+ end
+end
diff --git a/app/models/onchain/chain_adapter.rb b/app/models/onchain/chain_adapter.rb
new file mode 100644
index 0000000000..b64cbfc2b6
--- /dev/null
+++ b/app/models/onchain/chain_adapter.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+# The contract every chain implementation fulfils. An adapter is the only
+# place in the codebase allowed to know how a specific chain works; it turns
+# that knowledge into an Onchain::Snapshot and nothing else.
+module Onchain::ChainAdapter
+ # @param address [String]
+ # @return [Boolean] whether the address is well-formed for this chain.
+ # Must never make a network call.
+ def valid_address?(_address)
+ raise NotImplementedError, "#{self.class} must implement #valid_address?"
+ end
+
+ # The form of an address this chain considers canonical, so that two spellings
+ # of the same address cannot become two wallets. Case matters on some chains and
+ # not others, which is why only the adapter can answer it.
+ def canonical_address(address)
+ address.to_s.strip
+ end
+
+ # @param address [String]
+ # @return [Onchain::Snapshot]
+ def fetch_snapshot(_address)
+ raise NotImplementedError, "#{self.class} must implement #fetch_snapshot"
+ end
+
+ # The error classes this chain's data sources raise, as
+ # [rate limit class(es), base class(es)]. Either entry may be a single class or
+ # an array, because a chain may read through more than one backend.
+ def provider_error_classes
+ []
+ end
+
+ # Translates a data source's own errors into Onchain::Chains errors. Anything
+ # else — a bug in our code — is left alone so it surfaces as the unexpected
+ # failure it is instead of being reported to the user as a dead explorer.
+ def wrap_provider_errors
+ yield
+ rescue Onchain::Chains::Error
+ raise
+ rescue StandardError => e
+ rate_limit_classes, base_classes = provider_error_classes
+ raise Onchain::Chains::RateLimitedError, e.message if Array(rate_limit_classes).any? { |klass| e.is_a?(klass) }
+ raise Onchain::Chains::UnreachableError, e.message if Array(base_classes).any? { |klass| e.is_a?(klass) }
+
+ raise
+ end
+
+ # Reads transfer history without letting its failure cost the balances.
+ #
+ # A balance is one bounded request and is what a wallet fundamentally is;
+ # history is paginated, an order of magnitude more expensive, and the first
+ # thing a throttled public endpoint refuses. Failing the whole snapshot over it
+ # means a wallet that could have been valued correctly shows nothing at all —
+ # on some free endpoints, permanently.
+ #
+ # Returns nil when the history could not be read, which the caller reports as
+ # an incomplete history rather than as an empty one. Anything that is not the
+ # data source failing still raises: a bug here must not be silently swallowed.
+ def best_effort_movements
+ yield
+ rescue Onchain::Chains::Error
+ raise
+ rescue StandardError => e
+ rate_limit_classes, base_classes = provider_error_classes
+ known = Array(rate_limit_classes).any? { |klass| e.is_a?(klass) } ||
+ Array(base_classes).any? { |klass| e.is_a?(klass) }
+ raise unless known
+
+ Rails.logger.warn("#{self.class.name} - history unavailable, keeping balances only: #{e.class}")
+ nil
+ end
+
+ # Whether this address is worth tracking on this chain, answered with at most
+ # ONE bounded request and never by reading paginated history. Only chains that
+ # share an address format with other chains (every EVM network) need to
+ # override this; elsewhere a well-formed address is answer enough.
+ #
+ # Three answers, not two: true, false, and nil for "could not tell" — a source
+ # that timed out or refused has not reported an empty address. An override
+ # that collapses the third into false lets detection settle on another chain
+ # without asking, which is how a wallet gets linked to the wrong network.
+ def has_activity?(address)
+ valid_address?(address)
+ end
+end
diff --git a/app/models/onchain/chains.rb b/app/models/onchain/chains.rb
new file mode 100644
index 0000000000..90e2d5a006
--- /dev/null
+++ b/app/models/onchain/chains.rb
@@ -0,0 +1,195 @@
+# frozen_string_literal: true
+
+# The single source of truth for which chains exist.
+#
+# Address validation, native asset metadata and which adapter to instantiate
+# all live here. No other file in app/ may name a chain: everything downstream
+# receives an Onchain::Snapshot and works the same for every chain. Adding a
+# chain means adding one entry to BUILTIN and one adapter.
+module Onchain
+ module Chains
+ Error = Class.new(StandardError)
+ UnknownChainError = Class.new(Error)
+ # A chain's data source refused or could not answer. Adapters translate
+ # whatever their explorer raises into these, so callers — the controller
+ # above all — never need to know one chain's error types from another's.
+ UnreachableError = Class.new(Error)
+ RateLimitedError = Class.new(Error)
+
+ # Assets identified by their address alone.
+ NATIVE_KIND = "native"
+
+ # Token identity models that the schema has a partial unique index for
+ # (see CreateOnchainWalletItemsAndAccounts). Registering a chain whose
+ # tokens don't fit one of these would silently lose DB-level uniqueness,
+ # so `register` refuses it.
+ INDEXED_TOKEN_KINDS = %w[erc20 spl].freeze
+
+ # Token kinds whose contract identifier carries no case: an EVM contract is
+ # hex, so 0xAbC and 0xabc are one token. An SPL mint is a Base58 public key
+ # where case is part of the value — downcasing one corrupts it, and two
+ # distinct mints can collide once folded.
+ CASE_INSENSITIVE_CONTRACT_KINDS = %w[erc20].freeze
+
+ NativeAsset = Data.define(:symbol, :name, :decimals)
+
+ Definition = Data.define(:key, :native, :token_kind, :adapter_class_name, :adapter_options) do
+ def label
+ I18n.t("onchain.chains.#{key}", default: key.to_s.titleize)
+ end
+
+ def adapter(credentials: {})
+ adapter_class_name.constantize.new(**adapter_options, credentials: credentials)
+ end
+
+ def supports_tokens?
+ token_kind.present?
+ end
+
+ def asset_kinds
+ [ NATIVE_KIND, token_kind ].compact
+ end
+
+ def native_asset(quantity:)
+ Onchain::Asset.native(
+ symbol: native.symbol,
+ name: native.name,
+ decimals: native.decimals,
+ quantity: quantity
+ )
+ end
+
+ def token_asset(symbol:, name:, decimals:, quantity:, contract:, notable: false)
+ raise Error, "#{key} does not support tokens" unless supports_tokens?
+
+ Onchain::Asset.token(
+ kind: token_kind,
+ symbol: symbol,
+ name: name,
+ decimals: decimals,
+ quantity: quantity,
+ contract: contract,
+ notable: notable
+ )
+ end
+ end
+
+ BITCOIN = "bitcoin"
+
+ ETHEREUM = "ethereum"
+
+ # Every EVM network shares one adapter; what makes them different is data.
+ # `etherscan_chain_id` is set only where a family-supplied Etherscan key is
+ # accepted, which today is Ethereum alone.
+ EVM = [
+ { key: ETHEREUM, symbol: "ETH", name: "Ethereum", explorer_url: "https://eth.blockscout.com", etherscan_chain_id: "1" },
+ { key: "base", symbol: "ETH", name: "Ethereum", explorer_url: "https://base.blockscout.com" },
+ { key: "arbitrum", symbol: "ETH", name: "Ethereum", explorer_url: "https://arbitrum.blockscout.com" },
+ { key: "optimism", symbol: "ETH", name: "Ethereum", explorer_url: "https://optimism.blockscout.com" },
+ { key: "polygon", symbol: "POL", name: "Polygon", explorer_url: "https://polygon.blockscout.com" },
+ { key: "gnosis", symbol: "XDAI", name: "xDai", explorer_url: "https://gnosis.blockscout.com" }
+ ].freeze
+
+ SOLANA = "solana"
+
+ BUILTIN = [
+ Definition.new(
+ key: BITCOIN,
+ native: NativeAsset.new(symbol: "BTC", name: "Bitcoin", decimals: 8),
+ token_kind: nil,
+ adapter_class_name: "Onchain::BitcoinAdapter",
+ adapter_options: {}
+ ),
+ *EVM.map do |evm|
+ Definition.new(
+ key: evm[:key],
+ native: NativeAsset.new(symbol: evm[:symbol], name: evm[:name], decimals: 18),
+ token_kind: "erc20",
+ adapter_class_name: "Onchain::EvmAdapter",
+ adapter_options: {
+ chain: evm[:key],
+ explorer_url: evm[:explorer_url],
+ etherscan_chain_id: evm[:etherscan_chain_id]
+ }.compact
+ )
+ end,
+ Definition.new(
+ key: SOLANA,
+ native: NativeAsset.new(symbol: "SOL", name: "Solana", decimals: 9),
+ token_kind: "spl",
+ adapter_class_name: "Onchain::SolanaAdapter",
+ adapter_options: {}
+ )
+ ].freeze
+
+ class << self
+ def all
+ registry.values
+ end
+
+ def keys
+ registry.keys
+ end
+
+ def find(key)
+ registry[key.to_s]
+ end
+
+ def find!(key)
+ find(key) || raise(UnknownChainError, "Unknown chain: #{key}")
+ end
+
+ def exists?(key)
+ find(key).present?
+ end
+
+ def adapter_for(key, credentials: {})
+ find!(key).adapter(credentials: credentials)
+ end
+
+ def valid_address?(key, address)
+ definition = find(key)
+ return false unless definition
+
+ definition.adapter.valid_address?(address)
+ end
+
+ def contract_case_sensitive?(asset_kind)
+ !CASE_INSENSITIVE_CONTRACT_KINDS.include?(asset_kind.to_s)
+ end
+
+ # The canonical spelling of an address on a chain, or the input stripped when
+ # the chain is unknown.
+ def canonical_address(key, address)
+ definition = find(key)
+ return address.to_s.strip unless definition
+
+ definition.adapter.canonical_address(address)
+ end
+
+ # Chains whose address format accepts this string. A 0x address matches
+ # every EVM network, which is what makes chain detection necessary.
+ def matching(address)
+ all.select { |definition| definition.adapter.valid_address?(address) }
+ end
+
+ # Test seam for the fake chain, and the hook a future plugin would use.
+ def register(definition)
+ unless definition.token_kind.nil? || INDEXED_TOKEN_KINDS.include?(definition.token_kind)
+ raise Error, "token_kind #{definition.token_kind.inspect} has no unique index"
+ end
+
+ registry[definition.key.to_s] = definition
+ end
+
+ def unregister(key)
+ registry.delete(key.to_s)
+ end
+
+ private
+ def registry
+ @registry ||= BUILTIN.index_by { |definition| definition.key.to_s }
+ end
+ end
+ end
+end
diff --git a/app/models/onchain/detection_budget.rb b/app/models/onchain/detection_budget.rb
new file mode 100644
index 0000000000..86f16d61d9
--- /dev/null
+++ b/app/models/onchain/detection_budget.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+# How long detection may spend answering "is this address worth tracking here?".
+#
+# Detection runs on the request thread, and an address shape can match several
+# chains, so this is what stands between a linking form and a page that hangs.
+#
+# Two numbers, because one is not enough. TIMEOUT is handed to the HTTP client,
+# which applies it *per socket operation* — HTTParty maps it onto net/http's
+# open, read and write timeouts individually, so a single probe can legitimately
+# take a multiple of it. DEADLINE is therefore the one that actually bounds the
+# page: probes run concurrently and are abandoned once it passes, whatever their
+# client is doing.
+#
+# The timeout is deliberately generous. It was 5s, which sat directly on the
+# median latency of one of the public explorers and turned roughly a fifth of
+# probes into a timeout that read as "this wallet is empty". Being slow to
+# answer and having nothing to report are different things, and the cost of
+# confusing them is a wallet the user cannot link.
+module Onchain
+ module DetectionBudget
+ DEFAULT_TIMEOUT = 10
+ MAX_TIMEOUT = 30
+
+ # Headroom over a single probe's timeout, so that a probe which is merely
+ # slow still lands, while a stuck one is dropped.
+ DEADLINE_HEADROOM = 2
+
+ RETRIES = 0
+
+ class << self
+ def timeout
+ configured = ENV["ONCHAIN_DETECTION_TIMEOUT"].to_i
+ return DEFAULT_TIMEOUT unless configured.positive?
+
+ configured.clamp(1, MAX_TIMEOUT)
+ end
+
+ def deadline
+ timeout + DEADLINE_HEADROOM
+ end
+
+ def retries
+ RETRIES
+ end
+ end
+ end
+end
diff --git a/app/models/onchain/evm_adapter.rb b/app/models/onchain/evm_adapter.rb
new file mode 100644
index 0000000000..42c514c4b4
--- /dev/null
+++ b/app/models/onchain/evm_adapter.rb
@@ -0,0 +1,212 @@
+# frozen_string_literal: true
+
+# Every EVM network, read through an interchangeable explorer backend.
+#
+# One adapter class serves all of them: the network's identity (its label,
+# native coin and explorer URL) is data in the chain registry, so adding a
+# network is a registry entry rather than a branch here.
+#
+# The unit being tracked is the (chain, address) couple. A 0x address is valid on
+# every EVM network and holds different balances on each, which is why detection
+# asks each candidate network whether the address is worth tracking there — one
+# bounded request per network, never history — and why the user chooses when more
+# than one answers yes.
+class Onchain::EvmAdapter
+ include Onchain::ChainAdapter
+
+ ADDRESS_PATTERN = /\A0x[0-9a-fA-F]{40}\z/
+ NATIVE_DECIMALS = 18
+
+ # Below this, a priced holding is dust rather than something the holder is
+ # tracking on purpose. Only used to decide what the review screen pre-ticks:
+ # measured on a real airdropped address, market-cap presence alone leaves
+ # thousands of tokens looking credible, while holding value separates them.
+ DUST_VALUE = 1.to_d
+
+ attr_reader :chain, :explorer_url, :etherscan_chain_id
+
+ def initialize(chain:, explorer_url:, etherscan_chain_id: nil, credentials: {})
+ @chain = chain.to_s
+ @explorer_url = explorer_url
+ @etherscan_chain_id = etherscan_chain_id
+ @credentials = credentials
+ end
+
+ def valid_address?(address)
+ ADDRESS_PATTERN.match?(address.to_s.strip)
+ end
+
+ # Hex is hex: the mixed case of a checksummed address carries no identity, so
+ # 0xABC… and 0xabc… are one wallet and must not become two.
+ def canonical_address(address)
+ address.to_s.strip.downcase
+ end
+
+ # Deliberately asks the keyless backend: its address summary reports token
+ # holdings as well as the coin balance, so a wallet holding only ERC-20 tokens
+ # is still found, and it costs exactly one request. An explorer being down
+ # must not break the linking flow, so a failure means "not detected here"
+ # rather than an error the user has to interpret.
+ def has_activity?(address)
+ return false unless valid_address?(address)
+
+ detection_backend.has_activity?(address)
+ rescue StandardError => e
+ Rails.logger.warn("Onchain::EvmAdapter(#{chain}) - activity probe failed: #{e.class}")
+ # Not false: an explorer that timed out has not told us the address is
+ # empty here, and answering "no" would let detection settle on another
+ # chain without ever asking the user.
+ nil
+ end
+
+ def fetch_snapshot(address)
+ raise Onchain::Chains::Error, "Invalid EVM address" unless valid_address?(address)
+
+ wrap_provider_errors do
+ tokens = token_assets(address)
+ movements = best_effort_movements { movements(address) }
+
+ Onchain::Snapshot.new(
+ assets: [ native_asset(address), *tokens ],
+ movements: movements || [],
+ history_truncated: movements.nil? || history_backend.truncated,
+ assets_truncated: @assets_truncated
+ )
+ end
+ end
+
+ # Either backend can be in play within one snapshot, so both error families
+ # have to map onto the chain-agnostic ones.
+ def provider_error_classes
+ [
+ [ Provider::Blockscout::RateLimitError, Provider::Etherscan::RateLimitError ],
+ [ Provider::Blockscout::Error, Provider::Etherscan::Error ]
+ ]
+ end
+
+ # What an address currently holds always comes from the keyless indexer, even
+ # when a key is configured. Etherscan has no free endpoint that enumerates an
+ # address's tokens, so a keyed read would have to sum transfer history — which
+ # is wrong for a rebasing token and wrong outright once history is capped. The
+ # summary that answers this is one request either way, so there is nothing to
+ # buy here.
+ def balance_backend
+ keyless_backend
+ end
+
+ # History is where a key actually helps: it is the paginated, rate-limited
+ # half of the work.
+ def history_backend
+ etherscan_backend || keyless_backend
+ end
+
+ private
+ attr_reader :credentials
+
+ def definition
+ Onchain::Chains.find!(chain)
+ end
+
+ def keyless_backend
+ @keyless_backend ||= Provider::Blockscout.new(
+ chain: chain,
+ base_url: explorer_url,
+ max_pages: Onchain::HistoryBudget.pages
+ )
+ end
+
+ # Detection asks every candidate network in turn on the request thread, so it
+ # reads with the detection budget rather than the sync's: one short attempt,
+ # no retry.
+ def detection_backend
+ @detection_backend ||= Provider::Blockscout.new(
+ chain: chain,
+ base_url: explorer_url,
+ request_timeout: Onchain::DetectionBudget.timeout,
+ max_retries: Onchain::DetectionBudget.retries
+ )
+ end
+
+ def etherscan_backend
+ return nil if etherscan_chain_id.blank?
+ return nil if credentials[:etherscan_api_key].blank?
+
+ @etherscan_backend ||= Provider::Etherscan.new(
+ api_key: credentials[:etherscan_api_key],
+ chain_id: etherscan_chain_id,
+ max_pages: Onchain::HistoryBudget.pages
+ )
+ end
+
+ # Always present, even at zero: the native coin is what the wallet is, and a
+ # wallet that spent everything still has a history worth keeping.
+ def native_asset(address)
+ definition.native_asset(quantity: scale(balance_backend.native_balance(address), NATIVE_DECIMALS))
+ end
+
+ def token_assets(address)
+ held = balance_backend.token_balances(address).select do |token|
+ scale(token[:raw_amount], token[:decimals]).positive?
+ end
+
+ surfaced = rank(held).first(Onchain::AssetBudget.tokens)
+ @assets_truncated = held.size > surfaced.size
+
+ surfaced.map do |token|
+ definition.token_asset(
+ symbol: token[:symbol].presence || short_contract(token[:contract]),
+ name: token[:name].presence || token[:symbol].presence || short_contract(token[:contract]),
+ decimals: token[:decimals],
+ quantity: scale(token[:raw_amount], token[:decimals]),
+ contract: token[:contract],
+ notable: notable?(token)
+ )
+ end
+ end
+
+ # A holding the indexer can price, worth more than dust.
+ def notable?(token)
+ return false if token[:rate].nil?
+
+ (scale(token[:raw_amount], token[:decimals]) * token[:rate]) >= DUST_VALUE
+ end
+
+ # Market cap first, because that is the signal the indexer already gives us
+ # for telling a real asset from an airdrop, then contract address so the
+ # order — and therefore what survives the cap — is identical between two
+ # reads of an unchanged address.
+ def rank(tokens)
+ tokens.sort_by do |token|
+ [ token[:market_cap].present? ? 0 : 1, -token[:market_cap].to_d, token[:contract].to_s ]
+ end
+ end
+
+ def movements(address)
+ history_backend.transfers(address).filter_map do |transfer|
+ next if transfer[:timestamp].blank?
+
+ amount = scale(transfer[:raw_amount], transfer[:decimals])
+ next if amount.zero?
+
+ Onchain::Movement.new(
+ external_id: transfer[:external_id],
+ symbol: transfer[:symbol].presence || definition.native.symbol,
+ contract: transfer[:contract],
+ amount: amount,
+ timestamp: transfer[:timestamp]
+ )
+ end
+ end
+
+ # Explorers report amounts in a token's smallest unit; decimals turn that
+ # back into whole units.
+ def scale(raw_amount, decimals)
+ BigDecimal(raw_amount.to_s.presence || "0") / (10.to_d**decimals.to_i)
+ rescue ArgumentError
+ 0.to_d
+ end
+
+ def short_contract(contract)
+ contract.to_s.first(10)
+ end
+end
diff --git a/app/models/onchain/history_budget.rb b/app/models/onchain/history_budget.rb
new file mode 100644
index 0000000000..58a77f7816
--- /dev/null
+++ b/app/models/onchain/history_budget.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+# How deep a single sync reads an address's transfer history.
+#
+# Every source is a free, shared endpoint that throttles, so history has to be
+# bounded — but the bound is a hosting decision, not a property of a chain. A
+# self-hoster with their own node or indexer can raise it; the default keeps a
+# public endpoint usable.
+#
+# Balances never depend on this: they come from a summary, not from history.
+module Onchain
+ module HistoryBudget
+ DEFAULT_PAGES = 10
+ PAGE_SIZE = 25
+ MAX_PAGES = 200
+
+ # Sources that answer one transaction per request (Solana's getTransaction)
+ # get their own, much smaller budget: reading a page of 25 costs one request
+ # on Bitcoin and 25 on Solana, so the same nominal depth is an order of
+ # magnitude more expensive there. Scaled off the page budget so one knob
+ # still moves both, anchored on defaults that a public endpoint can serve.
+ DEFAULT_TRANSACTIONS = 25
+
+ class << self
+ def pages
+ configured = ENV["ONCHAIN_HISTORY_MAX_PAGES"].to_i
+ return DEFAULT_PAGES unless configured.positive?
+
+ configured.clamp(1, MAX_PAGES)
+ end
+
+ def transactions
+ [ (DEFAULT_TRANSACTIONS * pages / DEFAULT_PAGES.to_f).round, 1 ].max
+ end
+ end
+ end
+end
diff --git a/app/models/onchain/movement.rb b/app/models/onchain/movement.rb
new file mode 100644
index 0000000000..01ab23b1bc
--- /dev/null
+++ b/app/models/onchain/movement.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+# A single inbound or outbound transfer of one asset. `amount` is signed in
+# whole units of the asset (positive = received, negative = sent), already
+# scaled out of the chain's smallest unit by the adapter.
+module Onchain
+ Movement = Data.define(:external_id, :symbol, :contract, :amount, :timestamp) do
+ # Left as reported: whether case matters depends on the token kind, which a
+ # movement does not know. Onchain::Snapshot folds when it compares.
+ def contract_key
+ contract.presence
+ end
+
+ def date
+ timestamp&.to_date
+ end
+ end
+end
diff --git a/app/models/onchain/pricing.rb b/app/models/onchain/pricing.rb
new file mode 100644
index 0000000000..b74fc747e0
--- /dev/null
+++ b/app/models/onchain/pricing.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+# Whether an on-chain asset can be valued in a family's currency, and why not.
+#
+# Two things have to be in place, and each is a separate setting the user has to
+# have made. The only provider that prices bare crypto symbols quotes in USD, so
+# a family whose currency is not USD needs one exchange rate on top — and Sure's
+# default exchange rate provider requires an API key, so a self-hosted install
+# with no key has no FX at all.
+#
+# Either gap ends the same way: quantities tracked, everything valued at zero,
+# reported as a broken sync. So both are stated before linking rather than
+# discovered afterwards.
+class Onchain::Pricing
+ PRICE_CURRENCY = "USD"
+
+ class << self
+ def ready_for?(currency)
+ missing_for(currency).empty?
+ end
+
+ # @return [Array<Symbol>] :crypto_provider, :exchange_rate
+ def missing_for(currency)
+ reasons = []
+ reasons << :crypto_provider unless Onchain::SecurityResolver.price_provider_enabled?
+ reasons << :exchange_rate if fx_required?(currency) && !fx_configured?
+ reasons
+ end
+
+ def fx_required?(currency)
+ currency.to_s.upcase.presence && currency.to_s.upcase != PRICE_CURRENCY
+ end
+
+ def fx_configured?
+ ExchangeRate.provider.present?
+ rescue StandardError
+ false
+ end
+ end
+end
diff --git a/app/models/onchain/security_resolver.rb b/app/models/onchain/security_resolver.rb
new file mode 100644
index 0000000000..30b7d6d39c
--- /dev/null
+++ b/app/models/onchain/security_resolver.rb
@@ -0,0 +1,104 @@
+# frozen_string_literal: true
+
+# Maps an on-chain asset symbol onto a Security.
+#
+# The ticker is bound straight to the crypto price provider instead of going
+# through Security::Resolver's provider search: a search for "USDC" can come
+# back as a EUR- or TRY-quoted pair, which would silently value the holding in
+# the wrong currency and then need FX to repair. A "CRYPTO:<SYMBOL>" ticker is
+# understood by the crypto provider as the USD-quoted asset, full stop.
+class Onchain::SecurityResolver
+ TICKER_PREFIX = "CRYPTO:"
+
+ # The only securities provider that prices bare crypto symbols.
+ PRICE_PROVIDER = "binance_public"
+ EXCHANGE_MIC = Provider::BinancePublic::BINANCE_MIC
+
+ # Tickers we are willing to create. Spam airdrops routinely use their symbol
+ # as an advertisement ("Visit site to claim", emoji, URLs); those resolve to
+ # nil rather than polluting the securities table.
+ SYMBOL_PATTERN = /\A[A-Z0-9][A-Z0-9.\-]{0,11}\z/
+
+ class << self
+ # @return [Security, nil] nil when the symbol cannot be a ticker
+ def resolve(symbol:, name: nil)
+ new(symbol: symbol, name: name).resolve
+ end
+
+ # Whether this symbol resolves to something the price provider can quote.
+ # Used to decide which detected tokens are pre-checked for import.
+ def priceable?(symbol)
+ new(symbol: symbol).ticker_symbol.present?
+ end
+
+ # Whether anything is configured that can price crypto at all. When it is
+ # not, every on-chain holding is valued at zero — which users report as a
+ # sync bug — so the UI says so before they link rather than after.
+ def price_provider_enabled?
+ Setting.enabled_securities_providers.include?(PRICE_PROVIDER)
+ end
+
+ # Adds the crypto provider to the enabled securities providers, leaving the
+ # others alone — enabling crypto prices must not turn off whatever is pricing
+ # the user's equities.
+ def enable_price_provider!
+ return if price_provider_enabled?
+
+ Setting.securities_providers = (Setting.enabled_securities_providers + [ PRICE_PROVIDER ]).uniq.join(",")
+ end
+ end
+
+ def initialize(symbol:, name: nil)
+ @symbol = symbol
+ @name = name
+ end
+
+ def resolve
+ return nil if ticker_symbol.blank?
+
+ existing_security || create_security
+ end
+
+ # The canonical symbol this asset is tracked under, or nil when unusable.
+ def ticker_symbol
+ return @ticker_symbol if defined?(@ticker_symbol)
+
+ candidate = Onchain::AssetSymbol.canonical(symbol)
+ @ticker_symbol = SYMBOL_PATTERN.match?(candidate) ? candidate : nil
+ end
+
+ private
+ attr_reader :symbol, :name
+
+ def ticker
+ "#{TICKER_PREFIX}#{ticker_symbol}"
+ end
+
+ # Deliberately ignores exchange_operating_mic. A Security for this ticker may
+ # already exist under another MIC (an exchange provider created it first);
+ # reusing it keeps one asset in one record instead of splitting holdings
+ # across two rows for the same coin.
+ def existing_security
+ security = Security.find_by(ticker: ticker)
+ return nil if security.nil?
+
+ # A blank price_provider falls back to whichever provider happens to be
+ # enabled first, and only the crypto one quotes a bare coin symbol — so a
+ # reused row would price at zero and read as a broken sync. A provider
+ # another integration deliberately chose is left alone: the CRYPTO: prefix
+ # is shared with the exchange integrations, and stomping their choice would
+ # break their pricing to fix ours.
+ security.update!(price_provider: PRICE_PROVIDER) if security.price_provider.blank?
+
+ security
+ end
+
+ def create_security
+ Security.create!(
+ ticker: ticker,
+ name: name.presence || ticker_symbol,
+ exchange_operating_mic: EXCHANGE_MIC,
+ price_provider: PRICE_PROVIDER
+ )
+ end
+end
diff --git a/app/models/onchain/snapshot.rb b/app/models/onchain/snapshot.rb
new file mode 100644
index 0000000000..77e48c34bc
--- /dev/null
+++ b/app/models/onchain/snapshot.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+# Everything one chain adapter can see for one address: the assets currently
+# held, and the movements that produced them. This is the only shape the
+# importer, processor and UI ever consume, which is what keeps them free of
+# per-chain branches.
+module Onchain
+ Snapshot = Data.define(:assets, :movements, :history_truncated, :assets_truncated) do
+ # Both flags default, so a chain that reads everything an address has in one
+ # go says nothing about truncation.
+ def initialize(assets:, movements:, history_truncated: false, assets_truncated: false)
+ super
+ end
+
+ def self.empty
+ new(assets: [], movements: [])
+ end
+
+ def history_truncated?
+ history_truncated == true
+ end
+
+ # True when the address holds more tokens than one read surfaces.
+ def assets_truncated?
+ assets_truncated == true
+ end
+
+ # Movements belonging to a given asset. Tokens match on contract; native
+ # assets match on symbol among the movements that carry no contract.
+ def movements_for(asset)
+ if asset.contract.present?
+ movements.select { |movement| same_contract?(movement.contract, asset.contract, asset.kind) }
+ else
+ movements.select do |movement|
+ movement.contract.blank? && movement.symbol.to_s.casecmp?(asset.symbol.to_s)
+ end
+ end
+ end
+
+ def find_asset(kind:, contract: nil)
+ assets.find do |asset|
+ next false unless asset.kind == kind
+ next asset.contract.blank? if contract.blank?
+
+ same_contract?(asset.contract, contract, kind)
+ end
+ end
+
+ private
+ # Case matters on some token kinds and not others, and only the kind can say
+ # which — see Onchain::Chains::CASE_INSENSITIVE_CONTRACT_KINDS.
+ def same_contract?(left, right, kind)
+ return false if left.blank? || right.blank?
+
+ Onchain::Chains.contract_case_sensitive?(kind) ? left == right : left.casecmp?(right)
+ end
+ end
+end
diff --git a/app/models/onchain/solana_adapter.rb b/app/models/onchain/solana_adapter.rb
new file mode 100644
index 0000000000..32fbaecfb2
--- /dev/null
+++ b/app/models/onchain/solana_adapter.rb
@@ -0,0 +1,307 @@
+# frozen_string_literal: true
+
+# Solana.
+#
+# Unlike an EVM chain, a Solana wallet does not hold its tokens: each SPL token
+# sits in its own token account, owned by the wallet but addressed separately.
+# So balances come from enumerating those accounts (both token programs), not
+# from reading the wallet address, and several accounts can exist for one mint —
+# they are summed. Emptied token accounts are left behind by design and are
+# dropped here.
+#
+# RPC gives no token metadata, only mints, so names come from a keyless token
+# list — and only for mints it reports as verified. Anyone can mint a token
+# calling itself USDC, so an unverified or unknown mint keeps a label that
+# deliberately cannot pass for a ticker: tracked by quantity, valued at zero,
+# rather than handed an unrelated asset's price.
+class Onchain::SolanaAdapter
+ include Onchain::ChainAdapter
+
+ LAMPORTS_PER_SOL = 1_000_000_000.to_d
+
+ # Base58 (no 0, O, I or l). 32-byte keys encode to 43-44 characters, but
+ # shorter encodings are legal, and Bitcoin's Base58 addresses fall inside this
+ # range too — which is exactly why activity is probed rather than assumed.
+ ADDRESS_PATTERN = /\A[1-9A-HJ-NP-Za-km-z]{32,44}\z/
+
+ # Fallback for the handful of mints that must resolve even when the token list
+ # is unreachable. Deliberately short: a wrong guess here would value a holding
+ # as an unrelated asset.
+ KNOWN_MINTS = {
+ "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" => { symbol: "USDC", name: "USD Coin" },
+ "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" => { symbol: "USDT", name: "Tether USD" },
+ "2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo" => { symbol: "PYUSD", name: "PayPal USD" },
+ "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263" => { symbol: "BONK", name: "Bonk" },
+ "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN" => { symbol: "JUP", name: "Jupiter" },
+ "jtojtomepa8beP8AuQc6eXt5FriJwfFMwQx2v2f9mCL" => { symbol: "JTO", name: "Jito" }
+ }.freeze
+
+ # Each signature costs one getTransaction, so the transaction budget is what
+ # bounds a sync on a rate-limited public endpoint. It comes from
+ # Onchain::HistoryBudget so a self-hoster with their own node can raise it.
+ SIGNATURES_PER_SOURCE = 25
+ MAX_TOKEN_ACCOUNTS_FOR_HISTORY = 5
+
+ # Below this, a native balance change is a transaction fee rather than a
+ # transfer worth recording.
+ FEE_DUST = BigDecimal("0.0001")
+
+ def initialize(credentials: {})
+ @credentials = credentials
+ end
+
+ def valid_address?(address)
+ ADDRESS_PATTERN.match?(address.to_s.strip)
+ end
+
+ # One request. A Bitcoin address fits Solana's Base58 shape but is not a valid
+ # 32-byte key, so the node rejects it and we answer "not here" — which is how
+ # the linking flow tells the two apart.
+ def has_activity?(address)
+ return false unless valid_address?(address)
+
+ return true if detection_provider.get_balance(address).positive?
+
+ # A wallet can hold SPL tokens with no SOL of its own: each token account
+ # carries its own rent, so an empty wallet address is not an empty wallet.
+ # Only asked once the balance comes back zero, so the ordinary case still
+ # costs the single request this probe is meant to be. Emptied token accounts
+ # are left behind on Solana by design and are not activity.
+ held_token_accounts(detection_provider.get_token_accounts(address)).any?
+ rescue StandardError => e
+ Rails.logger.warn("Onchain::SolanaAdapter - activity probe failed: #{e.class}")
+ # Not false — see Onchain::ChainAdapter#has_activity? on the third answer.
+ nil
+ end
+
+ def fetch_snapshot(address)
+ raise Onchain::Chains::Error, "Invalid Solana address" unless valid_address?(address)
+
+ wrap_provider_errors do
+ held = held_token_accounts(provider.get_token_accounts(address))
+ token_accounts = surfaced_token_accounts(held)
+ # Resolved once per snapshot, for every surfaced mint at once: assets and
+ # movements must agree on what a token is called. Capping first bounds the
+ # lookups too — an airdrop dump would otherwise cost dozens of requests.
+ load_mint_metadata(token_accounts.map { |account| account[:mint] })
+
+ movements = best_effort_movements { movements(address, token_accounts) }
+
+ Onchain::Snapshot.new(
+ assets: [ native_asset(address), *token_assets(token_accounts) ],
+ movements: movements || [],
+ history_truncated: movements.nil? || @history_truncated,
+ assets_truncated: @assets_truncated
+ )
+ end
+ end
+
+ def provider_error_classes
+ [ Provider::SolanaRpc::RateLimitError, Provider::SolanaRpc::Error ]
+ end
+
+ private
+ attr_reader :credentials
+
+ def definition
+ Onchain::Chains.find!(Onchain::Chains::SOLANA)
+ end
+
+ def provider
+ @provider ||= Provider::SolanaRpc.new
+ end
+
+ # Detection asks every candidate chain in turn on the request thread, so it
+ # reads with the detection budget rather than the sync's: one short attempt,
+ # no retry.
+ def detection_provider
+ @detection_provider ||= Provider::SolanaRpc.new(
+ request_timeout: Onchain::DetectionBudget.timeout,
+ max_retries: Onchain::DetectionBudget.retries
+ )
+ end
+
+ def native_asset(address)
+ definition.native_asset(quantity: provider.get_balance(address).to_d / LAMPORTS_PER_SOL)
+ end
+
+ # Emptied token accounts are left behind on Solana by design.
+ def held_token_accounts(token_accounts)
+ token_accounts.reject { |account| BigDecimal(account[:raw_amount].presence || "0").zero? }
+ end
+
+ # RPC offers no market signal to rank by, so the order is the mint itself:
+ # arbitrary, but identical between two reads of an unchanged address, which is
+ # what keeps the cap from reshuffling the wallet every sync.
+ def surfaced_token_accounts(held)
+ mints = held.map { |account| account[:mint] }.uniq.sort
+ surfaced_mints = mints.first(Onchain::AssetBudget.tokens).to_set
+ @assets_truncated = mints.size > surfaced_mints.size
+
+ held.select { |account| surfaced_mints.include?(account[:mint]) }
+ end
+
+ # Summed per mint: one wallet can own several token accounts for the same
+ # token, and they are one position.
+ def token_assets(token_accounts)
+ token_accounts.group_by { |account| account[:mint] }.filter_map do |mint, accounts|
+ decimals = accounts.first[:decimals]
+ quantity = accounts.sum { |account| BigDecimal(account[:raw_amount].presence || "0") } / (10.to_d**decimals)
+ next if quantity.zero?
+
+ metadata = mint_metadata(mint)
+ definition.token_asset(
+ symbol: metadata[:symbol],
+ name: metadata[:name],
+ decimals: decimals,
+ quantity: quantity,
+ contract: mint,
+ # Only a mint the token list vouches for, or one we ship, is an asset
+ # rather than an airdrop.
+ notable: metadata[:verified] == true
+ )
+ end
+ end
+
+ # Verified metadata for every mint in one request, cached per mint. A token
+ # list that is down or rate limiting is a naming inconvenience, not a sync
+ # failure, so it degrades to the placeholder rather than raising.
+ def load_mint_metadata(mints)
+ unknown = mints.uniq.reject { |mint| KNOWN_MINTS.key?(mint) }
+ @resolved_mints = unknown.any? ? token_list.metadata_for(unknown) : {}
+ rescue StandardError => e
+ Rails.logger.warn("Onchain::SolanaAdapter - token metadata unavailable: #{e.class}")
+ @resolved_mints = {}
+ end
+
+ def token_list
+ @token_list ||= Provider::JupiterTokens.new
+ end
+
+ # Falls back to a placeholder that cannot pass for a ticker, so security
+ # resolution declines it instead of pricing an unrelated asset.
+ def mint_metadata(mint)
+ known = KNOWN_MINTS[mint] || @resolved_mints&.dig(mint)
+ return known.merge(verified: true) if known
+
+ { symbol: "SPL:#{mint.first(4)}…#{mint.last(4)}", name: "SPL token #{mint}", verified: false }
+ end
+
+ def movements(address, token_accounts)
+ pages = signature_sources(address, token_accounts).map do |pubkey|
+ provider.get_signatures(pubkey, limit: SIGNATURES_PER_SOURCE)
+ end
+
+ seen = pages.flatten
+ .uniq { |entry| entry[:signature] }
+ .sort_by { |entry| -entry[:block_time].to_i }
+
+ # A source that fills its page has older signatures we never ask for: the
+ # adapter passes no cursor, so a full page means the read stopped short of
+ # the address's history rather than reaching the end of it. Counting only
+ # the budget would call that history complete.
+ capped_source = pages.any? { |page| page.size >= SIGNATURES_PER_SOURCE }
+
+ budget = Onchain::HistoryBudget.transactions
+ @history_truncated = capped_source || seen.size > budget
+ signatures = seen.first(budget)
+
+ signatures.flat_map do |entry|
+ transaction = provider.get_transaction(entry[:signature])
+ next [] if transaction.blank?
+
+ movements_from(transaction, address, entry)
+ rescue Provider::SolanaRpc::Error => e
+ Rails.logger.warn("Onchain::SolanaAdapter - could not read #{entry[:signature]}: #{e.class}")
+ []
+ end
+ end
+
+ # The wallet's own history plus its largest token accounts: an SPL transfer
+ # is signed against the token account, so the wallet address alone would miss
+ # it.
+ def signature_sources(address, token_accounts)
+ largest = token_accounts
+ .sort_by { |account| -BigDecimal(account[:raw_amount].presence || "0") }
+ .first(MAX_TOKEN_ACCOUNTS_FOR_HISTORY)
+ .filter_map { |account| account[:pubkey] }
+
+ [ address, *largest ].uniq
+ end
+
+ def movements_from(transaction, address, signature_entry)
+ meta = transaction["meta"].to_h
+ return [] if meta["err"].present?
+
+ timestamp = signature_time(transaction, signature_entry)
+ return [] if timestamp.nil?
+
+ signature = signature_entry[:signature]
+
+ [
+ native_movement(transaction, meta, address, signature, timestamp),
+ *token_movements(meta, address, signature, timestamp)
+ ].compact
+ end
+
+ def signature_time(transaction, signature_entry)
+ block_time = signature_entry[:block_time] || transaction["blockTime"]
+ return nil if block_time.blank?
+
+ Time.zone.at(block_time.to_i)
+ end
+
+ def native_movement(transaction, meta, address, signature, timestamp)
+ keys = Array(transaction.dig("transaction", "message", "accountKeys"))
+ index = keys.index { |key| (key.is_a?(Hash) ? key["pubkey"] : key) == address }
+ return nil if index.nil?
+
+ pre = Array(meta["preBalances"])[index]
+ post = Array(meta["postBalances"])[index]
+ return nil if pre.nil? || post.nil?
+
+ amount = (post.to_i - pre.to_i).to_d / LAMPORTS_PER_SOL
+ return nil if amount.abs <= FEE_DUST
+
+ Onchain::Movement.new(
+ external_id: signature,
+ symbol: definition.native.symbol,
+ contract: nil,
+ amount: amount,
+ timestamp: timestamp
+ )
+ end
+
+ def token_movements(meta, address, signature, timestamp)
+ before = token_balances_by_mint(meta["preTokenBalances"], address)
+ after = token_balances_by_mint(meta["postTokenBalances"], address)
+
+ (before.keys | after.keys).filter_map do |mint|
+ amount = after.fetch(mint, 0.to_d) - before.fetch(mint, 0.to_d)
+ next if amount.zero?
+
+ Onchain::Movement.new(
+ external_id: "#{signature}_#{mint}",
+ symbol: mint_metadata(mint)[:symbol],
+ contract: mint,
+ amount: amount,
+ timestamp: timestamp
+ )
+ end
+ end
+
+ def token_balances_by_mint(balances, address)
+ Array(balances).each_with_object({}) do |balance, totals|
+ next unless balance["owner"] == address
+
+ mint = balance["mint"].to_s
+ amount = balance.dig("uiTokenAmount", "amount")
+ decimals = balance.dig("uiTokenAmount", "decimals").to_i
+ next if mint.blank? || amount.blank?
+
+ totals[mint] = totals.fetch(mint, 0.to_d) + (BigDecimal(amount.to_s) / (10.to_d**decimals))
+ end
+ rescue ArgumentError
+ {}
+ end
+end
diff --git a/app/models/onchain_wallet_account.rb b/app/models/onchain_wallet_account.rb
new file mode 100644
index 0000000000..b0e84fc386
--- /dev/null
+++ b/app/models/onchain_wallet_account.rb
@@ -0,0 +1,126 @@
+# frozen_string_literal: true
+
+# One tracked asset, at one address, on one chain. Uniqueness is enforced by
+# three partial indexes — one per asset kind — because a native coin is
+# identified by its address while a token is identified by its contract.
+class OnchainWalletAccount < ApplicationRecord
+ belongs_to :onchain_wallet_item
+
+ has_one :account_provider, as: :provider, dependent: :destroy
+ has_one :account, through: :account_provider, source: :account
+
+ validates :chain, :wallet_address, :asset_kind, :symbol, :currency, presence: true
+ validates :quantity, presence: true
+ validates :decimals, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
+ validate :chain_is_registered
+ validate :asset_kind_is_valid_for_chain
+ validate :contract_matches_asset_kind
+
+ before_validation :normalize_contract_address
+
+ # Native asset first within each wallet, then tokens alphabetically.
+ scope :ordered, -> {
+ order(:chain, :wallet_address, Arel.sql("CASE WHEN asset_kind = 'native' THEN 0 ELSE 1 END"), :symbol)
+ }
+ scope :for_wallet, ->(chain, address) { where(chain: chain, wallet_address: address) }
+ scope :native, -> { where(asset_kind: Onchain::Chains::NATIVE_KIND) }
+ scope :linked, -> { joins(:account_provider) }
+ scope :unlinked, -> { left_joins(:account_provider).where(account_providers: { id: nil }) }
+
+ def native?
+ asset_kind == Onchain::Chains::NATIVE_KIND
+ end
+
+ # True when the last sync stopped on the history budget rather than on the end
+ # of this address's history.
+ def history_truncated?
+ extra.to_h.dig("onchain_wallet", "history_truncated") == true
+ end
+
+ # True when the address holds more tokens than one read surfaces.
+ def assets_truncated?
+ extra.to_h.dig("onchain_wallet", "assets_truncated") == true
+ end
+
+ def chain_definition
+ Onchain::Chains.find(chain)
+ end
+
+ def chain_label
+ chain_definition&.label || chain.to_s.titleize
+ end
+
+ def truncated_address
+ return wallet_address if wallet_address.to_s.length <= 12
+
+ "#{wallet_address.first(6)}…#{wallet_address.last(4)}"
+ end
+
+ def display_name
+ "#{symbol} · #{truncated_address}"
+ end
+
+ # The asset identity this row stands for, so the importer can match it against
+ # a freshly fetched snapshot without caring which chain produced either. Shared
+ # with the review screen, which has to agree on what identifies an asset.
+ def asset_key
+ [ asset_kind, contract_address.presence ].compact.join(":")
+ end
+
+ def matches_asset?(asset)
+ asset.kind == asset_kind && asset.contract_key == contract_address.presence
+ end
+
+ def current_account
+ account
+ end
+
+ def ensure_account_provider!(target_account = nil)
+ acct = target_account || current_account
+ return nil unless acct
+
+ AccountProvider
+ .find_or_initialize_by(provider_type: self.class.name, provider_id: id)
+ .tap do |link|
+ link.account = acct
+ link.save!
+ end
+ end
+
+ private
+ # Folded only where case carries no meaning, so an SPL mint is stored as the
+ # Base58 key it is rather than an unusable lowercase copy.
+ def normalize_contract_address
+ value = contract_address.presence
+ self.contract_address = if value.nil? || Onchain::Chains.contract_case_sensitive?(asset_kind)
+ value
+ else
+ value.downcase
+ end
+ end
+
+ def chain_is_registered
+ return if chain.blank?
+ return if Onchain::Chains.exists?(chain)
+
+ errors.add(:chain, :invalid)
+ end
+
+ def asset_kind_is_valid_for_chain
+ definition = chain_definition
+ return if definition.nil? || asset_kind.blank?
+ return if definition.asset_kinds.include?(asset_kind)
+
+ errors.add(:asset_kind, :invalid)
+ end
+
+ def contract_matches_asset_kind
+ return if asset_kind.blank?
+
+ if native? && contract_address.present?
+ errors.add(:contract_address, :present)
+ elsif !native? && contract_address.blank?
+ errors.add(:contract_address, :blank)
+ end
+ end
+end
diff --git a/app/models/onchain_wallet_account/processor.rb b/app/models/onchain_wallet_account/processor.rb
new file mode 100644
index 0000000000..6da18fd197
--- /dev/null
+++ b/app/models/onchain_wallet_account/processor.rb
@@ -0,0 +1,373 @@
+# frozen_string_literal: true
+
+# Writes one tracked asset into the account it is linked to: the holding, the
+# account balance, and the entries that reconstruct how the position was built.
+#
+# Chain-agnostic by construction — it only ever reads the row and the payloads
+# the importer stored on it.
+class OnchainWalletAccount::Processor
+ SOURCE = "onchain_wallet"
+
+ attr_reader :onchain_wallet_account
+
+ def initialize(onchain_wallet_account)
+ @onchain_wallet_account = onchain_wallet_account
+ end
+
+ def process
+ return unless account
+
+ security = resolve_security
+ backfill_prices(security) if security
+ price = security ? price_on(security, Date.current) : nil
+ amount = price ? (quantity * price).round(4) : 0.to_d
+
+ import_holding(security, price, amount) if security
+ update_balances(amount)
+ materialize_movements(security) if security
+ report_zero_valuation(security) if security && price.nil?
+ end
+
+ # Converts movements that were recorded as display-only into trades, once a
+ # price for their date exists.
+ #
+ # On a first sync the price history usually is not there yet, so transfers land
+ # as zero-amount excluded entries. Nothing brought them back afterwards: the
+ # syncer only reprocesses assets whose on-chain state changed, and an old
+ # transfer never changes. The cost basis stayed broken for exactly the wallets
+ # that were linked before market data caught up.
+ #
+ # Reads prices from the database only — no network — so this can run for every
+ # linked asset on every sync.
+ # @return [Integer] number of entries upgraded
+ def repair_display_only_movements
+ return 0 unless account
+
+ candidates = display_only_entries
+ return 0 if candidates.empty?
+
+ security = resolve_security
+ return 0 if security.nil?
+
+ candidates.count { |entry| upgrade_to_trade(entry, security) }
+ end
+
+ private
+ def account
+ onchain_wallet_account.current_account
+ end
+
+ def currency
+ onchain_wallet_account.currency.presence || account.currency
+ end
+
+ def quantity
+ onchain_wallet_account.quantity.to_d
+ end
+
+ def resolve_security
+ Onchain::SecurityResolver.resolve(
+ symbol: onchain_wallet_account.symbol,
+ name: onchain_wallet_account.name
+ )
+ end
+
+ # A brand-new Security has no price history, so on a first sync every
+ # movement would fall back to a display-only entry and the cost basis would
+ # never reconstruct. One batched provider call covers the whole window
+ # instead of one call per movement date. A no-op when no crypto price
+ # provider is enabled — the settings panel warns about that up front.
+ def backfill_prices(security)
+ return if security.price_data_provider.blank?
+
+ dates = movement_dates
+ missing = dates.reject { |date| priced_dates(security, dates).include?(date) }
+ return if missing.empty?
+
+ security.import_provider_prices(start_date: missing.min, end_date: Date.current)
+ security.prices.reload
+ rescue StandardError => e
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "Could not backfill on-chain asset prices: #{e.class}",
+ source: self.class.name,
+ provider_key: "onchain_wallet",
+ family: onchain_wallet_account.onchain_wallet_item.family,
+ account: account,
+ metadata: { security_id: security.id, ticker: security.ticker, error: e.message }
+ )
+ end
+
+ # Today included, so a wallet whose movements all predate the sync window
+ # still gets a current valuation.
+ def movement_dates
+ dates = movements.filter_map { |movement| parse_date(movement["date"]) }
+ (dates + [ Date.current ]).uniq
+ end
+
+ def priced_dates(security, dates)
+ @priced_dates ||= security.prices.where(date: dates.min..dates.max).pluck(:date).to_set
+ end
+
+ # The asset's price in the account's currency on (or most recently before)
+ # a date, or nil when it isn't known. An asset with no price is tracked by
+ # quantity and valued at zero rather than guessed at.
+ def price_on(security, date)
+ price = security.prices.where(date: ..date).order(date: :desc).first
+ return nil if price.nil?
+
+ convert(price.price.to_d, from: price.currency, date: date)
+ end
+
+ # Prices come from the crypto provider quoted in USD, so at most one
+ # conversion stands between a price and the account currency.
+ def convert(amount, from:, date:)
+ return amount if from.to_s.upcase == currency.to_s.upcase
+
+ rate = ExchangeRate.find_or_fetch_rate(from: from, to: currency, date: date)
+ return nil if rate.nil?
+
+ amount * rate.rate.to_d
+ end
+
+ # A holding that ends up worth zero because nothing can price crypto, or
+ # because USD cannot be converted into the family's currency, is a
+ # configuration problem rather than chain data. Users report it as a broken
+ # sync, so the reason is recorded where support can see it — once per asset
+ # per changed sync, and only for these causes: a price merely missing for
+ # today is ordinary and already covered by the backfill.
+ def report_zero_valuation(security)
+ reasons = Onchain::Pricing.missing_for(currency)
+ return if reasons.empty?
+
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "On-chain asset valued at zero: #{reasons.map { |reason| reason.to_s.humanize.downcase }.join(" and ")} not configured",
+ source: self.class.name,
+ provider_key: "onchain_wallet",
+ family: onchain_wallet_account.onchain_wallet_item.family,
+ account: account,
+ metadata: {
+ onchain_wallet_account_id: onchain_wallet_account.id,
+ chain: onchain_wallet_account.chain,
+ symbol: onchain_wallet_account.symbol,
+ ticker: security.ticker,
+ quantity: quantity.to_s("F"),
+ currency: currency,
+ reasons: reasons.map(&:to_s)
+ }
+ )
+ end
+
+ def import_holding(security, price, amount)
+ import_adapter.import_holding(
+ security: security,
+ quantity: quantity,
+ amount: amount,
+ currency: currency,
+ date: Date.current,
+ # Holdings must carry a price; an unpriced asset is worth zero rather
+ # than absent, so the quantity still shows up in the portfolio.
+ price: price || 0,
+ external_id: holding_external_id,
+ account_provider_id: onchain_wallet_account.account_provider&.id,
+ source: SOURCE
+ )
+ end
+
+ def update_balances(amount)
+ account.update!(balance: amount, cash_balance: 0, currency: currency)
+ onchain_wallet_account.update!(current_balance: amount)
+ end
+
+ # Movements become one of two things:
+ # - a signed trade, when a price for that date is known, so cost basis and
+ # the value chart reconstruct back to acquisition;
+ # - otherwise a display-only, excluded entry with amount 0, so the transfer
+ # is still visible and its raw payload preserved, without inventing a
+ # value that would distort the account's history.
+ def materialize_movements(security)
+ movements.each do |movement|
+ date = parse_date(movement["date"])
+ next if date.nil?
+
+ amount = parse_amount(movement["amount"])
+ next if amount.nil? || amount.zero?
+
+ price = exact_price_on(security, date)
+
+ if price
+ import_trade(security, movement, date, amount, price)
+ else
+ import_display_only_entry(movement, date, amount)
+ end
+ end
+ end
+
+ def import_trade(security, movement, date, quantity, price)
+ write_trade(
+ security: security,
+ external_id: movement_external_id(movement),
+ date: date,
+ quantity: quantity,
+ price: price
+ )
+ end
+
+ # The one place a movement becomes a trade, used both on the way in and by the
+ # repair pass.
+ #
+ # A movement first seen while its price was unknown already exists as a
+ # display-only entry, and an Entry cannot change entryable type in place —
+ # the shared importer refuses an external_id held by a Transaction. So the
+ # display-only entry is discarded first and the trade takes over its
+ # identity. Without this, every wallet linked before prices were available
+ # raised on the first sync that could price it, which also meant the repair
+ # pass — running after the sync — was never reached.
+ def write_trade(security:, external_id:, date:, quantity:, price:)
+ # One transaction, because the two halves are one change: if writing the
+ # trade fails after the display-only entry is gone, the transfer would
+ # vanish from the account until a later sync happened to rewrite it.
+ Entry.transaction do
+ discard_display_only_entry(external_id)
+
+ import_adapter.import_trade(
+ security: security,
+ quantity: quantity,
+ price: price,
+ # Sure's convention for trades: money leaves the account on a buy.
+ amount: -(quantity * price).round(4),
+ 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),
+ external_id: external_id,
+ source: SOURCE,
+ activity_label: quantity.positive? ? "Buy" : "Sell"
+ )
+ end
+ end
+
+ def discard_display_only_entry(external_id)
+ entry = account.entries.find_by(external_id: external_id, source: SOURCE)
+ return if entry.nil? || !entry.entryable.is_a?(Transaction)
+
+ entry.destroy!
+ end
+
+ def import_display_only_entry(movement, date, quantity)
+ # Built directly rather than through the import adapter: this entry exists
+ # only to be seen, so it must carry amount 0, excluded: true and the raw
+ # movement, none of which the shared transaction importer models.
+ entry = account.entries.find_or_initialize_by(
+ external_id: movement_external_id(movement),
+ source: SOURCE
+ ) { |new_entry| new_entry.entryable = Transaction.new }
+
+ return unless entry.entryable.is_a?(Transaction)
+
+ entry.assign_attributes(
+ date: date,
+ amount: 0,
+ currency: currency,
+ name: movement_name(quantity),
+ excluded: true
+ )
+ entry.entryable.extra = (entry.entryable.extra || {}).merge(SOURCE => movement)
+ entry.save!
+ end
+
+ # The zero-amount, excluded entries this processor writes for unpriced
+ # movements, identified by the external_id prefix it gave them.
+ def display_only_entries
+ account.entries
+ .where(source: SOURCE, entryable_type: "Transaction", excluded: true, amount: 0)
+ .where("external_id LIKE ?", "#{holding_external_id}_%")
+ .includes(:entryable)
+ .to_a
+ end
+
+ def upgrade_to_trade(entry, security)
+ movement = entry.entryable.extra.to_h[SOURCE].to_h
+ amount = parse_amount(movement["amount"])
+ return false if amount.nil? || amount.zero?
+
+ price = exact_price_on(security, entry.date)
+ return false if price.nil?
+
+ Entry.transaction do
+ write_trade(
+ security: security,
+ external_id: entry.external_id,
+ date: entry.date,
+ quantity: amount,
+ price: price
+ )
+ end
+
+ 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
+
+ def translated_name(key, quantity)
+ I18n.t(
+ key,
+ quantity: quantity.abs.round(8).to_s("F"),
+ symbol: onchain_wallet_account.symbol
+ )
+ end
+
+ def movements
+ Array(onchain_wallet_account.raw_movements_payload&.dig("movements"))
+ end
+
+ # Trades need the price of that day, not the nearest one: valuing a
+ # two-year-old transfer at today's price would invent a cost basis.
+ def exact_price_on(security, date)
+ price = security.prices.find_by(date: date)
+ return nil if price.nil?
+
+ convert(price.price.to_d, from: price.currency, date: date)
+ end
+
+ # Stored payloads are written by this code, but a row that survived an older
+ # format should cost one movement rather than the whole asset's processing.
+ #
+ # NaN and the infinities have to be rejected explicitly: BigDecimal parses all
+ # three, and neither is zero, so they would sail through into a trade and only
+ # blow up on rounding.
+ def parse_amount(value)
+ amount = BigDecimal(value.to_s)
+ amount.finite? ? amount : nil
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ def parse_date(value)
+ Date.parse(value.to_s)
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ def holding_external_id
+ "onchain_#{onchain_wallet_account.id}"
+ end
+
+ def movement_external_id(movement)
+ "onchain_#{onchain_wallet_account.id}_#{movement["external_id"]}"
+ end
+
+ def import_adapter
+ @import_adapter ||= Account::ProviderImportAdapter.new(account)
+ end
+end
diff --git a/app/models/onchain_wallet_item.rb b/app/models/onchain_wallet_item.rb
new file mode 100644
index 0000000000..fe2d7f0a39
--- /dev/null
+++ b/app/models/onchain_wallet_item.rb
@@ -0,0 +1,146 @@
+# frozen_string_literal: true
+
+# A family's self-custody connection. One item groups every on-chain address
+# the family tracks; the addresses and the assets held at them live on
+# onchain_wallet_accounts.
+class OnchainWalletItem < ApplicationRecord
+ include Syncable, Provided, Encryptable
+
+ enum :status, { good: "good", requires_update: "requires_update" }, default: :good
+
+ if encryption_ready?
+ encrypts :etherscan_api_key
+ end
+
+ validates :name, presence: true
+
+ belongs_to :family
+
+ has_many :onchain_wallet_accounts, dependent: :destroy
+ has_many :accounts, through: :onchain_wallet_accounts
+
+ scope :active, -> { where(scheduled_for_deletion: false) }
+ scope :syncable, -> { active }
+ scope :ordered, -> { order(created_at: :desc) }
+ scope :needs_update, -> { where(status: :requires_update) }
+
+ before_validation :strip_credentials
+
+ def destroy_later
+ update!(scheduled_for_deletion: true)
+ DestroyJob.perform_later(self)
+ end
+
+ # Self-custody needs no credentials: every chain is readable keyless. The
+ # optional Etherscan key only raises Ethereum's rate limit.
+ def credentials_configured?
+ true
+ end
+
+ def import_latest_onchain_data
+ OnchainWalletItem::Importer.new(self).import
+ end
+
+ # Writes the given rows into the accounts they are linked to. One failing
+ # asset must not stop the rest of the wallet from syncing.
+ def process_accounts(onchain_accounts)
+ onchain_accounts.map do |onchain_account|
+ OnchainWalletAccount::Processor.new(onchain_account).process
+ { onchain_wallet_account_id: onchain_account.id, success: true }
+ rescue StandardError => e
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Failed to process on-chain asset: #{e.class}",
+ source: self.class.name,
+ provider_key: "onchain_wallet",
+ family: family,
+ account: onchain_account.current_account,
+ metadata: {
+ onchain_wallet_item_id: id,
+ onchain_wallet_account_id: onchain_account.id,
+ chain: onchain_account.chain,
+ error: e.message
+ }
+ )
+ { onchain_wallet_account_id: onchain_account.id, success: false, error: e.message }
+ end
+ end
+
+ def schedule_account_syncs(accounts:, parent_sync: nil, window_start_date: nil, window_end_date: nil)
+ accounts.map do |account|
+ account.sync_later(
+ parent_sync: parent_sync,
+ window_start_date: window_start_date,
+ window_end_date: window_end_date
+ )
+ { account_id: account.id, success: true }
+ rescue StandardError => e
+ Rails.logger.error("OnchainWalletItem #{id} - failed to schedule sync for account #{account.id}: #{e.message}")
+ { account_id: account.id, success: false, error: e.message }
+ end
+ end
+
+ # [[chain, address], ...] for every address this item tracks.
+ def wallet_keys
+ onchain_wallet_accounts.distinct.pluck(:chain, :wallet_address)
+ end
+
+ def accounts_for_wallet(chain, address)
+ onchain_wallet_accounts.for_wallet(chain, address)
+ end
+
+ # { [chain, address] => [account, ...] } for the manage UI, ordered so the
+ # native asset of each wallet comes first.
+ def grouped_accounts
+ onchain_wallet_accounts.ordered.group_by { |account| [ account.chain, account.wallet_address ] }
+ end
+
+ # 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
+ 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.
+ def disconnect_wallet!(chain:, address:)
+ accounts_for_wallet(chain, address).destroy_all.size
+ end
+
+ def tracks_address?(chain, address)
+ onchain_wallet_accounts.for_wallet(chain, address).exists?
+ end
+
+ def institution_display_name
+ institution_name.presence || name
+ end
+
+ def set_onchain_institution_defaults!
+ update!(institution_name: I18n.t("onchain.institution_name"))
+ end
+
+ private
+ def strip_credentials
+ return unless etherscan_api_key_changed? && !etherscan_api_key.nil?
+
+ self.etherscan_api_key = etherscan_api_key.to_s.strip.presence
+ end
+end
diff --git a/app/models/onchain_wallet_item/chain_detector.rb b/app/models/onchain_wallet_item/chain_detector.rb
new file mode 100644
index 0000000000..340a478467
--- /dev/null
+++ b/app/models/onchain_wallet_item/chain_detector.rb
@@ -0,0 +1,89 @@
+# frozen_string_literal: true
+
+# Works out which chain an address belongs to.
+#
+# Address formats are not unique to a chain: one 0x address is valid on every
+# EVM network and holds different balances on each, and Bitcoin's Base58 shape
+# overlaps Solana's. So candidates come from the address format, and when there
+# is more than one, each candidate is asked whether the address is worth tracking
+# there — one bounded request per chain, never transfer history.
+#
+# When several chains answer yes, or none does, the user chooses. Silently
+# keeping the first match would link the wrong network and look like a sync bug
+# later.
+class OnchainWalletItem::ChainDetector
+ Result = Data.define(:chain, :candidates, :detected_keys) do
+ def resolved?
+ chain.present?
+ end
+
+ def unrecognized?
+ candidates.empty?
+ end
+
+ def ambiguous?
+ chain.blank? && candidates.any?
+ end
+
+ def detected?(candidate)
+ detected_keys.include?(candidate.key)
+ end
+ end
+
+ def initialize(onchain_wallet_item, address)
+ @onchain_wallet_item = onchain_wallet_item
+ @address = address
+ end
+
+ def detect
+ candidates = onchain_wallet_item.matching_chain_adapters(address)
+ return Result.new(chain: nil, candidates: [], detected_keys: []) if candidates.empty?
+
+ definitions = candidates.map(&:first)
+ return Result.new(chain: definitions.first.key, candidates: definitions, detected_keys: []) if candidates.one?
+
+ answers = probe(candidates)
+ detected = definitions.select { |definition| answers[definition.key] == true }
+
+ Result.new(
+ # One chain answering yes settles it only when every other chain actually
+ # answered. If one could not tell, the address may well belong there too,
+ # and taking the single yes would link the wrong network for good — so the
+ # user is asked, which is the screen an ambiguous answer already produces.
+ chain: (detected.one? && answers.values.none?(&:nil?)) ? detected.first.key : nil,
+ candidates: definitions,
+ detected_keys: detected.map(&:key)
+ )
+ end
+
+ private
+ attr_reader :onchain_wallet_item, :address
+
+ # Concurrently, because the page waits on this: asked in turn, the form's
+ # latency is the sum of every chain's, and a 0x address is a candidate on
+ # six. The deadline is shared and absolute, so it bounds the whole detection
+ # instead of each probe — which is precisely what a per-socket client
+ # timeout cannot do.
+ def probe(candidates)
+ finish_by = Process.clock_gettime(Process::CLOCK_MONOTONIC) + Onchain::DetectionBudget.deadline
+
+ threads = candidates.map do |definition, adapter|
+ thread = Thread.new do
+ Rails.application.executor.wrap { adapter.has_activity?(address) }
+ rescue StandardError => e
+ Rails.logger.warn("OnchainWalletItem::ChainDetector - probe failed for #{definition.key}: #{e.class}")
+ nil
+ end
+
+ [ definition.key, thread ]
+ end
+
+ threads.to_h do |key, thread|
+ remaining = finish_by - Process.clock_gettime(Process::CLOCK_MONOTONIC)
+ answer = thread.join([ remaining, 0 ].max) ? thread.value : nil
+ thread.kill
+
+ [ key, answer ]
+ end
+ end
+end
diff --git a/app/models/onchain_wallet_item/importer.rb b/app/models/onchain_wallet_item/importer.rb
new file mode 100644
index 0000000000..94f6db0d7f
--- /dev/null
+++ b/app/models/onchain_wallet_item/importer.rb
@@ -0,0 +1,233 @@
+# frozen_string_literal: true
+
+# Turns what the chains say into rows on onchain_wallet_accounts.
+#
+# The importer consumes Onchain::Snapshots and knows nothing about any chain:
+# it asks the registry for an adapter, matches the assets it gets back against
+# the rows the user chose to track, and records a digest of that state so the
+# syncer can tell whether anything actually moved.
+#
+# It deliberately never creates rows. Real wallets are full of spam airdrops, so
+# a newly seen token becomes trackable only when the user ticks it in the token
+# review screen.
+class OnchainWalletItem::Importer
+ attr_reader :onchain_wallet_item
+
+ def initialize(onchain_wallet_item)
+ @onchain_wallet_item = onchain_wallet_item
+ @truncation_reported = Set.new
+ end
+
+ # @return [Hash] :wallets_imported, :changed_account_ids
+ def import
+ wallet_keys = onchain_wallet_item.wallet_keys
+ changed_account_ids = []
+ failures = []
+
+ wallet_keys.each do |chain, address|
+ changed_account_ids.concat(import_wallet(chain: chain, address: address))
+ rescue Onchain::Chains::Error => e
+ # One chain being unreachable is not a reason to leave the family's other
+ # wallets unsynced. Recorded per address and carried on; only a wallet whose
+ # every address failed is reported as a failed sync.
+ failures << e
+ report_unreachable(chain: chain, address: address, error: e)
+ end
+
+ raise failures.first if failures.any? && failures.size == wallet_keys.size
+
+ {
+ success: true,
+ wallets_imported: wallet_keys.size - failures.size,
+ wallets_failed: failures.size,
+ changed_account_ids: changed_account_ids
+ }
+ end
+
+ # Refreshes one address. Returns the ids of the rows whose on-chain state
+ # changed, which is what the syncer reprocesses.
+ def import_wallet(chain:, address:)
+ snapshot = fetch_snapshot(chain: chain, address: address)
+
+ onchain_wallet_item.accounts_for_wallet(chain, address).filter_map do |account|
+ apply_snapshot(account, snapshot, chain: chain, address: address)
+ end
+ end
+
+ # Reads an address without touching the database. Used by the linking and
+ # token review flows to show the user what is there before anything is saved.
+ def fetch_snapshot(chain:, address:)
+ onchain_wallet_item.chain_adapter(chain).fetch_snapshot(address)
+ end
+
+ private
+ def apply_snapshot(account, snapshot, chain:, address:)
+ asset = snapshot.assets.find { |candidate| account.matches_asset?(candidate) }
+ attributes = if asset.nil? && snapshot.assets_truncated?
+ # The read was capped before it reached this asset, so its absence says
+ # nothing: we did not learn that it holds nothing, we failed to look.
+ # Zeroing it here would take a real balance off the user's net worth —
+ # the same distinction already made for an address we could not read.
+ last_known_attributes(account, snapshot)
+ else
+ observed_attributes(account, snapshot, asset)
+ end
+
+ # The digest is taken from exactly what is about to be written, so the two
+ # cannot drift apart. Deriving it from a hand-picked subset is how the symbol
+ # was left out once — a Solana placeholder that gained a real name produced
+ # the old digest and was never rewritten — and then the truncation flags,
+ # leaving the UI claiming an incomplete history after one became complete.
+ digest = Digest::SHA256.hexdigest(canonical(attributes).to_json)
+
+ return nil if account.content_hash == digest
+
+ report_truncation(chain: chain, address: address, snapshot: snapshot) if snapshot.history_truncated? || snapshot.assets_truncated?
+
+ account.update!(attributes.merge(content_hash: digest))
+
+ account.id
+ end
+
+ # Key order carries no information, and jsonb does not preserve it: an `extra`
+ # written as {history, assets} comes back as {assets, history}, which would make
+ # the digest of an unchanged wallet flip every other sync. Numbers are compared
+ # by value rather than by representation for the same reason.
+ def canonical(value)
+ case value
+ when Hash then value.map { |key, nested| [ key.to_s, canonical(nested) ] }.sort_by(&:first).to_h
+ when Array then value.map { |entry| canonical(entry) }
+ when BigDecimal then value.to_s("F")
+ else value
+ end
+ end
+
+ # What the chain just said about this asset. An asset genuinely gone from a
+ # complete read is worth zero, not stale.
+ def observed_attributes(account, snapshot, asset)
+ # Sorted so that two reads of the same state produce the same payload, and
+ # therefore the same digest, whatever order the source listed them in.
+ movements = asset ? relevant_movements(snapshot.movements_for(asset)).sort_by { |movement| [ movement.date.to_s, movement.external_id.to_s ] } : []
+
+ {
+ quantity: normalize(asset&.quantity || 0),
+ symbol: asset&.symbol.presence || account.symbol,
+ name: asset&.name.presence || account.name,
+ decimals: asset&.decimals || account.decimals,
+ raw_payload: asset_payload(asset),
+ raw_movements_payload: { "movements" => movements.map { |movement| movement_payload(movement) } },
+ extra: truncation_extra(account, snapshot)
+ }
+ end
+
+ # Everything the row already holds, with only the completeness flags refreshed.
+ def last_known_attributes(account, snapshot)
+ {
+ quantity: account.quantity,
+ symbol: account.symbol,
+ name: account.name,
+ decimals: account.decimals,
+ raw_payload: account.raw_payload,
+ raw_movements_payload: account.raw_movements_payload,
+ extra: truncation_extra(account, snapshot)
+ }
+ end
+
+ # Recorded on the row so the UI can say the read was incomplete instead of
+ # implying what it returned is all there is.
+ def truncation_extra(account, snapshot)
+ account.extra.to_h.deep_merge(
+ "onchain_wallet" => {
+ "history_truncated" => snapshot.history_truncated?,
+ "assets_truncated" => snapshot.assets_truncated?
+ }
+ )
+ end
+
+ def report_unreachable(chain:, address:, error:)
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "On-chain address could not be read: #{error.class.name.demodulize}",
+ source: self.class.name,
+ provider_key: "onchain_wallet",
+ family: onchain_wallet_item.family,
+ metadata: { onchain_wallet_item_id: onchain_wallet_item.id, chain: chain, address: address }
+ )
+ end
+
+ # A capped history is worth a support-visible note, but only once per address
+ # per import, and only when something changed anyway — otherwise an idle
+ # wallet with deep history would log the same line every night.
+ def report_truncation(chain:, address:, snapshot:)
+ return unless @truncation_reported.add?([ chain, address ])
+
+ reasons = []
+ reasons << "not every transfer was read" if snapshot.history_truncated?
+ reasons << "not every token held is surfaced" if snapshot.assets_truncated?
+
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "On-chain read truncated: #{reasons.join("; ")}",
+ source: self.class.name,
+ provider_key: "onchain_wallet",
+ family: onchain_wallet_item.family,
+ metadata: {
+ onchain_wallet_item_id: onchain_wallet_item.id,
+ chain: chain,
+ address: address,
+ history_truncated: snapshot.history_truncated?,
+ assets_truncated: snapshot.assets_truncated?,
+ max_pages: Onchain::HistoryBudget.pages,
+ max_tokens: Onchain::AssetBudget.tokens
+ }
+ )
+ end
+
+ # Movements before the connection's start date are outside the window the
+ # user asked us to reconstruct.
+ def relevant_movements(movements)
+ start_date = onchain_wallet_item.sync_start_date&.to_date
+ movements = movements.reject { |movement| movement.date.nil? }
+ return movements if start_date.nil?
+
+ movements.select { |movement| movement.date >= start_date }
+ end
+
+ # Digest of everything that would change what we write downstream. No
+ # timestamps: two identical reads of an idle wallet must produce the same
+ # digest so the syncer can skip it.
+ def asset_payload(asset)
+ return {} if asset.nil?
+
+ {
+ "kind" => asset.kind,
+ "symbol" => asset.symbol,
+ "name" => asset.name,
+ "decimals" => asset.decimals,
+ "contract" => asset.contract_key,
+ "quantity" => normalize(asset.quantity).to_s("F")
+ }
+ end
+
+ def movement_payload(movement)
+ {
+ "external_id" => movement.external_id,
+ "symbol" => movement.symbol,
+ "contract" => movement.contract_key,
+ "amount" => normalize(movement.amount).to_s("F"),
+ "date" => movement.date.to_s
+ }
+ end
+
+ # Postgres numeric happily stores NaN, and one NaN quantity would poison every
+ # total that reads it, so a non-finite amount is treated as unknown rather
+ # than written.
+ def normalize(value)
+ amount = BigDecimal(value.to_s)
+ amount.finite? ? amount : 0.to_d
+ rescue ArgumentError, TypeError
+ 0.to_d
+ end
+end
diff --git a/app/models/onchain_wallet_item/provided.rb b/app/models/onchain_wallet_item/provided.rb
new file mode 100644
index 0000000000..35ab7da5c1
--- /dev/null
+++ b/app/models/onchain_wallet_item/provided.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+# Connects the item to the chain adapters, injecting the family's optional
+# explorer credential. Adapters are resolved through Onchain::Chains so this
+# concern never learns a chain name.
+module OnchainWalletItem::Provided
+ extend ActiveSupport::Concern
+
+ def chain_adapter(chain)
+ Onchain::Chains.adapter_for(chain, credentials: onchain_credentials)
+ end
+
+ # Chains whose address format matches, paired with their adapter. Used by the
+ # linking flow to work out which chain(s) an address could belong to.
+ def matching_chain_adapters(address)
+ Onchain::Chains.matching(address).map do |definition|
+ [ definition, definition.adapter(credentials: onchain_credentials) ]
+ end
+ end
+
+ def onchain_credentials
+ { etherscan_api_key: etherscan_api_key.presence }
+ end
+end
diff --git a/app/models/onchain_wallet_item/sync_complete_event.rb b/app/models/onchain_wallet_item/sync_complete_event.rb
new file mode 100644
index 0000000000..c5e3e11f47
--- /dev/null
+++ b/app/models/onchain_wallet_item/sync_complete_event.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+class OnchainWalletItem::SyncCompleteEvent
+ def initialize(onchain_wallet_item)
+ @onchain_wallet_item = onchain_wallet_item
+ end
+
+ def broadcast
+ Turbo::StreamsChannel.broadcast_replace_to(
+ @onchain_wallet_item.family,
+ target: ActionView::RecordIdentifier.dom_id(@onchain_wallet_item),
+ partial: "onchain_wallet_items/onchain_wallet_item",
+ locals: { onchain_wallet_item: @onchain_wallet_item }
+ )
+ rescue StandardError => e
+ Rails.logger.warn("OnchainWalletItem::SyncCompleteEvent failed for #{@onchain_wallet_item.id}: #{e.class}")
+ end
+end
diff --git a/app/models/onchain_wallet_item/syncer.rb b/app/models/onchain_wallet_item/syncer.rb
new file mode 100644
index 0000000000..90c5bced62
--- /dev/null
+++ b/app/models/onchain_wallet_item/syncer.rb
@@ -0,0 +1,78 @@
+# frozen_string_literal: true
+
+# Reads every tracked address, then reprocesses only the rows whose on-chain
+# state actually changed. An idle wallet costs reads and nothing else: no
+# holdings, entries or balances are rewritten, and no account syncs are queued.
+class OnchainWalletItem::Syncer
+ include SyncStats::Collector
+
+ attr_reader :onchain_wallet_item
+
+ def initialize(onchain_wallet_item)
+ @onchain_wallet_item = onchain_wallet_item
+ end
+
+ def perform_sync(sync)
+ result = onchain_wallet_item.import_latest_onchain_data
+ onchain_wallet_item.update!(status: :good) if onchain_wallet_item.requires_update?
+
+ collect_setup_stats(sync, provider_accounts: onchain_wallet_item.onchain_wallet_accounts.to_a)
+
+ changed = linked_accounts.where(id: result[:changed_account_ids]).to_a
+ return if changed.empty?
+
+ onchain_wallet_item.process_accounts(changed)
+
+ account_ids = changed.filter_map { |onchain_account| onchain_account.current_account&.id }
+ onchain_wallet_item.schedule_account_syncs(
+ accounts: Account.where(id: account_ids),
+ parent_sync: sync,
+ window_start_date: sync.window_start_date,
+ window_end_date: sync.window_end_date
+ )
+
+ return if account_ids.empty?
+
+ collect_trades_stats(sync, account_ids: account_ids, source: OnchainWalletAccount::Processor::SOURCE)
+ collect_transaction_stats(sync, account_ids: account_ids, source: OnchainWalletAccount::Processor::SOURCE)
+ rescue StandardError => e
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "On-chain wallet sync failed: #{e.class}",
+ source: self.class.name,
+ provider_key: "onchain_wallet",
+ family: onchain_wallet_item.family,
+ metadata: { onchain_wallet_item_id: onchain_wallet_item.id, error: e.message }
+ )
+ mark_failed(sync, e.message)
+ raise
+ end
+
+ # Runs for every linked asset, not just the ones that changed on chain: what
+ # changed here is the price history, which no chain read can tell us about.
+ def perform_post_sync
+ linked_accounts.each do |onchain_account|
+ OnchainWalletAccount::Processor.new(onchain_account).repair_display_only_movements
+ rescue StandardError => e
+ Rails.logger.warn("OnchainWalletItem::Syncer - movement repair failed for #{onchain_account.id}: #{e.class}")
+ end
+ end
+
+ private
+ def linked_accounts
+ onchain_wallet_item.onchain_wallet_accounts.linked.joins(:account).merge(Account.visible)
+ end
+
+ def mark_failed(sync, error_message)
+ sync.start! if sync.respond_to?(:may_start?) && sync.may_start?
+
+ if sync.respond_to?(:may_fail?) && sync.may_fail?
+ sync.fail!
+ elsif sync.respond_to?(:status)
+ sync.update!(status: :failed)
+ end
+
+ sync.update!(error: error_message) if sync.respond_to?(:error)
+ end
+end
diff --git a/app/models/onchain_wallet_item/token_review.rb b/app/models/onchain_wallet_item/token_review.rb
new file mode 100644
index 0000000000..cb2ea851d6
--- /dev/null
+++ b/app/models/onchain_wallet_item/token_review.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+# The list of assets found at an address, for the user to choose from.
+#
+# Nothing is imported without being ticked. Real wallets are full of spam
+# airdrops — and airdrops use plausible short symbols, so "the symbol looks like
+# a ticker" pre-ticks nearly all of them. An asset is pre-ticked only when the
+# data source also treats it as notable: a priced holding above dust on an EVM
+# indexer, a place on Solana's verified token list. Everything else is listed,
+# unchecked, and can still be tracked by quantity if the user wants it.
+class OnchainWalletItem::TokenReview
+ Row = Data.define(:asset, :key, :priceable, :tracked) do
+ def preselected?
+ tracked || (priceable && asset.notable?)
+ end
+
+ def native?
+ asset.native?
+ end
+ end
+
+ # Identifies an asset across the request boundary without trusting the client
+ # for anything else: the quantities and metadata are re-read from the chain
+ # when the selection is applied.
+ def self.key_for(asset)
+ [ asset.kind, asset.contract_key ].compact.join(":")
+ end
+
+ def initialize(snapshot:, tracked_accounts: [])
+ @snapshot = snapshot
+ @tracked_accounts = tracked_accounts
+ end
+
+ def rows
+ @rows ||= (snapshot_rows + orphan_rows).sort_by { |row| [ row.native? ? 0 : 1, row.asset.symbol.to_s ] }
+ end
+
+ # Assets the user is already tracking that the chain no longer reports. They
+ # stay listed so unticking them is still possible once they are gone.
+ def orphan_accounts
+ tracked_accounts.reject { |account| snapshot.assets.any? { |asset| account.matches_asset?(asset) } }
+ end
+
+ private
+ def snapshot_rows
+ snapshot.assets.map { |asset| row_for(asset) }
+ end
+
+ def orphan_rows
+ orphan_accounts.map do |account|
+ row_for(
+ Onchain::Asset.new(
+ kind: account.asset_kind,
+ symbol: account.symbol,
+ name: account.name,
+ decimals: account.decimals,
+ quantity: account.quantity,
+ contract: account.contract_address
+ )
+ )
+ end
+ end
+
+ def row_for(asset)
+ key = self.class.key_for(asset)
+
+ Row.new(
+ asset: asset,
+ key: key,
+ priceable: Onchain::SecurityResolver.priceable?(asset.symbol),
+ tracked: tracked_keys.include?(key)
+ )
+ end
+
+ attr_reader :snapshot, :tracked_accounts
+
+ def tracked_keys
+ @tracked_keys ||= tracked_accounts.map(&:asset_key)
+ end
+end
diff --git a/app/models/onchain_wallet_item/wallet_linker.rb b/app/models/onchain_wallet_item/wallet_linker.rb
new file mode 100644
index 0000000000..61c7fe9869
--- /dev/null
+++ b/app/models/onchain_wallet_item/wallet_linker.rb
@@ -0,0 +1,102 @@
+# frozen_string_literal: true
+
+# Creates the rows and accounts for the assets a user picked at an address.
+#
+# Metadata and quantities are re-read from the chain rather than taken from the
+# form, so a tampered or stale selection can only ever change *which* assets are
+# tracked, never what they claim to hold.
+class OnchainWalletItem::WalletLinker
+ Result = Data.define(:created, :removed, :errors) do
+ def success?
+ created.positive? || removed.positive?
+ end
+
+ def changed?
+ created.positive? || removed.positive?
+ end
+ end
+
+ attr_reader :onchain_wallet_item, :chain, :address
+
+ def initialize(onchain_wallet_item, chain:, address:)
+ @onchain_wallet_item = onchain_wallet_item
+ @chain = chain
+ @address = address
+ end
+
+ def link(snapshot:, selected_keys:)
+ selected = Array(selected_keys).map(&:to_s).to_set
+ created = 0
+ errors = []
+
+ snapshot.assets.each do |asset|
+ next unless selected.include?(OnchainWalletItem::TokenReview.key_for(asset))
+
+ begin
+ create_asset!(asset)
+ created += 1
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e
+ errors << asset.symbol
+ Rails.logger.warn("OnchainWalletItem::WalletLinker - could not link #{asset.symbol}: #{e.class}")
+ end
+ end
+
+ onchain_wallet_item.sync_later if created.positive?
+
+ Result.new(created: created, removed: 0, errors: errors)
+ end
+
+ # The same screen as linking, with the address left alone: ticking adds an
+ # asset, unticking stops tracking it. Without this the only way to drop a
+ # token would be to change the address, which is not the same thing.
+ def revise(snapshot:, selected_keys:)
+ selected = Array(selected_keys).map(&:to_s).to_set
+ tracked = onchain_wallet_item.accounts_for_wallet(chain, address).to_a
+ errors = []
+
+ removed = tracked.count do |onchain_account|
+ next false if selected.include?(onchain_account.asset_key)
+
+ onchain_account.destroy!
+ true
+ end
+
+ created = snapshot.assets.count do |asset|
+ next false unless selected.include?(OnchainWalletItem::TokenReview.key_for(asset))
+ next false if tracked.any? { |onchain_account| onchain_account.matches_asset?(asset) }
+
+ begin
+ create_asset!(asset)
+ true
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e
+ errors << asset.symbol
+ Rails.logger.warn("OnchainWalletItem::WalletLinker - could not link #{asset.symbol}: #{e.class}")
+ false
+ end
+ end
+
+ onchain_wallet_item.sync_later if created.positive?
+
+ Result.new(created: created, removed: removed, errors: errors)
+ end
+
+ private
+ def create_asset!(asset)
+ OnchainWalletAccount.transaction do
+ onchain_account = onchain_wallet_item.onchain_wallet_accounts.create!(
+ chain: chain,
+ wallet_address: address,
+ asset_kind: asset.kind,
+ contract_address: asset.contract,
+ symbol: asset.symbol,
+ name: asset.name,
+ decimals: asset.decimals,
+ quantity: asset.quantity,
+ currency: onchain_wallet_item.family.currency
+ )
+
+ account = Account.create_from_onchain_wallet_account(onchain_account)
+ onchain_account.ensure_account_provider!(account)
+ end
+ end
+end
diff --git a/app/models/provider/blockscout.rb b/app/models/provider/blockscout.rb
new file mode 100644
index 0000000000..348b1d53cc
--- /dev/null
+++ b/app/models/provider/blockscout.rb
@@ -0,0 +1,238 @@
+# frozen_string_literal: true
+
+# Keyless EVM data source backed by a public Blockscout instance.
+#
+# The default backend for every supported network: no API key, and its address
+# summary answers "is this address worth tracking here?" in a single request,
+# including for wallets that hold only tokens. The instance URL comes from the
+# chain registry; self-hosters running their own indexer can override it with
+# BLOCKSCOUT_<CHAIN>_URL.
+class Provider::Blockscout
+ include Provider::EvmExplorer
+ include HTTParty
+ include Provider::HttpTransport
+ extend SslConfigurable
+
+ class Error < StandardError; end
+ class RateLimitError < Error; end
+ class ApiError < Error; end
+
+ # Flags the v2 address summary returns alongside the coin balance. They are
+ # what lets a token-only wallet (zero native balance) be detected without
+ # touching transfer history.
+ ACTIVITY_FLAGS = %w[has_tokens has_token_transfers has_logs].freeze
+
+ ERC20_TYPE = "ERC-20"
+
+ DEFAULT_MAX_PAGES = 10
+ MIN_REQUEST_INTERVAL = 0.2
+ MAX_RETRIES = 3
+ RETRY_BASE_DELAY = 0.5
+
+ default_options.merge!({ timeout: 30 }.merge(httparty_ssl_options))
+
+ attr_reader :chain, :base_url
+
+ # True when any collection stopped on the page budget rather than on its last
+ # page.
+ attr_reader :truncated
+
+ # Detection reads on the request thread and cannot afford the sync's patience,
+ # so both the per-request timeout and the retry count are the caller's to set.
+ def initialize(chain:, base_url:, max_pages: DEFAULT_MAX_PAGES, request_timeout: nil, max_retries: MAX_RETRIES)
+ @chain = chain.to_s
+ @base_url = ENV["BLOCKSCOUT_#{@chain.upcase}_URL"].presence || base_url
+ @max_pages = max_pages
+ @request_timeout = request_timeout
+ @max_retries = max_retries
+ @truncated = false
+ end
+
+ def has_activity?(address)
+ summary = address_summary(address)
+ return false unless summary.is_a?(Hash)
+
+ summary["coin_balance"].to_s.to_d.positive? || ACTIVITY_FLAGS.any? { |flag| summary[flag] == true }
+ end
+
+ def native_balance(address)
+ summary = address_summary(address)
+ summary.is_a?(Hash) ? summary["coin_balance"].to_s : "0"
+ end
+
+ # This endpoint takes no `type` filter — passing one is a 422 — and it answers
+ # with every token standard the address holds, so ERC-20 has to be selected
+ # here. An ERC-721 or ERC-1155 row would otherwise be read as a fungible
+ # balance, turning one NFT into "1 token".
+ def token_balances(address)
+ paginate("/api/v2/addresses/#{encode(address)}/token-balances").filter_map do |entry|
+ token_data = entry["token"].to_h
+ next unless token_data["type"].to_s == ERC20_TYPE
+
+ contract = contract_of(token_data)
+ next if contract.blank?
+
+ {
+ contract: contract,
+ symbol: token_data["symbol"],
+ name: token_data["name"],
+ decimals: token_data["decimals"].to_i,
+ raw_amount: entry["value"].to_s,
+ # Blockscout's own market signals, used only to decide which tokens are
+ # worth surfacing first when an address holds thousands of them, and
+ # which are worth pre-ticking.
+ market_cap: token_data["circulating_market_cap"].to_s.presence&.to_d,
+ rate: token_data["exchange_rate"].to_s.presence&.to_d
+ }
+ end
+ end
+
+ def transfers(address)
+ native_transfers(address) + token_transfers(address)
+ end
+
+ private
+ def native_transfers(address)
+ paginate("/api/v2/addresses/#{encode(address)}/transactions").filter_map do |transaction|
+ raw_amount = signed_amount(transaction["value"], from: transaction.dig("from", "hash"), to: transaction.dig("to", "hash"), address: address)
+ next if raw_amount.zero?
+
+ {
+ external_id: transaction["hash"],
+ contract: nil,
+ symbol: nil,
+ decimals: 18,
+ raw_amount: raw_amount,
+ timestamp: parse_time(transaction["timestamp"])
+ }
+ end
+ end
+
+ def token_transfers(address)
+ paginate("/api/v2/addresses/#{encode(address)}/token-transfers?type=ERC-20").filter_map do |transfer|
+ token_data = transfer["token"].to_h
+ total = transfer["total"].to_h
+ contract = contract_of(token_data)
+ next if contract.blank?
+
+ raw_amount = signed_amount(total["value"], from: transfer.dig("from", "hash"), to: transfer.dig("to", "hash"), address: address)
+ next if raw_amount.zero?
+
+ {
+ external_id: transfer_external_id(transfer["transaction_hash"], contract, transfer["log_index"]),
+ contract: contract,
+ symbol: token_data["symbol"],
+ decimals: (total["decimals"] || token_data["decimals"]).to_i,
+ raw_amount: raw_amount,
+ timestamp: parse_time(transfer["timestamp"])
+ }
+ end
+ end
+
+ # A transaction can emit several transfers of the same token involving the
+ # same address — swap routers and batch payouts do it routinely — so the
+ # transaction hash and the contract are not unique together. The log index is
+ # what makes an event unique within a transaction; the contract is only a
+ # fallback for an instance that does not report one.
+ def transfer_external_id(transaction_hash, contract, log_index)
+ [ transaction_hash, log_index.nil? ? contract : log_index ].join("_")
+ end
+
+ # Blockscout renamed this field; accept both so an older self-hosted
+ # instance keeps working.
+ def contract_of(token)
+ (token["address_hash"] || token["address"]).to_s.presence&.downcase
+ end
+
+ def signed_amount(value, from:, to:, address:)
+ amount = value.to_s.presence&.to_i || 0
+ target = address.to_s.downcase
+ received = to.to_s.downcase == target
+ sent = from.to_s.downcase == target
+
+ return 0 if received == sent # neither, or a transfer to itself
+
+ received ? amount : -amount
+ end
+
+ def parse_time(value)
+ Time.zone.parse(value.to_s)
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ def address_summary(address)
+ @address_summary ||= {}
+ @address_summary[address.to_s] ||= api_get("/api/v2/addresses/#{encode(address)}")
+ end
+
+ def encode(address)
+ ERB::Util.url_encode(address.to_s)
+ end
+
+ def paginate(path)
+ items = []
+ next_params = nil
+
+ @max_pages.times do
+ url = path.dup
+ url += (url.include?("?") ? "&" : "?") + URI.encode_www_form(next_params) if next_params.present?
+
+ body = api_get(url)
+
+ # Some v2 collections (token-balances) return a bare, complete array;
+ # the paginated ones wrap items with cursor params.
+ if body.is_a?(Array)
+ items.concat(body)
+ break
+ end
+
+ page = Array(body.is_a?(Hash) ? body["items"] : nil)
+ items.concat(page)
+
+ next_params = body.is_a?(Hash) ? body["next_page_params"] : nil
+ break if next_params.blank? || page.empty?
+ end
+
+ # A cursor still in hand means there were more pages than the budget.
+ @truncated ||= next_params.present?
+
+ items
+ end
+
+ def api_get(path)
+ attempts = 0
+
+ begin
+ attempts += 1
+ throttle_request
+ translate_transport_errors { handle_response(self.class.get("#{base_url}#{path}", **request_options)) }
+ rescue RateLimitError => e
+ raise if attempts > @max_retries
+
+ Rails.logger.warn("Provider::Blockscout(#{chain}) - rate limited (attempt #{attempts}/#{@max_retries}): #{e.message}")
+ sleep(RETRY_BASE_DELAY * (2**(attempts - 1)))
+ retry
+ end
+ end
+
+ def request_options(**options)
+ return options if @request_timeout.nil?
+
+ options.merge(timeout: @request_timeout)
+ end
+
+ def throttle_request
+ @last_request_at ||= Time.at(0)
+ remaining = MIN_REQUEST_INTERVAL - (Time.current - @last_request_at)
+ sleep(remaining) if remaining.positive?
+ @last_request_at = Time.current
+ end
+
+ def handle_response(response)
+ raise RateLimitError, "Blockscout rate limit exceeded" if response.code == 429
+ raise ApiError, "Blockscout API error: #{response.code}" unless response.code.between?(200, 299)
+
+ response.parsed_response
+ end
+end
diff --git a/app/models/provider/etherscan.rb b/app/models/provider/etherscan.rb
new file mode 100644
index 0000000000..7a981dbadb
--- /dev/null
+++ b/app/models/provider/etherscan.rb
@@ -0,0 +1,203 @@
+# frozen_string_literal: true
+
+# Keyed EVM data source backed by Etherscan's v2 API.
+#
+# A history-only backend: optional, and only for the chain the registry gives an
+# Etherscan chain id. A key buys a higher rate limit on the paginated half of the
+# work and nothing else, so balances and activity detection stay on the keyless
+# indexer and this class refuses to answer them.
+class Provider::Etherscan
+ include Provider::EvmExplorer
+ include HTTParty
+ include Provider::HttpTransport
+ extend SslConfigurable
+
+ class Error < StandardError; end
+ class AuthenticationError < Error; end
+ class RateLimitError < Error; end
+ class ApiError < Error; end
+
+ BASE_URL = "https://api.etherscan.io/v2"
+ PAGE_SIZE = 1000
+ DEFAULT_MAX_PAGES = 10
+ # The free tier allows 5 requests/second; stay well inside it.
+ MIN_REQUEST_INTERVAL = 0.4
+ MAX_RETRIES = 3
+ RETRY_BASE_DELAY = 0.5
+
+ base_uri BASE_URL
+ default_options.merge!({ timeout: 30 }.merge(httparty_ssl_options))
+
+ attr_reader :api_key, :chain_id
+
+ # True when a walk stopped on the page budget rather than on its last page.
+ attr_reader :truncated
+
+ def initialize(api_key:, chain_id:, max_pages: DEFAULT_MAX_PAGES)
+ @api_key = api_key.to_s.strip
+ @chain_id = chain_id.to_s
+ @max_pages = max_pages
+ @truncated = false
+ raise AuthenticationError, "Etherscan API key is required" if @api_key.blank?
+ end
+
+ # Not implemented on purpose. Etherscan's one-request answer is the native
+ # balance, which reports "nothing here" for a wallet holding only ERC-20
+ # tokens, and the alternative is reading transfer history. Detection therefore
+ # stays on the keyless indexer, whose address summary answers correctly in one
+ # request.
+ def has_activity?(_address)
+ raise NotImplementedError, "Etherscan cannot answer activity in one request; use the keyless backend"
+ end
+
+ # Not implemented on purpose. Etherscan has no free endpoint that enumerates an
+ # address's tokens, and summing transfer history cannot see a rebasing token's
+ # current balance — nor anything older than the history cap. Balances always
+ # come from the keyless indexer, so both backends agree on what is held.
+ def token_balances(_address)
+ raise NotImplementedError, "Etherscan cannot enumerate token balances; use the keyless backend"
+ end
+
+ def transfers(address)
+ @transfers ||= {}
+ @transfers[address.to_s] ||= native_transfers(address) + token_transfers(address)
+ end
+
+ private
+ def native_transfers(address)
+ paged_get(action: "txlist", address: address).filter_map do |transaction|
+ raw_amount = signed_amount(transaction["value"], from: transaction["from"], to: transaction["to"], address: address)
+ next if raw_amount.zero?
+
+ {
+ external_id: transaction["hash"],
+ contract: nil,
+ symbol: nil,
+ name: nil,
+ decimals: 18,
+ raw_amount: raw_amount,
+ timestamp: parse_time(transaction["timeStamp"])
+ }
+ end
+ end
+
+ def token_transfers(address)
+ paged_get(action: "tokentx", address: address).filter_map do |transfer|
+ contract = transfer["contractAddress"].to_s.presence&.downcase
+ next if contract.blank?
+
+ raw_amount = signed_amount(transfer["value"], from: transfer["from"], to: transfer["to"], address: address)
+ next if raw_amount.zero?
+
+ {
+ external_id: transfer_external_id(transfer["hash"], contract, transfer["logIndex"]),
+ contract: contract,
+ symbol: transfer["tokenSymbol"],
+ name: transfer["tokenName"],
+ decimals: transfer["tokenDecimal"].to_i,
+ raw_amount: raw_amount,
+ timestamp: parse_time(transfer["timeStamp"])
+ }
+ end
+ end
+
+ # See Provider::Blockscout#transfer_external_id: the log index is what makes
+ # one of several same-token transfers in a transaction distinct.
+ def transfer_external_id(transaction_hash, contract, log_index)
+ [ transaction_hash, log_index.presence || contract ].join("_")
+ end
+
+ def signed_amount(value, from:, to:, address:)
+ amount = value.to_s.presence&.to_i || 0
+ target = address.to_s.downcase
+ received = to.to_s.downcase == target
+ sent = from.to_s.downcase == target
+
+ return 0 if received == sent
+
+ received ? amount : -amount
+ end
+
+ def parse_time(unix_timestamp)
+ return nil if unix_timestamp.blank?
+
+ Time.zone.at(unix_timestamp.to_i)
+ end
+
+ def paged_get(action:, address:)
+ results = []
+
+ 1.upto(@max_pages) do |page|
+ batch = api_get(
+ action: action,
+ address: address,
+ startblock: 0,
+ endblock: 999_999_999,
+ page: page,
+ offset: PAGE_SIZE,
+ sort: "asc"
+ )
+ batch = [] unless batch.is_a?(Array)
+ results.concat(batch)
+ break if batch.size < PAGE_SIZE
+
+ @truncated ||= page == @max_pages
+ end
+
+ results
+ end
+
+ def api_get(params)
+ attempts = 0
+
+ begin
+ attempts += 1
+ throttle_request
+ translate_transport_errors do
+ response = self.class.get("/api", query: {
+ apikey: api_key,
+ chainid: chain_id,
+ module: "account"
+ }.merge(params))
+ handle_response(response)
+ end
+ rescue RateLimitError => e
+ raise if attempts > MAX_RETRIES
+
+ Rails.logger.warn("Provider::Etherscan - rate limited (attempt #{attempts}/#{MAX_RETRIES}): #{e.message}")
+ sleep(RETRY_BASE_DELAY * (2**(attempts - 1)))
+ retry
+ end
+ end
+
+ def throttle_request
+ @last_request_at ||= Time.at(0)
+ remaining = MIN_REQUEST_INTERVAL - (Time.current - @last_request_at)
+ sleep(remaining) if remaining.positive?
+ @last_request_at = Time.current
+ end
+
+ def handle_response(response)
+ raise RateLimitError, "Etherscan rate limit exceeded" if response.code == 429
+ raise ApiError, "Etherscan API error: #{response.code}" unless response.code.between?(200, 299)
+
+ parsed = response.parsed_response
+ raise ApiError, "Unexpected Etherscan response" unless parsed.is_a?(Hash)
+
+ return parsed["result"] if parsed["status"].to_s == "1"
+ return [] if parsed["message"].to_s.match?(/No transactions found/i)
+
+ raise_for(parsed["result"].presence || parsed["message"].presence || "Etherscan API error")
+ end
+
+ def raise_for(message)
+ case message.to_s
+ when /invalid api key|missing.*chainid|apikey/i
+ raise AuthenticationError, message
+ when /rate limit|max rate|daily limit/i
+ raise RateLimitError, message
+ else
+ raise ApiError, message
+ end
+ end
+end
diff --git a/app/models/provider/evm_explorer.rb b/app/models/provider/evm_explorer.rb
new file mode 100644
index 0000000000..39bd4aeaf7
--- /dev/null
+++ b/app/models/provider/evm_explorer.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+# The contract an EVM data source fulfils, so Onchain::EvmAdapter can use a
+# keyless public indexer or a keyed one without changing.
+#
+# Amounts are returned in each token's smallest unit ("raw"), as strings or
+# integers, because that is what every explorer reports and the only lossless
+# form; the adapter scales them by the token's decimals.
+module Provider::EvmExplorer
+ # Whether this address is worth tracking on this chain.
+ #
+ # MUST cost at most one request and MUST NOT read paginated transfer history:
+ # this is called once per candidate network every time someone pastes a 0x
+ # address, so a history walk here would turn linking into dozens of requests.
+ # @return [Boolean]
+ def has_activity?(_address)
+ raise NotImplementedError, "#{self.class} must implement #has_activity?"
+ end
+
+ # @return [String, Integer] native coin balance in wei
+ def native_balance(_address)
+ raise NotImplementedError, "#{self.class} must implement #native_balance"
+ end
+
+ # @return [Array<Hash>] { contract:, symbol:, name:, decimals:, raw_amount: }
+ def token_balances(_address)
+ raise NotImplementedError, "#{self.class} must implement #token_balances"
+ end
+
+ # Signed transfers, native and ERC-20 together. Positive raw_amount means the
+ # address received; negative means it sent. `contract` is nil for the native
+ # coin.
+ # @return [Array<Hash>] { external_id:, contract:, symbol:, decimals:, raw_amount:, timestamp: }
+ def transfers(_address)
+ raise NotImplementedError, "#{self.class} must implement #transfers"
+ end
+end
diff --git a/app/models/provider/http_transport.rb b/app/models/provider/http_transport.rb
new file mode 100644
index 0000000000..e25ffe72de
--- /dev/null
+++ b/app/models/provider/http_transport.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+# Turns transport-level failures into the including provider's own ApiError.
+#
+# A connection that never opened, timed out, was reset, or answered with
+# something that is not JSON is the data source being unavailable — the same
+# thing as a 5xx, and nothing a caller can act on differently. Left
+# untranslated they escape as unexpected exceptions, so the chain adapters
+# cannot recognise them and the user is told something went wrong with Sure
+# rather than with a public explorer.
+#
+# The message deliberately carries only the error class: a transport error's
+# message can contain the full URL, and these are logged.
+module Provider::HttpTransport
+ TRANSPORT_ERRORS = [
+ Timeout::Error,
+ Net::OpenTimeout,
+ Net::ReadTimeout,
+ Net::WriteTimeout,
+ Net::HTTPBadResponse,
+ SocketError,
+ EOFError,
+ IOError,
+ Errno::ECONNREFUSED,
+ Errno::ECONNRESET,
+ Errno::EHOSTUNREACH,
+ Errno::ENETUNREACH,
+ Errno::ETIMEDOUT,
+ Errno::EPIPE,
+ OpenSSL::SSL::SSLError,
+ HTTParty::Error,
+ JSON::ParserError
+ ].freeze
+
+ private
+ def translate_transport_errors
+ yield
+ rescue *TRANSPORT_ERRORS => e
+ raise self.class::ApiError, "#{self.class.name.demodulize} is unavailable (#{e.class})"
+ end
+end
diff --git a/app/models/provider/jupiter_tokens.rb b/app/models/provider/jupiter_tokens.rb
new file mode 100644
index 0000000000..cc9276b555
--- /dev/null
+++ b/app/models/provider/jupiter_tokens.rb
@@ -0,0 +1,109 @@
+# frozen_string_literal: true
+
+# Keyless SPL token metadata.
+#
+# Solana RPC returns mints, not names, so without this every SPL token that is
+# not hard-coded shows up as its mint and can never be priced. Jupiter's token
+# search answers a batch of mints in one request and, crucially, says whether a
+# token is *verified*.
+#
+# Only verified tokens are trusted. Anyone can mint a token calling itself USDC;
+# naming an unverified one would hand it the real asset's price and value dust at
+# thousands. An unverified or unknown mint keeps its placeholder instead.
+class Provider::JupiterTokens
+ include HTTParty
+ include Provider::HttpTransport
+ extend SslConfigurable
+
+ class Error < StandardError; end
+ class RateLimitError < Error; end
+ class ApiError < Error; end
+
+ DEFAULT_URL = "https://lite-api.jup.ag/tokens/v2/search"
+
+ # Mints per request. The endpoint accepts a comma-separated batch; this bounds
+ # both the URL length and the response size.
+ BATCH_SIZE = 50
+ # Metadata is effectively static, and a mint that resolves to nothing usually
+ # stays that way, so misses are cached too rather than retried every sync.
+ CACHE_TTL = 24.hours
+ MISS = "unverified"
+
+ default_options.merge!({ timeout: 15 }.merge(httparty_ssl_options))
+
+ def self.url
+ ENV["SOLANA_TOKEN_LIST_URL"].presence || DEFAULT_URL
+ end
+
+ # @param mints [Array<String>]
+ # @return [Hash{String => Hash}] mint => { symbol:, name: }, verified mints only
+ def metadata_for(mints)
+ wanted = Array(mints).map(&:to_s).reject(&:blank?).uniq
+ return {} if wanted.empty?
+
+ resolved = {}
+ missing = []
+
+ wanted.each do |mint|
+ cached = Rails.cache.read(cache_key(mint))
+ if cached.nil?
+ missing << mint
+ elsif cached != MISS
+ resolved[mint] = cached.symbolize_keys
+ end
+ end
+
+ # The fetch returns what it found rather than reading its own writes back:
+ # the cache is an optimisation here, not the source of truth (it may be a
+ # null store).
+ resolved.merge!(fetch_and_cache(missing)) if missing.any?
+ resolved
+ end
+
+ private
+ def fetch_and_cache(mints)
+ found = {}
+
+ mints.each_slice(BATCH_SIZE) do |batch|
+ verified = verified_tokens(batch)
+
+ batch.each do |mint|
+ metadata = verified[mint]
+ # Misses are cached too: a mint the list does not vouch for today is
+ # unlikely to change by the next sync, and spam wallets hold many.
+ Rails.cache.write(cache_key(mint), metadata || MISS, expires_in: CACHE_TTL)
+ found[mint] = metadata.symbolize_keys if metadata
+ end
+ end
+
+ found
+ end
+
+ def verified_tokens(mints)
+ Array(get_json(mints)).each_with_object({}) do |token, resolved|
+ mint = token["id"].to_s
+ next if mint.blank?
+ next unless token["isVerified"] == true
+
+ symbol = token["symbol"].to_s.strip
+ next if symbol.blank?
+
+ resolved[mint] = { "symbol" => symbol, "name" => token["name"].to_s.presence || symbol }
+ end
+ end
+
+ def cache_key(mint)
+ "onchain:solana_mint:#{mint}"
+ end
+
+ def get_json(mints)
+ translate_transport_errors do
+ response = self.class.get(self.class.url, query: { query: mints.join(",") })
+
+ raise RateLimitError, "Jupiter rate limit exceeded" if response.code == 429
+ raise ApiError, "Jupiter token search error: #{response.code}" unless response.code.between?(200, 299)
+
+ response.parsed_response
+ end
+ end
+end
diff --git a/app/models/provider/mempool_space.rb b/app/models/provider/mempool_space.rb
new file mode 100644
index 0000000000..b2fda47676
--- /dev/null
+++ b/app/models/provider/mempool_space.rb
@@ -0,0 +1,106 @@
+# frozen_string_literal: true
+
+# Keyless Bitcoin data source backed by mempool.space's REST API.
+#
+# A dumb HTTP client: address validation and the mapping into an
+# Onchain::Snapshot both live in Onchain::BitcoinAdapter. Self-hosters can point
+# this at their own instance with MEMPOOL_SPACE_URL.
+class Provider::MempoolSpace
+ include HTTParty
+ include Provider::HttpTransport
+ extend SslConfigurable
+
+ class Error < StandardError; end
+ class InvalidAddressError < Error; end
+ class RateLimitError < Error; end
+ class ApiError < Error; end
+
+ DEFAULT_BASE_URL = "https://mempool.space/api"
+ # mempool.space returns 25 confirmed transactions per page.
+ PAGE_SIZE = 25
+ DEFAULT_MAX_PAGES = 10
+ MIN_REQUEST_INTERVAL = 0.25
+ MAX_RETRIES = 3
+ RETRY_BASE_DELAY = 0.5
+
+ default_options.merge!({ timeout: 30 }.merge(httparty_ssl_options))
+
+ def self.base_url
+ ENV["MEMPOOL_SPACE_URL"].presence || DEFAULT_BASE_URL
+ end
+
+ # True when the walk stopped on the page budget rather than on the end of the
+ # address's history, so the caller can say so instead of implying it read
+ # everything.
+ attr_reader :truncated
+
+ def initialize(max_pages: DEFAULT_MAX_PAGES)
+ @max_pages = max_pages
+ @truncated = false
+ end
+
+ # Address summary: confirmed and mempool funded/spent totals.
+ def get_address(address)
+ get_json("/address/#{ERB::Util.url_encode(address)}")
+ end
+
+ # Confirmed transactions, newest first, plus anything still in the mempool.
+ def get_address_transactions(address)
+ encoded = ERB::Util.url_encode(address)
+ page = Array(get_json("/address/#{encoded}/txs"))
+ transactions = page.dup
+ pages_read = 1
+ @truncated = false
+
+ while page.size >= PAGE_SIZE && pages_read < @max_pages
+ last_txid = page.last["txid"]
+ break if last_txid.blank?
+
+ page = Array(get_json("/address/#{encoded}/txs/chain/#{last_txid}"))
+ transactions.concat(page)
+ pages_read += 1
+ end
+
+ @truncated = page.size >= PAGE_SIZE
+
+ transactions
+ end
+
+ private
+ def get_json(path)
+ attempts = 0
+
+ begin
+ attempts += 1
+ throttle_request
+ translate_transport_errors { handle_response(self.class.get("#{self.class.base_url}#{path}")) }
+ rescue RateLimitError => e
+ raise if attempts > MAX_RETRIES
+
+ delay = RETRY_BASE_DELAY * (2**(attempts - 1))
+ Rails.logger.warn("Provider::MempoolSpace - rate limited (attempt #{attempts}/#{MAX_RETRIES}): #{e.message}")
+ sleep(delay)
+ retry
+ end
+ end
+
+ def throttle_request
+ @last_request_at ||= Time.at(0)
+ remaining = MIN_REQUEST_INTERVAL - (Time.current - @last_request_at)
+ sleep(remaining) if remaining.positive?
+ @last_request_at = Time.current
+ end
+
+ def handle_response(response)
+ case response.code
+ when 200..299
+ response.parsed_response
+ when 400, 404
+ raise InvalidAddressError, "mempool.space rejected the address"
+ when 429
+ raise RateLimitError, "mempool.space rate limit exceeded"
+ else
+ raise ApiError, "mempool.space API error: #{response.code}"
+ end
+ end
+end
diff --git a/app/models/provider/metadata.rb b/app/models/provider/metadata.rb
index 220acb6c18..4baf2a4ab0 100644
--- a/app/models/provider/metadata.rb
+++ b/app/models/provider/metadata.rb
@@ -21,7 +21,8 @@ class Provider
plaid: { region: "US", kinds: %w[Bank], maturity: :stable, logo_text: "PL", logo_bg: "bg-indigo-600", tier: "Paid" },
plaid_eu: { region: "EU", kinds: %w[Bank], maturity: :stable, logo_text: "PL", logo_bg: "bg-indigo-600", tier: "Paid", name: "Plaid EU" },
questrade: { region: "CA", kinds: %w[Investment], maturity: :beta, logo_text: "QT", logo_bg: "bg-teal-600" },
- redbark: { region: "AU", kinds: %w[Bank], maturity: :beta, logo_text: "RB", logo_bg: "bg-red-700" }
+ redbark: { region: "AU", kinds: %w[Bank], maturity: :beta, logo_text: "RB", logo_bg: "bg-red-700" },
+ onchain_wallet: { region: "Global", kinds: %w[Crypto], maturity: :alpha, logo_text: "OC", logo_bg: "bg-amber-600", name: "On-chain wallets" }
}.freeze
def self.for(provider_key)
diff --git a/app/models/provider/onchain_wallet_adapter.rb b/app/models/provider/onchain_wallet_adapter.rb
new file mode 100644
index 0000000000..8c28e036c0
--- /dev/null
+++ b/app/models/provider/onchain_wallet_adapter.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+class Provider::OnchainWalletAdapter < Provider::Base
+ include Provider::Syncable
+ include Provider::InstitutionMetadata
+
+ Provider::Factory.register("OnchainWalletAccount", self)
+
+ def self.supported_account_types
+ %w[Crypto]
+ end
+
+ def self.connection_configs(family:)
+ return [] unless family.can_connect_onchain_wallet?
+
+ [
+ {
+ key: "onchain_wallet",
+ name: I18n.t("onchain_wallet_items.provider_connection.name"),
+ description: I18n.t("onchain_wallet_items.provider_connection.description"),
+ can_connect: true,
+ new_account_path: ->(accountable_type, return_to) {
+ Rails.application.routes.url_helpers.new_wallet_onchain_wallet_items_path(
+ accountable_type: accountable_type,
+ return_to: return_to
+ )
+ }
+ }
+ ]
+ end
+
+ def provider_name
+ "onchain_wallet"
+ end
+
+ def sync_path
+ return unless item
+
+ Rails.application.routes.url_helpers.sync_onchain_wallet_item_path(item)
+ end
+
+ def item
+ provider_account.onchain_wallet_item
+ end
+
+ # On-chain balances are derived entirely from what the chain reports, so a
+ # holding that disappears from a snapshot is set to zero rather than deleted.
+ def can_delete_holdings?
+ false
+ end
+
+ # There is no institution behind a self-custody wallet; the chain is the
+ # closest thing to one.
+ def institution_name
+ provider_account.chain_label
+ end
+end
diff --git a/app/models/provider/solana_rpc.rb b/app/models/provider/solana_rpc.rb
new file mode 100644
index 0000000000..1d5c69061d
--- /dev/null
+++ b/app/models/provider/solana_rpc.rb
@@ -0,0 +1,124 @@
+# frozen_string_literal: true
+
+# Keyless Solana data source backed by a public JSON-RPC endpoint.
+#
+# A dumb RPC client: the SPL token model and the mapping into an
+# Onchain::Snapshot both live in Onchain::SolanaAdapter. Self-hosters, and anyone
+# who outgrows the public endpoint's rate limit, can point this at their own node
+# with SOLANA_RPC_URL.
+class Provider::SolanaRpc
+ include HTTParty
+ include Provider::HttpTransport
+ extend SslConfigurable
+
+ class Error < StandardError; end
+ class RateLimitError < Error; end
+ class ApiError < Error; end
+
+ DEFAULT_URL = "https://api.mainnet-beta.solana.com"
+
+ # SPL tokens live in per-mint token accounts owned by the wallet. Both the
+ # original token program and Token-2022 have to be asked.
+ TOKEN_PROGRAM_IDS = [
+ "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
+ "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"
+ ].freeze
+
+ MIN_REQUEST_INTERVAL = 0.2
+ MAX_RETRIES = 3
+ RETRY_BASE_DELAY = 0.5
+
+ headers "Content-Type" => "application/json"
+ default_options.merge!({ timeout: 30 }.merge(httparty_ssl_options))
+
+ def self.url
+ ENV["SOLANA_RPC_URL"].presence || DEFAULT_URL
+ end
+
+ # Detection reads on the request thread and cannot afford the sync's patience,
+ # so both the per-request timeout and the retry count are the caller's to set.
+ def initialize(request_timeout: nil, max_retries: MAX_RETRIES)
+ @request_timeout = request_timeout
+ @max_retries = max_retries
+ end
+
+ # @return [Integer] lamports
+ def get_balance(address)
+ result = rpc("getBalance", [ address ])
+ (result.is_a?(Hash) ? result["value"] : result).to_i
+ end
+
+ # @return [Array<Hash>] { pubkey:, mint:, raw_amount:, decimals: }
+ def get_token_accounts(address)
+ TOKEN_PROGRAM_IDS.flat_map do |program_id|
+ result = rpc("getTokenAccountsByOwner", [ address, { programId: program_id }, { encoding: "jsonParsed" } ])
+ accounts = result.is_a?(Hash) ? Array(result["value"]) : []
+
+ accounts.filter_map do |account|
+ info = account.dig("account", "data", "parsed", "info").to_h
+ mint = info["mint"].to_s
+ next if mint.blank?
+
+ {
+ pubkey: account["pubkey"],
+ mint: mint,
+ raw_amount: info.dig("tokenAmount", "amount").to_s,
+ decimals: info.dig("tokenAmount", "decimals").to_i
+ }
+ end
+ end
+ end
+
+ # @return [Array<Hash>] { signature:, block_time: }
+ def get_signatures(pubkey, limit:)
+ Array(rpc("getSignaturesForAddress", [ pubkey, { limit: limit } ])).map do |entry|
+ { signature: entry["signature"], block_time: entry["blockTime"] }
+ end
+ end
+
+ def get_transaction(signature)
+ rpc("getTransaction", [ signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 0 } ])
+ end
+
+ private
+ def rpc(method, params)
+ attempts = 0
+ body = { jsonrpc: "2.0", id: 1, method: method, params: params }.to_json
+
+ begin
+ attempts += 1
+ throttle_request
+ translate_transport_errors { handle_response(self.class.post(self.class.url, **request_options(body: body))) }
+ rescue RateLimitError => e
+ raise if attempts > @max_retries
+
+ Rails.logger.warn("Provider::SolanaRpc - rate limited (attempt #{attempts}/#{@max_retries}): #{e.message}")
+ sleep(RETRY_BASE_DELAY * (2**(attempts - 1)))
+ retry
+ end
+ end
+
+ def request_options(**options)
+ return options if @request_timeout.nil?
+
+ options.merge(timeout: @request_timeout)
+ end
+
+ def throttle_request
+ @last_request_at ||= Time.at(0)
+ remaining = MIN_REQUEST_INTERVAL - (Time.current - @last_request_at)
+ sleep(remaining) if remaining.positive?
+ @last_request_at = Time.current
+ end
+
+ def handle_response(response)
+ raise RateLimitError, "Solana RPC rate limit exceeded" if response.code == 429
+ raise ApiError, "Solana RPC error: #{response.code}" unless response.code.between?(200, 299)
+
+ payload = response.parsed_response
+ raise ApiError, "Unexpected Solana RPC response" unless payload.is_a?(Hash)
+ raise ApiError, "Solana RPC error: #{payload.dig("error", "message")}" if payload["error"]
+
+ payload["result"]
+ end
+end
diff --git a/app/models/provider_connection_status.rb b/app/models/provider_connection_status.rb
index 89ee10382e..8586eadf0b 100644
--- a/app/models/provider_connection_status.rb
+++ b/app/models/provider_connection_status.rb
@@ -11,6 +11,7 @@ class ProviderConnectionStatus
{ key: "coinbase", type: "CoinbaseItem", association: :coinbase_items, accounts: :coinbase_accounts },
{ key: "binance", type: "BinanceItem", association: :binance_items, accounts: :binance_accounts },
{ key: "kraken", type: "KrakenItem", association: :kraken_items, accounts: :kraken_accounts },
+ { key: "onchain_wallet", type: "OnchainWalletItem", association: :onchain_wallet_items, accounts: :onchain_wallet_accounts },
{ key: "coinstats", type: "CoinstatsItem", association: :coinstats_items, accounts: :coinstats_accounts },
{ key: "snaptrade", type: "SnaptradeItem", association: :snaptrade_items, accounts: :snaptrade_accounts, linked_accounts: :linked_accounts },
{ key: "ibkr", type: "IbkrItem", association: :ibkr_items, accounts: :ibkr_accounts },
diff --git a/app/views/onchain_wallet_items/_onchain_wallet_item.html.erb b/app/views/onchain_wallet_items/_onchain_wallet_item.html.erb
new file mode 100644
index 0000000000..6566816e37
--- /dev/null
+++ b/app/views/onchain_wallet_items/_onchain_wallet_item.html.erb
@@ -0,0 +1,35 @@
+<div id="<%= dom_id(onchain_wallet_item) %>" class="space-y-2">
+ <% onchain_wallet_item.grouped_accounts.each do |(chain, address), accounts| %>
+ <div class="flex items-center justify-between gap-3 p-3 border border-primary rounded-lg">
+ <div class="flex items-center gap-3 min-w-0">
+ <div class="flex items-center justify-center h-8 w-8 rounded-full bg-surface-inset shrink-0">
+ <%= icon "wallet", size: "sm", class: "text-primary" %>
+ </div>
+ <div class="min-w-0">
+ <p class="font-medium text-primary truncate">
+ <%= accounts.first.chain_label %> · <%= accounts.first.truncated_address %>
+ </p>
+ <p class="text-xs text-secondary">
+ <% if onchain_wallet_item.syncing? %>
+ <%= t("onchain_wallet_items.onchain_wallet_item.syncing") %>
+ <% else %>
+ <%= t("onchain_wallet_items.onchain_wallet_item.assets_tracked", count: accounts.size) %>
+ <% end %>
+ </p>
+ </div>
+ </div>
+
+ <div class="flex items-center gap-1 shrink-0">
+ <%= render DS::Button.new(
+ variant: :icon,
+ size: :sm,
+ icon: "refresh-cw",
+ href: sync_onchain_wallet_item_path(onchain_wallet_item),
+ method: :post,
+ title: t("onchain_wallet_items.onchain_wallet_item.sync"),
+ disabled: onchain_wallet_item.syncing?
+ ) %>
+ </div>
+ </div>
+ <% end %>
+</div>
diff --git a/app/views/onchain_wallet_items/_price_provider_warning.html.erb b/app/views/onchain_wallet_items/_price_provider_warning.html.erb
new file mode 100644
index 0000000000..c8090e0b28
--- /dev/null
+++ b/app/views/onchain_wallet_items/_price_provider_warning.html.erb
@@ -0,0 +1,46 @@
+<%# Shown before linking, not after: with either of these missing, every wallet %>
+<%# is valued at zero, which reads as a broken sync rather than a setting the %>
+<%# user never made. %>
+<% missing = Onchain::Pricing.missing_for(Current.family.currency) %>
+<% if missing.any? %>
+ <% if missing.include?(:crypto_provider) %>
+ <%= render DS::Alert.new(
+ variant: :warning,
+ title: t("onchain_wallet_items.price_provider_warning.title"),
+ message: t("onchain_wallet_items.price_provider_warning.body")
+ ) %>
+ <% end %>
+
+ <% if missing.include?(:exchange_rate) %>
+ <%= render DS::Alert.new(
+ variant: :warning,
+ title: t("onchain_wallet_items.price_provider_warning.exchange_rate_title"),
+ message: t("onchain_wallet_items.price_provider_warning.exchange_rate_body", currency: Current.family.currency)
+ ) %>
+ <% end %>
+
+ <%# Self-hosted admins only: these are site-wide settings, so on a managed %>
+ <%# instance it is the operator's call, not a family's — and the settings page %>
+ <%# itself is gated the same way, so offering either control to anyone else is %>
+ <%# a dead end. The warning text stands on its own. %>
+ <% if self_hosted? && Current.user.admin? %>
+ <div class="flex flex-wrap items-center gap-2 -mt-2">
+ <% if missing.include?(:crypto_provider) %>
+ <%= render DS::Button.new(
+ text: t("onchain_wallet_items.price_provider_warning.enable"),
+ icon: "zap",
+ variant: :outline,
+ size: :sm,
+ href: enable_crypto_prices_onchain_wallet_items_path,
+ method: :post,
+ frame: "_top"
+ ) %>
+ <% end %>
+
+ <%= link_to t("onchain_wallet_items.price_provider_warning.link"),
+ settings_hosting_path,
+ class: "text-sm underline text-secondary hover:text-primary",
+ data: { turbo_frame: "_top" } %>
+ </div>
+ <% end %>
+<% end %>
diff --git a/app/views/onchain_wallet_items/_token_review_form.html.erb b/app/views/onchain_wallet_items/_token_review_form.html.erb
new file mode 100644
index 0000000000..21a11fb22e
--- /dev/null
+++ b/app/views/onchain_wallet_items/_token_review_form.html.erb
@@ -0,0 +1,60 @@
+<%# Shared by initial linking and the later "review tokens" action, which is the %>
+<%# same screen with the address left alone. %>
+<% turbo_frame = local_assigns.fetch(:turbo_frame, "_top") %>
+<%= styled_form_with url: url,
+ method: :post,
+ data: { turbo_frame: turbo_frame },
+ class: "space-y-4" do |form| %>
+ <%= hidden_field_tag :chain, chain %>
+ <%= hidden_field_tag :address, address %>
+
+ <%= render "onchain_wallet_items/price_provider_warning" %>
+
+ <%= render DS::Alert.new(variant: :info, message: t("onchain_wallet_items.token_review_form.explanation")) %>
+
+ <% if local_assigns[:assets_truncated] %>
+ <%= render DS::Alert.new(
+ variant: :warning,
+ message: t("onchain_wallet_items.token_review_form.assets_truncated", count: Onchain::AssetBudget.tokens)
+ ) %>
+ <% end %>
+
+ <% if review.rows.empty? %>
+ <p class="text-sm text-secondary py-4"><%= t("onchain_wallet_items.token_review_form.nothing_found") %></p>
+ <% else %>
+ <div class="space-y-2 max-h-96 overflow-y-auto">
+ <% review.rows.each do |row| %>
+ <label for="asset_<%= row.key.parameterize %>"
+ class="flex items-center gap-3 p-3 border border-primary rounded-lg hover:bg-surface cursor-pointer">
+ <%= check_box_tag "assets[]", row.key, row.preselected?,
+ id: "asset_#{row.key.parameterize}",
+ class: "checkbox checkbox--dark" %>
+ <div class="flex-1 min-w-0">
+ <p class="font-medium text-primary truncate">
+ <%= row.asset.symbol %>
+ <% if row.native? %>
+ <span class="text-xs text-secondary"><%= t("onchain_wallet_items.token_review_form.native") %></span>
+ <% end %>
+ </p>
+ <p class="text-xs text-secondary truncate"><%= row.asset.name %></p>
+ <% unless row.priceable %>
+ <p class="text-xs text-warning"><%= t("onchain_wallet_items.token_review_form.no_price") %></p>
+ <% end %>
+ </div>
+ <p class="text-sm font-medium text-primary shrink-0 tabular-nums">
+ <%= number_with_delimiter(row.asset.quantity.round(8).to_s("F")) %>
+ </p>
+ </label>
+ <% end %>
+ </div>
+ <% end %>
+
+ <div class="flex justify-end gap-2">
+ <%= render DS::Link.new(
+ text: t("onchain_wallet_items.token_review_form.cancel"),
+ variant: "secondary",
+ href: local_assigns.fetch(:cancel_path, settings_providers_path)
+ ) %>
+ <%= form.submit submit_label %>
+ </div>
+<% end %>
diff --git a/app/views/onchain_wallet_items/choose_chain.html.erb b/app/views/onchain_wallet_items/choose_chain.html.erb
new file mode 100644
index 0000000000..2d24b267ca
--- /dev/null
+++ b/app/views/onchain_wallet_items/choose_chain.html.erb
@@ -0,0 +1,26 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title"), subtitle: t(".subtitle", address: @address)) %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-3">
+ <%= render DS::Alert.new(variant: :info, message: t(".explanation")) %>
+
+ <div class="space-y-2">
+ <% @detection.candidates.each do |candidate| %>
+ <%= button_to preview_wallet_onchain_wallet_items_path,
+ method: :post,
+ params: { address: @address, chain: candidate.key },
+ class: "w-full flex items-center justify-between gap-3 p-3 border border-primary rounded-lg hover:bg-surface text-left",
+ form: { data: { turbo_frame: "modal" } } do %>
+ <span class="font-medium text-primary"><%= candidate.label %></span>
+ <% if @detection.detected?(candidate) %>
+ <span class="text-xs text-success"><%= t(".activity_found") %></span>
+ <% else %>
+ <span class="text-xs text-subdued"><%= t(".no_activity_found") %></span>
+ <% end %>
+ <% end %>
+ <% end %>
+ </div>
+ </div>
+ <% end %>
+<% end %>
diff --git a/app/views/onchain_wallet_items/edit_wallet.html.erb b/app/views/onchain_wallet_items/edit_wallet.html.erb
new file mode 100644
index 0000000000..48ed3f29d2
--- /dev/null
+++ b/app/views/onchain_wallet_items/edit_wallet.html.erb
@@ -0,0 +1,40 @@
+<%= 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
new file mode 100644
index 0000000000..683a6bb782
--- /dev/null
+++ b/app/views/onchain_wallet_items/manage.html.erb
@@ -0,0 +1,100 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title"), subtitle: t(".subtitle")) %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-4">
+ <%= render "onchain_wallet_items/price_provider_warning" %>
+
+ <% grouped = @onchain_wallet_item.grouped_accounts %>
+
+ <% if grouped.empty? %>
+ <p class="text-sm text-secondary py-4"><%= t(".no_wallets") %></p>
+ <% end %>
+
+ <% grouped.each do |(chain, address), accounts| %>
+ <section class="rounded-xl border border-primary bg-container p-4 space-y-3">
+ <div class="flex items-start justify-between gap-3">
+ <div class="min-w-0">
+ <p class="font-medium text-primary"><%= accounts.first.chain_label %></p>
+ <p class="text-xs text-secondary break-all"><%= address %></p>
+ </div>
+ </div>
+
+ <% if accounts.any?(&:history_truncated?) %>
+ <p class="flex items-start gap-2 text-xs text-warning">
+ <%= icon "alert-triangle", size: "sm", class: "shrink-0 mt-0.5" %>
+ <span><%= t(".history_truncated") %></span>
+ </p>
+ <% end %>
+
+ <% if accounts.any?(&:assets_truncated?) %>
+ <p class="flex items-start gap-2 text-xs text-warning">
+ <%= icon "alert-triangle", size: "sm", class: "shrink-0 mt-0.5" %>
+ <span><%= t(".assets_truncated", count: Onchain::AssetBudget.tokens) %></span>
+ </p>
+ <% end %>
+
+ <ul class="divide-y divide-primary border border-primary rounded-lg">
+ <% accounts.each do |onchain_account| %>
+ <li class="flex items-center justify-between gap-3 p-3">
+ <div class="min-w-0">
+ <p class="text-sm font-medium text-primary truncate">
+ <%= onchain_account.symbol %>
+ <% if onchain_account.native? %>
+ <span class="text-xs text-secondary"><%= t(".native") %></span>
+ <% end %>
+ </p>
+ <p class="text-xs text-secondary tabular-nums">
+ <%= number_with_delimiter(onchain_account.quantity.round(8).to_s("F")) %>
+ </p>
+ </div>
+
+ <%= render DS::Button.new(
+ text: t(".disconnect_asset"),
+ icon: "unlink",
+ variant: :outline_destructive,
+ size: :sm,
+ href: disconnect_asset_onchain_wallet_item_path(@onchain_wallet_item),
+ method: :delete,
+ params: { onchain_wallet_account_id: onchain_account.id },
+ confirm: t(".disconnect_asset_confirm", symbol: onchain_account.symbol)
+ ) %>
+ </li>
+ <% 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
+ ) %>
+
+ <%= 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")
+ ) %>
+ </div>
+ </section>
+ <% end %>
+
+ <p class="text-xs text-secondary"><%= t(".history_note") %></p>
+ </div>
+ <% end %>
+<% end %>
diff --git a/app/views/onchain_wallet_items/new_wallet.html.erb b/app/views/onchain_wallet_items/new_wallet.html.erb
new file mode 100644
index 0000000000..017742cdce
--- /dev/null
+++ b/app/views/onchain_wallet_items/new_wallet.html.erb
@@ -0,0 +1,47 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title"), subtitle: t(".subtitle")) %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-4">
+ <%= render "onchain_wallet_items/price_provider_warning" %>
+
+ <% if @error_message.present? %>
+ <%= render DS::Alert.new(message: @error_message, variant: :error) %>
+ <% end %>
+
+ <%= styled_form_with url: preview_wallet_onchain_wallet_items_path,
+ method: :post,
+ data: { turbo_frame: "modal" },
+ class: "space-y-4" do |form| %>
+ <%= form.text_field :address,
+ label: t(".address_label"),
+ placeholder: t(".address_placeholder"),
+ value: @address,
+ required: true %>
+
+ <%= form.select :chain,
+ options_for_select(
+ Onchain::Chains.all.map { |chain| [ chain.label, chain.key ] }.sort_by(&:first),
+ @chain
+ ),
+ { include_blank: t(".chain_auto_detect"), label: t(".chain_label") },
+ class: "w-full rounded-md border border-primary px-3 py-2 text-sm bg-container-inset text-primary" %>
+
+ <div class="rounded-lg bg-surface p-3 space-y-2 text-sm text-secondary">
+ <p class="flex items-start gap-2">
+ <%= icon "info", size: "sm", class: "text-primary mt-0.5 shrink-0" %>
+ <span><%= t(".bitcoin_single_address_note") %></span>
+ </p>
+ <p class="flex items-start gap-2">
+ <%= icon "eye", size: "sm", class: "text-primary mt-0.5 shrink-0" %>
+ <span><%= t(".read_only_note") %></span>
+ </p>
+ </div>
+
+ <div class="flex justify-end">
+ <%= form.submit t(".continue") %>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+<% end %>
diff --git a/app/views/onchain_wallet_items/review_tokens.html.erb b/app/views/onchain_wallet_items/review_tokens.html.erb
new file mode 100644
index 0000000000..95bdac3779
--- /dev/null
+++ b/app/views/onchain_wallet_items/review_tokens.html.erb
@@ -0,0 +1,17 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title"), subtitle: t(".subtitle", chain: Onchain::Chains.find!(@chain).label, address: @address)) %>
+
+ <% dialog.with_body do %>
+ <%# Same screen as linking, and deliberately without an address field: this %>
+ <%# action changes which assets are tracked, nothing else. %>
+ <%= render "onchain_wallet_items/token_review_form",
+ chain: @chain,
+ address: @address,
+ review: @review,
+ url: update_tokens_onchain_wallet_item_path(@onchain_wallet_item),
+ submit_label: t(".save"),
+ assets_truncated: @assets_truncated,
+ turbo_frame: "modal",
+ cancel_path: manage_onchain_wallet_item_path(@onchain_wallet_item) %>
+ <% end %>
+<% end %>
diff --git a/app/views/onchain_wallet_items/token_review.html.erb b/app/views/onchain_wallet_items/token_review.html.erb
new file mode 100644
index 0000000000..c9ae52e153
--- /dev/null
+++ b/app/views/onchain_wallet_items/token_review.html.erb
@@ -0,0 +1,13 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title"), subtitle: t(".subtitle", chain: Onchain::Chains.find!(@chain).label, address: @address)) %>
+
+ <% dialog.with_body do %>
+ <%= render "onchain_wallet_items/token_review_form",
+ chain: @chain,
+ address: @address,
+ review: @review,
+ url: link_wallet_onchain_wallet_items_path,
+ submit_label: t(".import_selected"),
+ assets_truncated: @assets_truncated %>
+ <% end %>
+<% end %>
diff --git a/app/views/settings/providers/_onchain_wallet_panel.html.erb b/app/views/settings/providers/_onchain_wallet_panel.html.erb
new file mode 100644
index 0000000000..c3a1c0701e
--- /dev/null
+++ b/app/views/settings/providers/_onchain_wallet_panel.html.erb
@@ -0,0 +1,87 @@
+<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. %>
+ <% 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 %>
+ <% end %>
+
+ <div class="flex flex-wrap items-center gap-2">
+ <%= render DS::Link.new(
+ text: t("settings.providers.onchain_wallet_panel.add_wallet"),
+ icon: "plus",
+ variant: "primary",
+ href: new_wallet_onchain_wallet_items_path,
+ frame: :modal
+ ) %>
+
+ <% if connection.present? %>
+ <%= render DS::Link.new(
+ text: t("settings.providers.onchain_wallet_panel.manage_wallets"),
+ icon: "settings",
+ variant: "secondary",
+ href: manage_onchain_wallet_item_path(connection),
+ frame: :modal
+ ) %>
+ <% end %>
+ </div>
+
+ <% 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),
+ 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"),
+ 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 %>
+
+ <p class="text-xs text-secondary"><%= t("settings.providers.onchain_wallet_panel.sync_start_date_hint") %></p>
+
+ <div class="flex justify-end">
+ <%= form.submit t("settings.providers.onchain_wallet_panel.save") %>
+ </div>
+ <% end %>
+
+ <%= render DS::Button.new(
+ text: t("settings.providers.onchain_wallet_panel.disconnect_all"),
+ icon: "trash-2",
+ variant: :outline_destructive,
+ size: :sm,
+ href: onchain_wallet_item_path(item),
+ method: :delete,
+ confirm: t("settings.providers.onchain_wallet_panel.disconnect_all_confirm")
+ ) %>
+ </div>
+ <% end %>
+ <% end %>
+</div>
diff --git a/config/locales/models/onchain_wallet_item/en.yml b/config/locales/models/onchain_wallet_item/en.yml
new file mode 100644
index 0000000000..48bb0e843a
--- /dev/null
+++ b/config/locales/models/onchain_wallet_item/en.yml
@@ -0,0 +1,20 @@
+---
+en:
+ onchain:
+ chains:
+ arbitrum: Arbitrum
+ base: Base
+ bitcoin: Bitcoin
+ ethereum: Ethereum
+ gnosis: Gnosis
+ optimism: Optimism
+ polygon: Polygon
+ solana: Solana
+ institution_name: Self-custody wallets
+ onchain_wallet_item:
+ 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
new file mode 100644
index 0000000000..77853fcf3b
--- /dev/null
+++ b/config/locales/views/onchain_wallet_items/en.yml
@@ -0,0 +1,114 @@
+---
+en:
+ onchain_wallet_items:
+ choose_chain:
+ activity_found: Activity found
+ explanation: This address format is used by more than one network, and the balances on each are different. Pick the one you want to track.
+ no_activity_found: Nothing found
+ subtitle: "%{address}"
+ 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.
+ errors:
+ address_required: Enter a wallet address.
+ already_linked: That address is already being tracked on this network. Use Review tokens to change which assets are tracked.
+ chain_unreachable: The public explorer for this network could not be reached. Try again in a moment.
+ rate_limited: The public explorer is rate limiting requests right now. Try again in a few minutes.
+ unexpected: Something went wrong reading this wallet. The details were recorded for support.
+ unrecognized_address: That does not look like an address on any supported network.
+ wallet_not_found: That wallet is not tracked by this connection.
+ link_wallet:
+ errors:
+ none_tracked: "Nothing was tracked: %{assets} could not be added. Try again in a moment."
+ nothing_selected: Pick at least one asset to track.
+ some_failed: "%{assets} could not be tracked and was left out."
+ success:
+ one: Tracking 1 asset from this wallet.
+ 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
+ disconnect_wallet_confirm: Stop tracking every asset at this address?
+ history_note: Disconnecting keeps the accounts and their history; they simply stop updating.
+ history_truncated: Not every transfer for this address could be read — there is more history than one sync covers, or the explorer refused it. Balances are complete; some transfers are missing.
+ native: Native
+ no_wallets: No wallets are tracked yet.
+ review_tokens: Review tokens
+ subtitle: Every address this connection reads, and what it tracks at each.
+ title: Manage self-custody wallets
+ new_wallet:
+ address_label: Wallet address
+ address_placeholder: bc1..., 0x..., or a Solana address
+ bitcoin_single_address_note: Bitcoin is tracked one address at a time. Extended keys (xpub/ypub/zpub) are not supported, so a wallet that spreads funds across derived addresses will show only the balance of the address you enter.
+ chain_auto_detect: Detect automatically
+ chain_label: Network
+ continue: Continue
+ read_only_note: Only public chain data is read. Never enter a seed phrase or private key.
+ subtitle: Track a wallet you hold the keys to, from its public address.
+ title: Add a self-custody wallet
+ onchain_wallet_item:
+ assets_tracked:
+ one: 1 asset tracked
+ other: "%{count} assets tracked"
+ sync: Sync now
+ syncing: Syncing...
+ price_provider_warning:
+ body: No enabled market data provider can price crypto, so these wallets track quantities but show a value of zero.
+ enable: Enable crypto prices
+ exchange_rate_body: "Crypto is priced in USD, and no exchange rate provider is configured to convert it into %{currency}, so these wallets track quantities but show a value of zero. Set EXCHANGE_RATE_PROVIDER — Frankfurter needs no API key."
+ exchange_rate_title: No exchange rate provider is configured
+ link: Open market data settings
+ title: Crypto prices are not configured
+ provider_connection:
+ description: Track a wallet you hold the keys to, from its public address.
+ name: Self-custody wallet
+ review_tokens:
+ save: Save tracked assets
+ subtitle: "%{chain} · %{address}"
+ title: Review tracked assets
+ token_review:
+ import_selected: Track selected assets
+ subtitle: "%{chain} · %{address}"
+ title: Choose what to track
+ token_review_form:
+ assets_truncated: "This address holds more tokens than one read surfaces, so only the %{count} most credible are listed."
+ cancel: Cancel
+ explanation: Assets with a known price are ticked. Anything else is left unticked — wallets collect spam airdrops, and tracking one has no value attached to it.
+ native: Native
+ no_price: No price available; tracked by quantity only
+ nothing_found: This address holds nothing we can see on this network.
+ update:
+ success: Updated the self-custody connection.
+ update_tokens:
+ errors:
+ no_changes: Nothing changed; the same assets are still ticked.
+ none_tracked: "Nothing changed: %{assets} could not be added. Try again in a moment."
+ some_failed: "%{assets} could not be tracked and was left out."
+ success: "Tracked assets updated (%{created} added, %{removed} removed)."
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index e67f32bba1..c4f1eeb661 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -423,6 +423,7 @@ en:
coinbase: Import your Coinbase crypto holdings and track performance.
binance: Sync your Binance spot balances using a read-only API key.
kraken: Sync Kraken balances and spot trade fills using a read-only API key.
+ onchain_wallet: Track self-custody Bitcoin, EVM and Solana wallets from their public addresses.
snaptrade: Connect brokerage accounts via the SnapTrade aggregation network.
trading212: Sync your Trading 212 investment portfolio using a read-only API key.
ibkr: Sync Interactive Brokers investment accounts via Flex Query imports.
@@ -502,6 +503,21 @@ en:
sync: Sync
disconnect: Disconnect
disconnect_confirm: "Are you sure you want to disconnect %{name}?"
+ onchain_wallet_panel:
+ add_wallet: Add wallet
+ advanced: Advanced
+ disconnect_all: Disconnect all wallets
+ disconnect_all_confirm: This removes every tracked address and its accounts. Continue?
+ etherscan_api_key_label: Etherscan API key (optional)
+ etherscan_api_key_placeholder: Paste an Etherscan API key
+ etherscan_hint: Ethereum reads work without a key. Adding an Etherscan key only raises the rate limit for Ethereum.
+ keep_etherscan_api_key: Leave blank to keep the existing key
+ manage_wallets: Manage wallets
+ keyless_body: Sure only ever reads public chain data. No keys, seed phrases or signatures are involved, and nothing can be spent.
+ keyless_title: Read-only, no keys required
+ save: Save
+ sync_start_date_hint: Transfers before this date are ignored. Leave blank to import everything the explorer reports.
+ sync_start_date_label: Ignore transfers before
enable_banking_panel:
callback_url_instruction: "For the callback URL, use %{callback_url}."
connection_error: Connection Error
diff --git a/config/routes.rb b/config/routes.rb
index 1a44144904..5208eac108 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -127,6 +127,27 @@ Rails.application.routes.draw do
end
end
+ # Self-custody / on-chain wallets
+ resources :onchain_wallet_items, only: [ :update, :destroy ] do
+ collection do
+ get :new_wallet
+ post :preview_wallet
+ post :link_wallet
+ post :enable_crypto_prices
+ end
+
+ member do
+ post :sync
+ get :manage
+ get :review_tokens
+ post :update_tokens
+ get :edit_wallet
+ patch :change_address
+ delete :disconnect_wallet
+ delete :disconnect_asset
+ end
+ end
+
resources :snaptrade_items, only: [ :index, :show, :destroy ] do
collection do
get :preload_accounts
diff --git a/db/migrate/20260818120000_create_onchain_wallet_items_and_accounts.rb b/db/migrate/20260818120000_create_onchain_wallet_items_and_accounts.rb
new file mode 100644
index 0000000000..ff3a4a4d1b
--- /dev/null
+++ b/db/migrate/20260818120000_create_onchain_wallet_items_and_accounts.rb
@@ -0,0 +1,101 @@
+# frozen_string_literal: true
+
+class CreateOnchainWalletItemsAndAccounts < ActiveRecord::Migration[7.2]
+ def change
+ # Family-level connection. One item groups every self-custody address a
+ # family tracks; addresses live on onchain_wallet_accounts so a future
+ # extended-key (xpub) wallet can add its derived addresses as extra rows
+ # without changing any column or index defined here.
+ create_table :onchain_wallet_items, id: :uuid do |t|
+ t.references :family, null: false, foreign_key: true, type: :uuid
+ t.string :name
+
+ t.string :institution_name
+ t.string :institution_domain
+ t.string :institution_url
+ t.string :institution_color
+
+ t.string :status, default: "good", null: false
+ t.boolean :scheduled_for_deletion, default: false, null: false
+
+ t.datetime :sync_start_date
+
+ # Optional per-family explorer credential. Every chain works keyless; a
+ # key only raises Ethereum's rate limit.
+ t.text :etherscan_api_key
+
+ t.timestamps
+ end
+
+ add_index :onchain_wallet_items, :status
+
+ # One row per tracked asset, per address, per chain.
+ create_table :onchain_wallet_accounts, id: :uuid do |t|
+ t.references :onchain_wallet_item, null: false, foreign_key: true, type: :uuid
+
+ t.string :chain, null: false
+ t.string :wallet_address, null: false
+ t.string :asset_kind, null: false
+ t.string :contract_address
+
+ t.string :symbol, null: false
+ t.string :name
+ t.integer :decimals, null: false, default: 0
+
+ # Quantities are chain-native: 18 decimals covers every ERC-20 we can see.
+ t.decimal :quantity, precision: 32, scale: 18, default: 0, null: false
+ t.string :currency, null: false
+ t.decimal :current_balance, precision: 19, scale: 4
+
+ # Digest of the on-chain state last processed. Equal digests mean the
+ # chain has not moved, which is how the syncer stays idempotent.
+ t.string :content_hash
+
+ t.jsonb :raw_payload
+ t.jsonb :raw_movements_payload
+ t.jsonb :extra, default: {}, null: false
+
+ t.timestamps
+
+ # A token is identified by its contract, and the partial unique indexes
+ # below key on it — but NULLs are distinct to Postgres, so a token row that
+ # reached the table without one would slip past its index and duplicate.
+ # The model enforces this as well; a direct write does not go through it.
+ t.check_constraint "asset_kind = 'native' OR contract_address IS NOT NULL",
+ name: "chk_onchain_wallet_accounts_token_has_contract"
+
+ # The partial unique indexes below name their kind, so a row carrying any
+ # other one is keyed by nothing and duplicates freely. Adding a token kind
+ # already means adding its index here; this keeps the table from silently
+ # accepting rows for one that has none.
+ t.check_constraint "asset_kind IN ('native', 'erc20', 'spl')",
+ name: "chk_onchain_wallet_accounts_known_asset_kind"
+ end
+
+ add_index :onchain_wallet_accounts, [ :onchain_wallet_item_id, :chain, :wallet_address ],
+ name: "index_onchain_wallet_accounts_on_item_and_address"
+
+ # One partial unique index per asset kind, because the identity of an asset
+ # differs by kind: a native coin is identified by its address alone, while a
+ # token is identified by its contract/mint. A single index over all columns
+ # would treat two native rows with NULL contract_address as distinct and let
+ # duplicates through.
+ add_index :onchain_wallet_accounts,
+ [ :onchain_wallet_item_id, :chain, :wallet_address ],
+ unique: true,
+ where: "asset_kind = 'native'",
+ name: "index_onchain_wallet_accounts_unique_native"
+
+ add_index :onchain_wallet_accounts,
+ [ :onchain_wallet_item_id, :chain, :wallet_address, :contract_address ],
+ unique: true,
+ where: "asset_kind = 'erc20'",
+ name: "index_onchain_wallet_accounts_unique_erc20"
+
+ add_index :onchain_wallet_accounts,
+ [ :onchain_wallet_item_id, :chain, :wallet_address, :contract_address ],
+ unique: true,
+ where: "asset_kind = 'spl'",
+ name: "index_onchain_wallet_accounts_unique_spl"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index c28397175d..7e63ad32b2 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1502,6 +1502,50 @@ ActiveRecord::Schema[7.2].define(version: 2026_08_20_120000) do
t.index ["user_id"], name: "index_oidc_identities_on_user_id"
end
+ create_table "onchain_wallet_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.uuid "onchain_wallet_item_id", null: false
+ t.string "chain", null: false
+ t.string "wallet_address", null: false
+ t.string "asset_kind", null: false
+ t.string "contract_address"
+ t.string "symbol", null: false
+ t.string "name"
+ t.integer "decimals", default: 0, null: false
+ t.decimal "quantity", precision: 32, scale: 18, default: "0.0", null: false
+ t.string "currency", null: false
+ t.decimal "current_balance", precision: 19, scale: 4
+ t.string "content_hash"
+ t.jsonb "raw_payload"
+ t.jsonb "raw_movements_payload"
+ t.jsonb "extra", default: {}, null: false
+ t.datetime "created_at", null: false
+ t.datetime "updated_at", null: false
+ t.index ["onchain_wallet_item_id", "chain", "wallet_address", "contract_address"], name: "index_onchain_wallet_accounts_unique_erc20", unique: true, where: "((asset_kind)::text = 'erc20'::text)"
+ t.index ["onchain_wallet_item_id", "chain", "wallet_address", "contract_address"], name: "index_onchain_wallet_accounts_unique_spl", unique: true, where: "((asset_kind)::text = 'spl'::text)"
+ t.index ["onchain_wallet_item_id", "chain", "wallet_address"], name: "index_onchain_wallet_accounts_on_item_and_address"
+ t.index ["onchain_wallet_item_id", "chain", "wallet_address"], name: "index_onchain_wallet_accounts_unique_native", unique: true, where: "((asset_kind)::text = 'native'::text)"
+ t.index ["onchain_wallet_item_id"], name: "index_onchain_wallet_accounts_on_onchain_wallet_item_id"
+ t.check_constraint "asset_kind::text = 'native'::text OR contract_address IS NOT NULL", name: "chk_onchain_wallet_accounts_token_has_contract"
+ t.check_constraint "asset_kind::text = ANY (ARRAY['native'::character varying, 'erc20'::character varying, 'spl'::character varying]::text[])", name: "chk_onchain_wallet_accounts_known_asset_kind"
+ end
+
+ create_table "onchain_wallet_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.uuid "family_id", null: false
+ t.string "name"
+ t.string "institution_name"
+ t.string "institution_domain"
+ t.string "institution_url"
+ t.string "institution_color"
+ t.string "status", default: "good", null: false
+ t.boolean "scheduled_for_deletion", default: false, null: false
+ t.datetime "sync_start_date"
+ t.text "etherscan_api_key"
+ t.datetime "created_at", null: false
+ t.datetime "updated_at", null: false
+ t.index ["family_id"], name: "index_onchain_wallet_items_on_family_id"
+ t.index ["status"], name: "index_onchain_wallet_items_on_status"
+ end
+
create_table "other_assets", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
@@ -2435,6 +2479,8 @@ ActiveRecord::Schema[7.2].define(version: 2026_08_20_120000) do
add_foreign_key "oauth_access_grants", "oauth_applications", column: "application_id"
add_foreign_key "oauth_access_tokens", "oauth_applications", column: "application_id"
add_foreign_key "oidc_identities", "users"
+ add_foreign_key "onchain_wallet_accounts", "onchain_wallet_items"
+ add_foreign_key "onchain_wallet_items", "families"
add_foreign_key "plaid_accounts", "plaid_items"
add_foreign_key "plaid_items", "families"
add_foreign_key "questrade_accounts", "questrade_items"
diff --git a/docs/hosting/onchain-wallets.md b/docs/hosting/onchain-wallets.md
new file mode 100644
index 0000000000..333bcdf46f
--- /dev/null
+++ b/docs/hosting/onchain-wallets.md
@@ -0,0 +1,310 @@
+# On-chain (self-custody) wallets
+
+Sure can track wallets you hold the keys to — Bitcoin, six EVM networks and
+Solana — from their **public addresses only**. Nothing is signed, no key or seed
+phrase is ever entered, and no API key is required for any chain.
+
+This document covers where the data comes from, what needs configuring, the
+limits you will hit, and how to diagnose a wallet that looks wrong.
+
+## What gets tracked
+
+One Sure account is created per **asset**, per **address**, per **network**. A
+wallet holding ETH and USDC on Ethereum becomes two accounts, both Crypto
+accounts with the "wallet" subtype.
+
+For each asset Sure records:
+
+- the **quantity** held, read from the chain;
+- a **holding** valued at the current price, or at zero when no price is
+ available;
+- the **transfers** in and out, as investment trades when the price for that day
+ is known, so cost basis and the value chart reconstruct back to acquisition.
+ When that day's price is not known, the transfer still appears as an excluded,
+ zero-amount entry so you can see it happened without a made-up value entering
+ your history — and it is upgraded to a trade on the first sync after the price
+ becomes available.
+
+Balances are read-only and always derived from the chain. Editing them by hand is
+pointless: the next sync overwrites them.
+
+## Prices need two settings, not one (read this first)
+
+On-chain data sources report **quantities, not values**. Prices come from Sure's
+market data providers, and the only provider that can quote bare crypto symbols
+is **Binance public** (keyless).
+
+If no crypto-capable market data provider is enabled, every on-chain wallet is
+tracked by quantity and **valued at zero**. This is by far the most common
+support report for this feature, and it is a settings issue rather than a sync
+failure.
+
+The settings panel and the linking modal both warn you before you link
+anything, and on a self-hosted instance an admin can fix it from the warning
+itself with **Enable crypto prices** — that adds `binance_public` to the
+enabled providers and leaves the others alone. Otherwise, enable it under
+**Settings → Self hosting → Market data providers**, or set
+`SECURITIES_PROVIDERS` to a comma-separated list including `binance_public`.
+On a managed instance this is the operator's setting, so the button is not
+offered.
+
+### And an exchange rate, if your currency is not USD
+
+The crypto provider quotes in USD, so valuing a wallet in any other family
+currency needs one conversion — and Sure's default exchange rate provider
+(`twelve_data`) requires an API key. With no key and a non-USD family, there is no
+FX at all and every on-chain wallet is valued at zero for that second, separate
+reason.
+
+Set `EXCHANGE_RATE_PROVIDER` (or **Settings → Self hosting**) to a provider you
+can actually use; `frankfurter` needs no API key. The linking UI warns about this
+gap specifically, naming your currency, and a USD family never sees the warning
+because it needs no conversion.
+
+When an asset ends up valued at zero for either reason, it is recorded in
+**Settings → Debug logs** under the `onchain_wallet` provider, with the reasons
+listed, so the cause is visible without having to reproduce it.
+
+## Data sources
+
+| Network | Source | Key required | Override |
+|---|---|---|---|
+| Bitcoin | [mempool.space](https://mempool.space) REST API | No | `MEMPOOL_SPACE_URL` |
+| Ethereum | Blockscout (`eth.blockscout.com`) | No | `BLOCKSCOUT_ETHEREUM_URL` |
+| Base | Blockscout (`base.blockscout.com`) | No | `BLOCKSCOUT_BASE_URL` |
+| Arbitrum | Blockscout (`arbitrum.blockscout.com`) | No | `BLOCKSCOUT_ARBITRUM_URL` |
+| Optimism | Blockscout (`optimism.blockscout.com`) | No | `BLOCKSCOUT_OPTIMISM_URL` |
+| Polygon | Blockscout (`polygon.blockscout.com`) | No | `BLOCKSCOUT_POLYGON_URL` |
+| Gnosis | Blockscout (`gnosis.blockscout.com`) | No | `BLOCKSCOUT_GNOSIS_URL` |
+| Solana | Public JSON-RPC (`api.mainnet-beta.solana.com`) | No | `SOLANA_RPC_URL` |
+| Solana token names | Jupiter token search (`lite-api.jup.ag`) | No | `SOLANA_TOKEN_LIST_URL` |
+
+Every override expects the base URL of a compatible instance, without a trailing
+slash — useful if you run your own indexer or node, or if a public endpoint rate
+limits you.
+
+### Optional Etherscan key
+
+Ethereum, and only Ethereum, can be read through Etherscan instead of
+Blockscout. A key buys nothing except a higher rate limit. Add it under
+**Settings → Providers → On-chain wallets → Advanced**; it is stored encrypted,
+per family.
+
+A key only moves **transfer history** onto Etherscan. Balances and network
+detection always come from the keyless indexer, because Etherscan has no free
+endpoint that lists an address's tokens and summing transfer history would be
+wrong for a rebasing token — and wrong outright for anything older than the
+history cap. History is the paginated, rate-limited half of the work, so that is
+where a key actually helps. Leave the field empty unless you are being rate
+limited.
+
+## Rate limits and request cost
+
+All the default endpoints are free and shared, so they throttle. Each client
+paces its own requests and retries a 429 with exponential backoff. Per sync, per
+address, the cost is roughly:
+
+| Network | Requests per sync |
+|---|---|
+| Bitcoin | 1 + up to 10 history pages |
+| EVM | 1 summary + up to 10 pages of transfers + up to 10 pages of token transfers |
+| Solana | ~2 + up to 25 transaction reads |
+
+History is capped by default at 10 pages per source — 250 transactions for
+Bitcoin, 10 pages per EVM collection — and at 25 transactions for Solana, which
+spends one request per transaction rather than per page. Wallets with more
+history than that keep their **current balance correct** — balances come from an
+address summary, never from history — but their oldest transfers are not
+imported.
+
+Raise both caps with `ONCHAIN_HISTORY_MAX_PAGES` (default 10, maximum 200); the
+Solana budget scales with it proportionally. The request cost in the table above
+scales too, so raise it if you run your own node or indexer rather than against a
+public endpoint.
+
+**History is best effort; balances are not.** If a source refuses or times out
+on the paginated history, the balances are still recorded and the history is
+marked incomplete, rather than the whole read failing. This matters on the free
+Solana endpoint, which routinely throttles `getTransaction`: without it a Solana
+wallet would show nothing at all instead of showing what it holds.
+
+When a cap is hit, the affected address says so in **Manage wallets**, and the
+event is recorded in **Settings → Debug logs** under the `onchain_wallet`
+provider — once per address per sync, not once per night forever.
+
+### How many tokens one address surfaces
+
+Real addresses are airdrop dumping grounds: a well-known Ethereum address holds
+close to 8,000 ERC-20 tokens, and a comparable Solana one nearly 3,000 token
+accounts. Listing all of them would make the review screen unusable, so one read
+surfaces at most **200 tokens** per address, settable with
+`ONCHAIN_MAX_TOKENS_PER_ADDRESS` (maximum 5,000).
+
+The native coin is never affected, and anything already tracked keeps syncing
+regardless. On EVM networks the tokens kept are ranked by the market cap the
+indexer reports, so real assets survive the cap and airdrops fall off the end.
+Solana RPC offers no such signal, so there the order is by mint address —
+arbitrary, but identical between syncs, which is what stops the cap from
+reshuffling a wallet every night. The cap is stated in the review screen and in
+Manage wallets whenever it applies.
+
+Detecting which network an address belongs to costs **exactly one request per
+candidate network**, and never reads history. If an explorer is down during
+detection, that network simply reports "nothing found" instead of failing the
+whole flow; you can still pick it by hand.
+
+## Linking a wallet
+
+**Settings → Providers → On-chain wallets → Add wallet.**
+
+1. Paste the public address. Leave the network on "Detect automatically" unless
+ you know which one you want.
+2. If the address format belongs to several networks — every `0x` address is
+ valid on all six EVM networks, and Bitcoin's Base58 shape overlaps Solana's —
+ Sure probes each and asks you to choose, marking the ones where it found
+ activity.
+3. Pick the assets to track. The native coin and assets the data source treats
+ as notable are ticked; everything else is listed unticked. "Notable" means a
+ priced holding worth more than a dollar on EVM networks, or a place on
+ Solana's verified token list — because airdrops use perfectly plausible
+ symbols, so the symbol alone says nothing. On a heavily airdropped address
+ this is the difference between a handful of pre-ticked assets and two hundred.
+ You can still track anything listed; unpriceable assets show a quantity and a
+ value of zero.
+
+Nothing is imported that you did not tick.
+
+## Managing a wallet
+
+**Settings → Providers → On-chain wallets → Manage wallets.**
+
+- **Review tokens** — reopens the asset selection with the address unchanged.
+ This is how you start tracking a token that arrived later, or stop tracking one
+ you no longer want.
+- **Stop tracking** (per asset) — drops one asset.
+- **Change address** — corrects the address while keeping the accounts, holdings
+ and balance history attached to it.
+- **Disconnect wallet** — drops every asset at one address.
+
+Disconnecting never deletes an account. The provider link is removed, holdings
+are detached, and what you can see stays as a manual account that no longer
+updates. Delete the account itself if you want it gone.
+
+An address can only be tracked once per network. To change which assets are
+tracked, use Review tokens rather than adding the address again.
+
+## Limitations
+
+**Only tokens the crypto price provider quotes get a value, and it quotes by
+symbol.** This is the largest limitation of the feature, so read it before
+judging a number you disagree with. Valuation goes through a `CRYPTO:<SYMBOL>`
+ticker, and a symbol is not a token's identity — its contract is. In practice the
+provider covers major assets and little else: measured on a real Ethereum
+address, of its ten largest token positions it quoted two. The other eight —
+including holdings worth roughly $406,000, $141,000 and $74,000 — showed a value
+of zero while their quantities were tracked correctly.
+
+So: **a zero next to a token you know is worth something almost always means the
+provider does not list that token, not that the balance is wrong.** Check the
+quantity, which is read straight from the chain. Native coins (BTC, ETH, SOL,
+POL, XDAI) and large-cap tokens are the well-covered case.
+
+Pricing by contract address instead of by symbol would close most of the gap, and
+the data is already close at hand — the EVM indexer returns an exchange rate per
+token and Jupiter returns a USD price per mint, neither of which this version
+uses for valuation. That change belongs to how crypto enters Sure's price
+pipeline rather than to this feature, so it is not something you can configure
+your way out of today.
+
+**DeFi positions are not seen at all.** Staked ETH, liquidity-pool tokens,
+lending positions and Solana stake accounts are invisible: only natively-held
+coins and fungible tokens sitting at the address are read. A wallet holding most
+of its value in a staking or lending protocol will report a fraction of it. This
+is a scope limit, not a bug — nothing in the UI claims those positions were
+checked.
+
+**Bitcoin is one address at a time.** Extended keys (`xpub`, `ypub`, `zpub`) are
+not supported and are rejected as addresses. This matters: most Bitcoin wallets
+are HD wallets, where one extended key derives thousands of addresses and change
+is sent to derived ones. Tracking a single address of such a wallet reports only
+that address's balance, which is usually a fraction of the wallet. Supporting
+extended keys would require BIP32 derivation — a dependency this codebase
+deliberately avoids — or a descriptor-indexing backend. If you use a single-address
+setup, or want to follow one specific address, this works exactly as expected.
+
+**Solana token names depend on a token list.** RPC returns mints, not names, so
+names come from Jupiter's token search — and only for mints it reports as
+*verified*. Anyone can mint a token calling itself USDC, so an unverified or
+unknown mint keeps a label built from its mint address and is tracked by quantity
+only, rather than being handed the real asset's price. A handful of major mints
+resolve without the list, so they keep working if it is unreachable. Names are
+cached for 24 hours per mint, misses included.
+
+**Fees are not itemised.** Network fees are included in the net effect of each
+transfer rather than recorded separately. On Solana, native balance changes below
+0.0001 SOL are treated as fees and ignored.
+
+**Bridged assets are normalised.** USDC.e, USDbC, USDT0, WETH and similar
+1:1-redeemable forms are tracked as their canonical asset, so the same asset held
+on two networks is one Security rather than two.
+
+**Prices are daily and USD-quoted.** Values are converted into your family
+currency using Sure's exchange rates. A transfer whose day has no price becomes a
+zero-amount excluded entry rather than a trade.
+
+**NFTs are not tracked.** They are filtered out by token standard, so an NFT is
+never mistaken for a balance of one fungible token.
+
+## Troubleshooting
+
+**Every wallet shows a value of zero.** Either no crypto-capable market data
+provider is enabled, or your family currency is not USD and no exchange rate
+provider is configured. Both are covered above, and the linking UI says which one
+applies.
+
+**One token shows zero while the others in the same wallet are fine.** Different
+cause: the price provider does not quote that token. Pricing is by symbol and
+covers major assets, so long-tail tokens are tracked by quantity and valued at
+zero. See "Limitations" — there is no setting that changes this.
+
+**A Bitcoin balance is much lower than my wallet app shows.** You are tracking one
+address of an HD wallet. See "Limitations".
+
+**Sync says the explorer could not be reached.** The public endpoint is down,
+throttling you, or too slow to answer. Retry later, or point the relevant
+`*_URL` override at your own instance. This is the message for any transport
+failure — a refused connection, a timeout, a TLS error — as opposed to the
+generic "something went wrong", which means a bug worth reporting.
+
+**Solana shows balances but no transfers.** The free endpoint throttles the
+history methods; balances are kept and the history is marked incomplete. Set
+`SOLANA_RPC_URL` to your own node or a paid endpoint to get the transfers.
+
+**Solana times out entirely on a very large wallet.** `getTokenAccountsByOwner`
+returns every token account in one response, and the public endpoint struggles
+with wallets holding thousands of them (a well-known one has ~2,800). Same fix:
+point `SOLANA_RPC_URL` at a real node.
+
+**A token I received is not showing up.** New assets are never imported
+automatically. Use **Review tokens** and tick it.
+
+**A Solana token shows as `SPL:abcd…wxyz`.** The token list does not vouch for
+that mint, so Sure will not name or price it. Tick it anyway to track the
+quantity.
+
+**Transfers appear with a value of 0 and are excluded from totals.** No price was
+available for that date yet. Once market data covers the range, the next sync
+upgrades those entries to trades automatically — they keep their identity, so
+nothing is duplicated. If they stay at zero, the date is outside what your market
+data provider can serve.
+
+**Manage wallets says the history is incomplete.** The address has more transfers
+than one sync reads. Balances are unaffected. Raise
+`ONCHAIN_HISTORY_MAX_PAGES` if you need the full history and can afford the extra
+requests.
+
+**Balances are correct but nothing updates.** Syncs only rewrite an account when
+the chain actually changed — an idle wallet is meant to produce no writes at all.
+Check **Settings → Providers** for the last sync time, and
+**Settings → Debug logs** (super admin), filtered to the `onchain_wallet`
+provider, for recorded failures.
diff --git a/test/controllers/onchain_wallet_items_controller_test.rb b/test/controllers/onchain_wallet_items_controller_test.rb
new file mode 100644
index 0000000000..f7b8114d16
--- /dev/null
+++ b/test/controllers/onchain_wallet_items_controller_test.rb
@@ -0,0 +1,646 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class OnchainWalletItemsControllerTest < ActionDispatch::IntegrationTest
+ include OnchainTestHelper
+
+ setup do
+ sign_in users(:family_admin)
+ SyncJob.stubs(:perform_later)
+ register_fake_chain!
+ @family = families(:dylan_family)
+ end
+
+ teardown do
+ unregister_fake_chain!
+ end
+
+ test "new_wallet renders the address form with the read-only and Bitcoin notes" do
+ get new_wallet_onchain_wallet_items_url
+
+ assert_response :success
+ assert_match I18n.t("onchain_wallet_items.new_wallet.bitcoin_single_address_note"), response.body
+ assert_match I18n.t("onchain_wallet_items.new_wallet.read_only_note"), response.body
+ end
+
+ test "the settings panel renders before anything is linked" do
+ 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
+
+ test "the settings panel renders the tracked wallets and the connection settings" do
+ item = create_onchain_wallet_item(family: @family)
+ create_onchain_wallet_account(item: item)
+
+ get connect_form_settings_providers_path(provider_key: "onchain_wallet")
+
+ assert_response :success
+ assert_match OnchainTestHelper::FAKE_ADDRESS.first(6), response.body
+ assert_match I18n.t("settings.providers.onchain_wallet_panel.etherscan_api_key_label"), response.body
+ assert_match I18n.t("settings.providers.onchain_wallet_panel.sync_start_date_label"), response.body
+ assert_select "form[action=?]", sync_onchain_wallet_item_path(item)
+ assert_select "a[href=?]", manage_onchain_wallet_item_path(item)
+ end
+
+ test "the price provider warning appears only when no crypto provider is enabled" do
+ get new_wallet_onchain_wallet_items_url
+ assert_match I18n.t("onchain_wallet_items.price_provider_warning.title"), response.body
+
+ Setting.stubs(:enabled_securities_providers).returns([ Onchain::SecurityResolver::PRICE_PROVIDER ])
+
+ get new_wallet_onchain_wallet_items_url
+ assert_no_match I18n.t("onchain_wallet_items.price_provider_warning.title"), response.body
+ end
+
+ test "a non-USD family is warned that nothing can convert USD prices" do
+ Setting.stubs(:enabled_securities_providers).returns([ Onchain::SecurityResolver::PRICE_PROVIDER ])
+ ExchangeRate.stubs(:provider).returns(nil)
+ @family.update!(currency: "EUR")
+
+ get new_wallet_onchain_wallet_items_url
+
+ assert_match I18n.t("onchain_wallet_items.price_provider_warning.exchange_rate_title"), response.body
+ assert_no_match I18n.t("onchain_wallet_items.price_provider_warning.title"), response.body
+ end
+
+ test "a USD family with crypto prices on sees no pricing warning at all" do
+ Setting.stubs(:enabled_securities_providers).returns([ Onchain::SecurityResolver::PRICE_PROVIDER ])
+
+ get new_wallet_onchain_wallet_items_url
+
+ assert_no_match I18n.t("onchain_wallet_items.price_provider_warning.title"), response.body
+ assert_no_match I18n.t("onchain_wallet_items.price_provider_warning.exchange_rate_title"), response.body
+ end
+
+ test "the warning offers a one-click fix on a self-hosted instance" do
+ Rails.configuration.stubs(:app_mode).returns(ActiveSupport::StringInquirer.new("self_hosted"))
+
+ get new_wallet_onchain_wallet_items_url
+
+ assert_select "form[action=?]", enable_crypto_prices_onchain_wallet_items_path
+ end
+
+ test "enable_crypto_prices adds the crypto provider without disabling the others" do
+ Rails.configuration.stubs(:app_mode).returns(ActiveSupport::StringInquirer.new("self_hosted"))
+ Setting.securities_providers = "twelve_data"
+
+ post enable_crypto_prices_onchain_wallet_items_url
+
+ assert_response :redirect
+ assert Onchain::SecurityResolver.price_provider_enabled?
+ assert_includes Setting.enabled_securities_providers, "twelve_data"
+ end
+
+ test "enable_crypto_prices is refused on a managed instance where the operator decides" do
+ Setting.securities_providers = "twelve_data"
+
+ post enable_crypto_prices_onchain_wallet_items_url
+
+ assert_response :redirect
+ assert_not Onchain::SecurityResolver.price_provider_enabled?
+ assert_equal I18n.t("onchain_wallet_items.enable_crypto_prices.not_self_hosted"), flash[:alert]
+ end
+
+ test "a member without admin rights is not offered the one-click fix" do
+ Rails.configuration.stubs(:app_mode).returns(ActiveSupport::StringInquirer.new("self_hosted"))
+ sign_in users(:family_member)
+
+ get manage_onchain_wallet_item_url(create_onchain_wallet_item(family: @family))
+
+ assert_response :redirect
+ end
+
+ test "preview_wallet lists what the address holds, pre-checking only vouched-for assets" do
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(
+ assets: [
+ fake_native_asset(quantity: 2),
+ fake_token_asset(symbol: "USDC", contract: "0xusdc", quantity: 10),
+ fake_token_asset(symbol: "Visit site to claim", contract: "0xspam", quantity: 1),
+ # An airdrop with a perfectly plausible symbol: only the data source's
+ # own signal separates it from the real thing.
+ fake_token_asset(symbol: "0XBTC", contract: "0xairdrop", quantity: 1, notable: false)
+ ],
+ movements: []
+ )
+ )
+
+ post preview_wallet_onchain_wallet_items_url, params: { address: OnchainTestHelper::FAKE_ADDRESS }
+
+ assert_response :success
+ assert_match "USDC", response.body
+ assert_match I18n.t("onchain_wallet_items.token_review_form.no_price"), response.body
+ assert_select "input[name='assets[]'][value='native'][checked]"
+ assert_select "input[name='assets[]'][value='erc20:0xusdc'][checked]"
+ assert_select "input[name='assets[]'][value='erc20:0xspam']"
+ assert_select "input[name='assets[]'][value='erc20:0xspam'][checked]", false
+ assert_select "input[name='assets[]'][value='erc20:0xairdrop']"
+ assert_select "input[name='assets[]'][value='erc20:0xairdrop'][checked]", false
+ end
+
+ test "preview_wallet rejects an address that belongs to no supported chain" do
+ post preview_wallet_onchain_wallet_items_url, params: { address: "definitely-not-an-address" }
+
+ assert_response :unprocessable_entity
+ assert_match I18n.t("onchain_wallet_items.errors.unrecognized_address"), response.body
+ end
+
+ test "preview_wallet asks which chain when several report activity" do
+ other = "otherchain"
+ Onchain::Chains.register(
+ Onchain::Chains::Definition.new(
+ key: other,
+ native: Onchain::Chains::NativeAsset.new(symbol: "OTHER", name: "Other", decimals: 8),
+ token_kind: nil,
+ adapter_class_name: "OnchainTestHelper::FakeAdapter",
+ adapter_options: {}
+ )
+ )
+
+ post preview_wallet_onchain_wallet_items_url, params: { address: OnchainTestHelper::FAKE_ADDRESS }
+
+ assert_response :success
+ assert_match I18n.t("onchain_wallet_items.choose_chain.title"), response.body
+ assert_match I18n.t("onchain_wallet_items.choose_chain.activity_found"), response.body
+ ensure
+ Onchain::Chains.unregister(other)
+ end
+
+ test "an expected explorer failure surfaces as a localized message" do
+ OnchainTestHelper::FakeAdapter.error = Onchain::Chains::UnreachableError.new("blockscout down")
+
+ post preview_wallet_onchain_wallet_items_url, params: { address: OnchainTestHelper::FAKE_ADDRESS }
+
+ assert_response :unprocessable_entity
+ assert_match I18n.t("onchain_wallet_items.errors.chain_unreachable"), response.body
+ assert_no_match "blockscout down", response.body
+ end
+
+ test "a data source that times out reads as unreachable, not as our own failure" do
+ OnchainTestHelper::FakeAdapter.error = Provider::MempoolSpace::ApiError.new("MempoolSpace is unavailable (Net::ReadTimeout)")
+ OnchainTestHelper::FakeAdapter.provider_error_classes = [ Provider::MempoolSpace::RateLimitError, Provider::MempoolSpace::Error ]
+
+ assert_no_difference "DebugLogEntry.count" do
+ post preview_wallet_onchain_wallet_items_url, params: { address: OnchainTestHelper::FAKE_ADDRESS }
+ end
+
+ assert_response :unprocessable_entity
+ assert_match I18n.t("onchain_wallet_items.errors.chain_unreachable"), response.body
+ assert_no_match "Net::ReadTimeout", response.body
+ end
+
+ test "an unexpected failure is recorded and never interpolated into the response" do
+ OnchainTestHelper::FakeAdapter.error = NoMethodError.new("undefined method 'boom' for nil")
+
+ assert_difference "DebugLogEntry.count", 1 do
+ post preview_wallet_onchain_wallet_items_url, params: { address: OnchainTestHelper::FAKE_ADDRESS }
+ end
+
+ assert_response :unprocessable_entity
+ assert_match I18n.t("onchain_wallet_items.errors.unexpected"), response.body
+ assert_no_match "undefined method", response.body
+ assert_equal "onchain_wallet", DebugLogEntry.order(:created_at).last.provider_key
+ end
+
+ test "link_wallet tracks only the ticked assets and creates one account each" do
+ stub_wallet_with_token
+
+ assert_difference [ "OnchainWalletAccount.count", "Account.count" ], 1 do
+ post link_wallet_onchain_wallet_items_url, params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ assets: [ "native" ]
+ }
+ end
+
+ assert_redirected_to accounts_path
+ onchain_account = OnchainWalletAccount.order(:created_at).last
+ assert_equal "native", onchain_account.asset_kind
+ assert_equal @family, onchain_account.onchain_wallet_item.family
+ assert_equal "Crypto", onchain_account.account.accountable_type
+ assert_equal "wallet", onchain_account.account.accountable.subtype
+ end
+
+ test "link_wallet ignores an asset the chain does not report" do
+ stub_wallet_with_token
+
+ assert_difference "OnchainWalletAccount.count", 1 do
+ post link_wallet_onchain_wallet_items_url, params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ assets: [ "native", "erc20:0xnothere" ]
+ }
+ end
+ end
+
+ test "link_wallet refuses an address the family already tracks" do
+ item = create_onchain_wallet_item(family: @family)
+ create_onchain_wallet_account(item: item)
+ stub_wallet_with_token
+
+ assert_no_difference "OnchainWalletAccount.count" do
+ post link_wallet_onchain_wallet_items_url, params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ assets: [ "native" ]
+ }
+ end
+
+ assert_response :unprocessable_entity
+ assert_match I18n.t("onchain_wallet_items.errors.already_linked"), response.body
+ end
+
+ test "preview_wallet refuses an address the family already tracks" do
+ item = create_onchain_wallet_item(family: @family)
+ create_onchain_wallet_account(item: item)
+
+ post preview_wallet_onchain_wallet_items_url, params: {
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ chain: OnchainTestHelper::FAKE_CHAIN
+ }
+
+ assert_response :unprocessable_entity
+ assert_match I18n.t("onchain_wallet_items.errors.already_linked"), response.body
+ end
+
+ test "a failed read leaves no empty connection behind" do
+ OnchainTestHelper::FakeAdapter.error = Onchain::Chains::UnreachableError.new("explorer down")
+
+ assert_no_difference "OnchainWalletItem.count" do
+ post link_wallet_onchain_wallet_items_url, params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ assets: [ "native" ]
+ }
+ end
+
+ assert_response :unprocessable_entity
+ assert_match I18n.t("onchain_wallet_items.errors.chain_unreachable"), response.body
+ end
+
+ test "assets that were ticked but could not be tracked are named, not blamed on the user" do
+ stub_wallet_with_token
+ OnchainWalletItem::WalletLinker.any_instance.stubs(:link).returns(
+ OnchainWalletItem::WalletLinker::Result.new(created: 0, removed: 0, errors: [ "USDC" ])
+ )
+
+ post link_wallet_onchain_wallet_items_url, params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ assets: [ "erc20:0xusdc" ]
+ }
+
+ assert_response :unprocessable_entity
+ assert_match "USDC", response.body
+ # Being told to "pick at least one asset" would send them back to tick the
+ # same one.
+ assert_no_match I18n.t("onchain_wallet_items.link_wallet.errors.nothing_selected"), response.body
+ end
+
+ test "a partial failure is reported alongside what did get tracked" do
+ stub_wallet_with_token
+ OnchainWalletItem::WalletLinker.any_instance.stubs(:link).returns(
+ OnchainWalletItem::WalletLinker::Result.new(created: 1, removed: 0, errors: [ "USDC" ])
+ )
+
+ post link_wallet_onchain_wallet_items_url, params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ assets: [ "native", "erc20:0xusdc" ]
+ }
+
+ assert_redirected_to accounts_path
+ assert_match "USDC", flash[:alert]
+ end
+
+ test "the settings link is not offered to anyone who cannot open that page" do
+ # Managed instance: market data is the operator's setting and the page is
+ # gated, so a link there is a dead end. Asserted on the link's own text —
+ # the settings layout mentions that path for its own reasons.
+ link = I18n.t("onchain_wallet_items.price_provider_warning.link")
+
+ get new_wallet_onchain_wallet_items_url
+ assert_match I18n.t("onchain_wallet_items.price_provider_warning.title"), response.body
+ assert_no_match link, response.body
+
+ Rails.configuration.stubs(:app_mode).returns(ActiveSupport::StringInquirer.new("self_hosted"))
+ get new_wallet_onchain_wallet_items_url
+ assert_match link, response.body
+
+ sign_in users(:family_member)
+ get manage_onchain_wallet_item_url(create_onchain_wallet_item(family: @family))
+ assert_response :redirect
+ end
+
+ test "link_wallet with nothing ticked reopens the selection" do
+ stub_wallet_with_token
+
+ assert_no_difference "OnchainWalletAccount.count" do
+ post link_wallet_onchain_wallet_items_url, params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS
+ }
+ end
+
+ assert_response :unprocessable_entity
+ assert_match I18n.t("onchain_wallet_items.link_wallet.errors.nothing_selected"), response.body
+ end
+
+ test "previewing an address never leaves an empty connection behind" do
+ stub_wallet_with_token
+
+ assert_no_difference "OnchainWalletItem.count" do
+ post preview_wallet_onchain_wallet_items_url, params: { address: OnchainTestHelper::FAKE_ADDRESS }
+ end
+ end
+
+ test "sync schedules a sync for the family's own connection only" do
+ item = create_onchain_wallet_item(family: @family)
+ other_family_item = create_onchain_wallet_item(family: families(:empty))
+
+ post sync_onchain_wallet_item_url(item)
+ assert_redirected_to settings_providers_path
+
+ post sync_onchain_wallet_item_url(other_family_item)
+ assert_response :not_found
+ end
+
+ test "destroy schedules the connection for deletion" do
+ item = create_onchain_wallet_item(family: @family)
+
+ delete onchain_wallet_item_url(item)
+
+ assert_redirected_to settings_providers_path
+ assert item.reload.scheduled_for_deletion
+ end
+
+ test "update stores an explorer key and keeps it when the field is left blank" do
+ item = create_onchain_wallet_item(family: @family)
+
+ patch onchain_wallet_item_url(item), params: { onchain_wallet_item: { etherscan_api_key: "abc123" } }
+ assert_equal "abc123", item.reload.etherscan_api_key
+
+ patch onchain_wallet_item_url(item), params: { onchain_wallet_item: { etherscan_api_key: "" } }
+ assert_equal "abc123", item.reload.etherscan_api_key
+ end
+
+ test "update stores the date before which transfers are ignored" do
+ item = create_onchain_wallet_item(family: @family)
+
+ patch onchain_wallet_item_url(item), params: { onchain_wallet_item: { sync_start_date: "2026-01-15" } }
+
+ assert_equal Date.new(2026, 1, 15), item.reload.sync_start_date.to_date
+ end
+
+ test "linking creates the single connection every wallet hangs off" do
+ stub_wallet_with_token
+ stub_wallet_with_token(address: OnchainTestHelper::FAKE_ADDRESS_ALT)
+
+ assert_difference "OnchainWalletItem.count", 1 do
+ post link_wallet_onchain_wallet_items_url, params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ assets: [ "native" ]
+ }
+ end
+
+ assert_no_difference "OnchainWalletItem.count" do
+ post link_wallet_onchain_wallet_items_url, params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS_ALT,
+ assets: [ "native" ]
+ }
+ end
+
+ assert_equal 2, @family.reload.onchain_wallet_items.sole.wallet_keys.size
+ end
+
+ test "a member without admin rights cannot link a wallet" do
+ sign_in users(:family_member)
+
+ get new_wallet_onchain_wallet_items_url
+
+ assert_response :redirect
+ end
+
+ test "manage lists every tracked address and offers all four 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"))
+
+ get manage_onchain_wallet_item_url(item)
+
+ 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
+ assert_match native.symbol, response.body
+ assert_match token_asset.symbol, response.body
+ end
+
+ test "review_tokens reopens the selection with the address unchanged" do
+ item = create_onchain_wallet_item(family: @family)
+ create_onchain_wallet_account(item: item)
+ stub_wallet_with_token
+
+ get review_tokens_onchain_wallet_item_url(item, chain: OnchainTestHelper::FAKE_CHAIN, address: OnchainTestHelper::FAKE_ADDRESS)
+
+ assert_response :success
+ assert_select "input[name=address][value=?]", OnchainTestHelper::FAKE_ADDRESS
+ assert_select "input[name='new_address']", false
+ assert_select "input[name='assets[]'][value='native'][checked]"
+ assert_select "input[name='assets[]'][value='erc20:0xusdc'][checked]"
+ end
+
+ test "update_tokens adds a newly ticked asset and stops tracking an unticked one" do
+ item = create_onchain_wallet_item(family: @family)
+ native = create_onchain_wallet_account(item: item)
+ stub_wallet_with_token
+
+ assert_difference "OnchainWalletAccount.count", 0 do
+ post update_tokens_onchain_wallet_item_url(item), params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ assets: [ "erc20:0xusdc" ]
+ }
+ end
+
+ assert_redirected_to manage_onchain_wallet_item_path(item)
+ assert_not OnchainWalletAccount.exists?(native.id)
+ assert_equal [ "USDC" ], item.reload.onchain_wallet_accounts.pluck(:symbol)
+ end
+
+ test "unticking one asset removes only it" 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"))
+ stub_wallet_with_token
+
+ post update_tokens_onchain_wallet_item_url(item), params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ assets: [ "native" ]
+ }
+
+ assert OnchainWalletAccount.exists?(native.id)
+ assert_not OnchainWalletAccount.exists?(token_asset.id)
+ end
+
+ test "an asset the chain no longer reports can still be unticked" do
+ item = create_onchain_wallet_item(family: @family)
+ gone = create_onchain_wallet_account(item: item, asset: fake_token_asset(symbol: "GONE", contract: "0xgone"))
+ create_onchain_wallet_account(item: item)
+ stub_wallet_with_token
+
+ get review_tokens_onchain_wallet_item_url(item, chain: OnchainTestHelper::FAKE_CHAIN, address: OnchainTestHelper::FAKE_ADDRESS)
+ assert_select "input[name='assets[]'][value='erc20:0xgone'][checked]"
+
+ post update_tokens_onchain_wallet_item_url(item), params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS,
+ assets: [ "native" ]
+ }
+
+ 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)
+ create_onchain_wallet_account(item: item)
+ 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 "disconnect_wallet stops tracking every asset at that address only" do
+ item = create_onchain_wallet_item(family: @family)
+ create_onchain_wallet_account(item: item)
+ create_onchain_wallet_account(item: item, asset: fake_token_asset(contract: "0xusdc"))
+ kept = create_onchain_wallet_account(item: item, address: OnchainTestHelper::FAKE_ADDRESS_ALT)
+
+ assert_difference "OnchainWalletAccount.count", -2 do
+ delete disconnect_wallet_onchain_wallet_item_url(item), params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS
+ }
+ end
+
+ assert OnchainWalletAccount.exists?(kept.id)
+ end
+
+ test "disconnecting keeps the account and its holdings as a manual account" do
+ item = create_onchain_wallet_item(family: @family)
+ onchain_account = create_onchain_wallet_account(item: item)
+ account = link_onchain_wallet_account!(onchain_account)
+ security = Onchain::SecurityResolver.resolve(symbol: onchain_account.symbol)
+ holding = account.holdings.create!(
+ security: security, date: Date.current, qty: 1, price: 1, amount: 1,
+ currency: account.currency, account_provider_id: onchain_account.account_provider.id
+ )
+
+ delete disconnect_asset_onchain_wallet_item_url(item), params: { onchain_wallet_account_id: onchain_account.id }
+
+ assert Account.exists?(account.id)
+ assert holding.reload.persisted?
+ assert_nil holding.account_provider_id
+ assert_not AccountProvider.exists?(provider_type: "OnchainWalletAccount", provider_id: onchain_account.id)
+ end
+
+ test "management actions refuse a wallet this connection does not track" do
+ item = create_onchain_wallet_item(family: @family)
+ create_onchain_wallet_account(item: item)
+
+ get review_tokens_onchain_wallet_item_url(item, chain: OnchainTestHelper::FAKE_CHAIN, address: OnchainTestHelper::FAKE_ADDRESS_ALT)
+
+ assert_redirected_to manage_onchain_wallet_item_path(item)
+ assert_equal I18n.t("onchain_wallet_items.errors.wallet_not_found"), flash[:alert]
+ end
+
+ test "management actions cannot reach another family's connection" do
+ other_family_item = create_onchain_wallet_item(family: families(:empty))
+ create_onchain_wallet_account(item: other_family_item)
+
+ get manage_onchain_wallet_item_url(other_family_item)
+ assert_response :not_found
+
+ delete disconnect_wallet_onchain_wallet_item_url(other_family_item), params: {
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ address: OnchainTestHelper::FAKE_ADDRESS
+ }
+ assert_response :not_found
+ assert_equal 1, other_family_item.onchain_wallet_accounts.count
+ end
+
+ test "disconnect_asset cannot reach a row belonging to another connection" do
+ item = create_onchain_wallet_item(family: @family)
+ other_item = create_onchain_wallet_item(family: families(:empty))
+ other_account = create_onchain_wallet_account(item: other_item)
+
+ delete disconnect_asset_onchain_wallet_item_url(item), params: { onchain_wallet_account_id: other_account.id }
+
+ assert_response :not_found
+ assert OnchainWalletAccount.exists?(other_account.id)
+ end
+
+ private
+ def stub_wallet_with_token(address: OnchainTestHelper::FAKE_ADDRESS)
+ stub_fake_snapshot(
+ address,
+ Onchain::Snapshot.new(
+ assets: [ fake_native_asset(quantity: 2), fake_token_asset(symbol: "USDC", contract: "0xusdc", quantity: 10) ],
+ movements: []
+ )
+ )
+ end
+end
diff --git a/test/models/onchain/asset_budget_test.rb b/test/models/onchain/asset_budget_test.rb
new file mode 100644
index 0000000000..b5f323b0bc
--- /dev/null
+++ b/test/models/onchain/asset_budget_test.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::AssetBudgetTest < ActiveSupport::TestCase
+ test "defaults to a reviewable number of tokens" do
+ assert_equal Onchain::AssetBudget::DEFAULT_TOKENS, Onchain::AssetBudget.tokens
+ end
+
+ test "is configurable and clamped rather than able to reach zero" do
+ with_env("500") { assert_equal 500, Onchain::AssetBudget.tokens }
+ with_env("0") { assert_equal Onchain::AssetBudget::DEFAULT_TOKENS, Onchain::AssetBudget.tokens }
+ with_env("nope") { assert_equal Onchain::AssetBudget::DEFAULT_TOKENS, Onchain::AssetBudget.tokens }
+ with_env("999999") { assert_equal Onchain::AssetBudget::MAX_TOKENS, Onchain::AssetBudget.tokens }
+ end
+
+ private
+ def with_env(value)
+ previous = ENV["ONCHAIN_MAX_TOKENS_PER_ADDRESS"]
+ ENV["ONCHAIN_MAX_TOKENS_PER_ADDRESS"] = value
+ yield
+ ensure
+ ENV["ONCHAIN_MAX_TOKENS_PER_ADDRESS"] = previous
+ end
+end
diff --git a/test/models/onchain/asset_symbol_test.rb b/test/models/onchain/asset_symbol_test.rb
new file mode 100644
index 0000000000..6ea4f5819b
--- /dev/null
+++ b/test/models/onchain/asset_symbol_test.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::AssetSymbolTest < ActiveSupport::TestCase
+ test "strips bridge suffixes" do
+ assert_equal "USDC", Onchain::AssetSymbol.canonical("USDC.e")
+ assert_equal "BTC", Onchain::AssetSymbol.canonical("BTC.b")
+ assert_equal "DAI", Onchain::AssetSymbol.canonical("dai.e")
+ end
+
+ test "maps bridged and wrapped aliases to their canonical asset" do
+ assert_equal "USDT", Onchain::AssetSymbol.canonical("USDT0")
+ assert_equal "USDC", Onchain::AssetSymbol.canonical("USDbC")
+ assert_equal "ETH", Onchain::AssetSymbol.canonical("weth")
+ assert_equal "POL", Onchain::AssetSymbol.canonical("WMATIC")
+ end
+
+ test "leaves an unknown symbol alone apart from case and whitespace" do
+ assert_equal "PEPE", Onchain::AssetSymbol.canonical(" pepe ")
+ assert_equal "", Onchain::AssetSymbol.canonical(nil)
+ end
+end
diff --git a/test/models/onchain/bitcoin_adapter_test.rb b/test/models/onchain/bitcoin_adapter_test.rb
new file mode 100644
index 0000000000..aa74d37b75
--- /dev/null
+++ b/test/models/onchain/bitcoin_adapter_test.rb
@@ -0,0 +1,206 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::BitcoinAdapterTest < ActiveSupport::TestCase
+ P2PKH = "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"
+ P2SH = "3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy"
+ BECH32 = "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq"
+ TAPROOT = "bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg3297"
+
+ setup do
+ @adapter = Onchain::Chains.adapter_for(Onchain::Chains::BITCOIN)
+ end
+
+ test "accepts every address format Bitcoin wallets produce" do
+ [ P2PKH, P2SH, BECH32, TAPROOT ].each do |address|
+ assert @adapter.valid_address?(address), "#{address} should be accepted"
+ end
+ end
+
+ test "rejects malformed addresses without making a network call" do
+ # WebMock raises on any unstubbed request, so a network call here fails the test.
+ [
+ "",
+ "not-an-address",
+ "1A1zP1eP5QGefi2DMPTfTL5SLmv7Divf0a", # Base58 excludes 0
+ "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdb", # bech32 excludes b
+ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", # an EVM address
+ "xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz"
+ ].each do |address|
+ assert_not @adapter.valid_address?(address), "#{address.inspect} should be rejected"
+ end
+ end
+
+ test "bech32 is canonically lowercase while Base58 keeps its case" do
+ # An uppercase bech32 address is valid, but the API reports outputs in lower
+ # case: left as typed it yields a correct balance and silently zero movements.
+ assert_equal BECH32, @adapter.canonical_address(BECH32.upcase)
+ assert_equal TAPROOT, @adapter.canonical_address(" #{TAPROOT.upcase} ")
+ # Base58 is case-sensitive; folding it would change the address.
+ assert_equal P2PKH, @adapter.canonical_address(P2PKH)
+ end
+
+ test "fetch_snapshot refuses a malformed address before any request" do
+ assert_raises Onchain::Chains::Error do
+ @adapter.fetch_snapshot("not-an-address")
+ end
+ end
+
+ test "balance is funded minus spent, including the mempool" do
+ stub_address(
+ chain_stats: { "funded_txo_sum" => 150_000_000, "spent_txo_sum" => 50_000_000 },
+ mempool_stats: { "funded_txo_sum" => 0, "spent_txo_sum" => 25_000_000 }
+ )
+ stub_transactions([])
+
+ snapshot = @adapter.fetch_snapshot(BECH32)
+
+ asset = snapshot.assets.sole
+ assert asset.native?
+ assert_equal "BTC", asset.symbol
+ assert_equal 8, asset.decimals
+ assert_equal BigDecimal("0.75"), asset.quantity
+ assert_nil asset.contract
+ end
+
+ test "movements are the net effect of each transaction on the address" do
+ stub_address
+ stub_transactions([
+ {
+ "txid" => "received",
+ "vin" => [ { "prevout" => { "scriptpubkey_address" => "other", "value" => 100_000_000 } } ],
+ "vout" => [ { "scriptpubkey_address" => BECH32, "value" => 20_000_000 } ],
+ "status" => { "confirmed" => true, "block_time" => Time.utc(2026, 1, 2).to_i }
+ },
+ {
+ "txid" => "spent",
+ "vin" => [ { "prevout" => { "scriptpubkey_address" => BECH32, "value" => 20_000_000 } } ],
+ "vout" => [
+ { "scriptpubkey_address" => "other", "value" => 15_000_000 },
+ { "scriptpubkey_address" => BECH32, "value" => 4_000_000 }
+ ],
+ "status" => { "confirmed" => true, "block_time" => Time.utc(2026, 1, 3).to_i }
+ }
+ ])
+
+ movements = @adapter.fetch_snapshot(BECH32).movements
+
+ assert_equal [ "received", "spent" ], movements.map(&:external_id)
+ assert_equal BigDecimal("0.2"), movements.first.amount
+ assert_equal BigDecimal("-0.16"), movements.last.amount
+ assert_equal Date.new(2026, 1, 2), movements.first.date
+ assert_nil movements.first.contract
+ end
+
+ test "self-transfers and unrelated transactions produce no movement" do
+ stub_address
+ stub_transactions([
+ {
+ "txid" => "self",
+ "vin" => [ { "prevout" => { "scriptpubkey_address" => BECH32, "value" => 10_000_000 } } ],
+ "vout" => [ { "scriptpubkey_address" => BECH32, "value" => 10_000_000 } ],
+ "status" => { "confirmed" => true, "block_time" => Time.utc(2026, 1, 2).to_i }
+ },
+ {
+ "txid" => "unrelated",
+ "vin" => [ { "prevout" => { "scriptpubkey_address" => "other", "value" => 10_000_000 } } ],
+ "vout" => [ { "scriptpubkey_address" => "another", "value" => 9_000_000 } ],
+ "status" => { "confirmed" => true, "block_time" => Time.utc(2026, 1, 2).to_i }
+ }
+ ])
+
+ assert_empty @adapter.fetch_snapshot(BECH32).movements
+ end
+
+ test "a history longer than the budget is reported as truncated" do
+ stub_address
+ full_page = Array.new(Provider::MempoolSpace::PAGE_SIZE) do |i|
+ {
+ "txid" => "tx#{i}",
+ "vin" => [],
+ "vout" => [ { "scriptpubkey_address" => BECH32, "value" => 1_000 } ],
+ "status" => { "confirmed" => true, "block_time" => Time.utc(2026, 1, 2).to_i }
+ }
+ end
+ stub_transactions(full_page)
+ stub_request(:get, %r{/address/#{BECH32}/txs/chain/}).to_return(
+ status: 200, body: full_page.to_json, headers: { "Content-Type" => "application/json" }
+ )
+
+ with_history_budget(2) do
+ snapshot = @adapter.fetch_snapshot(BECH32)
+
+ assert snapshot.history_truncated?
+ # Balances come from the summary, so they are unaffected by the cap.
+ assert_equal 0, snapshot.assets.sole.quantity
+ end
+ end
+
+ test "an explorer that refuses history still yields the balance" do
+ stub_address(chain_stats: { "funded_txo_sum" => 100_000_000, "spent_txo_sum" => 0 })
+ stub_request(:get, "#{base_url}/address/#{BECH32}/txs").to_return(status: 429)
+
+ snapshot = @adapter.fetch_snapshot(BECH32)
+
+ assert_equal BigDecimal("1"), snapshot.assets.sole.quantity
+ assert_empty snapshot.movements
+ assert snapshot.history_truncated?
+ end
+
+ test "a timed-out explorer is reported as unreachable, not as an unexpected failure" do
+ stub_request(:get, "#{base_url}/address/#{BECH32}").to_timeout
+
+ assert_raises Onchain::Chains::UnreachableError do
+ @adapter.fetch_snapshot(BECH32)
+ end
+ end
+
+ test "a history that fits is not reported as truncated" do
+ stub_address
+ stub_transactions([])
+
+ assert_not @adapter.fetch_snapshot(BECH32).history_truncated?
+ end
+
+ test "an unconfirmed transaction is dated today" do
+ stub_address
+ stub_transactions([
+ {
+ "txid" => "pending",
+ "vin" => [],
+ "vout" => [ { "scriptpubkey_address" => BECH32, "value" => 1_000_000 } ],
+ "status" => { "confirmed" => false }
+ }
+ ])
+
+ assert_equal Date.current, @adapter.fetch_snapshot(BECH32).movements.sole.date
+ end
+
+ private
+ def with_history_budget(pages)
+ previous = ENV["ONCHAIN_HISTORY_MAX_PAGES"]
+ ENV["ONCHAIN_HISTORY_MAX_PAGES"] = pages.to_s
+ yield
+ ensure
+ ENV["ONCHAIN_HISTORY_MAX_PAGES"] = previous
+ end
+
+ def base_url
+ Provider::MempoolSpace.base_url
+ end
+
+ def stub_address(chain_stats: { "funded_txo_sum" => 0, "spent_txo_sum" => 0 }, mempool_stats: { "funded_txo_sum" => 0, "spent_txo_sum" => 0 })
+ stub_request(:get, "#{base_url}/address/#{BECH32}")
+ .to_return(
+ status: 200,
+ body: { "chain_stats" => chain_stats, "mempool_stats" => mempool_stats }.to_json,
+ headers: { "Content-Type" => "application/json" }
+ )
+ end
+
+ def stub_transactions(transactions)
+ stub_request(:get, "#{base_url}/address/#{BECH32}/txs")
+ .to_return(status: 200, body: transactions.to_json, headers: { "Content-Type" => "application/json" })
+ end
+end
diff --git a/test/models/onchain/chains_test.rb b/test/models/onchain/chains_test.rb
new file mode 100644
index 0000000000..acbadbd276
--- /dev/null
+++ b/test/models/onchain/chains_test.rb
@@ -0,0 +1,91 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::ChainsTest < ActiveSupport::TestCase
+ include OnchainTestHelper
+
+ setup do
+ register_fake_chain!
+ end
+
+ teardown do
+ unregister_fake_chain!
+ end
+
+ test "registers and finds a chain" do
+ assert Onchain::Chains.exists?(OnchainTestHelper::FAKE_CHAIN)
+ assert_equal OnchainTestHelper::FAKE_CHAIN, Onchain::Chains.find(OnchainTestHelper::FAKE_CHAIN).key
+ assert_includes Onchain::Chains.keys, OnchainTestHelper::FAKE_CHAIN
+ end
+
+ test "unregistering removes the chain" do
+ unregister_fake_chain!
+
+ assert_not Onchain::Chains.exists?(OnchainTestHelper::FAKE_CHAIN)
+ assert_raises Onchain::Chains::UnknownChainError do
+ Onchain::Chains.find!(OnchainTestHelper::FAKE_CHAIN)
+ end
+ end
+
+ test "refuses a token kind the schema has no unique index for" do
+ definition = Onchain::Chains::Definition.new(
+ key: "unindexed",
+ native: Onchain::Chains::NativeAsset.new(symbol: "UNI", name: "Unindexed", decimals: 18),
+ token_kind: "cw20",
+ adapter_class_name: "OnchainTestHelper::FakeAdapter",
+ adapter_options: {}
+ )
+
+ assert_raises Onchain::Chains::Error do
+ Onchain::Chains.register(definition)
+ end
+ ensure
+ Onchain::Chains.unregister("unindexed")
+ end
+
+ test "builds the adapter with the item credentials" do
+ adapter = Onchain::Chains.adapter_for(OnchainTestHelper::FAKE_CHAIN, credentials: { etherscan_api_key: "key" })
+
+ assert_instance_of OnchainTestHelper::FakeAdapter, adapter
+ assert_equal "key", adapter.credentials[:etherscan_api_key]
+ end
+
+ test "matching returns every chain whose address format accepts the address" do
+ matches = Onchain::Chains.matching(OnchainTestHelper::FAKE_ADDRESS)
+
+ assert_equal [ OnchainTestHelper::FAKE_CHAIN ], matches.map(&:key)
+ assert_empty Onchain::Chains.matching("not-an-address")
+ end
+
+ test "valid_address? returns false for an unregistered chain instead of raising" do
+ assert_not Onchain::Chains.valid_address?("nosuchchain", OnchainTestHelper::FAKE_ADDRESS)
+ end
+
+ test "native_asset carries the registry metadata" do
+ asset = fake_chain.native_asset(quantity: BigDecimal("2"))
+
+ assert asset.native?
+ assert_equal "FAKE", asset.symbol
+ assert_equal 8, asset.decimals
+ assert_nil asset.contract
+ end
+
+ test "token_asset uses the chain token kind and raises for chains without tokens" do
+ asset = fake_chain.token_asset(symbol: "FUSD", name: "Fake USD", decimals: 6, quantity: 1, contract: "0xAbC")
+
+ assert_equal OnchainTestHelper::FAKE_TOKEN_KIND, asset.kind
+ assert_equal "0xabc", asset.contract_key
+
+ unregister_fake_chain!
+ register_fake_chain!(token_kind: nil)
+
+ assert_raises Onchain::Chains::Error do
+ fake_chain.token_asset(symbol: "FUSD", name: "Fake USD", decimals: 6, quantity: 1, contract: "0xabc")
+ end
+ end
+
+ test "asset_kinds lists native plus the token kind" do
+ assert_equal [ "native", OnchainTestHelper::FAKE_TOKEN_KIND ], fake_chain.asset_kinds
+ end
+end
diff --git a/test/models/onchain/evm_adapter_test.rb b/test/models/onchain/evm_adapter_test.rb
new file mode 100644
index 0000000000..34aa0f5b69
--- /dev/null
+++ b/test/models/onchain/evm_adapter_test.rb
@@ -0,0 +1,429 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::EvmAdapterTest < ActiveSupport::TestCase
+ ADDRESS = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
+ USDC = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
+
+ setup do
+ @adapter = Onchain::Chains.adapter_for(Onchain::Chains::ETHEREUM)
+ end
+
+ test "accepts a 0x address and rejects anything else without a network call" do
+ assert @adapter.valid_address?(ADDRESS)
+ assert @adapter.valid_address?(ADDRESS.downcase)
+
+ [ "", "0x123", "0xZZZa6BF26964aF9D7eEd9e03E53415D37aA96045", "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq" ].each do |address|
+ assert_not @adapter.valid_address?(address), "#{address.inspect} should be rejected"
+ end
+ end
+
+ test "a checksummed address and its lowercase form are one address" do
+ assert_equal ADDRESS.downcase, @adapter.canonical_address(ADDRESS)
+ assert_equal ADDRESS.downcase, @adapter.canonical_address(" #{ADDRESS.upcase.sub("0X", "0x")} ")
+ end
+
+ test "the same address is valid on every EVM network, which is why detection exists" do
+ evm_chains = Onchain::Chains.matching(ADDRESS).map(&:key)
+
+ assert_includes evm_chains, Onchain::Chains::ETHEREUM
+ assert_operator evm_chains.size, :>, 1
+ assert_not_includes evm_chains, Onchain::Chains::BITCOIN
+ end
+
+ test "detection costs exactly one request per network" do
+ summary = stub_summary(coin_balance: "5000000000000000000")
+
+ assert @adapter.has_activity?(ADDRESS)
+ assert_requested summary, times: 1
+ end
+
+ test "a wallet holding only tokens with no native balance is still detected" do
+ stub_summary(coin_balance: "0", flags: { "has_tokens" => true })
+
+ assert @adapter.has_activity?(ADDRESS)
+ end
+
+ test "an empty address is not detected" do
+ stub_summary(coin_balance: "0")
+
+ assert_not @adapter.has_activity?(ADDRESS)
+ end
+
+ test "a failing explorer does not break the linking flow" do
+ stub_request(:get, summary_url).to_return(status: 500)
+
+ assert_not @adapter.has_activity?(ADDRESS)
+ end
+
+ test "two transfers of the same token in one transaction stay two movements" do
+ stub_summary(coin_balance: "0")
+ stub_token_balances([])
+ stub_transactions([])
+ # A swap router routinely emits several transfers of one token to the same
+ # address within a transaction; the hash and contract alone do not tell them
+ # apart, so one of them used to overwrite the other.
+ stub_token_transfers([
+ token_transfer(hash: "0xswap", log_index: 12, value: "1000000"),
+ token_transfer(hash: "0xswap", log_index: 27, value: "3000000")
+ ])
+
+ movements = @adapter.fetch_snapshot(ADDRESS).movements
+
+ assert_equal 2, movements.size
+ assert_equal 2, movements.map(&:external_id).uniq.size
+ assert_equal [ BigDecimal("1"), BigDecimal("3") ], movements.map(&:amount)
+ end
+
+ test "an explorer that refuses history still yields the balances" do
+ stub_summary(coin_balance: "1500000000000000000")
+ stub_token_balances([ erc20(contract: USDC, symbol: "USDC", value: "2500000") ])
+ stub_request(:get, "#{explorer_url}/api/v2/addresses/#{ADDRESS}/transactions").to_return(status: 429)
+ stub_token_transfers([])
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ assert_equal BigDecimal("1.5"), snapshot.find_asset(kind: "native").quantity
+ assert_equal BigDecimal("2.5"), snapshot.find_asset(kind: "erc20", contract: USDC).quantity
+ assert_empty snapshot.movements
+ assert snapshot.history_truncated?
+ end
+
+ test "a timed-out explorer is reported as unreachable, not as an unexpected failure" do
+ stub_request(:get, %r{#{explorer_url}}).to_timeout
+
+ assert_raises Onchain::Chains::UnreachableError do
+ @adapter.fetch_snapshot(ADDRESS)
+ end
+ end
+
+ test "detection asks once and does not retry a rate-limited explorer" do
+ probe = stub_request(:get, summary_url).to_return(status: 429, body: "rate limited")
+
+ assert_not @adapter.has_activity?(ADDRESS)
+ # A 0x address is a candidate on every EVM network and they are asked in
+ # turn on the request thread, so retrying with backoff per network is what
+ # turns detection into a page that hangs.
+ assert_requested probe, times: 1
+ end
+
+ test "a timed-out explorer during detection means not detected here" do
+ stub_request(:get, summary_url).to_timeout
+
+ assert_not @adapter.has_activity?(ADDRESS)
+ end
+
+ test "a malformed address is not probed at all" do
+ assert_not @adapter.has_activity?("0x123")
+ end
+
+ test "fetch_snapshot refuses a malformed address before any request" do
+ assert_raises Onchain::Chains::Error do
+ @adapter.fetch_snapshot("0x123")
+ end
+ end
+
+ test "reads the native coin and ERC-20 balances, scaled by their decimals" do
+ stub_summary(coin_balance: "1500000000000000000")
+ stub_token_balances([
+ erc20(contract: USDC, symbol: "USDC", name: "USD Coin", value: "2500000"),
+ erc20(contract: "0xdust", symbol: "DUST", value: "0", decimals: "18")
+ ])
+ stub_transactions([])
+ stub_token_transfers([])
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ native = snapshot.find_asset(kind: "native")
+ assert_equal "ETH", native.symbol
+ assert_equal BigDecimal("1.5"), native.quantity
+
+ token_asset = snapshot.find_asset(kind: "erc20", contract: USDC)
+ assert_equal "USDC", token_asset.symbol
+ assert_equal 6, token_asset.decimals
+ assert_equal BigDecimal("2.5"), token_asset.quantity
+
+ # Zero-balance tokens are dropped: real wallets are full of spam dust.
+ assert_equal 2, snapshot.assets.size
+ end
+
+ test "token balances are asked for without a type filter, which the API rejects" do
+ stub_summary(coin_balance: "0")
+ request = stub_token_balances([])
+ stub_transactions([])
+ stub_token_transfers([])
+
+ @adapter.fetch_snapshot(ADDRESS)
+
+ # Passing ?type=ERC-20 here is a 422: the filter exists on token-transfers,
+ # not on token-balances.
+ assert_requested request, times: 1
+ assert_requested :get, "#{explorer_url}/api/v2/addresses/#{ADDRESS}/token-balances", query: {}
+ end
+
+ test "only ERC-20 rows become assets, so an NFT is not read as one token" do
+ stub_summary(coin_balance: "0")
+ stub_token_balances([
+ erc20(contract: USDC, symbol: "USDC", value: "1000000"),
+ { "token" => { "address_hash" => "0xnft", "symbol" => "PUNK", "name" => "Punk", "decimals" => nil, "type" => "ERC-721" }, "value" => "1", "token_id" => "42" },
+ { "token" => { "address_hash" => "0xmulti", "symbol" => "MULTI", "name" => "Multi", "decimals" => nil, "type" => "ERC-1155" }, "value" => "3" }
+ ])
+ stub_transactions([])
+ stub_token_transfers([])
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ assert_equal [ USDC ], snapshot.assets.filter_map(&:contract_key)
+ assert_nil snapshot.find_asset(kind: "erc20", contract: "0xnft")
+ end
+
+ test "only a priced holding above dust is pre-ticked, whatever its symbol" do
+ stub_summary(coin_balance: "1000000000000000000")
+ stub_token_balances([
+ erc20(contract: USDC, symbol: "USDC", value: "2500000", market_cap: "40000000000", rate: "1"),
+ # A plausible symbol, a real market cap, and 0.000001 of it: an airdrop.
+ erc20(contract: "0xdust", symbol: "0XBTC", value: "1", market_cap: "5000000", rate: "0.5"),
+ # Priced by nothing at all.
+ erc20(contract: "0xunpriced", symbol: "MEH", value: "5000000")
+ ])
+ stub_transactions([])
+ stub_token_transfers([])
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ assert snapshot.find_asset(kind: "native").notable?
+ assert snapshot.find_asset(kind: "erc20", contract: USDC).notable?
+ assert_not snapshot.find_asset(kind: "erc20", contract: "0xdust").notable?
+ assert_not snapshot.find_asset(kind: "erc20", contract: "0xunpriced").notable?
+ end
+
+ test "an airdrop dump is capped, keeping the tokens with a market cap" do
+ stub_summary(coin_balance: "0")
+ stub_token_balances([
+ erc20(contract: "0xspam1", symbol: "SPAM1", value: "1000000"),
+ erc20(contract: USDC, symbol: "USDC", value: "1000000", market_cap: "40000000000"),
+ erc20(contract: "0xspam2", symbol: "SPAM2", value: "1000000"),
+ erc20(contract: "0xmid", symbol: "MID", value: "1000000", market_cap: "1000000")
+ ])
+ stub_transactions([])
+ stub_token_transfers([])
+
+ with_asset_budget(2) do
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ assert snapshot.assets_truncated?
+ # Ranked by market cap, so the credible assets survive the cap and the
+ # native coin is never at risk.
+ assert_equal [ nil, USDC, "0xmid" ], snapshot.assets.map(&:contract_key)
+ end
+ end
+
+ test "the cap keeps the same tokens between two reads of an unchanged address" do
+ stub_summary(coin_balance: "0")
+ stub_token_balances([
+ erc20(contract: "0xbbb", symbol: "B", value: "1000000"),
+ erc20(contract: "0xaaa", symbol: "A", value: "1000000"),
+ erc20(contract: "0xccc", symbol: "C", value: "1000000")
+ ])
+ stub_transactions([])
+ stub_token_transfers([])
+
+ with_asset_budget(2) do
+ first = @adapter.fetch_snapshot(ADDRESS).assets.map(&:contract_key)
+ second = Onchain::Chains.adapter_for(Onchain::Chains::ETHEREUM).fetch_snapshot(ADDRESS).assets.map(&:contract_key)
+
+ assert_equal first, second
+ end
+ end
+
+ test "an address within the budget is not reported as capped" do
+ stub_summary(coin_balance: "0")
+ stub_token_balances([ erc20(contract: USDC, symbol: "USDC", value: "1000000") ])
+ stub_transactions([])
+ stub_token_transfers([])
+
+ assert_not @adapter.fetch_snapshot(ADDRESS).assets_truncated?
+ end
+
+ test "the native asset is reported even when the wallet is empty" do
+ stub_summary(coin_balance: "0")
+ stub_token_balances([])
+ stub_transactions([])
+ stub_token_transfers([])
+
+ assert_equal 0, @adapter.fetch_snapshot(ADDRESS).find_asset(kind: "native").quantity
+ end
+
+ test "movements are signed by direction and carry the token contract" do
+ stub_summary(coin_balance: "0")
+ stub_token_balances([])
+ stub_transactions([
+ { "hash" => "0xin", "from" => { "hash" => "0xother" }, "to" => { "hash" => ADDRESS.downcase }, "value" => "2000000000000000000", "timestamp" => "2026-01-02T00:00:00.000000Z" },
+ { "hash" => "0xout", "from" => { "hash" => ADDRESS.downcase }, "to" => { "hash" => "0xother" }, "value" => "1000000000000000000", "timestamp" => "2026-01-03T00:00:00.000000Z" },
+ { "hash" => "0xself", "from" => { "hash" => ADDRESS.downcase }, "to" => { "hash" => ADDRESS.downcase }, "value" => "5", "timestamp" => "2026-01-04T00:00:00.000000Z" }
+ ])
+ stub_token_transfers([
+ {
+ "transaction_hash" => "0xtoken",
+ "from" => { "hash" => "0xother" },
+ "to" => { "hash" => ADDRESS.downcase },
+ "timestamp" => "2026-01-05T00:00:00.000000Z",
+ "token" => { "address_hash" => USDC, "symbol" => "USDC", "decimals" => "6" },
+ "total" => { "value" => "1500000", "decimals" => "6" }
+ }
+ ])
+
+ movements = @adapter.fetch_snapshot(ADDRESS).movements
+
+ assert_equal [ "0xin", "0xout", "0xtoken_#{USDC}" ], movements.map(&:external_id)
+ assert_equal BigDecimal("2"), movements[0].amount
+ assert_equal BigDecimal("-1"), movements[1].amount
+ assert_nil movements[0].contract
+ assert_equal BigDecimal("1.5"), movements[2].amount
+ assert_equal USDC, movements[2].contract_key
+ assert_equal Date.new(2026, 1, 5), movements[2].date
+ end
+
+ test "a key moves history onto Etherscan but never balances" do
+ assert_instance_of Provider::Blockscout, @adapter.balance_backend
+ assert_instance_of Provider::Blockscout, @adapter.history_backend
+
+ keyed = Onchain::Chains.adapter_for(Onchain::Chains::ETHEREUM, credentials: { etherscan_api_key: "key" })
+
+ assert_instance_of Provider::Blockscout, keyed.balance_backend
+ assert_instance_of Provider::Etherscan, keyed.history_backend
+ end
+
+ test "an Etherscan key is ignored on networks the registry does not enable it for" do
+ polygon = Onchain::Chains.adapter_for("polygon", credentials: { etherscan_api_key: "key" })
+
+ assert_instance_of Provider::Blockscout, polygon.history_backend
+ end
+
+ test "with a key configured, balances still come from the indexer and history from Etherscan" do
+ keyed = Onchain::Chains.adapter_for(Onchain::Chains::ETHEREUM, credentials: { etherscan_api_key: "key" })
+ stub_summary(coin_balance: "3000000000000000000")
+ stub_token_balances([ erc20(contract: USDC, symbol: "USDC", name: "USD Coin", value: "7000000") ])
+ etherscan_history = stub_etherscan_history
+
+ snapshot = keyed.fetch_snapshot(ADDRESS)
+
+ # Summing Etherscan's transfers would report 1 USDC, not the 7 actually held:
+ # the indexer is the only backend that can answer this.
+ assert_equal BigDecimal("7"), snapshot.find_asset(kind: "erc20", contract: USDC).quantity
+ assert_equal BigDecimal("3"), snapshot.find_asset(kind: "native").quantity
+ assert_equal [ "0xkeyed", "0xkeyedtoken_#{USDC}" ], snapshot.movements.map(&:external_id)
+ assert_requested etherscan_history, times: 2
+ end
+
+ test "Etherscan refuses to answer token balances rather than approximating them" do
+ keyed = Onchain::Chains.adapter_for(Onchain::Chains::ETHEREUM, credentials: { etherscan_api_key: "key" })
+
+ assert_raises NotImplementedError do
+ keyed.history_backend.token_balances(ADDRESS)
+ end
+ end
+
+ test "each network reads its own explorer" do
+ ethereum = Onchain::Chains.adapter_for(Onchain::Chains::ETHEREUM)
+ base = Onchain::Chains.adapter_for("base")
+
+ assert_not_equal ethereum.explorer_url, base.explorer_url
+ end
+
+ private
+ def with_asset_budget(tokens)
+ previous = ENV["ONCHAIN_MAX_TOKENS_PER_ADDRESS"]
+ ENV["ONCHAIN_MAX_TOKENS_PER_ADDRESS"] = tokens.to_s
+ yield
+ ensure
+ ENV["ONCHAIN_MAX_TOKENS_PER_ADDRESS"] = previous
+ end
+
+ def summary_url
+ "#{explorer_url}/api/v2/addresses/#{ADDRESS}"
+ end
+
+ def explorer_url
+ @adapter.explorer_url
+ end
+
+ def stub_summary(coin_balance:, flags: {})
+ stub_request(:get, summary_url).to_return(
+ status: 200,
+ body: { "coin_balance" => coin_balance }.merge(flags).to_json,
+ headers: { "Content-Type" => "application/json" }
+ )
+ end
+
+ # Blockscout returns this collection as a bare array rather than a paginated
+ # envelope, unlike the transfer endpoints below, and it rejects a `type`
+ # filter outright — hence the bare path.
+ def stub_token_balances(items)
+ stub_request(:get, "#{explorer_url}/api/v2/addresses/#{ADDRESS}/token-balances")
+ .to_return(status: 200, body: items.to_json, headers: { "Content-Type" => "application/json" })
+ end
+
+ def erc20(contract:, symbol:, value:, decimals: "6", name: nil, market_cap: nil, rate: nil)
+ {
+ "token" => {
+ "address_hash" => contract, "symbol" => symbol, "name" => name || symbol,
+ "decimals" => decimals, "type" => "ERC-20",
+ "circulating_market_cap" => market_cap, "exchange_rate" => rate
+ },
+ "value" => value
+ }
+ end
+
+ def stub_transactions(items)
+ stub_items("#{explorer_url}/api/v2/addresses/#{ADDRESS}/transactions", items)
+ end
+
+ def stub_token_transfers(items)
+ stub_items("#{explorer_url}/api/v2/addresses/#{ADDRESS}/token-transfers?type=ERC-20", items)
+ end
+
+ # One stub for both Etherscan actions; the query string differs only by action.
+ def stub_etherscan_history
+ stub_request(:get, "#{Provider::Etherscan::BASE_URL}/api")
+ .with(query: hash_including({ "module" => "account" }))
+ .to_return do |request|
+ action = CGI.parse(URI(request.uri).query)["action"].first
+ result = case action
+ when "txlist"
+ [ { "hash" => "0xkeyed", "from" => "0xother", "to" => ADDRESS.downcase, "value" => "1000000000000000000", "timeStamp" => Time.utc(2026, 1, 2).to_i.to_s } ]
+ when "tokentx"
+ [ {
+ "hash" => "0xkeyedtoken", "from" => "0xother", "to" => ADDRESS.downcase,
+ "contractAddress" => USDC, "tokenSymbol" => "USDC", "tokenDecimal" => "6",
+ "value" => "1000000", "timeStamp" => Time.utc(2026, 1, 3).to_i.to_s
+ } ]
+ else
+ []
+ end
+
+ { status: 200, body: { "status" => "1", "message" => "OK", "result" => result }.to_json, headers: { "Content-Type" => "application/json" } }
+ end
+ end
+
+ def token_transfer(hash:, log_index:, value:, contract: USDC)
+ {
+ "transaction_hash" => hash,
+ "log_index" => log_index,
+ "from" => { "hash" => "0xother" },
+ "to" => { "hash" => ADDRESS.downcase },
+ "timestamp" => "2026-01-05T00:00:00.000000Z",
+ "token" => { "address_hash" => contract, "symbol" => "USDC", "decimals" => "6", "type" => "ERC-20" },
+ "total" => { "value" => value, "decimals" => "6" }
+ }
+ end
+
+ def stub_items(url, items)
+ stub_request(:get, url).to_return(
+ status: 200,
+ body: { "items" => items, "next_page_params" => nil }.to_json,
+ headers: { "Content-Type" => "application/json" }
+ )
+ end
+end
diff --git a/test/models/onchain/history_budget_test.rb b/test/models/onchain/history_budget_test.rb
new file mode 100644
index 0000000000..2144cd6e6a
--- /dev/null
+++ b/test/models/onchain/history_budget_test.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::HistoryBudgetTest < ActiveSupport::TestCase
+ test "defaults to a depth a public endpoint can serve" do
+ assert_equal Onchain::HistoryBudget::DEFAULT_PAGES, Onchain::HistoryBudget.pages
+ assert_equal Onchain::HistoryBudget::DEFAULT_TRANSACTIONS, Onchain::HistoryBudget.transactions
+ end
+
+ # One transaction is one request on a per-transaction source, so this budget
+ # must stay an order of magnitude below the page budget's row count or a sync
+ # takes minutes instead of seconds.
+ test "the per-transaction budget is far smaller than the paginated row count" do
+ assert_operator Onchain::HistoryBudget.transactions, :<,
+ Onchain::HistoryBudget.pages * Onchain::HistoryBudget::PAGE_SIZE / 5
+ end
+
+ test "one knob scales both budgets" do
+ with_env("50") do
+ assert_equal 50, Onchain::HistoryBudget.pages
+ assert_equal 125, Onchain::HistoryBudget.transactions
+ end
+
+ with_env("1") do
+ assert_equal 1, Onchain::HistoryBudget.pages
+ assert_operator Onchain::HistoryBudget.transactions, :>=, 1
+ end
+ end
+
+ test "a self-hoster can raise it" do
+ with_env("50") { assert_equal 50, Onchain::HistoryBudget.pages }
+ end
+
+ test "nonsense values fall back or are clamped rather than disabling history" do
+ with_env("0") { assert_equal Onchain::HistoryBudget::DEFAULT_PAGES, Onchain::HistoryBudget.pages }
+ with_env("-5") { assert_equal Onchain::HistoryBudget::DEFAULT_PAGES, Onchain::HistoryBudget.pages }
+ with_env("nope") { assert_equal Onchain::HistoryBudget::DEFAULT_PAGES, Onchain::HistoryBudget.pages }
+ with_env("100000") { assert_equal Onchain::HistoryBudget::MAX_PAGES, Onchain::HistoryBudget.pages }
+ end
+
+ private
+ def with_env(value)
+ previous = ENV["ONCHAIN_HISTORY_MAX_PAGES"]
+ ENV["ONCHAIN_HISTORY_MAX_PAGES"] = value
+ yield
+ ensure
+ ENV["ONCHAIN_HISTORY_MAX_PAGES"] = previous
+ end
+end
diff --git a/test/models/onchain/pricing_test.rb b/test/models/onchain/pricing_test.rb
new file mode 100644
index 0000000000..22499b0a09
--- /dev/null
+++ b/test/models/onchain/pricing_test.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::PricingTest < ActiveSupport::TestCase
+ test "a USD family needs only the crypto provider" do
+ with_crypto_provider(enabled: true) do
+ assert Onchain::Pricing.ready_for?("USD")
+ assert_empty Onchain::Pricing.missing_for("USD")
+ end
+ end
+
+ test "a non-USD family also needs an exchange rate provider" do
+ with_crypto_provider(enabled: true) do
+ ExchangeRate.stubs(:provider).returns(nil)
+
+ assert_not Onchain::Pricing.ready_for?("EUR")
+ assert_equal [ :exchange_rate ], Onchain::Pricing.missing_for("EUR")
+ # USD needs no conversion, so the same install is fine for a USD family.
+ assert_empty Onchain::Pricing.missing_for("USD")
+ end
+ end
+
+ test "both gaps are reported together" do
+ with_crypto_provider(enabled: false) do
+ ExchangeRate.stubs(:provider).returns(nil)
+
+ assert_equal [ :crypto_provider, :exchange_rate ], Onchain::Pricing.missing_for("EUR")
+ end
+ end
+
+ test "a configured exchange rate provider closes the second gap" do
+ with_crypto_provider(enabled: true) do
+ ExchangeRate.stubs(:provider).returns(Provider::Frankfurter.new)
+
+ assert Onchain::Pricing.ready_for?("EUR")
+ end
+ end
+
+ test "an unusable exchange rate setting reads as not configured rather than raising" do
+ with_crypto_provider(enabled: true) do
+ ExchangeRate.stubs(:provider).raises(Provider::Registry::Error, "nope")
+
+ assert_not Onchain::Pricing.fx_configured?
+ assert_equal [ :exchange_rate ], Onchain::Pricing.missing_for("EUR")
+ end
+ end
+
+ private
+ def with_crypto_provider(enabled:)
+ providers = enabled ? [ Onchain::SecurityResolver::PRICE_PROVIDER ] : [ "twelve_data" ]
+ Setting.stubs(:enabled_securities_providers).returns(providers)
+ yield
+ end
+end
diff --git a/test/models/onchain/security_resolver_test.rb b/test/models/onchain/security_resolver_test.rb
new file mode 100644
index 0000000000..438ac2a426
--- /dev/null
+++ b/test/models/onchain/security_resolver_test.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::SecurityResolverTest < ActiveSupport::TestCase
+ test "binds a new security to the crypto price provider" do
+ security = Onchain::SecurityResolver.resolve(symbol: "sol", name: "Solana")
+
+ assert_equal "CRYPTO:SOL", security.ticker
+ assert_equal Onchain::SecurityResolver::PRICE_PROVIDER, security.price_provider
+ assert_equal Onchain::SecurityResolver::EXCHANGE_MIC, security.exchange_operating_mic
+ assert_equal "Solana", security.name
+ end
+
+ test "bridged and wrapped variants resolve to the canonical security" do
+ usdc = Onchain::SecurityResolver.resolve(symbol: "USDC")
+
+ [ "USDC.e", "USDbC", "axlUSDC" ].each do |variant|
+ assert_equal usdc, Onchain::SecurityResolver.resolve(symbol: variant), "#{variant} should resolve to USDC"
+ end
+
+ assert_equal "CRYPTO:USDT", Onchain::SecurityResolver.resolve(symbol: "USDT0").ticker
+ assert_equal "CRYPTO:ETH", Onchain::SecurityResolver.resolve(symbol: "WETH").ticker
+ end
+
+ test "reuses an existing security for the ticker whatever its MIC" do
+ existing = Security.create!(ticker: "CRYPTO:BTC", name: "Bitcoin", exchange_operating_mic: "XKRA")
+
+ assert_no_difference "Security.count" do
+ assert_equal existing, Onchain::SecurityResolver.resolve(symbol: "BTC")
+ end
+ end
+
+ test "an unresolvable symbol returns nil without raising" do
+ [ nil, "", " ", "Visit site to claim rewards", "🚀🚀", "https://spam.example", "A" * 30 ].each do |symbol|
+ assert_nil Onchain::SecurityResolver.resolve(symbol: symbol), "#{symbol.inspect} should not resolve"
+ assert_not Onchain::SecurityResolver.priceable?(symbol)
+ end
+ end
+
+ test "priceable? recognises a plausible ticker without creating a security" do
+ assert_no_difference "Security.count" do
+ assert Onchain::SecurityResolver.priceable?("wbtc")
+ end
+ end
+
+ test "a reused security with no price provider is bound to the crypto one" do
+ existing = Security.create!(ticker: "CRYPTO:BTC", name: "Bitcoin", price_provider: nil)
+
+ resolved = Onchain::SecurityResolver.resolve(symbol: "BTC")
+
+ assert_equal existing, resolved
+ # A blank provider falls back to whichever is enabled first, and only the
+ # crypto one quotes a bare coin symbol, so the holding would value at zero.
+ assert_equal Onchain::SecurityResolver::PRICE_PROVIDER, resolved.reload.price_provider
+ end
+
+ test "a price provider another integration chose is left alone" do
+ existing = Security.create!(ticker: "CRYPTO:BTC", name: "Bitcoin", price_provider: "yahoo_finance")
+
+ resolved = Onchain::SecurityResolver.resolve(symbol: "BTC")
+
+ assert_equal existing, resolved
+ # The CRYPTO: prefix is shared with the exchange integrations; stomping their
+ # choice would break their pricing to fix ours.
+ assert_equal "yahoo_finance", resolved.reload.price_provider
+ end
+end
diff --git a/test/models/onchain/snapshot_test.rb b/test/models/onchain/snapshot_test.rb
new file mode 100644
index 0000000000..b74606b07b
--- /dev/null
+++ b/test/models/onchain/snapshot_test.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::SnapshotTest < ActiveSupport::TestCase
+ include OnchainTestHelper
+
+ setup do
+ register_fake_chain!
+ end
+
+ teardown do
+ unregister_fake_chain!
+ end
+
+ test "movements_for matches tokens on contract regardless of case" do
+ token_asset = fake_token_asset(contract: "0xAAA")
+ matching = fake_movement(external_id: "a", symbol: "FUSD", contract: "0xaaa")
+ other = fake_movement(external_id: "b", symbol: "FUSD", contract: "0xbbb")
+ snapshot = Onchain::Snapshot.new(assets: [ token_asset ], movements: [ matching, other ])
+
+ assert_equal [ "a" ], snapshot.movements_for(token_asset).map(&:external_id)
+ end
+
+ test "movements_for matches native assets on symbol and ignores token movements" do
+ native = fake_native_asset
+ native_movement = fake_movement(external_id: "native", symbol: "FAKE")
+ token_movement = fake_movement(external_id: "token", symbol: "FAKE", contract: "0xaaa")
+ snapshot = Onchain::Snapshot.new(assets: [ native ], movements: [ native_movement, token_movement ])
+
+ assert_equal [ "native" ], snapshot.movements_for(native).map(&:external_id)
+ end
+
+ test "find_asset looks an asset up by kind and contract" do
+ native = fake_native_asset
+ token_asset = fake_token_asset(contract: "0xAAA")
+ snapshot = Onchain::Snapshot.new(assets: [ native, token_asset ], movements: [])
+
+ assert_equal native, snapshot.find_asset(kind: "native")
+ assert_equal token_asset, snapshot.find_asset(kind: OnchainTestHelper::FAKE_TOKEN_KIND, contract: "0xaaa")
+ assert_nil snapshot.find_asset(kind: OnchainTestHelper::FAKE_TOKEN_KIND, contract: "0xccc")
+ end
+
+ test "empty snapshot has no assets or movements" do
+ assert_empty Onchain::Snapshot.empty.assets
+ assert_empty Onchain::Snapshot.empty.movements
+ end
+end
diff --git a/test/models/onchain/solana_adapter_test.rb b/test/models/onchain/solana_adapter_test.rb
new file mode 100644
index 0000000000..0261efe77f
--- /dev/null
+++ b/test/models/onchain/solana_adapter_test.rb
@@ -0,0 +1,410 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::SolanaAdapterTest < ActiveSupport::TestCase
+ ADDRESS = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"
+ TOKEN_ACCOUNT = "4Qk1Ai1cWJKQZ4pQ9sTLC1z3TBcvxRuHF6vRzGBNRUR2"
+ USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
+ UNKNOWN_MINT = "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"
+
+ setup do
+ @adapter = Onchain::Chains.adapter_for(Onchain::Chains::SOLANA)
+ end
+
+ test "accepts a Base58 pubkey and rejects anything outside the character set" do
+ assert @adapter.valid_address?(ADDRESS)
+
+ [ "", "short", "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "#{ADDRESS[0..-2]}0" ].each do |address|
+ assert_not @adapter.valid_address?(address), "#{address.inspect} should be rejected"
+ end
+ end
+
+ test "fetch_snapshot refuses a malformed address before any request" do
+ assert_raises Onchain::Chains::Error do
+ @adapter.fetch_snapshot("nope")
+ end
+ end
+
+ test "activity is one request, and a node that rejects the key means not here" do
+ balance = stub_rpc("getBalance", { "value" => 2_000_000_000 })
+
+ assert @adapter.has_activity?(ADDRESS)
+ assert_requested balance, times: 1
+ end
+
+ test "an address the node rejects is not detected instead of raising" do
+ stub_request(:post, Provider::SolanaRpc.url)
+ .to_return(status: 200, body: { "error" => { "message" => "Invalid param: WrongSize" } }.to_json, headers: json_headers)
+
+ assert_not @adapter.has_activity?(ADDRESS)
+ end
+
+ test "a node that refuses history still yields the balances" do
+ stub_request(:post, Provider::SolanaRpc.url).to_return do |request|
+ method = JSON.parse(request.body)["method"]
+ # Balances answer; the history methods are throttled, as the free endpoint
+ # does in practice.
+ case method
+ when "getBalance"
+ { status: 200, body: { "result" => { "value" => 2_000_000_000 } }.to_json, headers: json_headers }
+ when "getTokenAccountsByOwner"
+ accounts = request.body.include?(Provider::SolanaRpc::TOKEN_PROGRAM_IDS.first) ?
+ [ token_account(mint: USDC_MINT, amount: "1000000", decimals: 6) ] : []
+ { status: 200, body: { "result" => { "value" => accounts } }.to_json, headers: json_headers }
+ else
+ { status: 429, body: "rate limited" }
+ end
+ end
+ stub_token_list([])
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ assert_equal BigDecimal("2"), snapshot.find_asset(kind: "native").quantity
+ assert_equal BigDecimal("1"), snapshot.find_asset(kind: "spl", contract: USDC_MINT).quantity
+ assert_empty snapshot.movements
+ # Reported as incomplete, not as a wallet that never moved.
+ assert snapshot.history_truncated?
+ end
+
+ test "a timed-out node is reported as unreachable, not as an unexpected failure" do
+ stub_request(:post, Provider::SolanaRpc.url).to_timeout
+
+ assert_raises Onchain::Chains::UnreachableError do
+ @adapter.fetch_snapshot(ADDRESS)
+ end
+ end
+
+ test "SPL balances come from the wallet's token accounts, summed per mint" do
+ stub_snapshot(
+ lamports: 1_500_000_000,
+ token_accounts: [
+ token_account(mint: USDC_MINT, amount: "2000000", decimals: 6),
+ token_account(mint: USDC_MINT, amount: "500000", decimals: 6, pubkey: "second"),
+ token_account(mint: UNKNOWN_MINT, amount: "0", decimals: 9)
+ ]
+ )
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ native = snapshot.find_asset(kind: "native")
+ assert_equal "SOL", native.symbol
+ assert_equal BigDecimal("1.5"), native.quantity
+
+ usdc = snapshot.find_asset(kind: "spl", contract: USDC_MINT)
+ assert_equal "USDC", usdc.symbol
+ assert_equal BigDecimal("2.5"), usdc.quantity
+
+ # An emptied token account is left behind on Solana by design.
+ assert_nil snapshot.find_asset(kind: "spl", contract: UNKNOWN_MINT)
+ end
+
+ test "a verified mint gets its real symbol from the token list" do
+ stub_snapshot(lamports: 0, token_accounts: [ token_account(mint: UNKNOWN_MINT, amount: "1500000", decimals: 6) ])
+ stub_token_list([ { "id" => UNKNOWN_MINT, "symbol" => "PYTH", "name" => "Pyth Network", "isVerified" => true } ])
+
+ asset = @adapter.fetch_snapshot(ADDRESS).find_asset(kind: "spl", contract: UNKNOWN_MINT)
+
+ assert_equal "PYTH", asset.symbol
+ assert_equal "Pyth Network", asset.name
+ assert_equal "CRYPTO:PYTH", Onchain::SecurityResolver.resolve(symbol: asset.symbol).ticker
+ end
+
+ test "only a mint the list vouches for is pre-tickable" do
+ stub_snapshot(lamports: 0, token_accounts: [
+ token_account(mint: USDC_MINT, amount: "1000000", decimals: 6),
+ token_account(mint: UNKNOWN_MINT, amount: "1000000", decimals: 6, pubkey: "other")
+ ])
+ stub_token_list([])
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ assert snapshot.find_asset(kind: "spl", contract: USDC_MINT).notable?
+ assert_not snapshot.find_asset(kind: "spl", contract: UNKNOWN_MINT).notable?
+ end
+
+ test "an unverified mint keeps a label that cannot be mistaken for a ticker" do
+ # A token calling itself USDC, which the list does not vouch for. Naming it
+ # would hand it the real dollar's price.
+ stub_snapshot(lamports: 0, token_accounts: [ token_account(mint: UNKNOWN_MINT, amount: "1000000000", decimals: 9) ])
+ stub_token_list([ { "id" => UNKNOWN_MINT, "symbol" => "USDC", "name" => "USD Coin", "isVerified" => false } ])
+
+ asset = @adapter.fetch_snapshot(ADDRESS).find_asset(kind: "spl", contract: UNKNOWN_MINT)
+
+ assert_no_match(/USDC/, asset.symbol)
+ assert_nil Onchain::SecurityResolver.resolve(symbol: asset.symbol)
+ end
+
+ test "a mint keeps its Base58 case, because case is part of the key" do
+ mixed = "So11111111111111111111111111111111111111112"
+ stub_snapshot(lamports: 0, token_accounts: [ token_account(mint: mixed, amount: "1000000", decimals: 6) ])
+ stub_token_list([])
+
+ asset = @adapter.fetch_snapshot(ADDRESS).assets.find { |a| !a.native? }
+
+ assert_equal mixed, asset.contract
+ assert_equal mixed, asset.contract_key
+ # A Solana address is not canonicalised either: every character is meaningful.
+ assert_equal ADDRESS, @adapter.canonical_address(" #{ADDRESS} ")
+ end
+
+ test "an unknown mint is labelled so it cannot be mistaken for a ticker" do
+ stub_snapshot(lamports: 0, token_accounts: [ token_account(mint: UNKNOWN_MINT, amount: "1000000000", decimals: 9) ])
+ stub_token_list([])
+
+ asset = @adapter.fetch_snapshot(ADDRESS).find_asset(kind: "spl", contract: UNKNOWN_MINT)
+
+ assert_equal UNKNOWN_MINT, asset.contract
+ assert_nil Onchain::SecurityResolver.resolve(symbol: asset.symbol)
+ end
+
+ test "an airdrop dump is capped, and the cap bounds the metadata lookups too" do
+ mints = Array.new(5) { |i| "#{UNKNOWN_MINT[0..-3]}#{i}#{i}" }
+ stub_snapshot(
+ lamports: 0,
+ token_accounts: mints.map { |mint| token_account(mint: mint, amount: "1000000", decimals: 6) }
+ )
+ list = stub_token_list([])
+
+ with_asset_budget(2) do
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ assert snapshot.assets_truncated?
+ # Native plus the two surfaced mints, and one metadata request rather than
+ # one per batch of the whole dump.
+ assert_equal 3, snapshot.assets.size
+ assert_requested list, times: 1
+ end
+ end
+
+ test "the cap keeps the same mints between two reads of an unchanged address" do
+ mints = %w[ccc aaa bbb].map { |suffix| "#{UNKNOWN_MINT[0..-4]}#{suffix}" }
+ stub_snapshot(
+ lamports: 0,
+ token_accounts: mints.map { |mint| token_account(mint: mint, amount: "1000000", decimals: 6) }
+ )
+ stub_token_list([])
+
+ with_asset_budget(2) do
+ first = @adapter.fetch_snapshot(ADDRESS).assets.map(&:contract)
+ second = Onchain::Chains.adapter_for(Onchain::Chains::SOLANA).fetch_snapshot(ADDRESS).assets.map(&:contract)
+
+ assert_equal first, second
+ end
+ end
+
+ test "a token list that is down leaves the wallet readable" do
+ stub_snapshot(lamports: 1_000_000_000, token_accounts: [ token_account(mint: UNKNOWN_MINT, amount: "1000000000", decimals: 9) ])
+ stub_request(:get, /lite-api\.jup\.ag/).to_return(status: 503)
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ assert_equal BigDecimal("1"), snapshot.find_asset(kind: "native").quantity
+ assert_equal 2, snapshot.assets.size
+ end
+
+ test "hard-coded mints resolve without asking the token list" do
+ stub_snapshot(lamports: 0, token_accounts: [ token_account(mint: USDC_MINT, amount: "1000000", decimals: 6) ])
+ list = stub_token_list([])
+
+ assert_equal "USDC", @adapter.fetch_snapshot(ADDRESS).find_asset(kind: "spl", contract: USDC_MINT).symbol
+ assert_not_requested list
+ end
+
+ test "movements and assets agree on a token's name" do
+ stub_snapshot(
+ lamports: 0,
+ token_accounts: [ token_account(mint: UNKNOWN_MINT, amount: "1000000", decimals: 6) ],
+ signatures: [ { "signature" => "sig1", "blockTime" => Time.utc(2026, 2, 3).to_i } ],
+ transaction: {
+ "blockTime" => Time.utc(2026, 2, 3).to_i,
+ "meta" => {
+ "err" => nil, "preBalances" => [ 0 ], "postBalances" => [ 0 ],
+ "preTokenBalances" => [],
+ "postTokenBalances" => [ { "owner" => ADDRESS, "mint" => UNKNOWN_MINT, "uiTokenAmount" => { "amount" => "1000000", "decimals" => 6 } } ]
+ },
+ "transaction" => { "message" => { "accountKeys" => [ { "pubkey" => ADDRESS } ] } }
+ }
+ )
+ stub_token_list([ { "id" => UNKNOWN_MINT, "symbol" => "PYTH", "name" => "Pyth Network", "isVerified" => true } ])
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ assert_equal "PYTH", snapshot.movements.sole.symbol
+ assert_equal [ "PYTH" ], snapshot.assets.select { |asset| asset.contract == UNKNOWN_MINT }.map(&:symbol)
+ end
+
+ test "the snapshot has the same shape as the other chains" do
+ stub_snapshot(lamports: 1_000_000_000, token_accounts: [])
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ assert_instance_of Onchain::Snapshot, snapshot
+ assert snapshot.assets.all? { |asset| asset.is_a?(Onchain::Asset) }
+ assert snapshot.movements.all? { |movement| movement.is_a?(Onchain::Movement) }
+ end
+
+ test "movements come from pre/post balances, with fee-only changes dropped" do
+ stub_snapshot(
+ lamports: 1_000_000_000,
+ token_accounts: [ token_account(mint: USDC_MINT, amount: "1000000", decimals: 6) ],
+ signatures: [ { "signature" => "sig1", "blockTime" => Time.utc(2026, 2, 3).to_i } ],
+ transaction: {
+ "blockTime" => Time.utc(2026, 2, 3).to_i,
+ "meta" => {
+ "err" => nil,
+ "preBalances" => [ 1_000_000_000 ],
+ "postBalances" => [ 2_000_000_000 ],
+ "preTokenBalances" => [ { "owner" => ADDRESS, "mint" => USDC_MINT, "uiTokenAmount" => { "amount" => "0", "decimals" => 6 } } ],
+ "postTokenBalances" => [ { "owner" => ADDRESS, "mint" => USDC_MINT, "uiTokenAmount" => { "amount" => "1000000", "decimals" => 6 } } ]
+ },
+ "transaction" => { "message" => { "accountKeys" => [ { "pubkey" => ADDRESS } ] } }
+ }
+ )
+
+ movements = @adapter.fetch_snapshot(ADDRESS).movements
+
+ native = movements.find { |movement| movement.contract.nil? }
+ assert_equal "sig1", native.external_id
+ assert_equal BigDecimal("1"), native.amount
+ assert_equal Date.new(2026, 2, 3), native.date
+
+ token_asset = movements.find { |movement| movement.contract == USDC_MINT }
+ assert_equal "sig1_#{USDC_MINT}", token_asset.external_id
+ assert_equal BigDecimal("1"), token_asset.amount
+ end
+
+ test "a failed transaction produces no movements" do
+ stub_snapshot(
+ lamports: 0,
+ token_accounts: [],
+ signatures: [ { "signature" => "sig1", "blockTime" => Time.utc(2026, 2, 3).to_i } ],
+ transaction: {
+ "meta" => { "err" => { "InstructionError" => [] }, "preBalances" => [ 0 ], "postBalances" => [ 5_000_000_000 ] },
+ "transaction" => { "message" => { "accountKeys" => [ { "pubkey" => ADDRESS } ] } }
+ }
+ )
+
+ assert_empty @adapter.fetch_snapshot(ADDRESS).movements
+ end
+
+ test "a fee-only balance change is not a transfer" do
+ stub_snapshot(
+ lamports: 0,
+ token_accounts: [],
+ signatures: [ { "signature" => "sig1", "blockTime" => Time.utc(2026, 2, 3).to_i } ],
+ transaction: {
+ "meta" => { "err" => nil, "preBalances" => [ 1_000_000_000 ], "postBalances" => [ 999_995_000 ] },
+ "transaction" => { "message" => { "accountKeys" => [ { "pubkey" => ADDRESS } ] } }
+ }
+ )
+
+ assert_empty @adapter.fetch_snapshot(ADDRESS).movements
+ end
+
+ test "a full page of signatures is incomplete history, not the whole of it" do
+ page = Array.new(Onchain::SolanaAdapter::SIGNATURES_PER_SOURCE) do |index|
+ { "signature" => "sig#{index}", "blockTime" => Time.utc(2026, 2, 3).to_i - index }
+ end
+ stub_snapshot(lamports: 1_000_000_000, token_accounts: [], signatures: page)
+ stub_token_list([])
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ # The page came back full and the adapter passes no cursor, so older
+ # signatures exist that were never asked for. Counting against the budget
+ # alone would call this a complete history.
+ assert snapshot.history_truncated?
+ end
+
+ test "a wallet holding SPL tokens but no SOL is still detected" do
+ stub_snapshot(
+ lamports: 0,
+ token_accounts: [ token_account(mint: USDC_MINT, amount: "1000000", decimals: 6) ]
+ )
+
+ # Each token account carries its own rent, so a wallet address emptied of SOL
+ # is not an emptied wallet.
+ assert @adapter.has_activity?(ADDRESS)
+ end
+
+ test "token accounts left behind empty are not activity" do
+ stub_snapshot(
+ lamports: 0,
+ token_accounts: [ token_account(mint: USDC_MINT, amount: "0", decimals: 6) ]
+ )
+
+ assert_not @adapter.has_activity?(ADDRESS)
+ end
+
+ test "detection asks once and does not retry a rate-limited node" do
+ probe = stub_request(:post, Provider::SolanaRpc.url).to_return(status: 429, body: "rate limited")
+
+ assert_not @adapter.has_activity?(ADDRESS)
+ # Detection runs on the request thread: retrying with backoff here is what
+ # turns one slow chain into a page that hangs.
+ assert_requested probe, times: 1
+ end
+
+ private
+ def with_asset_budget(tokens)
+ previous = ENV["ONCHAIN_MAX_TOKENS_PER_ADDRESS"]
+ ENV["ONCHAIN_MAX_TOKENS_PER_ADDRESS"] = tokens.to_s
+ yield
+ ensure
+ ENV["ONCHAIN_MAX_TOKENS_PER_ADDRESS"] = previous
+ end
+
+ def stub_token_list(tokens)
+ stub_request(:get, /lite-api\.jup\.ag/)
+ .to_return(status: 200, body: tokens.to_json, headers: json_headers)
+ end
+
+ def json_headers
+ { "Content-Type" => "application/json" }
+ end
+
+ def token_account(mint:, amount:, decimals:, pubkey: TOKEN_ACCOUNT)
+ {
+ "pubkey" => pubkey,
+ "account" => {
+ "data" => {
+ "parsed" => {
+ "info" => { "mint" => mint, "tokenAmount" => { "amount" => amount, "decimals" => decimals } }
+ }
+ }
+ }
+ }
+ end
+
+ # One stub per RPC method, dispatched on the JSON-RPC method name so a single
+ # endpoint can serve the whole snapshot.
+ def stub_snapshot(lamports:, token_accounts:, signatures: [], transaction: nil)
+ responses = {
+ "getBalance" => { "value" => lamports },
+ "getTokenAccountsByOwner" => { "value" => token_accounts },
+ "getSignaturesForAddress" => signatures,
+ "getTransaction" => transaction
+ }
+
+ stub_request(:post, Provider::SolanaRpc.url).to_return do |request|
+ payload = JSON.parse(request.body)
+ result = responses[payload["method"]]
+
+ # Both token programs are asked; only the original one holds these
+ # accounts, as it would on chain.
+ if payload["method"] == "getTokenAccountsByOwner" &&
+ payload.dig("params", 1, "programId") != Provider::SolanaRpc::TOKEN_PROGRAM_IDS.first
+ result = { "value" => [] }
+ end
+
+ { status: 200, body: { "jsonrpc" => "2.0", "id" => 1, "result" => result }.to_json, headers: json_headers }
+ end
+ end
+
+ def stub_rpc(method, result)
+ stub_request(:post, Provider::SolanaRpc.url)
+ .with(body: hash_including("method" => method))
+ .to_return(status: 200, body: { "result" => result }.to_json, headers: json_headers)
+ end
+end
diff --git a/test/models/onchain_wallet_account/processor_test.rb b/test/models/onchain_wallet_account/processor_test.rb
new file mode 100644
index 0000000000..6f730bcd15
--- /dev/null
+++ b/test/models/onchain_wallet_account/processor_test.rb
@@ -0,0 +1,384 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class OnchainWalletAccount::ProcessorTest < ActiveSupport::TestCase
+ include OnchainTestHelper
+
+ setup do
+ register_fake_chain!
+ @family = families(:dylan_family)
+ @item = create_onchain_wallet_item(family: @family)
+ @onchain_account = create_onchain_wallet_account(item: @item, asset: fake_native_asset(quantity: 2))
+ @account = link_onchain_wallet_account!(@onchain_account)
+ end
+
+ teardown do
+ unregister_fake_chain!
+ end
+
+ test "creates a holding and sets the account balance from the current price" do
+ price_asset_at(Date.current, 100)
+
+ assert_difference "@account.holdings.count", 1 do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ holding = @account.holdings.order(:created_at).last
+ assert_equal 2, holding.qty
+ assert_equal 200, holding.amount
+ assert_equal 200, @account.reload.balance
+ assert_equal 0, @account.cash_balance
+ assert_equal 200, @onchain_account.reload.current_balance
+ end
+
+ test "tracks quantity but values the asset at zero when no price is known" do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ holding = @account.holdings.order(:created_at).last
+ assert_equal 2, holding.qty
+ assert_equal 0, holding.amount
+ assert_equal 0, @account.reload.balance
+ end
+
+ test "records why an asset ended up valued at zero when crypto pricing is off" do
+ assert_difference "DebugLogEntry.count", 1 do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "onchain_wallet", entry.provider_key
+ assert_equal @family, entry.family
+ assert_equal "CRYPTO:FAKE", entry.metadata["ticker"]
+ end
+
+ test "a merely missing price is not reported as a configuration problem" do
+ Setting.stubs(:enabled_securities_providers).returns([ Onchain::SecurityResolver::PRICE_PROVIDER ])
+ Security.any_instance.stubs(:price_data_provider).returns(nil)
+
+ assert_no_difference "DebugLogEntry.count" do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+ end
+
+ test "a non-USD asset with no exchange rate provider says so instead of just showing zero" do
+ Setting.stubs(:enabled_securities_providers).returns([ Onchain::SecurityResolver::PRICE_PROVIDER ])
+ Security.any_instance.stubs(:price_data_provider).returns(nil)
+ ExchangeRate.stubs(:provider).returns(nil)
+ @onchain_account.update!(currency: "EUR")
+
+ assert_difference "DebugLogEntry.count", 1 do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal [ "exchange_rate" ], entry.metadata["reasons"]
+ assert_equal "EUR", entry.metadata["currency"]
+ assert_equal 0, @account.reload.balance
+ end
+
+ test "creates no holding when the symbol cannot be a ticker" do
+ @onchain_account.update_columns(symbol: "Visit site to claim rewards")
+
+ assert_no_difference "Holding.count" do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ assert_equal 0, @account.reload.balance
+ end
+
+ test "materializes an inbound movement as a Buy trade 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))
+
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ entry = @account.entries.find_by(external_id: "onchain_#{@onchain_account.id}_tx1")
+ assert_equal "Trade", entry.entryable_type
+ 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
+ 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
+ end
+
+ test "materializes an outbound movement as a Sell trade" do
+ date = 3.days.ago.to_date
+ price_asset_at(date, 50)
+ store_movements(fake_movement(external_id: "tx2", amount: "-1", timestamp: date))
+
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ 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
+ end
+
+ test "materializes a display-only excluded entry when that day's price is unknown" do
+ date = 3.days.ago.to_date
+ store_movements(fake_movement(external_id: "tx3", amount: "1.5", timestamp: date))
+
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ entry = @account.entries.find_by(external_id: "onchain_#{@onchain_account.id}_tx3")
+ assert_equal "Transaction", entry.entryable_type
+ assert_equal 0, entry.amount
+ assert entry.excluded
+ assert_equal "1.5", entry.entryable.extra.dig("onchain_wallet", "amount")
+ end
+
+ test "a movement priced on another date does not become a trade" do
+ date = 3.days.ago.to_date
+ price_asset_at(Date.current, 100)
+ store_movements(fake_movement(external_id: "tx4", amount: "1", timestamp: date))
+
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ entry = @account.entries.find_by(external_id: "onchain_#{@onchain_account.id}_tx4")
+ assert_equal "Transaction", entry.entryable_type
+ assert entry.excluded
+ end
+
+ test "processing twice does not duplicate holdings or entries" do
+ date = 3.days.ago.to_date
+ price_asset_at(date, 50)
+ price_asset_at(Date.current, 60)
+ store_movements(
+ fake_movement(external_id: "tx1", amount: "1", timestamp: date),
+ fake_movement(external_id: "tx2", amount: "1", timestamp: 2.days.ago.to_date)
+ )
+
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ assert_no_difference [ "Holding.count", "Entry.count" ] do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+ end
+
+ test "backfills missing prices in one batched provider call so cost basis reconstructs" do
+ date = 5.days.ago.to_date
+ store_movements(fake_movement(external_id: "tx1", amount: "1", timestamp: date))
+ Security.any_instance.stubs(:price_data_provider).returns(Provider::BinancePublic.new)
+ Security.any_instance.expects(:import_provider_prices).with(start_date: date, end_date: Date.current).once.returns([ 0, nil ])
+
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ test "does not backfill when every needed price is already known" do
+ date = 5.days.ago.to_date
+ price_asset_at(date, 50)
+ price_asset_at(Date.current, 60)
+ store_movements(fake_movement(external_id: "tx1", amount: "1", timestamp: date))
+ Security.any_instance.stubs(:price_data_provider).returns(Provider::BinancePublic.new)
+ Security.any_instance.expects(:import_provider_prices).never
+
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ test "does not reach for prices at all when no crypto price provider is enabled" do
+ store_movements(fake_movement(external_id: "tx1", amount: "1", timestamp: 5.days.ago.to_date))
+ Security.any_instance.expects(:import_provider_prices).never
+
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ assert_equal 0, @account.reload.balance
+ end
+
+ test "a failing price provider does not stop the holding from being written" do
+ store_movements(fake_movement(external_id: "tx1", amount: "1", timestamp: 5.days.ago.to_date))
+ Security.any_instance.stubs(:price_data_provider).returns(Provider::BinancePublic.new)
+ Security.any_instance.stubs(:import_provider_prices).raises(StandardError, "provider down")
+
+ assert_difference "Holding.count", 1 do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ assert_includes DebugLogEntry.pluck(:message).join(" "), "Could not backfill"
+ end
+
+ test "a movement priced only on a later sync does not collide with its display-only entry" do
+ date = 3.days.ago.to_date
+ store_movements(fake_movement(external_id: "tx1", amount: "1.5", timestamp: date))
+
+ # First sync: no price for that day, so the movement is display-only.
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ assert_equal "Transaction", onchain_entry("tx1").entryable_type
+
+ # Second sync, with the price now known and the wallet having moved. This
+ # used to raise, taking the whole item sync — and the repair pass that runs
+ # after it — down with it.
+ price_asset_at(date, 40)
+ @onchain_account.update!(quantity: 3)
+
+ assert_nothing_raised do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ entry = onchain_entry("tx1")
+ assert_equal "Trade", entry.entryable_type
+ assert_equal BigDecimal("1.5"), entry.entryable.qty
+ assert_equal(-60, entry.amount)
+ assert_equal 1, @account.entries.where(external_id: entry.external_id).count
+ end
+
+ test "a failed trade write does not lose the transfer it was replacing" do
+ date = 3.days.ago.to_date
+ store_movements(fake_movement(external_id: "tx1", amount: "1.5", timestamp: date))
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ price_asset_at(date, 40)
+
+ Account::ProviderImportAdapter.any_instance.stubs(:import_trade).raises(ActiveRecord::RecordInvalid.new(Entry.new))
+
+ assert_raises ActiveRecord::RecordInvalid do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ # The display-only entry is still there rather than having been dropped in
+ # favour of a trade that never landed.
+ assert_equal "Transaction", onchain_entry("tx1").entryable_type
+ end
+
+ test "a display-only movement becomes a trade once its price is known" do
+ date = 3.days.ago.to_date
+ store_movements(fake_movement(external_id: "tx1", amount: "1.5", timestamp: date))
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ entry = onchain_entry("tx1")
+ assert_equal "Transaction", entry.entryable_type
+
+ price_asset_at(date, 40)
+
+ assert_equal 1, OnchainWalletAccount::Processor.new(@onchain_account).repair_display_only_movements
+
+ upgraded = onchain_entry("tx1")
+ assert_equal "Trade", upgraded.entryable_type
+ assert_equal entry.external_id, upgraded.external_id
+ assert_equal BigDecimal("1.5"), upgraded.entryable.qty
+ assert_equal 40, upgraded.entryable.price
+ assert_equal(-60, upgraded.amount)
+ assert_not upgraded.excluded
+ end
+
+ test "the repair leaves a movement alone while its price is still unknown" do
+ store_movements(fake_movement(external_id: "tx1", amount: "1", timestamp: 3.days.ago.to_date))
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ assert_equal 0, OnchainWalletAccount::Processor.new(@onchain_account).repair_display_only_movements
+ 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
+ price_asset_at(Date.current, 100)
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+
+ assert_no_difference [ "Entry.count", "Holding.count" ] do
+ assert_equal 0, OnchainWalletAccount::Processor.new(@onchain_account).repair_display_only_movements
+ end
+ end
+
+ test "the repair does not touch another provider's excluded entries" do
+ foreign = @account.entries.create!(
+ date: 3.days.ago.to_date, amount: 0, currency: @account.currency, name: "Manual note",
+ excluded: true, external_id: "#{@onchain_account.id}_manual", source: "kraken",
+ entryable: Transaction.new
+ )
+
+ assert_equal 0, OnchainWalletAccount::Processor.new(@onchain_account).repair_display_only_movements
+ assert_equal "Transaction", foreign.reload.entryable_type
+ end
+
+ test "a malformed stored amount costs its movement, not the whole asset" do
+ date = 3.days.ago.to_date
+ price_asset_at(date, 50)
+ @onchain_account.update!(
+ raw_movements_payload: {
+ "movements" => [
+ { "external_id" => "junk", "symbol" => "FAKE", "contract" => nil, "amount" => "not-a-number", "date" => date.to_s },
+ { "external_id" => "good", "symbol" => "FAKE", "contract" => nil, "amount" => "2", "date" => date.to_s }
+ ]
+ }
+ )
+
+ assert_nothing_raised do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ assert_nil @account.entries.find_by(external_id: "onchain_#{@onchain_account.id}_junk")
+ assert_equal "Trade", onchain_entry("good").entryable_type
+ end
+
+ test "NaN and the infinities are rejected, not carried into a trade" do
+ date = 3.days.ago.to_date
+ price_asset_at(date, 50)
+ movements = [ "NaN", "Infinity", "-Infinity" ].each_with_index.map do |amount, index|
+ { "external_id" => "tx#{index}", "symbol" => "FAKE", "contract" => nil, "amount" => amount, "date" => date.to_s }
+ end
+ movements << { "external_id" => "good", "symbol" => "FAKE", "contract" => nil, "amount" => "2", "date" => date.to_s }
+ @onchain_account.update!(raw_movements_payload: { "movements" => movements })
+
+ assert_nothing_raised do
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ end
+
+ # BigDecimal parses all three and none of them is zero, so only an explicit
+ # finite check keeps them out.
+ 3.times { |index| assert_nil @account.entries.find_by(external_id: "onchain_#{@onchain_account.id}_tx#{index}") }
+ assert_equal "Trade", onchain_entry("good").entryable_type
+ end
+
+ test "the repair pass survives a malformed stored amount too" do
+ date = 3.days.ago.to_date
+ store_movements(fake_movement(external_id: "tx1", amount: "1", timestamp: date))
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ entry = onchain_entry("tx1")
+ entry.entryable.update!(extra: { "onchain_wallet" => { "amount" => "not-a-number", "date" => date.to_s } })
+ price_asset_at(date, 50)
+
+ assert_nothing_raised do
+ assert_equal 0, OnchainWalletAccount::Processor.new(@onchain_account).repair_display_only_movements
+ end
+ end
+
+ test "does nothing when the asset is not linked to an account" do
+ unlinked = create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xaaa"))
+
+ assert_nothing_raised do
+ OnchainWalletAccount::Processor.new(unlinked).process
+ end
+ end
+
+ private
+ def onchain_entry(movement_id)
+ @account.entries.find_by!(external_id: "onchain_#{@onchain_account.id}_#{movement_id}")
+ end
+
+ def security
+ @security ||= Onchain::SecurityResolver.resolve(symbol: @onchain_account.symbol, name: @onchain_account.name)
+ end
+
+ def price_asset_at(date, price)
+ Security::Price.create!(security: security, date: date, price: price, currency: "USD")
+ end
+
+ def store_movements(*movements)
+ @onchain_account.update!(
+ raw_movements_payload: {
+ "movements" => movements.map do |movement|
+ {
+ "external_id" => movement.external_id,
+ "symbol" => movement.symbol,
+ "contract" => movement.contract_key,
+ "amount" => movement.amount.to_s("F"),
+ "date" => movement.date.to_s
+ }
+ end
+ }
+ )
+ end
+end
diff --git a/test/models/onchain_wallet_account_test.rb b/test/models/onchain_wallet_account_test.rb
new file mode 100644
index 0000000000..bedb424eda
--- /dev/null
+++ b/test/models/onchain_wallet_account_test.rb
@@ -0,0 +1,171 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class OnchainWalletAccountTest < ActiveSupport::TestCase
+ include OnchainTestHelper
+
+ setup do
+ register_fake_chain!
+ @family = families(:dylan_family)
+ @item = create_onchain_wallet_item(family: @family)
+ end
+
+ teardown do
+ unregister_fake_chain!
+ end
+
+ test "the database rejects a second native row for the same address" do
+ create_onchain_wallet_account(item: @item)
+
+ duplicate = @item.onchain_wallet_accounts.new(
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ wallet_address: OnchainTestHelper::FAKE_ADDRESS,
+ asset_kind: "native",
+ symbol: "FAKE",
+ decimals: 8,
+ quantity: 3,
+ currency: "USD"
+ )
+
+ # save(validate: false) proves the guarantee comes from the partial unique
+ # index and not from the ActiveRecord validation above it.
+ assert_raises ActiveRecord::RecordNotUnique do
+ duplicate.save!(validate: false)
+ end
+ end
+
+ test "the database rejects a second token row for the same contract" do
+ create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xAAA"))
+
+ duplicate = @item.onchain_wallet_accounts.new(
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ wallet_address: OnchainTestHelper::FAKE_ADDRESS,
+ asset_kind: OnchainTestHelper::FAKE_TOKEN_KIND,
+ contract_address: "0xaaa",
+ symbol: "FUSD",
+ decimals: 6,
+ quantity: 1,
+ currency: "USD"
+ )
+
+ assert_raises ActiveRecord::RecordNotUnique do
+ duplicate.save!(validate: false)
+ end
+ end
+
+ test "the database rejects a token row with no contract address" do
+ orphan = @item.onchain_wallet_accounts.new(
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ wallet_address: OnchainTestHelper::FAKE_ADDRESS,
+ asset_kind: OnchainTestHelper::FAKE_TOKEN_KIND,
+ contract_address: nil,
+ symbol: "FUSD",
+ decimals: 6,
+ quantity: 1,
+ currency: "USD"
+ )
+
+ # A token is keyed on its contract, and NULLs are distinct to Postgres, so
+ # this row would slip past the partial unique index and duplicate freely.
+ # The model refuses it too; validate: false proves the table does.
+ assert_raises ActiveRecord::StatementInvalid do
+ orphan.save!(validate: false)
+ end
+ end
+
+ test "the database rejects an asset kind no index keys on" do
+ odd = @item.onchain_wallet_accounts.new(
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ wallet_address: OnchainTestHelper::FAKE_ADDRESS,
+ asset_kind: "trc20",
+ contract_address: "0xccc",
+ symbol: "FUSD",
+ decimals: 6,
+ quantity: 1,
+ currency: "USD"
+ )
+
+ # Each partial unique index names its kind, so a row carrying another one is
+ # keyed by nothing and would duplicate freely.
+ assert_raises ActiveRecord::StatementInvalid do
+ odd.save!(validate: false)
+ end
+ 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"))
+ create_onchain_wallet_account(item: @item, asset: fake_token_asset(symbol: "FDAI", contract: "0xbbb"))
+
+ assert_equal 3, @item.onchain_wallet_accounts.count
+ end
+
+ test "the same asset is tracked separately per address" do
+ create_onchain_wallet_account(item: @item)
+ other = create_onchain_wallet_account(item: @item, address: OnchainTestHelper::FAKE_ADDRESS_ALT)
+
+ assert other.persisted?
+ assert_equal 2, @item.onchain_wallet_accounts.count
+ end
+
+ test "requires a registered chain" do
+ account = @item.onchain_wallet_accounts.new(
+ chain: "nosuchchain",
+ wallet_address: OnchainTestHelper::FAKE_ADDRESS,
+ asset_kind: "native",
+ symbol: "FAKE",
+ currency: "USD",
+ quantity: 1
+ )
+
+ assert_not account.valid?
+ assert_includes account.errors.attribute_names, :chain
+ end
+
+ test "rejects an asset kind the chain does not support" do
+ account = @item.onchain_wallet_accounts.new(
+ chain: OnchainTestHelper::FAKE_CHAIN,
+ wallet_address: OnchainTestHelper::FAKE_ADDRESS,
+ asset_kind: "spl",
+ contract_address: "0xaaa",
+ symbol: "FUSD",
+ currency: "USD",
+ quantity: 1
+ )
+
+ assert_not account.valid?
+ assert_includes account.errors.attribute_names, :asset_kind
+ end
+
+ test "native rows must not carry a contract and token rows must" do
+ native_with_contract = @item.onchain_wallet_accounts.new(
+ chain: OnchainTestHelper::FAKE_CHAIN, wallet_address: OnchainTestHelper::FAKE_ADDRESS,
+ asset_kind: "native", contract_address: "0xaaa", symbol: "FAKE", currency: "USD", quantity: 1
+ )
+ token_without_contract = @item.onchain_wallet_accounts.new(
+ chain: OnchainTestHelper::FAKE_CHAIN, wallet_address: OnchainTestHelper::FAKE_ADDRESS,
+ asset_kind: OnchainTestHelper::FAKE_TOKEN_KIND, symbol: "FUSD", currency: "USD", quantity: 1
+ )
+
+ assert_not native_with_contract.valid?
+ assert_not token_without_contract.valid?
+ assert_includes native_with_contract.errors.attribute_names, :contract_address
+ assert_includes token_without_contract.errors.attribute_names, :contract_address
+ end
+
+ test "contract addresses are stored downcased so matching is case-insensitive" do
+ account = create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xAbCdEf"))
+
+ assert_equal "0xabcdef", account.contract_address
+ assert account.matches_asset?(fake_token_asset(contract: "0xABCDEF"))
+ assert_not account.matches_asset?(fake_native_asset)
+ end
+
+ test "ordered puts the native asset of each wallet first" do
+ token_asset = create_onchain_wallet_account(item: @item, asset: fake_token_asset(symbol: "AAA", contract: "0xaaa"))
+ native = create_onchain_wallet_account(item: @item)
+
+ assert_equal [ native.id, token_asset.id ], @item.onchain_wallet_accounts.ordered.map(&:id)
+ end
+end
diff --git a/test/models/onchain_wallet_item/chain_detector_test.rb b/test/models/onchain_wallet_item/chain_detector_test.rb
new file mode 100644
index 0000000000..d3ac6f6671
--- /dev/null
+++ b/test/models/onchain_wallet_item/chain_detector_test.rb
@@ -0,0 +1,79 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class OnchainWalletItem::ChainDetectorTest < ActiveSupport::TestCase
+ include OnchainTestHelper
+
+ ADDRESS = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
+
+ # Only #key is read off a candidate here, and only #has_activity? off its
+ # adapter, so the detector is exercised without standing up chains.
+ Candidate = Struct.new(:key)
+
+ Probe = Struct.new(:answer, :delay) do
+ def has_activity?(_address)
+ sleep(delay) if delay
+ answer
+ end
+ end
+
+ setup do
+ register_fake_chain!
+ @item = create_onchain_wallet_item(family: families(:dylan_family))
+ end
+
+ teardown do
+ unregister_fake_chain!
+ end
+
+ test "one chain answering yes settles it when every other chain answered no" do
+ result = detect("alpha" => true, "beta" => false)
+
+ assert result.resolved?
+ assert_equal "alpha", result.chain
+ assert_equal [ "alpha" ], result.detected_keys
+ end
+
+ test "a chain that could not answer sends the user to the chooser" do
+ result = detect("alpha" => true, "beta" => nil)
+
+ # The single yes is not enough: a source that timed out has not said the
+ # address is absent there, and settling on alpha would link the wrong
+ # network with no way back.
+ assert_not result.resolved?
+ assert result.ambiguous?
+ assert_equal [ "alpha" ], result.detected_keys
+ end
+
+ test "a probe that outlives the deadline counts as could not tell" do
+ Onchain::DetectionBudget.stubs(:deadline).returns(0.2)
+
+ result = detect({ "alpha" => true, "beta" => [ true, 5 ] })
+
+ assert result.ambiguous?, "a probe still running at the deadline must not be read as an answer"
+ assert_equal [ "alpha" ], result.detected_keys
+ end
+
+ test "candidates are probed concurrently rather than one after another" do
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
+ detect({ "alpha" => [ false, 0.3 ], "beta" => [ false, 0.3 ], "gamma" => [ false, 0.3 ] })
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
+
+ # In sequence this is 0.9s, and the form waits on it: a 0x address is a
+ # candidate on six chains.
+ assert_operator elapsed, :<, 0.6, "three 0.3s probes took #{elapsed.round(2)}s, so they ran in sequence"
+ end
+
+ private
+ def detect(answers)
+ pairs = answers.map do |key, answer|
+ value, delay = answer.is_a?(Array) ? answer : [ answer, nil ]
+ [ Candidate.new(key), Probe.new(value, delay) ]
+ end
+
+ @item.stubs(:matching_chain_adapters).returns(pairs)
+
+ OnchainWalletItem::ChainDetector.new(@item, ADDRESS).detect
+ end
+end
diff --git a/test/models/onchain_wallet_item/importer_test.rb b/test/models/onchain_wallet_item/importer_test.rb
new file mode 100644
index 0000000000..2f55f2ac3f
--- /dev/null
+++ b/test/models/onchain_wallet_item/importer_test.rb
@@ -0,0 +1,354 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class OnchainWalletItem::ImporterTest < ActiveSupport::TestCase
+ include OnchainTestHelper
+
+ setup do
+ register_fake_chain!
+ @family = families(:dylan_family)
+ @item = create_onchain_wallet_item(family: @family)
+ end
+
+ teardown do
+ unregister_fake_chain!
+ end
+
+ test "records the quantity and movements of each tracked asset" do
+ account = create_onchain_wallet_account(item: @item, asset: fake_native_asset(quantity: 0))
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(
+ assets: [ fake_native_asset(quantity: "2.5") ],
+ movements: [ fake_movement(external_id: "tx1", amount: "2.5") ]
+ )
+ )
+
+ result = OnchainWalletItem::Importer.new(@item).import
+
+ assert_equal [ account.id ], result[:changed_account_ids]
+ account.reload
+ assert_equal BigDecimal("2.5"), account.quantity
+ assert_equal "2.5", account.raw_payload["quantity"]
+ assert_equal [ "tx1" ], account.raw_movements_payload["movements"].map { |m| m["external_id"] }
+ assert account.content_hash.present?
+ end
+
+ test "does not create rows for assets the user never chose to track" do
+ create_onchain_wallet_account(item: @item)
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(
+ assets: [ fake_native_asset, fake_token_asset(symbol: "SPAM", contract: "0xspam") ],
+ movements: []
+ )
+ )
+
+ assert_no_difference "OnchainWalletAccount.count" do
+ OnchainWalletItem::Importer.new(@item).import
+ end
+ end
+
+ test "an asset the cap never reached keeps its balance instead of being zeroed" do
+ tracked = create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xaaa", quantity: 42))
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ # The token is not in the snapshot because the read stopped at the cap,
+ # not because the wallet stopped holding it.
+ Onchain::Snapshot.new(assets: [ fake_native_asset ], movements: [], assets_truncated: true)
+ )
+
+ OnchainWalletItem::Importer.new(@item).import
+
+ assert_equal 42, tracked.reload.quantity
+ assert tracked.assets_truncated?
+ end
+
+ test "an asset that disappeared from the wallet is set to zero" do
+ account = create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xaaa", quantity: 10))
+ stub_fake_snapshot(OnchainTestHelper::FAKE_ADDRESS, Onchain::Snapshot.new(assets: [ fake_native_asset ], movements: []))
+
+ OnchainWalletItem::Importer.new(@item).import
+
+ assert_equal 0, account.reload.quantity
+ end
+
+ test "a second import of an unchanged wallet writes nothing" do
+ account = create_onchain_wallet_account(item: @item)
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ fake_native_asset ], movements: [ fake_movement(external_id: "tx1") ])
+ )
+
+ OnchainWalletItem::Importer.new(@item).import
+ updated_at = account.reload.updated_at
+
+ result = OnchainWalletItem::Importer.new(@item).import
+
+ assert_empty result[:changed_account_ids]
+ assert_equal updated_at, account.reload.updated_at
+ end
+
+ test "a changed quantity is detected even when the movements are identical" do
+ account = create_onchain_wallet_account(item: @item)
+ movements = [ fake_movement(external_id: "tx1") ]
+ stub_fake_snapshot(OnchainTestHelper::FAKE_ADDRESS, Onchain::Snapshot.new(assets: [ fake_native_asset(quantity: 1) ], movements: movements))
+ OnchainWalletItem::Importer.new(@item).import
+
+ stub_fake_snapshot(OnchainTestHelper::FAKE_ADDRESS, Onchain::Snapshot.new(assets: [ fake_native_asset(quantity: 2) ], movements: movements))
+ result = OnchainWalletItem::Importer.new(@item).import
+
+ assert_equal [ account.id ], result[:changed_account_ids]
+ assert_equal 2, account.reload.quantity
+ end
+
+ test "reads each tracked address exactly once" do
+ create_onchain_wallet_account(item: @item)
+ create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xaaa"))
+ create_onchain_wallet_account(item: @item, address: OnchainTestHelper::FAKE_ADDRESS_ALT)
+
+ OnchainWalletItem::Importer.new(@item).import
+
+ assert_equal(
+ [ OnchainTestHelper::FAKE_ADDRESS, OnchainTestHelper::FAKE_ADDRESS_ALT ].sort,
+ OnchainTestHelper::FakeAdapter.snapshot_calls.sort
+ )
+ end
+
+ test "a truncated history is recorded on the row and reported once per address" do
+ account = create_onchain_wallet_account(item: @item)
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ fake_native_asset ], movements: [], history_truncated: true)
+ )
+
+ assert_difference "DebugLogEntry.count", 1 do
+ OnchainWalletItem::Importer.new(@item).import
+ end
+
+ assert account.reload.history_truncated?
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "onchain_wallet", entry.provider_key
+ assert_equal OnchainTestHelper::FAKE_ADDRESS, entry.metadata["address"]
+ end
+
+ test "one report per address even when several assets are tracked there" do
+ create_onchain_wallet_account(item: @item)
+ create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xaaa"))
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(
+ assets: [ fake_native_asset, fake_token_asset(contract: "0xaaa") ],
+ movements: [],
+ history_truncated: true
+ )
+ )
+
+ assert_difference "DebugLogEntry.count", 1 do
+ OnchainWalletItem::Importer.new(@item).import
+ end
+ end
+
+ test "an idle wallet with deep history is not reported again on every sync" do
+ create_onchain_wallet_account(item: @item)
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ fake_native_asset ], movements: [], history_truncated: true)
+ )
+ OnchainWalletItem::Importer.new(@item).import
+
+ assert_no_difference "DebugLogEntry.count" do
+ OnchainWalletItem::Importer.new(@item).import
+ end
+ end
+
+ test "a complete history clears the truncation flag" do
+ account = create_onchain_wallet_account(item: @item)
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ fake_native_asset(quantity: 1) ], movements: [], history_truncated: true)
+ )
+ OnchainWalletItem::Importer.new(@item).import
+ assert account.reload.history_truncated?
+
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ fake_native_asset(quantity: 2) ], movements: [], history_truncated: false)
+ )
+ OnchainWalletItem::Importer.new(@item).import
+
+ assert_not account.reload.history_truncated?
+ end
+
+ test "a capped token list is recorded on the row and named in the report" do
+ account = create_onchain_wallet_account(item: @item)
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ fake_native_asset ], movements: [], assets_truncated: true)
+ )
+
+ assert_difference "DebugLogEntry.count", 1 do
+ OnchainWalletItem::Importer.new(@item).import
+ end
+
+ assert account.reload.assets_truncated?
+ assert_not account.history_truncated?
+ entry = DebugLogEntry.order(:created_at).last
+ assert_match "not every token held is surfaced", entry.message
+ assert_equal Onchain::AssetBudget.tokens, entry.metadata["max_tokens"]
+ end
+
+ test "one unreachable address does not stop the others from importing" do
+ reachable = create_onchain_wallet_account(item: @item)
+ unreachable = create_onchain_wallet_account(item: @item, address: OnchainTestHelper::FAKE_ADDRESS_ALT)
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ fake_native_asset(quantity: 3) ], movements: [])
+ )
+ OnchainTestHelper::FakeAdapter.errors_by_address[OnchainTestHelper::FAKE_ADDRESS_ALT] =
+ Onchain::Chains::UnreachableError.new("explorer down")
+
+ result = nil
+ assert_difference "DebugLogEntry.count", 1 do
+ result = OnchainWalletItem::Importer.new(@item).import
+ end
+
+ assert_equal [ reachable.id ], result[:changed_account_ids]
+ assert_equal 1, result[:wallets_failed]
+ assert_equal 3, reachable.reload.quantity
+ # Untouched rather than zeroed: we did not learn that it holds nothing, we
+ # failed to look.
+ assert_equal BigDecimal("1.5"), unreachable.reload.quantity
+ assert_nil unreachable.content_hash
+ end
+
+ test "a wallet whose every address failed is a failed sync, not a quiet success" do
+ create_onchain_wallet_account(item: @item)
+ OnchainTestHelper::FakeAdapter.error = Onchain::Chains::UnreachableError.new("explorer down")
+
+ assert_raises Onchain::Chains::UnreachableError do
+ OnchainWalletItem::Importer.new(@item).import
+ end
+ end
+
+ test "a symbol that arrives later replaces the placeholder it was given" do
+ placeholder = fake_token_asset(symbol: "SPL:abcd…wxyz", contract: "0xaaa", quantity: 5, name: "SPL token")
+ account = create_onchain_wallet_account(item: @item, asset: placeholder)
+ stub_fake_snapshot(OnchainTestHelper::FAKE_ADDRESS, Onchain::Snapshot.new(assets: [ placeholder ], movements: []))
+ OnchainWalletItem::Importer.new(@item).import
+ assert_equal "SPL:abcd…wxyz", account.reload.symbol
+
+ # Same quantity, same movements, only the name is known now: the digest has to
+ # notice, or the placeholder is permanent.
+ named = fake_token_asset(symbol: "PYTH", contract: "0xaaa", quantity: 5, name: "Pyth Network")
+ stub_fake_snapshot(OnchainTestHelper::FAKE_ADDRESS, Onchain::Snapshot.new(assets: [ named ], movements: []))
+
+ result = OnchainWalletItem::Importer.new(@item).import
+
+ assert_equal [ account.id ], result[:changed_account_ids]
+ assert_equal "PYTH", account.reload.symbol
+ assert_equal "Pyth Network", account.name
+ end
+
+ test "a non-finite quantity is not written to the database" do
+ account = create_onchain_wallet_account(item: @item)
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(
+ assets: [ fake_chain.native_asset(quantity: BigDecimal("NaN")) ],
+ movements: []
+ )
+ )
+
+ OnchainWalletItem::Importer.new(@item).import
+
+ # Postgres numeric would have stored NaN, and every total reading it would
+ # have become NaN too.
+ assert_predicate account.reload.quantity, :finite?
+ assert_equal 0, account.quantity
+ end
+
+ test "a truncation flag that changes on its own still updates the row" do
+ account = create_onchain_wallet_account(item: @item)
+ asset = fake_native_asset(quantity: 2)
+ movements = [ fake_movement(external_id: "tx1") ]
+
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ asset ], movements: movements, history_truncated: true)
+ )
+ OnchainWalletItem::Importer.new(@item).import
+ assert account.reload.history_truncated?
+
+ # Same quantity, same movements: only the completeness of the read changed.
+ # Missed, the UI keeps claiming an incomplete history forever.
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ asset ], movements: movements, history_truncated: false)
+ )
+
+ result = OnchainWalletItem::Importer.new(@item).import
+
+ assert_equal [ account.id ], result[:changed_account_ids]
+ assert_not account.reload.history_truncated?
+ end
+
+ test "an asset cap that starts applying updates the row too" do
+ account = create_onchain_wallet_account(item: @item)
+ asset = fake_native_asset(quantity: 2)
+
+ stub_fake_snapshot(OnchainTestHelper::FAKE_ADDRESS, Onchain::Snapshot.new(assets: [ asset ], movements: []))
+ OnchainWalletItem::Importer.new(@item).import
+ assert_not account.reload.assets_truncated?
+
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ asset ], movements: [], assets_truncated: true)
+ )
+
+ assert_equal [ account.id ], OnchainWalletItem::Importer.new(@item).import[:changed_account_ids]
+ assert account.reload.assets_truncated?
+ end
+
+ test "the order a source lists movements in does not count as a change" do
+ account = create_onchain_wallet_account(item: @item)
+ first = fake_movement(external_id: "aaa", timestamp: 2.days.ago.to_date)
+ second = fake_movement(external_id: "bbb", timestamp: 2.days.ago.to_date)
+
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ fake_native_asset ], movements: [ first, second ])
+ )
+ OnchainWalletItem::Importer.new(@item).import
+ updated_at = account.reload.updated_at
+
+ # The same two movements, listed the other way round.
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: [ fake_native_asset ], movements: [ second, first ])
+ )
+
+ assert_empty OnchainWalletItem::Importer.new(@item).import[:changed_account_ids]
+ assert_equal updated_at, account.reload.updated_at
+ end
+
+ test "movements before the connection start date are ignored" do
+ account = create_onchain_wallet_account(item: @item)
+ @item.update!(sync_start_date: 2.days.ago.to_date)
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(
+ assets: [ fake_native_asset ],
+ movements: [
+ fake_movement(external_id: "old", timestamp: 10.days.ago.to_date),
+ fake_movement(external_id: "recent", timestamp: Date.current)
+ ]
+ )
+ )
+
+ OnchainWalletItem::Importer.new(@item).import
+
+ assert_equal [ "recent" ], account.reload.raw_movements_payload["movements"].map { |m| m["external_id"] }
+ end
+end
diff --git a/test/models/onchain_wallet_item/syncer_test.rb b/test/models/onchain_wallet_item/syncer_test.rb
new file mode 100644
index 0000000000..e699ac98a1
--- /dev/null
+++ b/test/models/onchain_wallet_item/syncer_test.rb
@@ -0,0 +1,107 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class OnchainWalletItem::SyncerTest < ActiveSupport::TestCase
+ include OnchainTestHelper
+
+ setup do
+ register_fake_chain!
+ @family = families(:dylan_family)
+ @item = create_onchain_wallet_item(family: @family)
+ @onchain_account = create_onchain_wallet_account(item: @item, asset: fake_native_asset(quantity: 0))
+ @account = link_onchain_wallet_account!(@onchain_account)
+ @sync = @item.syncs.create!
+ end
+
+ teardown do
+ unregister_fake_chain!
+ end
+
+ test "processes an asset whose on-chain state changed" do
+ stub_wallet(quantity: "2")
+
+ OnchainWalletAccount::Processor.any_instance.expects(:process).once
+
+ OnchainWalletItem::Syncer.new(@item).perform_sync(@sync)
+
+ assert_equal BigDecimal("2"), @onchain_account.reload.quantity
+ end
+
+ test "a second sync with no on-chain change writes nothing and processes nothing" do
+ stub_wallet(quantity: "2")
+ OnchainWalletItem::Syncer.new(@item).perform_sync(@sync)
+
+ account_updated_at = @onchain_account.reload.updated_at
+ holdings = Holding.count
+ entries = Entry.count
+ syncs = Sync.count
+
+ OnchainWalletAccount::Processor.any_instance.expects(:process).never
+
+ OnchainWalletItem::Syncer.new(@item).perform_sync(@item.syncs.create!)
+
+ assert_equal account_updated_at, @onchain_account.reload.updated_at
+ assert_equal holdings, Holding.count
+ assert_equal entries, Entry.count
+ # Only the sync record this test created itself; no account syncs queued.
+ assert_equal syncs + 1, Sync.count
+ end
+
+ test "does not process an asset that is not linked to an account" do
+ unlinked = create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xaaa"))
+ stub_wallet(quantity: "2", assets: [ fake_native_asset(quantity: "2"), fake_token_asset(contract: "0xaaa", quantity: 5) ])
+
+ OnchainWalletAccount::Processor.any_instance.expects(:process).once
+
+ OnchainWalletItem::Syncer.new(@item).perform_sync(@sync)
+
+ assert_equal 5, unlinked.reload.quantity
+ end
+
+ test "records a debug log entry and re-raises when a chain is unreachable" do
+ OnchainTestHelper::FakeAdapter.error = StandardError.new("chain unreachable")
+
+ assert_difference "DebugLogEntry.count", 1 do
+ assert_raises StandardError do
+ OnchainWalletItem::Syncer.new(@item).perform_sync(@sync)
+ end
+ end
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "onchain_wallet", entry.provider_key
+ assert_equal @family, entry.family
+ assert_equal "error", entry.level
+ end
+
+ test "post sync repairs movements for every linked asset, even unchanged ones" do
+ stub_wallet(quantity: "2")
+ date = 3.days.ago.to_date
+ @onchain_account.update!(
+ raw_movements_payload: {
+ "movements" => [ { "external_id" => "tx1", "symbol" => "FAKE", "contract" => nil, "amount" => "1", "date" => date.to_s } ]
+ }
+ )
+ OnchainWalletAccount::Processor.new(@onchain_account).process
+ entry = @account.entries.find_by!(external_id: "onchain_#{@onchain_account.id}_tx1")
+ assert_equal "Transaction", entry.entryable_type
+
+ security = Onchain::SecurityResolver.resolve(symbol: @onchain_account.symbol)
+ Security::Price.create!(security: security, date: date, price: 30, currency: "USD")
+
+ # The wallet itself has not moved, so the sync changes nothing on chain — the
+ # repair still has to run.
+ OnchainWalletItem::Syncer.new(@item).perform_sync(@sync)
+ OnchainWalletItem::Syncer.new(@item).perform_post_sync
+
+ assert_equal "Trade", @account.entries.find_by!(external_id: "onchain_#{@onchain_account.id}_tx1").entryable_type
+ end
+
+ private
+ def stub_wallet(quantity: "1", assets: nil)
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(assets: assets || [ fake_native_asset(quantity: quantity) ], movements: [])
+ )
+ end
+end
diff --git a/test/models/onchain_wallet_item_test.rb b/test/models/onchain_wallet_item_test.rb
new file mode 100644
index 0000000000..25830b401a
--- /dev/null
+++ b/test/models/onchain_wallet_item_test.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class OnchainWalletItemTest < ActiveSupport::TestCase
+ include OnchainTestHelper, ActiveJob::TestHelper
+
+ setup do
+ register_fake_chain!
+ @family = families(:dylan_family)
+ @item = create_onchain_wallet_item(family: @family)
+ end
+
+ teardown do
+ unregister_fake_chain!
+ end
+
+ test "is syncable without credentials because chains are readable keyless" do
+ assert @item.credentials_configured?
+ end
+
+ test "wallet_keys lists each tracked address once" do
+ create_onchain_wallet_account(item: @item)
+ create_onchain_wallet_account(item: @item, asset: fake_token_asset(contract: "0xaaa"))
+ create_onchain_wallet_account(item: @item, address: OnchainTestHelper::FAKE_ADDRESS_ALT)
+
+ assert_equal(
+ [
+ [ OnchainTestHelper::FAKE_CHAIN, OnchainTestHelper::FAKE_ADDRESS ],
+ [ OnchainTestHelper::FAKE_CHAIN, OnchainTestHelper::FAKE_ADDRESS_ALT ]
+ ],
+ @item.wallet_keys.sort
+ )
+ end
+
+ test "strips a blank explorer credential down to nil" do
+ @item.update!(etherscan_api_key: " ")
+ assert_nil @item.reload.etherscan_api_key
+
+ @item.update!(etherscan_api_key: " abc ")
+ assert_equal "abc", @item.reload.etherscan_api_key
+ end
+
+ test "passes the explorer credential to chain adapters" do
+ @item.update!(etherscan_api_key: "abc")
+
+ assert_equal "abc", @item.chain_adapter(OnchainTestHelper::FAKE_CHAIN).credentials[:etherscan_api_key]
+ end
+
+ test "matching_chain_adapters only returns chains that accept the address" do
+ matches = @item.matching_chain_adapters(OnchainTestHelper::FAKE_ADDRESS)
+
+ assert_equal [ OnchainTestHelper::FAKE_CHAIN ], matches.map { |definition, _adapter| definition.key }
+ assert_empty @item.matching_chain_adapters("nope")
+ end
+
+ test "destroy_later flags the item and enqueues destruction" do
+ assert_enqueued_with(job: DestroyJob) do
+ @item.destroy_later
+ end
+
+ assert @item.reload.scheduled_for_deletion
+ assert_not_includes OnchainWalletItem.active, @item
+ end
+
+ test "family only reports linked addresses it actually tracks" do
+ assert_not @family.onchain_address_linked?(OnchainTestHelper::FAKE_CHAIN, OnchainTestHelper::FAKE_ADDRESS)
+
+ create_onchain_wallet_account(item: @item)
+
+ assert @family.onchain_address_linked?(OnchainTestHelper::FAKE_CHAIN, OnchainTestHelper::FAKE_ADDRESS)
+ assert_not @family.onchain_address_linked?(OnchainTestHelper::FAKE_CHAIN, OnchainTestHelper::FAKE_ADDRESS_ALT)
+ end
+end
diff --git a/test/models/provider/jupiter_tokens_test.rb b/test/models/provider/jupiter_tokens_test.rb
new file mode 100644
index 0000000000..6305d1fd43
--- /dev/null
+++ b/test/models/provider/jupiter_tokens_test.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Provider::JupiterTokensTest < ActiveSupport::TestCase
+ USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
+ SPAM = "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"
+
+ test "returns verified tokens and drops everything else" do
+ stub_search([
+ { "id" => USDC, "symbol" => "USDC", "name" => "USD Coin", "isVerified" => true },
+ { "id" => SPAM, "symbol" => "USDC", "name" => "USD Coin", "isVerified" => false }
+ ])
+
+ metadata = Provider::JupiterTokens.new.metadata_for([ USDC, SPAM ])
+
+ assert_equal({ symbol: "USDC", name: "USD Coin" }, metadata[USDC])
+ assert_nil metadata[SPAM]
+ end
+
+ test "asks for every mint in one request" do
+ request = stub_search([])
+
+ Provider::JupiterTokens.new.metadata_for([ USDC, SPAM, USDC ])
+
+ assert_requested request, times: 1
+ assert_requested :get, /lite-api\.jup\.ag/, query: hash_including({ "query" => "#{USDC},#{SPAM}" })
+ end
+
+ test "makes no request when there is nothing to look up" do
+ assert_empty Provider::JupiterTokens.new.metadata_for([])
+ assert_empty Provider::JupiterTokens.new.metadata_for([ nil, "" ])
+ assert_not_requested :get, /lite-api\.jup\.ag/
+ end
+
+ test "a token with no symbol is not named" do
+ stub_search([ { "id" => SPAM, "symbol" => "", "name" => "Nameless", "isVerified" => true } ])
+
+ assert_empty Provider::JupiterTokens.new.metadata_for([ SPAM ])
+ end
+
+ test "raises its own error types so the adapter can degrade" do
+ stub_request(:get, /lite-api\.jup\.ag/).to_return(status: 429)
+ assert_raises Provider::JupiterTokens::RateLimitError do
+ Provider::JupiterTokens.new.metadata_for([ USDC ])
+ end
+
+ stub_request(:get, /lite-api\.jup\.ag/).to_return(status: 500)
+ assert_raises Provider::JupiterTokens::ApiError do
+ Provider::JupiterTokens.new.metadata_for([ USDC ])
+ end
+ end
+
+ test "a timeout becomes its own error type so the adapter degrades" do
+ stub_request(:get, /lite-api\.jup\.ag/).to_timeout
+
+ assert_raises Provider::JupiterTokens::ApiError do
+ Provider::JupiterTokens.new.metadata_for([ USDC ])
+ end
+ end
+
+ private
+ def stub_search(tokens)
+ stub_request(:get, /lite-api\.jup\.ag/)
+ .to_return(status: 200, body: tokens.to_json, headers: { "Content-Type" => "application/json" })
+ end
+end
diff --git a/test/support/onchain_test_helper.rb b/test/support/onchain_test_helper.rb
new file mode 100644
index 0000000000..527b0aa0a2
--- /dev/null
+++ b/test/support/onchain_test_helper.rb
@@ -0,0 +1,160 @@
+# frozen_string_literal: true
+
+# A chain that does not exist, so the chain-agnostic half of the on-chain wallet
+# feature (registry, importer, processor, syncer, controller) can be tested
+# without any real network behaviour leaking in. Real chains get their own test
+# files so a failure names a chain.
+module OnchainTestHelper
+ FAKE_CHAIN = "fakechain"
+ FAKE_TOKEN_KIND = "erc20"
+ FAKE_ADDRESS = "fake1qqqqqqqqqqqqqqqqqqqq"
+ FAKE_ADDRESS_ALT = "fake1zzzzzzzzzzzzzzzzzzzz"
+
+ # Returns whatever snapshot the test told it to return, and records every call
+ # so tests can assert on request counts.
+ class FakeAdapter
+ include Onchain::ChainAdapter
+
+ ADDRESS_PATTERN = /\Afake1[a-z0-9]{4,}\z/
+
+ class << self
+ attr_accessor :snapshots, :activity, :error, :provider_error_classes, :errors_by_address
+ attr_reader :snapshot_calls, :activity_calls
+
+ def reset!
+ @snapshots = {}
+ @activity = {}
+ @error = nil
+ @errors_by_address = {}
+ @provider_error_classes = []
+ @snapshot_calls = []
+ @activity_calls = []
+ end
+
+ def record_snapshot_call(address)
+ @snapshot_calls << address
+ end
+
+ def record_activity_call(address)
+ @activity_calls << address
+ end
+ end
+
+ reset!
+
+ attr_reader :credentials
+
+ def initialize(credentials: {})
+ @credentials = credentials
+ end
+
+ def valid_address?(address)
+ address.to_s.match?(ADDRESS_PATTERN)
+ end
+
+ def fetch_snapshot(address)
+ wrap_provider_errors do
+ self.class.record_snapshot_call(address)
+ raise self.class.error if self.class.error
+
+ per_address = self.class.errors_by_address[address]
+ raise per_address if per_address
+
+ self.class.snapshots.fetch(address, Onchain::Snapshot.empty)
+ end
+ end
+
+ def has_activity?(address)
+ self.class.record_activity_call(address)
+ self.class.activity.fetch(address, super)
+ end
+
+ # Lets a test stand in for a real data source's error family, so the
+ # translation into chain-agnostic errors is exercised.
+ def provider_error_classes
+ self.class.provider_error_classes
+ end
+ end
+
+ def register_fake_chain!(token_kind: FAKE_TOKEN_KIND)
+ FakeAdapter.reset!
+
+ Onchain::Chains.register(
+ Onchain::Chains::Definition.new(
+ key: FAKE_CHAIN,
+ native: Onchain::Chains::NativeAsset.new(symbol: "FAKE", name: "Fake Coin", decimals: 8),
+ token_kind: token_kind,
+ adapter_class_name: "OnchainTestHelper::FakeAdapter",
+ adapter_options: {}
+ )
+ )
+ end
+
+ def unregister_fake_chain!
+ Onchain::Chains.unregister(FAKE_CHAIN)
+ FakeAdapter.reset!
+ end
+
+ def fake_chain
+ Onchain::Chains.find!(FAKE_CHAIN)
+ end
+
+ def stub_fake_snapshot(address, snapshot)
+ FakeAdapter.snapshots[address] = snapshot
+ end
+
+ def fake_native_asset(quantity: 1.5)
+ fake_chain.native_asset(quantity: BigDecimal(quantity.to_s))
+ end
+
+ # notable: whether the data source treats the token as a real asset, which is
+ # what the review screen pre-ticks on. Defaults to a real asset; pass false for
+ # an airdrop.
+ def fake_token_asset(symbol: "FUSD", contract: "0xabc", quantity: 100, decimals: 6, name: nil, notable: true)
+ fake_chain.token_asset(
+ symbol: symbol,
+ name: name || symbol,
+ decimals: decimals,
+ quantity: BigDecimal(quantity.to_s),
+ contract: contract,
+ notable: notable
+ )
+ end
+
+ def fake_movement(external_id:, symbol: "FAKE", contract: nil, amount: 1, timestamp: nil)
+ Onchain::Movement.new(
+ external_id: external_id,
+ symbol: symbol,
+ contract: contract,
+ amount: BigDecimal(amount.to_s),
+ timestamp: timestamp || 3.days.ago.to_date
+ )
+ end
+
+ def create_onchain_wallet_item(family:, **attrs)
+ OnchainWalletItem.create!({ family: family, name: "Wallets" }.merge(attrs))
+ end
+
+ # Links a tracked asset to a real Sure account, the way the linking flow does.
+ def link_onchain_wallet_account!(onchain_wallet_account)
+ account = Account.create_from_onchain_wallet_account(onchain_wallet_account)
+ onchain_wallet_account.ensure_account_provider!(account)
+ onchain_wallet_account.reload
+ account
+ end
+
+ def create_onchain_wallet_account(item:, asset: nil, chain: FAKE_CHAIN, address: FAKE_ADDRESS, **attrs)
+ asset ||= fake_native_asset
+ item.onchain_wallet_accounts.create!({
+ chain: chain,
+ wallet_address: address,
+ asset_kind: asset.kind,
+ contract_address: asset.contract,
+ symbol: asset.symbol,
+ name: asset.name,
+ decimals: asset.decimals,
+ quantity: asset.quantity,
+ currency: item.family.currency
+ }.merge(attrs))
+ end
+end
diff --git a/test/system/onchain_wallets_test.rb b/test/system/onchain_wallets_test.rb
new file mode 100644
index 0000000000..5afc2f387b
--- /dev/null
+++ b/test/system/onchain_wallets_test.rb
@@ -0,0 +1,108 @@
+# frozen_string_literal: true
+
+require "application_system_test_case"
+
+# The linking flow spans three Turbo frame navigations stacked on top of each
+# other (provider drawer → linking modal → token_asset review), which no controller
+# test exercises. This walks it in a real browser once; the branching cases stay
+# in the controller test.
+class OnchainWalletsTest < ApplicationSystemTestCase
+ include OnchainTestHelper
+
+ setup do
+ register_fake_chain!
+ stub_fake_snapshot(
+ OnchainTestHelper::FAKE_ADDRESS,
+ Onchain::Snapshot.new(
+ assets: [
+ fake_native_asset(quantity: 2),
+ fake_token_asset(symbol: "USDC", contract: "0xusdc", quantity: 250),
+ fake_token_asset(symbol: "Visit site to claim", contract: "0xspam", quantity: 1)
+ ],
+ movements: []
+ )
+ )
+ sign_in users(:family_admin)
+ end
+
+ teardown do
+ unregister_fake_chain!
+ end
+
+ # The panel is reached two different ways depending on whether anything is
+ # linked yet: as a card in "Available" opening the drawer, or as a disclosure
+ # row under "Your connections" with the panel rendered inline.
+ def open_onchain_panel
+ if page.has_selector?("summary", text: "On-chain wallets", wait: 2)
+ find("summary", text: "On-chain wallets").click
+ else
+ click_on "On-chain wallets"
+ end
+ end
+
+ test "linking a wallet from the settings panel creates an account per ticked asset" do
+ visit settings_providers_path
+ 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")
+
+ click_on I18n.t("settings.providers.onchain_wallet_panel.add_wallet")
+
+ # 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")
+
+ fill_in I18n.t("onchain_wallet_items.new_wallet.address_label"), with: OnchainTestHelper::FAKE_ADDRESS
+ click_on I18n.t("onchain_wallet_items.new_wallet.continue")
+
+ # Token review, in the same modal frame.
+ assert_text I18n.t("onchain_wallet_items.token_review.title")
+ assert_text "USDC"
+ assert_text I18n.t("onchain_wallet_items.token_review_form.no_price")
+
+ # Priceable assets arrive ticked, the unpriceable one does not.
+ assert find("input[value='native']").checked?
+ assert find("input[value='erc20:0xusdc']").checked?
+ assert_not find("input[value='erc20:0xspam']").checked?
+
+ assert_difference -> { Account.count }, 2 do
+ click_on I18n.t("onchain_wallet_items.token_review.import_selected")
+ assert_text I18n.t("onchain_wallet_items.link_wallet.success", count: 2)
+ end
+
+ assert_equal %w[FAKE USDC], OnchainWalletAccount.order(:symbol).pluck(:symbol)
+ end
+
+ test "managing a wallet reviews its tokens and disconnects one asset" do
+ item = create_onchain_wallet_item(family: families(:dylan_family))
+ native = create_onchain_wallet_account(item: item)
+ native_account = link_onchain_wallet_account!(native)
+ token_asset = create_onchain_wallet_account(item: item, asset: fake_token_asset(symbol: "USDC", contract: "0xusdc"))
+ token_account = link_onchain_wallet_account!(token_asset)
+
+ visit settings_providers_path
+ open_onchain_panel
+ click_on I18n.t("settings.providers.onchain_wallet_panel.manage_wallets")
+
+ assert_text I18n.t("onchain_wallet_items.manage.title")
+ assert_text OnchainTestHelper::FAKE_ADDRESS
+
+ # Review tokens reopens the selection with the address untouched.
+ 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']"
+
+ uncheck "asset_erc20-0xusdc"
+ click_on I18n.t("onchain_wallet_items.review_tokens.save")
+
+ assert_text I18n.t("onchain_wallet_items.manage.title")
+ assert_not OnchainWalletAccount.exists?(token_asset.id)
+ assert OnchainWalletAccount.exists?(native.id)
+ # Disconnecting keeps the account behind, it only stops updating.
+ assert Account.exists?(token_account.id)
+ assert Account.exists?(native_account.id)
+ assert_not AccountProvider.exists?(provider_type: "OnchainWalletAccount", provider_id: token_asset.id)
+ end
+end