mirror of
https://github.com/we-promise/sure.git
synced 2026-09-02 05:11:05 +00:00
* feat(onchain-wallets): foundation for self-custody wallet tracking
Adds the schema, models and the normalised contract every chain will
produce, with no chain implemented yet.
The central constraint of a multi-chain integration is that `case chain`
must not spread through the importer, processor, controller and views.
So a chain adapter's only job is to turn an address into an
Onchain::Snapshot — a list of Onchain::Assets and Onchain::Movements —
and Onchain::Chains is the single source of truth for which chains exist,
how their addresses are validated, what their native asset is, and which
adapter to instantiate. Everything downstream is written once.
Two tables:
- onchain_wallet_items: the family-level connection. Keyless by
default; the only credential is an optional Etherscan key, encrypted
via `encrypts`.
- onchain_wallet_accounts: one row per asset, per address, per chain.
Uniqueness uses three partial unique indexes, one per asset kind, because
the identity of an asset depends on its 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 a NULL
contract_address as distinct and let duplicates through — the model test
proves the rejection comes from the database by saving with
`validate: false`.
The schema also leaves room for extended-key (xpub) wallets later: an HD
wallet is a set of derived addresses under one item, which the current
uniqueness key already allows, so adding it needs no destructive change.
db/schema.rb is hand-edited to add only the two new tables: regenerating
it with the Rails version now in the Gemfile reorders every column in the
file, which is out of scope for this change.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): chain-agnostic importer, processor and syncer
The whole pipeline is written once here and never branches on chain: it
consumes Onchain::Snapshots, so a chain is only ever a registry key and an
adapter.
Importer: refreshes every tracked address and records a digest of what it
saw (quantity plus movements, no timestamps) on each row. 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. An asset that
disappears from a wallet goes to zero rather than going stale.
Syncer: reprocesses only the rows whose digest changed. Two consecutive
syncs of an idle wallet write nothing at all — no row updates, no
holdings, no entries, and no queued account syncs. Both the importer and
syncer tests for that were checked against the pre-fix behaviour: with the
content_hash guard removed they fail.
Processor: writes the holding, the account balance and the movements.
Movements materialise two ways. When that day's price is known, a signed
trade (positive = Buy, negative = Sell) so cost basis and the value chart
reconstruct back to acquisition. Otherwise a display-only entry with
amount 0 and excluded: true, raw movement preserved in `extra` — visible,
but not inventing a value that would distort the account's history. Prices
are matched on the exact day for trades, because valuing a two-year-old
transfer at today's price would fabricate a cost basis.
Onchain::SecurityResolver binds a "CRYPTO:<SYMBOL>" ticker straight to the
crypto price provider instead of going through provider search, where
"USDC" can come back as a EUR-quoted pair and then need FX to repair. It
reuses an existing Security for the ticker whatever its MIC, so one asset
never splits into two records. Symbol normalisation for bridged
stablecoins and the price backfill follow in the next commit.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): canonical asset symbols and price backfill
Two things stood between a linked wallet and a correct valuation.
Bridged and wrapped variants. The same dollar is 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, so one
gets priced and the others sit at zero, and the same asset held on two
chains reports two different values. Onchain::AssetSymbol maps the
variants that are redeemable 1:1 onto the canonical asset, so pricing them
as that asset is exact rather than approximate.
Missing price history. A Security created at link time has none, so on the
first sync every movement would fall back to a display-only entry and the
cost basis would never reconstruct — the feature would look broken exactly
when the user first looks at it. The processor now backfills the window in
one batched provider call rather than one call per movement date, includes
today so a wallet whose movements all predate the sync window still gets a
current valuation, and treats a provider failure as a logged warning: the
holding and the quantity are still written.
All of it is a no-op when no crypto price provider is enabled, which is
the case the settings panel has to warn about before linking.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): Bitcoin adapter
Bitcoin has no account balances: an address owns unspent outputs, so the
balance is everything ever paid to it minus everything spent from it, and
mempool totals count — a broadcast-but-unconfirmed spend has already left
the wallet as far as its owner is concerned. Movements are the net effect
of each transaction on the address, so a self-transfer nets to zero and
produces no entry.
All three address formats are accepted (Base58 P2PKH/P2SH, bech32
segwit, bech32m taproot) with the character-set exclusions each encoding
actually has, and a malformed address is rejected before any request is
made — the test relies on WebMock failing the run if a request escapes.
Single address, not extended keys. A Bitcoin wallet is normally an HD
wallet: one xpub derives thousands of addresses and change goes to derived
ones, so tracking a single address under-reports such a wallet. Extended
keys would need BIP32 derivation (a dependency this codebase does not
want) or a descriptor-indexing backend. The limitation is stated in the
adapter, will be stated in the linking UI, and an xpub is rejected as an
address rather than silently treated as one.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): EVM adapter for six networks, two backends
One adapter class serves every EVM network: a network's identity — label,
native coin, explorer URL, whether a family-supplied Etherscan key applies
— is data in the chain registry, so adding a network is an entry there
rather than a branch here.
The unit tracked is the (chain, address) couple, carried by the unique
index. A 0x address is valid on all six networks and holds different
balances on each, so detection asks each candidate network whether the
address is worth tracking there. That probe is exactly one request and
never reads paginated history: Blockscout's address summary carries the
coin balance and the token/transfer flags together, which is also why a
wallet holding only ERC-20 tokens with zero native balance is still found.
An explorer being down means "not detected here", not an error the user has
to interpret — a dead indexer must not break linking.
Two interchangeable backends behind Provider::EvmExplorer: keyless
Blockscout by default for every network, and Etherscan when the family
configured a key on a network the registry enables it for (today Ethereum
only), where a key buys nothing but a higher rate limit. Etherscan
deliberately does not implement the activity probe: its one-request answer
is the native balance, which reports "nothing here" for a token-only
wallet, so detection stays on the indexer that can answer correctly.
Zero-balance token rows are dropped — real wallets are full of spam dust —
while the native asset is always reported, even at zero, because a wallet
that spent everything still has a history worth keeping.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): Solana adapter
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 across both token programs rather
than from reading the wallet address — and because one wallet can own
several accounts for the same mint, they are summed into one position.
Emptied token accounts are left behind on chain by design and are dropped.
RPC gives mints, not metadata. Well-known mints get their real symbol;
anything else is labelled with its mint in a form that deliberately cannot
pass for a ticker, so security resolution declines it and the asset is
tracked by quantity rather than priced as some unrelated coin that happens
to share a name.
Activity is one request. Bitcoin's Base58 addresses fall inside Solana's
address shape, so the two are told apart by asking the node: it rejects a
non-32-byte key, which reads as "not here" rather than an error.
The Snapshot it returns has the same shape as Bitcoin's and the EVM
adapter's — asserted in the test — so nothing downstream changed.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): settings panel and linking flow
Linking is three steps: paste an address, confirm which network, choose
what to track.
The network step exists because address formats are not unique to a chain.
Candidates come from the address shape, and when there is more than one each
is asked whether the address is worth tracking there — one bounded request
each. When several answer yes, or none does, the user picks from a list that
marks which ones showed activity. Silently keeping the first match would
link the wrong network and surface later as a sync bug.
The token step imports nothing that was not ticked. Assets whose symbol a
price provider can quote are pre-checked; spam airdrops, whose "symbol" is
usually an advertisement, are listed unticked and can still be tracked by
quantity. Quantities and metadata are re-read from the chain when the
selection is applied, so a tampered selection can only change which assets
are tracked, never what they claim to hold. Previewing an address creates
no connection record, so an abandoned flow leaves nothing behind.
The panel and both modal steps carry a price-provider warning: with no
crypto market data enabled every wallet is valued at zero, which users
report as a broken sync rather than a missing setting, so it is said before
linking and links to where to fix it. The Bitcoin single-address limit and
"never enter a seed phrase" are stated in the linking UI too.
Errors are separated by kind. A rate limit or an unreachable explorer gets
its own localized message. Anything else is a bug: the user sees a generic
message and the class and message go to DebugLogEntry, never into the
response — asserted in the tests, which also check the exception text does
not appear in the body.
Adapters now translate their data source's errors into Onchain::Chains
errors, so the controller rescues two chain-agnostic types instead of
carrying a list of every explorer's error classes — which would have put
per-chain knowledge back into the controller.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): manage, review tokens, change address, disconnect
Four actions, because two would make the token choice irrevocable.
Review tokens reopens the selection screen with the address left alone —
deliberately without an address field. Without it the only way to untick a
token would be to change the address, which is a different operation
entirely. Assets the chain no longer reports stay listed and ticked, so
they can be dropped once they are gone.
Disconnect one asset is a per-row action with a button next to every asset.
A destroy route no view calls is dead code: the feature does not exist
until it has a button, so the test asserts one form per asset rather than
one per wallet.
Change address updates the existing rows instead of recreating them, so the
accounts, holdings, entries and balance history all survive — verified by
asserting a pre-existing balance is still there afterwards, and checked
against the recreate-instead-of-update behaviour, which fails it. The
content digest is cleared so the next sync reprocesses even if the new
address happens to hold the same amount, and an account still carrying its
generated name is renamed to match.
Disconnect wallet drops every asset at one address and leaves other
addresses alone.
Disconnecting never destroys an account: the provider link goes, holdings
are detached, and what the user can see stays as a manual account that
stops updating — the same contract every other provider's unlink has here.
The duplicate-address guard covers initial linking as well as address
changes. Without it, re-linking an already-tracked address would become the
unofficial way to add a token, quietly creating a second set of rows for
the same wallet; both guards are checked against that pre-fix behaviour.
Every lookup and mutation is scoped through Current.family, including the
per-row disconnect, which cannot reach a row belonging to another
connection.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* docs(onchain-wallets): hosting guide for self-custody wallet tracking
docs/hosting/onchain-wallets.md covers what the feature reads, which
endpoint serves each network and how to point it at your own instance, the
optional Etherscan key and why it is optional, the per-sync request cost and
where history is capped, and the management actions.
Two things get stated plainly because they generate the support traffic:
prices come from a separate market data setting, so with no crypto-capable
provider enabled every wallet is tracked by quantity and valued at zero; and
Bitcoin is one address at a time, which under-reports an HD wallet whose
funds are spread across derived addresses.
Every locale key the feature uses is checked to resolve, including the
pluralised ones.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): keep EVM balances on the keyless indexer when a key is set
Configuring an Etherscan key moved every read onto Etherscan, including
balances. That was wrong: Etherscan has no free endpoint that enumerates an
address's tokens, so its token balances are summed from transfer history —
which cannot see a rebasing token's current balance, and silently
under-reports any wallet whose history exceeds the page cap. A user adding a
key to fix a rate limit would have quietly traded it for wrong balances.
The two reads are now separated by what each backend can actually answer.
Balances and activity detection always go to the keyless indexer, whose
address summary answers both in one request — so adding a key buys nothing
there and cannot cost anything either. History, the paginated and
rate-limited half, is where a key helps and is the only thing it changes.
Provider::Etherscan drops its balance methods and refuses token_balances
with the reason, rather than offering an approximation that reads as a fact.
The chain-agnostic error mapping now accepts several error families per role,
since one snapshot can involve both backends.
Checked against the pre-fix behaviour: with balances routed through the
keyed backend, the new test reports 1 USDC held instead of the 7 the indexer
sees, and Etherscan raises on the balance call.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): name verified SPL tokens so they can be priced
Solana RPC returns mints, not names, so every SPL token outside the
hard-coded handful showed up as "SPL:abcd…wxyz" — which security resolution
correctly declines, leaving the asset tracked by quantity and valued at zero.
For a wallet holding anything beyond USDC that was most of its value.
Names now come from Jupiter's keyless token search, asked once per snapshot
for every mint at once, cached 24 hours per mint.
Only mints the list reports as *verified* are trusted. Anyone can mint a
token calling itself USDC; naming an unverified one would hand it the real
dollar's price and value dust at thousands. Unverified and unknown mints keep
the placeholder, and the test for that asserts the spam token is not named
USDC. Misses are cached as well, because spam wallets hold many mints that
will still be unvouched-for tomorrow.
Metadata is a naming nicety, not the wallet: a list that is down or rate
limiting degrades to placeholders instead of failing the snapshot, and the
hard-coded mints stay as an offline floor. Assets and movements resolve from
the same lookup, so a token cannot be called two different things within one
snapshot.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): enable crypto pricing in one click, and log zero valuations
The warning said what was wrong and where to fix it, but still made the user
navigate to another settings page and pick the right provider out of a list.
On a self-hosted instance an admin can now fix it from the warning itself:
the crypto provider is appended to the enabled securities providers, leaving
the others alone — enabling crypto prices must not turn off whatever prices
the user's equities, and the test fails if it does. On a managed instance the
providers are the operator's setting, so the button is not offered and the
action refuses.
The other half is diagnosis. Until now a holding valued at zero for this
reason looked exactly like a holding whose price simply had not been fetched
yet: nothing recorded it, so support had to infer it from a screenshot. The
processor now records it via DebugLogEntry — but only for this cause, since a
price merely missing for today is ordinary and already covered by the
backfill.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): upgrade display-only movements once their price is known
A wallet linked before market data covered its history got the worst of both
worlds: its transfers landed as zero-amount excluded entries, and nothing ever
brought them back. The syncer only reprocesses assets whose on-chain state
changed, and a two-year-old transfer never changes — so the cost basis stayed
broken for exactly the wallets that were linked earliest.
perform_post_sync now runs a repair over every linked asset, not just the ones
that moved: what changed is the price history, which no chain read can report.
It reads prices from the database only, makes no network call, and does
nothing when there is nothing to upgrade.
An upgraded entry keeps its external_id, so it is the same transfer rather
than a duplicate. The entry is destroyed and rewritten because an Entry cannot
change entryable type in place and import_trade refuses an id already held by
a Transaction. Entries from other providers are never touched — matched by
source and by this asset's own id prefix.
Checked against the pre-fix behaviour: with perform_post_sync empty again, the
syncer test fails.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* feat(onchain-wallets): make history truncation visible and its depth configurable
History was capped silently. A wallet with more transfers than one sync reads
looked exactly like a wallet whose history was fully imported — the only trace
was a Rails log line on Bitcoin, and nothing at all on the EVM and Solana
paths. A user reconciling their cost basis had no way to tell the difference
between "this is all there was" and "we stopped reading".
Each source now reports whether it stopped on the budget or on the end of the
history. That travels on the Snapshot, so it stays chain-agnostic; the flag is
recorded on the affected rows, the manage screen says the history is
incomplete for that address, and the importer records it once per address per
sync — only when something changed, so an idle wallet with deep history does
not log the same line every night. The message also states what is not
affected: balances come from an address summary, never from history.
The depth itself is a hosting decision, not a property of a chain, so it moves
out of the providers into Onchain::HistoryBudget and is settable with
ONCHAIN_HISTORY_MAX_PAGES (default 10, clamped to 200). Adapters inject it, so
the providers stay unaware of the policy and the budget is testable without
touching the environment.
What this does not do is resume where it stopped. Reading older history across
syncs needs a per-wallet cursor and changes what the content digest means —
which is what guarantees an idle wallet writes nothing — so it is a change of
its own rather than a rider on this one.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): read Blockscout token balances the way the API accepts
Verified against the live API: /api/v2/addresses/{address}/token-balances
rejects a `type` filter with HTTP 422 — the filter exists on token-transfers,
not here. Every EVM snapshot was therefore failing in production and
surfacing as "the explorer could not be reached", while the tests passed
because the stub encoded the same wrong assumption. No unit test can catch a
mistaken API contract; only asking the API can.
Without the filter the endpoint answers with every token standard the address
holds — ERC-20, ERC-721, ERC-1155, ERC-404 — so ERC-20 is now selected
client-side. An NFT row carries value "1" and no decimals, so it would have
been imported as a fungible balance of one token, priced by whatever its
symbol happened to resemble.
The tests now stub the endpoint the way it really answers and assert we ask
without a query, so re-adding the filter fails the run. Each token's
market-cap signal is carried through for the next commit, which has to decide
what to do about an address holding thousands of tokens.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): bound how many tokens one address can surface
Probing the live APIs turned up the other thing the stubs were hiding: real
addresses are airdrop dumping grounds. A well-known Ethereum address returns
7,924 ERC-20 balances (3.2 MB), and a comparable Solana one 2,801 token
accounts. Nothing bounded either. That meant a review screen with thousands of
rows nobody can use, and on Solana — where names are looked up in batches of
50 — around 56 extra requests per sync just to label an airdrop dump.
One read now surfaces at most 200 tokens per address
(ONCHAIN_MAX_TOKENS_PER_ADDRESS, clamped to 5,000). The native coin is never
affected, and anything already tracked keeps syncing regardless of the cap.
What survives the cap has to be both sensible and stable. On EVM the tokens
are ranked by the market cap the indexer already reports, so real assets stay
and airdrops fall off the end. Solana RPC gives no such signal, so the order
is the mint address: arbitrary, but identical between two reads of an unchanged
address — an unstable order would reshuffle the wallet, change the content
digest, and rewrite holdings every night. There is a test for that on both
chains. On Solana the cap is applied before metadata lookup, so it bounds the
requests as well as the rows.
The cap is not silent: it is recorded on the affected rows, stated in the token
review screen and in Manage wallets, and reported alongside history truncation
in the debug log with the limit that applied.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* test(onchain-wallets): walk the linking and management flow in a browser
The linking flow stacks three Turbo frame navigations — the provider drawer,
the linking modal on top of it, then the token review in that same modal —
and no controller test exercises any of that. Driving it in a real browser
found two things worth keeping:
The panel is reached two different ways. With nothing linked yet it is a card
under "Available" that opens the drawer; once a wallet exists the provider
moves to "Your connections", where the panel renders inline inside a
disclosure and there is no link to click at all. Only the first path had ever
been exercised.
Both paths now are, along with the parts of the flow that only exist in a
browser: assets arriving pre-ticked or not according to whether they can be
priced, review tokens reopening the selection with no address field present,
and disconnecting one asset leaving its account behind. One test per flow —
the branching cases stay in the controller test, where they cost a fraction
of the time.
Verified visually at each step: the warning banner, the Bitcoin
single-address note, the three-asset review with the spam token unticked, the
four management actions, and the accounts landing under Crypto with the wallet
subtype.
Full system suite green the documented way (DISABLE_PARALLELIZATION=true):
94 runs, 385 assertions, 0 failures.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): report a timed-out data source as unreachable
Reading a real Solana wallet turned up the hole: the public RPC timed out,
Net::ReadTimeout escaped every layer untranslated, and the user was told
something had gone wrong with Sure — the generic message reserved for our own
bugs — with a DebugLogEntry filed as if it were one. A public endpoint being
slow is the most ordinary failure this feature has.
All five clients now translate transport failures into their own ApiError:
timeouts, refused or reset connections, unreachable hosts, TLS errors, and a
response that is not JSON. The adapters already map a provider's own errors
onto Onchain::Chains::UnreachableError, so a timeout now reads as "the public
explorer could not be reached", the message that tells the user to retry,
while genuine bugs keep the generic one. During chain detection it goes back
to meaning "not detected here", so a slow explorer still cannot break linking.
The translated message carries only the error class, never the original
message, because a transport error's message contains the full URL and these
get logged.
Checked against the pre-fix behaviour on Bitcoin: with the translation
removed, the timeout test fails with the raw exception instead of the chain
error.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): name on-chain trades after the asset, not "shares"
Running a real Bitcoin address through the app showed every imported transfer
as "Buy 0.000003 shares of CRYPTO:BTC". That name comes from the shared trade
helper, which is written for equities; a wallet does not hold shares, and the
internal ticker is not what the user calls the coin. Trades are now named
"Buy 0.000003 BTC", through i18n like the display-only entries already were.
Also drops the sync status_text calls. Sync has no such attribute in this
schema, so every one of them was a guarded no-op and the four locale strings
they referenced could never render — dead weight copied from another
provider's syncer.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): keep balances when a source refuses history
Reading real wallets on the free Solana endpoint exposed two problems, one of
which I introduced.
The budget. Making history depth configurable scaled Solana's transaction cap
from 25 to 250, and on Solana one transaction is one RPC call rather than one
page — so the same nominal depth became an order of magnitude more expensive
and a sync went from seconds to minutes. The per-transaction budget is now its
own constant, scaled proportionally off the page knob so one setting still
moves both, with a test that pins it far below the paginated row count.
The bigger one: a failure while reading history threw away the balances too.
A balance is one bounded request and is what a wallet fundamentally is; history
is paginated, far more expensive, and the first thing a throttled endpoint
refuses. On the free Solana endpoint, which routinely throttles getTransaction,
that meant a wallet showed nothing at all rather than showing what it holds —
permanently, not transiently.
History is now best effort: when the data source refuses it, the balances are
still recorded and the history is marked incomplete, which the manage screen
already surfaces. Anything that is not the data source failing still raises, so
a bug here cannot be swallowed. Verified live: the same Solana wallet that
failed entirely now reports 52.06 SOL and its SPL tokens with the history
flagged.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): pre-tick what is worth something, not what parses as a ticker
Linking a real airdropped address showed 200 of its 201 assets arriving
pre-ticked, one click away from 200 accounts — the opposite of what reviewing
tokens before import is for. The pre-tick rule was "the symbol looks like a
ticker", and airdrops use perfectly plausible short symbols (0XBTC, 4CHAN), so
it selected nearly everything.
Assets now carry whether the data source treats them as notable, and only those
are pre-ticked. Two attempts at that signal, decided by measuring the real
address rather than guessing:
- Blockscout's `reputation` is "ok" for all 6,669 tokens it holds. Useless.
- Market-cap presence looks strong on the full list (365 of 6,669) but is
useless after the cap, which already ranks by market cap — hence every
surfaced token having one.
- Holding value discriminates: of the 365 priced tokens, 112 are worth more
than a dollar.
So on EVM networks a token is notable when the indexer can price it and the
holding is worth more than a dollar; on Solana when the verified token list
vouches for the mint; the native coin always. Pre-ticked count on that address
drops from 200 to 72, and everything else stays one click away.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): warn when nothing can convert USD prices into the family currency
A family whose currency is not USD needs two settings, not one, and only the
first was covered. The single provider that prices bare crypto symbols quotes in
USD, so valuing a wallet in EUR needs an exchange rate on top — and Sure's
default exchange rate provider requires an API key, so a self-hosted install
without one has no FX at all.
Tested against a real address in a EUR family: every wallet came out at zero,
with 275 transfers recorded as unpriced, and nothing anywhere said why. That is
the same support ticket the crypto-provider banner exists to prevent, arriving
through the other door.
Onchain::Pricing answers "can an on-chain asset be valued in this currency, and
if not, why" with the two reasons separately. The linking UI states whichever
applies — naming the currency for the FX one, and pointing at Frankfurter, which
needs no key — and a USD family never sees that warning because it needs no
conversion. The processor records the reasons when a holding lands at zero, so
support sees "exchange_rate" rather than guessing.
Verified live afterwards: with EXCHANGE_RATE_PROVIDER=frankfurter, the same EUR
family values the wallet at 416,198,342.25 EUR at 0.86363 USD/EUR, with all 275
transfers priced in EUR.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): let a movement become a trade after being display-only
Syncing a real wallet twice — once before its prices were reachable, once after
— raised ArgumentError from the shared importer: an Entry cannot change
entryable type in place, and the display-only Transaction already held the
external_id the trade needed.
That is the ordinary case, not an edge one. A wallet linked before market data
covers its history gets display-only entries on the first sync, and the first
sync that can price them dies. Worse, it dies inside perform_sync, so the repair
pass that exists precisely to upgrade those entries — and which runs in
perform_post_sync, afterwards — was never reached. The account stayed stuck.
Both paths now go through one writer that discards a stale display-only entry
before the trade takes over its identity, so the entry keeps being the same
transfer rather than becoming a duplicate. Checked against the pre-fix
behaviour: without the discard, the new test raises the original ArgumentError.
Found by running a EUR family through two syncs on real data, which is the only
way the two price states occur in order.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): write a trade and drop its display-only entry atomically
Replacing a display-only entry with the trade it became is one change, but it
was two writes outside a transaction. A failure between them left the account
with neither: the transfer disappeared until some later sync happened to rewrite
it, which for an idle wallet could be never.
The repair pass already wrapped this; the sync path did not, and that is the one
that runs first.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): tell apart two transfers of one token in one transaction
A token transfer was identified by its transaction hash and contract, which are
not unique together: a swap router or a batch payout routinely emits several
transfers of the same token involving the same address within one transaction.
The second overwrote the first, so a transfer disappeared from the account
without a trace.
Both EVM backends report the log index — the field that makes an event unique
inside a transaction — and neither was using it. It is now part of the
identifier, with the contract kept only as a fallback for an instance that does
not report one.
Reported by review on #3081; confirmed against the live Blockscout payload,
which carries log_index. The test fails against the previous identifier.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): canonicalise an address per chain before anything keys off it
Addresses were only stripped, never canonicalised, and what counts as the same
address differs by chain — so the duplicate guard could be walked straight past
and one Bitcoin case was worse than a duplicate.
On EVM, hex is hex: 0xABC… and 0xabc… are one wallet, but they linked as two,
each with its own accounts and holdings for the same balance.
On Bitcoin, bech32 is case-insensitive and canonically lowercase, and the API
reports outputs that way. An uppercase bech32 address passed validation, gave a
correct balance from the address summary, and matched no output at all — so the
wallet silently had zero movements and no cost basis, with nothing anywhere
saying why.
Canonicalisation is now the adapter's answer, since only the chain knows whether
case carries identity: EVM and bech32 fold, Base58 and Solana are left exactly
as given. The controller applies it as soon as the chain is known and before the
duplicate check, and on an address change too.
Reported by review on #3081. Both tests fail without the folding.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): stop folding the case of Solana mints
Contract identifiers were downcased everywhere on the assumption that a contract
address is hex. That holds for ERC-20 but not for an SPL mint, which is a Base58
public key where case is part of the value: the stored mint was an unusable copy
of the real one, and two distinct mints could collide once folded into the same
string — one wallet's balance landing on the other's row.
Whether case carries identity is a property of the token kind, so it is now
answered in one place and applied consistently: by the asset's identity key, by
the column, and by the two comparisons in Onchain::Snapshot. A Movement no longer
folds anything on its own, because a movement does not know its asset's kind.
That also removes the duplication review flagged: the asset key was derived in
three places and only one of them folded, so the review screen and the linker
could disagree about what identifies an asset. There is one definition now,
OnchainWalletAccount#asset_key.
Reported by review on #3081. The test fails with the unconditional fold.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): isolate a failing address, and let a late symbol land
Two problems in the importer, both reported by review on #3081.
One unreachable address took the whole connection down with it: the loop over a
family's addresses had no rescue, so a Bitcoin explorer being throttled left an
untouched Ethereum wallet unsynced as well. Each address is now recorded and
skipped on its own — a row we failed to read keeps its previous quantity rather
than being zeroed, since we did not learn that it holds nothing — and only a
connection whose every address failed is reported as a failed sync rather than a
quiet success.
The content digest covered quantity and movements but not the metadata written
alongside them, so a Solana mint that later gained a real symbol from the token
list produced the same digest as before: the row was never rewritten and its
placeholder label became permanent. That silently undid the token-naming work.
The digest now covers everything the update writes.
Both tests fail against the previous behaviour.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* refactor(onchain-wallets): use DS::Button for the wallet actions
Five hand-built button_to controls carried their own utility-class strings for
what DS::Button already does — sync, disconnect a connection, stop tracking one
asset, disconnect a wallet, enable crypto prices. They drifted from the design
system on size, hover and destructive treatment, and the confirm prompts were
wired by hand.
The browser test walks the two that matter, so the behaviour is unchanged; this
is the styling and the confirm handling moving to the component that owns them.
Reported by review on #3081, along with the raw `bg-amber-600` on the provider
badge — left as it is, deliberately: all 23 other providers set a raw palette
class for their badge, there is no functional token for a brand colour, and
changing one entry would make it the only different one.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): four smaller findings from the review on #3081
**A failed read no longer leaves an empty connection.** `link_wallet` created the
family's connection before fetching the address, so an explorer being down left a
connection with no wallets showing in the panel as connected. Reading needs no
saved connection — which is exactly why previewing uses an unsaved one — so it is
now created only once the read succeeds.
**Assets that could not be tracked are named instead of blamed on the user.**
`success?` is `created.positive?`, and the only failure message was "pick at least
one asset to track" — so a user who ticked three assets and hit three failed
creates was told to tick something, sending them back to tick the same three.
The linker already collected which assets failed; the message now says so, and a
partial failure is reported alongside what did get tracked instead of being
dropped silently. Same fix in the token revision action, which had the same shape.
**A malformed stored amount costs its movement, not the asset.** `BigDecimal()`
on a stored payload raises, and one unparseable row would fail the whole asset's
processing — including the repair pass. These payloads are written by this code,
so it takes a row that survived a format change, but the containment is two lines.
**No dead-end link.** The warning offered "open market data settings" to
everyone, while that page is gated to self-hosted admins — the same gate the
enable button already had. Both controls are now behind it, and the warning text
stands on its own for everyone else.
Each has a test that fails against the previous behaviour.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): reject non-finite amounts and quantities
The guard added an hour ago for malformed stored amounts was incomplete for the
very case it was written for: BigDecimal parses "NaN", "Infinity" and
"-Infinity", and none of them is zero, so all three sailed through
`parse_amount` into trade materialisation. Verified rather than assumed — the
test fails without the check with PG::NumericValueOutOfRange, so the infinity
reached the insert.
Fixed at both layers that write numbers. Movements: a non-finite amount skips its
movement, like any other unparseable one. Quantities: `normalize` treats
non-finite as unknown and writes zero, because Postgres numeric stores NaN
happily and one NaN quantity would turn every total that reads it into NaN.
Reported by review on #3081.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): derive the content digest from what actually gets written
Third time the digest missed a field it was supposed to cover: first the symbol,
so a Solana placeholder that gained a real name was never rewritten; now the
truncation flags, so a wallet whose history became complete — or started being
capped — kept showing the old completeness in the UI, since the early return
fires before `extra` is touched.
Rather than add a third field to a hand-picked list, the digest is now taken from
exactly the attribute hash that is about to be written. The two cannot drift
apart, which is what kept going wrong.
That needs two things to hold. Movements are sorted before the payload is built,
so the order a source happened to list them in is not mistaken for a change. And
the hash is canonicalised before hashing, because jsonb does not preserve key
order: `extra` written as {history, assets} comes back as {assets, history}, and
hashing that raw made an idle wallet's digest flip every other sync — the tests
caught it, and it is now covered by one asserting that reordered movements are
not a change.
Reported by review on #3081. Both halves checked against the pre-fix behaviour:
without the flags two tests fail, without the canonicalisation three.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* docs(onchain-wallets): state the pricing coverage limit, and that DeFi is unseen
The hosting guide explained how to configure prices but never said what the
crypto provider actually covers. It quotes by symbol, and a symbol is not a
token's identity — measured on a real Ethereum address, two of its ten largest
token positions were quoted and the other eight, including holdings worth
roughly $406k, $141k and $74k, showed zero with their quantities tracked
correctly.
That reads as a broken sync unless it is written down, so it is now the first
limitation in the list, with the practical rule a user needs: a zero next to a
token you know is worth something means the provider does not list it, not that
the balance is wrong. Troubleshooting gains the matching entry, separating it
from the two configuration causes that produce a zero across every wallet.
Also records that DeFi positions — staked ETH, LP tokens, lending, Solana stake
accounts — are invisible, which was missing from the list entirely. A wallet
holding most of its value in a staking protocol reports a fraction of it.
Docs only; no code touched, so the suite was not re-run — the last run on this
tree was green.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): do not zero an asset the token cap never reached
A tracked asset missing from a snapshot was always read as "the wallet no
longer holds it" and set to zero. That is right for a complete read, and wrong
for a capped one: at most 200 tokens per address are surfaced, so a tracked
token can be absent simply because the read stopped before reaching it. Its
balance was then wiped — a real holding removed from the user's net worth, with
a holding of zero written and the account balance reduced to match.
It is reachable: on Solana the surfaced set is ordered by mint address, which is
arbitrary, so a genuinely held USDC position on an airdropped wallet can fall
outside the cap and be zeroed on the next sync.
Absence of evidence is not evidence of absence — the same distinction this code
already makes for an address it could not read, where the row keeps its previous
quantity. When the snapshot is capped and the asset is not in it, the row now
keeps what was last known and only its completeness flags are refreshed.
Reported by review on #3081. The test fails against the previous behaviour, and
the "an asset that disappeared is set to zero" case still passes: a complete read
that no longer lists an asset still zeroes it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* refactor(onchain-wallets): rename the local `token` variables the secret scan trips on
Pipelock failed the PR with eleven "Credential in URL (high)" findings, all on
the same shape: a local variable named `token` being assigned. `token = ...`
is what a leaked credential looks like to a scanner, and the rule is a
reasonable one to keep.
Renamed rather than excluded. Excluding paths or adding `# pipelock:ignore`
would have kept the pattern and blunted the check for everyone; the new names
are at least as clear — `token_data` for the raw hash from an indexer,
`metadata` for the resolved symbol/name pair, `token_asset` for an
Onchain::Asset in tests.
Verified with the scanner itself rather than by inference: the same pipelock
2.8.0 the workflow pins, run locally over the branch diff, now reports "No
secrets found in diff". It also caught one site the CI log had truncated away
(the system test), which is why the local run was worth setting up.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): bound detection latency, and three review findings
Detection runs on the request thread but asked each candidate chain with a
sync's patience: a 30s timeout, three retries and exponential backoff, per
chain. A 0x address is a candidate on six networks, so one rate-limited
explorer could hold the page for minutes. Detection now reads with its own
budget - one short attempt, no retry, ONCHAIN_DETECTION_TIMEOUT to raise it -
while syncs keep the patient one. A chain that cannot answer in time is
reported as "no activity", which is the screen an ambiguous answer already
produces.
Also from review:
- A full page of Solana signatures is now reported as incomplete history.
The adapter passes no cursor, so a page that fills means the read stopped
short of the address's history; counting only against the transaction
budget called that complete.
- A reused CRYPTO: security with no price provider is bound to the crypto
one. A blank provider falls back to whichever is enabled first, and only
the crypto provider quotes a bare coin symbol, so the holding valued at
zero and read as a broken sync. A provider another integration chose is
left alone: the CRYPTO: prefix is shared with the exchange integrations.
- The chain select's label reached the form builder as an HTML attribute
instead of a label option, so no <label> was associated with the field.
Each regression test was checked against the pre-fix code: the two detection
tests fail with four requests instead of one, and the truncation test fails
by reporting complete history.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): let the table refuse a token row with no contract
The partial unique indexes key a token on its contract address, and NULLs
are distinct to Postgres, so a token row that reached the table without one
would slip past its index and duplicate freely. The model already refuses
it, but a direct write does not go through the model, and this repo puts
simple guarantees like this in the database.
Added to the existing migration rather than a new one: the table is created
by this branch, so the constraint belongs with it, and this leaves the
schema version untouched.
The regression test writes with validate: false, which is how the sibling
tests prove a guarantee comes from the table rather than from the model
above it. Without the constraint it fails with "expected but nothing was
raised".
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): detect a token-only Solana wallet, and pin asset_kind
Two findings from the review of the previous commits.
Detection read only the wallet's lamports, so a wallet emptied of SOL but
still holding SPL tokens answered "nothing here". Each token account carries
its own rent, so an empty wallet address is not an empty wallet. The token
accounts are asked only once the balance comes back zero, so the ordinary
case still costs the one request this probe is meant to be, and accounts
left behind empty do not count as activity.
The narrow blast radius is worth stating: has_activity? only runs when an
address matches more than one chain, and when no candidate answers the user
is asked to choose rather than turned away. So this was a worse screen, not
a rejected wallet.
Separately, the check constraint accepted any asset_kind that carried a
contract address. Each partial unique index names its kind, so a row with
any other one is keyed by nothing and duplicates freely. Adding a token kind
already means adding its index here, so pinning the three in the table adds
no coupling that the indexes did not already have.
Both regression tests fail on the previous code. The third test - emptied
token accounts are not activity - passes either way by design: it guards the
new branch rather than testing it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* test(onchain-wallets): cover the asset_kind constraint that shipped without it
The constraint landed in b3dae571 but its regression test did not: the `git
add` named the test/models/onchain directory, and this file sits beside it
rather than inside it. Committing the test the constraint was written for.
Without the constraint it fails with "expected but nothing was raised".
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(onchain-wallets): stop a slow explorer from reading as an empty wallet
Regression from the detection budget added two commits ago, caught by probing
the real endpoints rather than the stubs.
The 5s budget sat directly on base.blockscout.com's median latency (p50 4.79s,
slowest successful probe 9.5s), so roughly a fifth of probes timed out. The
timeout was swallowed into false, which detection cannot tell apart from "this
address is not here" — and when one other chain answers yes, a single yes
settles it. A Base wallet could therefore be linked as Ethereum-only, silently
and permanently.
Three changes, and they are one fix:
- A probe that cannot answer now returns nil rather than false, and a nil sends
the user to the chain chooser instead of letting a lone yes settle it. Being
slow and having nothing to report are different answers.
- Probes run concurrently under one absolute deadline. The client timeout could
never bound the page anyway: HTTParty applies it per socket operation, so a
"5s" probe was measured at 10.1s. The deadline is wall clock and covers the
whole detection, whatever the client is doing.
- The timeout is 10s, with the reason for the number written down.
Measured against the live explorers, before and after: base false negatives
4/18 -> 0/10, and detection of a 0x address across six chains 9.4-10.7s ->
4.3-4.8s, because the cost is now the slowest chain rather than their sum.
The detector had no test of its own; it has four now, three of which fail on
the previous code, including the concurrency one by reporting "three 0.3s
probes took 0.9s, so they ran in sequence".
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
410 lines
18 KiB
Ruby
410 lines
18 KiB
Ruby
class Settings::ProvidersController < ApplicationController
|
|
layout -> { turbo_frame_request? ? "turbo_rails/frame" : "settings" }
|
|
|
|
before_action :ensure_admin, only: [ :show, :update, :sync_all, :sync, :connect_form ]
|
|
|
|
def show
|
|
@breadcrumbs = [
|
|
[ t("breadcrumbs.home"), root_path ],
|
|
[ t("breadcrumbs.bank_sync"), nil ]
|
|
]
|
|
|
|
prepare_show_context
|
|
rescue ActiveRecord::Encryption::Errors::Configuration => e
|
|
Rails.logger.error("Active Record Encryption not configured: #{e.message}")
|
|
@encryption_error = true
|
|
end
|
|
|
|
def update
|
|
# Build index of valid configurable fields with their metadata
|
|
Provider::Factory.ensure_adapters_loaded
|
|
valid_fields = {}
|
|
Provider::ConfigurationRegistry.all.each do |config|
|
|
config.fields.each do |field|
|
|
valid_fields[field.setting_key.to_s] = field
|
|
end
|
|
end
|
|
|
|
updated_fields = []
|
|
|
|
# Perform all updates within a transaction for consistency
|
|
Setting.transaction do
|
|
provider_params.each do |param_key, param_value|
|
|
# Only process keys that exist in the configuration registry
|
|
field = valid_fields[param_key.to_s]
|
|
next unless field
|
|
|
|
# Clean the value and convert blank/empty strings to nil
|
|
value = param_value.to_s.strip
|
|
value = nil if value.empty?
|
|
|
|
# For secret fields only, skip placeholder values to prevent accidental overwrite
|
|
if field.secret && value == "********"
|
|
next
|
|
end
|
|
|
|
key_str = field.setting_key.to_s
|
|
|
|
# Check if the setting is a declared field in setting.rb
|
|
# Use method_defined? to check if the setter actually exists on the singleton class,
|
|
# not just respond_to? which returns true for dynamic fields due to respond_to_missing?
|
|
if Setting.singleton_class.method_defined?("#{key_str}=")
|
|
# If it's a declared field (e.g., openai_model), set it directly.
|
|
# This is safe and uses the proper setter.
|
|
Setting.public_send("#{key_str}=", value)
|
|
else
|
|
# If it's a dynamic field, set it as an individual entry
|
|
# Each field is stored independently, preventing race conditions
|
|
Setting[key_str] = value
|
|
end
|
|
|
|
updated_fields << param_key
|
|
end
|
|
end
|
|
|
|
if updated_fields.any?
|
|
# Reload provider configurations if needed
|
|
reload_provider_configs(updated_fields)
|
|
|
|
redirect_to settings_providers_path, notice: t(".updated_successfully")
|
|
else
|
|
redirect_to settings_providers_path, notice: t(".no_changes")
|
|
end
|
|
rescue => error
|
|
Rails.logger.error("Failed to update provider settings: #{error.class} - #{error.message}")
|
|
flash.now[:alert] = "Failed to update provider settings. Please try again."
|
|
prepare_show_context
|
|
render :show, status: :unprocessable_entity
|
|
end
|
|
|
|
def sync_all
|
|
family = Current.family
|
|
now = Time.current
|
|
|
|
updated_count = Family
|
|
.where(id: family.id)
|
|
.where("last_sync_all_attempted_at IS NULL OR last_sync_all_attempted_at <= ?", 30.seconds.ago)
|
|
.update_all(last_sync_all_attempted_at: now, updated_at: now)
|
|
|
|
if updated_count.zero?
|
|
return redirect_to settings_providers_path, notice: t("settings.providers.sync_all_recently")
|
|
end
|
|
|
|
SyncAllProvidersJob.perform_later(family.id)
|
|
redirect_to settings_providers_path, notice: t("settings.providers.sync_all_in_progress")
|
|
end
|
|
|
|
def sync
|
|
provider_key = params[:provider_key]
|
|
syncable_type = PANEL_SYNCABLE_TYPES[provider_key]
|
|
return redirect_to settings_providers_path unless syncable_type
|
|
|
|
items = syncable_type.constantize.where(family: Current.family).syncable
|
|
scheduled = items.reject(&:syncing?)
|
|
scheduled.each(&:sync_later)
|
|
|
|
notice_key = scheduled.any? ? "settings.providers.sync_provider_in_progress" : "settings.providers.sync_provider_no_items"
|
|
redirect_to settings_providers_path, notice: t(notice_key)
|
|
end
|
|
|
|
def connect_form
|
|
provider_key = params[:provider_key]
|
|
|
|
panel = FAMILY_PANELS.find { |p| p[:key] == provider_key }
|
|
if panel
|
|
@panel_key = panel[:key]
|
|
@panel_partial = panel[:partial]
|
|
@panel_title = panel[:title]
|
|
load_provider_items(provider_key)
|
|
return render :connect_form
|
|
end
|
|
|
|
Provider::Factory.ensure_adapters_loaded
|
|
config = Provider::ConfigurationRegistry.all.find { |c| c.provider_key.to_s == provider_key }
|
|
if config
|
|
@panel_title = Provider::Metadata.for(provider_key)[:name] || provider_key.titleize
|
|
@provider_configuration = config
|
|
return render :connect_form
|
|
end
|
|
|
|
redirect_to settings_providers_path, alert: t("settings.providers.not_found")
|
|
rescue ActiveRecord::Encryption::Errors::Configuration
|
|
redirect_to settings_providers_path, alert: t("settings.providers.encryption_error.title")
|
|
end
|
|
|
|
private
|
|
def provider_params
|
|
# Dynamically permit all provider configuration fields
|
|
Provider::Factory.ensure_adapters_loaded
|
|
permitted_fields = []
|
|
|
|
Provider::ConfigurationRegistry.all.each do |config|
|
|
config.fields.each do |field|
|
|
permitted_fields << field.setting_key
|
|
end
|
|
end
|
|
|
|
params.require(:setting).permit(*permitted_fields)
|
|
end
|
|
|
|
def ensure_admin
|
|
return if Current.user.admin?
|
|
|
|
redirect_to root_path, alert: t("settings.providers.not_authorized")
|
|
end
|
|
|
|
# Reload provider configurations after settings update
|
|
def reload_provider_configs(updated_fields)
|
|
# Build a set of provider keys that had fields updated
|
|
updated_provider_keys = Set.new
|
|
|
|
# Look up the provider key directly from the configuration registry
|
|
updated_fields.each do |field_key|
|
|
Provider::ConfigurationRegistry.all.each do |config|
|
|
field = config.fields.find { |f| f.setting_key.to_s == field_key.to_s }
|
|
if field
|
|
updated_provider_keys.add(field.provider_key)
|
|
break
|
|
end
|
|
end
|
|
end
|
|
|
|
# Reload configuration for each updated provider
|
|
updated_provider_keys.each do |provider_key|
|
|
adapter_class = Provider::ConfigurationRegistry.get_adapter_class(provider_key)
|
|
adapter_class&.reload_configuration
|
|
end
|
|
end
|
|
|
|
# Hardcoded family-scoped panels — provider connections are managed through
|
|
# their own models (SimplefinItem, LunchflowItem, etc.) rather than global
|
|
# settings, so they need custom UI per-provider for connection management,
|
|
# status display, and sync actions. The configuration registry excludes
|
|
# them (see prepare_show_context).
|
|
FAMILY_PANELS = [
|
|
{ key: "akahu", title: "Akahu", turbo_id: "akahu", partial: "akahu_panel" },
|
|
{ key: "up", title: "Up", turbo_id: "up", partial: "up_panel" },
|
|
{ key: "lunchflow", title: "Lunch Flow", turbo_id: "lunchflow", partial: "lunchflow_panel" },
|
|
{ key: "redbark", title: "Redbark", turbo_id: "redbark", partial: "redbark_panel" },
|
|
{ key: "simplefin", title: "SimpleFIN", turbo_id: "simplefin", partial: "simplefin_panel" },
|
|
{ key: "enable_banking", title: "Enable Banking", turbo_id: "enable_banking", partial: "enable_banking_panel" },
|
|
{ key: "coinstats", title: "CoinStats", turbo_id: "coinstats", partial: "coinstats_panel" },
|
|
{ key: "wise", title: "Wise", turbo_id: "wise", partial: "wise_panel" },
|
|
{ key: "mercury", title: "Mercury", turbo_id: "mercury", partial: "mercury_panel" },
|
|
{ key: "brex", title: "Brex", turbo_id: "brex", partial: "brex_panel" },
|
|
{ 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" },
|
|
{ key: "indexa_capital", title: "Indexa Capital", turbo_id: "indexa_capital", partial: "indexa_capital_panel" },
|
|
{ key: "sophtron", title: "Sophtron", turbo_id: "sophtron", partial: "sophtron_panel" },
|
|
{ key: "questrade", title: "Questrade", turbo_id: "questrade", partial: "questrade_panel" }
|
|
].freeze
|
|
|
|
FAMILY_PANEL_KEYS = FAMILY_PANELS.map { |p| p[:key] }.freeze
|
|
|
|
# Maps panel key → ActiveRecord model name for sync health queries
|
|
PANEL_SYNCABLE_TYPES = {
|
|
"akahu" => "AkahuItem",
|
|
"up" => "UpItem",
|
|
"simplefin" => "SimplefinItem",
|
|
"lunchflow" => "LunchflowItem",
|
|
"redbark" => "RedbarkItem",
|
|
"enable_banking" => "EnableBankingItem",
|
|
"coinstats" => "CoinstatsItem",
|
|
"wise" => "WiseItem",
|
|
"mercury" => "MercuryItem",
|
|
"brex" => "BrexItem",
|
|
"coinbase" => "CoinbaseItem",
|
|
"binance" => "BinanceItem",
|
|
"kraken" => "KrakenItem",
|
|
"onchain_wallet" => "OnchainWalletItem",
|
|
"snaptrade" => "SnaptradeItem",
|
|
"questrade" => "QuestradeItem",
|
|
"ibkr" => "IbkrItem",
|
|
"trading212" => "Trading212Item",
|
|
"indexa_capital" => "IndexaCapitalItem",
|
|
"sophtron" => "SophtronItem"
|
|
}.freeze
|
|
|
|
def load_provider_items(provider_key)
|
|
case provider_key
|
|
when "akahu"
|
|
@akahu_items = Current.family.akahu_items.active.ordered
|
|
when "up"
|
|
@up_items = Current.family.up_items.active.ordered
|
|
when "simplefin"
|
|
@simplefin_items = Current.family.simplefin_items.ordered
|
|
when "lunchflow"
|
|
@lunchflow_items = Current.family.lunchflow_items.ordered
|
|
when "redbark"
|
|
@redbark_items = Current.family.redbark_items.ordered
|
|
when "enable_banking"
|
|
@enable_banking_items = Current.family.enable_banking_items.ordered
|
|
when "coinstats"
|
|
@coinstats_items = Current.family.coinstats_items.ordered
|
|
when "wise"
|
|
@wise_items = Current.family.wise_items.active.ordered.includes(:syncs, :wise_accounts)
|
|
when "mercury"
|
|
@mercury_items = Current.family.mercury_items.active.ordered.includes(:syncs, :mercury_accounts)
|
|
when "brex"
|
|
@brex_items = Current.family.brex_items.active.ordered.includes(:syncs, :brex_accounts)
|
|
when "coinbase"
|
|
@coinbase_items = Current.family.coinbase_items.ordered
|
|
when "binance"
|
|
@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"
|
|
@ibkr_items = Current.family.ibkr_items.ordered
|
|
when "trading212"
|
|
@trading212_items = Current.family.trading212_items.ordered
|
|
when "indexa_capital"
|
|
@indexa_capital_items = Current.family.indexa_capital_items.ordered
|
|
when "sophtron"
|
|
@sophtron_items = Current.family.sophtron_items.ordered
|
|
when "questrade"
|
|
@questrade_items = Current.family.questrade_items.active.ordered
|
|
end
|
|
end
|
|
|
|
# Prepares instance vars needed by the show view and partials
|
|
def prepare_show_context
|
|
# Load all provider configurations (exclude family-scoped panels, which have their own UI below)
|
|
Provider::Factory.ensure_adapters_loaded
|
|
@provider_configurations = Provider::ConfigurationRegistry.all.reject do |config|
|
|
FAMILY_PANEL_KEYS.any? { |key| config.provider_key.to_s.casecmp(key).zero? }
|
|
end
|
|
|
|
@akahu_items = Current.family.akahu_items.active.ordered
|
|
@up_items = Current.family.up_items.active.ordered
|
|
# Providers page only needs to know whether any SimpleFin/Lunchflow connections exist with valid credentials
|
|
@simplefin_items = Current.family.simplefin_items.where.not(access_url: [ nil, "" ]).ordered.select(:id)
|
|
@lunchflow_items = Current.family.lunchflow_items.where.not(api_key: [ nil, "" ]).ordered.select(:id)
|
|
@redbark_items = Current.family.redbark_items.where.not(api_key: [ nil, "" ]).ordered.select(:id)
|
|
@enable_banking_items = Current.family.enable_banking_items.ordered # Enable Banking panel needs session info for status display
|
|
# Providers page only needs to know whether any Sophtron connections exist with valid credentials
|
|
@sophtron_items = Current.family.sophtron_items.where.not(user_id: [ nil, "" ], access_key: [ nil, "" ]).ordered.select(:id)
|
|
@coinstats_items = Current.family.coinstats_items.ordered # CoinStats panel needs account info for status display
|
|
@wise_items = Current.family.wise_items.active.ordered
|
|
@mercury_items = Current.family.mercury_items.active.ordered
|
|
@brex_items = Current.family.brex_items.active.ordered
|
|
@coinbase_items = Current.family.coinbase_items.ordered # Coinbase panel needs name and sync info for status display
|
|
@snaptrade_items = Current.family.snaptrade_items.ordered
|
|
@ibkr_items = Current.family.ibkr_items.ordered.select(:id)
|
|
@trading212_items = Current.family.trading212_items.ordered.select(:id)
|
|
@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)
|
|
|
|
entries = build_provider_entries
|
|
|
|
@connected = entries.select { |e| e[:summary][:status] == :ok }
|
|
@needs_attention = entries.select { |e| [ :warn, :err ].include?(e[:summary][:status]) }
|
|
@available = entries.select { |e| e[:summary][:status] == :off }
|
|
|
|
@health = view_context.provider_health_strip(connected: @connected, needs_attention: @needs_attention)
|
|
end
|
|
|
|
# Maps each family panel key to the loaded item collection. Used by
|
|
# compute_provider_sync_health and build_provider_entries to avoid relying
|
|
# on instance_variable_get for control flow.
|
|
def family_panel_items
|
|
{
|
|
"akahu" => @akahu_items,
|
|
"up" => @up_items,
|
|
"simplefin" => @simplefin_items,
|
|
"lunchflow" => @lunchflow_items,
|
|
"redbark" => @redbark_items,
|
|
"enable_banking" => @enable_banking_items,
|
|
"coinstats" => @coinstats_items,
|
|
"wise" => @wise_items,
|
|
"mercury" => @mercury_items,
|
|
"brex" => @brex_items,
|
|
"coinbase" => @coinbase_items,
|
|
"binance" => @binance_items,
|
|
"kraken" => @kraken_items,
|
|
"onchain_wallet" => @onchain_wallet_items,
|
|
"snaptrade" => @snaptrade_items,
|
|
"questrade" => @questrade_items,
|
|
"ibkr" => @ibkr_items,
|
|
"trading212" => @trading212_items,
|
|
"indexa_capital" => @indexa_capital_items,
|
|
"sophtron" => @sophtron_items
|
|
}
|
|
end
|
|
|
|
# Returns a hash mapping provider key → { error:, last_synced_at:, stale: }
|
|
# by querying the latest sync per item for each family panel provider.
|
|
def compute_provider_sync_health(items_map)
|
|
PANEL_SYNCABLE_TYPES.each_with_object({}) do |(key, syncable_type), health|
|
|
ids = items_map[key]&.map(&:id)&.compact
|
|
next if ids.blank?
|
|
|
|
health[key] = sync_health_for(syncable_type, ids)
|
|
end
|
|
end
|
|
|
|
# Determines error/stale status and last successful sync time for a set of items.
|
|
def sync_health_for(syncable_type, item_ids)
|
|
# Use window function to get the single latest sync per item (same pattern as ProviderConnectionStatus)
|
|
ranked_subq = Sync
|
|
.where(syncable_type: syncable_type, syncable_id: item_ids)
|
|
.select("syncs.*, ROW_NUMBER() OVER (PARTITION BY syncable_id ORDER BY created_at DESC, id DESC) AS sync_rank")
|
|
|
|
latest_per_item = Sync.from(ranked_subq, :syncs).where("sync_rank = 1").to_a
|
|
|
|
has_error = latest_per_item.any? { |s| s.failed? || s.stale? }
|
|
|
|
last_synced = Sync
|
|
.where(syncable_type: syncable_type, syncable_id: item_ids, status: "completed")
|
|
.maximum(:completed_at)
|
|
|
|
stale = !has_error && last_synced.present? && last_synced < 24.hours.ago
|
|
|
|
{ error: has_error, last_synced_at: last_synced, stale: stale }
|
|
end
|
|
|
|
# Builds a unified list of provider entries (registry-driven configurations
|
|
# and hardcoded family panels) with pre-computed status, sorted
|
|
# alphabetically by display title. Each entry carries enough data for the
|
|
# view to render either a provider_form or a family panel partial.
|
|
def build_provider_entries
|
|
configuration_entries = @provider_configurations.map do |config|
|
|
meta = Provider::Metadata.for(config.provider_key)
|
|
{
|
|
provider_key: config.provider_key.to_s,
|
|
title: meta[:name] || config.provider_key.to_s.titleize,
|
|
configuration: config,
|
|
maturity: meta[:maturity],
|
|
summary: view_context.provider_summary(config.provider_key)
|
|
}
|
|
end
|
|
|
|
family_entries = FAMILY_PANELS.map do |panel|
|
|
{
|
|
provider_key: panel[:key],
|
|
title: panel[:title],
|
|
turbo_id: panel[:turbo_id],
|
|
partial: panel[:partial],
|
|
auto_open_param: panel[:auto_open],
|
|
maturity: Provider::Metadata.for(panel[:key])[:maturity],
|
|
summary: view_context.provider_summary(panel[:key])
|
|
}
|
|
end
|
|
|
|
(configuration_entries + family_entries).sort_by { |entry| entry[:title].downcase }
|
|
end
|
|
end
|