Skip to content

fix(assets-controller): remove assetsForPriceUpdate - #10892

Merged
Kriys94 merged 20 commits into
mainfrom
fix/RemoveassetsForPriceUpdate
Oct 26, 2026
Merged

Kriys94 merged 20 commits into
mainfrom
fix/RemoveassetsForPriceUpdate

Conversation

@Kriys94

@Kriys94 Kriys94 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Explanation

https://consensyssoftware.atlassian.net/browse/ASSETS-3924

getAssets used to take an assetsForPriceUpdate list, and DetectionMiddleware wrote detectedAssets so TokenDataSource and PriceDataSource knew what to enrich. That split the "which assets need metadata or a price" decision across the request, a dedicated middleware, and the two sources.

This removes both. Each source now chooses its own set from the request, controller state, and the balance response:

  • PriceDataSource prices custom assets, balances, and metadata already in state, plus balances on the current response. Hidden, non-priceable, and unsupported assets are excluded. Pipeline fetches go through the price freshness cache so unchanged assets are not requested again.
  • TokenDataSource fetches metadata for state balances that have none and for balances on the current response, and excludes hidden assets. Balances already in state are treated as heals (enriched, not spam-filtered); balances new to state are still spam-filtered.
  • Fast, update, and websocket lanes no longer insert DetectionMiddleware. Token and price enrichment still run in parallel after balances.

Callers that need prices for an explicit CAIP-19 list use syncAssetsPrices(assetIds). It calls PriceDataSource.fetchAssetPrices directly (bypassing the freshness cache), merges into assetsPrice, and does not run the balance pipeline. setSelectedCurrency uses it after invalidating the price cache, passing every asset id currently in assetsBalance.

Breaking for @metamask/assets-controller consumers:

  • assetsForPriceUpdate is removed from DataRequest / getAssets options. Call syncAssetsPrices instead.
  • DetectionMiddleware and DetectionMiddlewareOptions are no longer exported.
  • FastFetchSources, UpdateSources, and WsUpdateSources no longer take detectionMiddleware.

References

No linked issue. Client adoption PRs are not open yet.

Checklist

  • I've updated the test suite for new or updated code as appropriate
  • I've updated documentation (JSDoc, Markdown, etc.) for new or updated code as appropriate
  • I've communicated my changes to consumers by updating changelogs for packages I've changed
  • I've introduced breaking changes in this PR and have prepared draft pull requests for clients and consumer packages to resolve them

Note

High Risk
Breaking API and pipeline changes affect token metadata, pricing, and messenger events across wallet refresh paths; incorrect asset selection could miss prices/metadata or spam-filter wrongly.

Overview
Breaking refactor of how @metamask/assets-controller picks tokens for metadata and prices after balances return. DetectionMiddleware is removed, along with detectedAssets on pipeline responses and the AssetsController:assetsDetected event. getAssets no longer accepts assetsForPriceUpdate.

TokenDataSource and PriceDataSource each build their own asset lists from the request, controller state, and the current balance response (hidden assets excluded). Metadata is refetched when any required field is missing—not only when image is absent. Balance refreshes price only unpriced tokens on the response; the price poll still refreshes held balances and custom assets from state.

syncAssetsPrices(assetIds) is added as AssetsController:syncAssetsPrices, force-fetching spot prices outside the balance pipeline (used for explicit lists and setSelectedCurrency after cache invalidation). Startup and network-switch flows drop the extra price-only getAssets pass; pricing runs inside the main pipeline, with native/default-tracked balances seeded before subscriptions where needed.

An ADR, changelog, and README updates document the new flow and migration (syncAssetsPrices replaces assetsForPriceUpdate; stop wiring DetectionMiddleware).

Reviewed by Cursor Bugbot for commit ff066f4. Bugbot is set up for automated code reviews on this repo. Configure here.

@Kriys94
Kriys94 force-pushed the fix/RemoveassetsForPriceUpdate branch from 6bd258b to 508bcdf Compare October 20, 2026 15:35
@Kriys94
Kriys94 force-pushed the fix/RemoveassetsForPriceUpdate branch from c22b626 to 1b0ec3b Compare October 20, 2026 22:14
@Kriys94
Kriys94 force-pushed the fix/RemoveassetsForPriceUpdate branch from 1b0ec3b to 3c57fb6 Compare October 20, 2026 22:52
@Kriys94
Kriys94 marked this pull request as ready for review October 21, 2026 08:53
@Kriys94
Kriys94 requested review from a team as code owners October 21, 2026 08:53

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@juanmigdr juanmigdr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice cleanup overall, the detection middleware split always felt awkward and this is way easier to follow. ci is green and the decision doc is great

couple things before i can approve tho

syncAssetsPrices isnt in MESSENGER_EXPOSED_METHODS so messenger callers cant actually use it, which is a problem since thats the migration path the changelog points everyone at. extension and mobile both go through the messenger so theyd be stuck. think you just need to add it to the list

also in runStartupRefresh the two seed calls moved above the try block, if either throws the mutex never releases and account refreshes stall. probably fine in practice since theyre just sync state writes but easy to move them inside the try like the other refresh path does

minor nits, changelog entries are missing the pr link and title says fix but this is really a breaking refactor

once those two things land im good to approve

controller.destroy();
});

it('middleware prices custom assets and metadata from state, excluding hidden assets', async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test specs are a little hard to read/understand.

Thoughts on converting this to a test-table/it.each([{}, {}])? Make the inputs and outputs in the test table clear without needing to read the test implementation.

Comment on lines +593 to +620
for (const [accountId, accountBalances] of Object.entries(
state.assetsBalance ?? {},
)) {
if (accountFilter && !accountFilter.has(accountId)) {
continue;
}
for (const assetId of Object.keys(accountBalances)) {
stateBalanceIds.add(assetId.toLowerCase());
if (!inRequestChains(assetId) || !needsMetadata(assetId)) {
continue;
}
assetIdsNeedingMetadata.add(assetId);
balanceHealAssetIds.add(assetId.toLowerCase());
}
}

for (const accountBalances of Object.values(response.assetsBalance ?? {})) {
for (const assetId of Object.keys(accountBalances)) {
if (!needsMetadata(assetId)) {
continue;
}
assetIdsNeedingMetadata.add(assetId);
const lowerId = assetId.toLowerCase();
if (stateBalanceIds.has(lowerId) || knownMetadataIds.has(lowerId)) {
balanceHealAssetIds.add(lowerId);
}
}
}

@Prithpal-Sooriya Prithpal-Sooriya Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't fully understand the need for these 2 loops.

  1. why are we going through both state & response?
  2. surely both loops should use the identical branching logic?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great comment, the issue is balanceHealAssetIds, where we try to recover metadata outside of the response, which is not great for understanding. We should comeback to something simpler, i.e. fetch metadata not in state but in response.

If we want to recover, it should be outside

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But that's outside of this PR

@Kriys94
Kriys94 force-pushed the fix/RemoveassetsForPriceUpdate branch from c703900 to c43bca4 Compare October 22, 2026 14:13

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@Kriys94
Kriys94 force-pushed the fix/RemoveassetsForPriceUpdate branch from 5bf9cab to ad7c31d Compare October 22, 2026 20:28

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@Kriys94
Kriys94 force-pushed the fix/RemoveassetsForPriceUpdate branch from 29c1be6 to cc592fc Compare October 23, 2026 11:39

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit ff066f4. Configure here.

Array.isArray(metadata.aggregators) &&
isFiniteNonNegative(metadata.occurrences)
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Heal fetch overwrites stored token images

Medium Severity

Metadata is now treated as incomplete without aggregators and occurrences, so tokens that already have an image are fetched again. That write replaces the whole assetsInfo record whenever the Tokens API returns a symbol and name, so a response that omits iconUrl drops the stored icon instead of filling only the missing fields.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ff066f4. Configure here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not an issue. Better to just re-fetch

@Kriys94
Kriys94 enabled auto-merge October 26, 2026 14:00
Comment on lines +144 to +149
hasText(metadata.symbol) &&
hasText(metadata.name) &&
isFiniteNonNegative(metadata.decimals) &&
hasText(metadata.image) &&
Array.isArray(metadata.aggregators) &&
isFiniteNonNegative(metadata.occurrences)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit - future - this seems like it can be schema validated (e.g. @metamask/superstruct or zod.

@Kriys94
Kriys94 added this pull request to the merge queue Oct 26, 2026
Merged via the queue into main with commit 162218e Oct 26, 2026
524 of 531 checks passed
@Kriys94
Kriys94 deleted the fix/RemoveassetsForPriceUpdate branch October 26, 2026 14:22
darkwing pushed a commit to darkwing/metamask-mobile that referenced this pull request Oct 29, 2026
…38308)

<!--
Please submit this PR as a draft initially.

Do not mark it as "Ready for review" until this PR meets the canonical
Definition of Ready For Review in `docs/readme/ready-for-review.md`.

In short: the template must be materially complete (not just section
titles
present), all status checks must be currently passing, and the only
expected
follow-up commits must be reviewer-driven.
-->
<!--
mms-check directive vocabulary — read by
.github/scripts/shared/pr-template-checks.ts
at module load to build the validation plan. Directives are invisible in
rendered
markdown and must NOT be removed or edited without updating the
validator registry.

  type=text           Section must contain non-placeholder prose.
  type=changelog      Section must have a valid CHANGELOG entry: line.
type=issue-link Section must have a Fixes:/Closes:/Refs: line with a
value.
type=manual-testing Section must have real testing steps or an explicit
N/A.
type=screenshot Section must have evidence (image/URL) or an explicit
N/A.
type=checklist Section must have all checkboxes consciously checked.
required=true|false Whether a missing/invalid section runs the validator
at all.
blocking=true|false Whether a failure of this check fails the CI
workflow.
Default: false — failures are shown as warnings in the sticky
                      comment but do not block the PR.

Sections without a directive are checked for structural presence only.
-->

## **Description**

<!-- mms-check: type=text required=true -->

Bumps `@metamask/assets-controller` from `^19.1.0` to `^20.0.0` and
moves the two call sites that forced a price fetch onto
`AssetsController.syncAssetsPrices`.

`20.0.0` ([core#10892](MetaMask/core#10892))
removes `assetsForPriceUpdate` from `getAssets`. An explicit price
refresh is now `syncAssetsPrices(assetIds)`, which force-fetches spot
prices for a CAIP-19 list and merges them into state. The same release
refetches metadata when `symbol`, `name`, `decimals`, `image`,
`aggregators`, or `occurrences` is missing, prices a balance from the
current response only when that asset has no stored price, skips hidden
assets, and removes `DetectionMiddleware` plus the
`AssetsController:assetsDetected` event.

Mobile called the removed option in two places:

- `useRefreshMusdFiatRate` (Money home pull-to-refresh) now calls
`syncAssetsPrices` with the Monad mUSD asset id. The
selected-EVM-account guard, the in-flight promise dedupe, and the
swallowed error log stay as they were.
- `useEnsurePayToken` still registers the token with `addCustomAsset` on
the pay account (or the selected account). The following price refresh
calls `syncAssetsPrices` with that token's CAIP-19 id. Registration and
the price refresh stay best-effort.

`@metamask/bridge-controller` (`^83.1.1`) and
`@metamask/transaction-pay-controller` (`^30.3.0`) move with the bump
because they depend on assets-controller 20. Unit tests for both hooks
assert `syncAssetsPrices`.

## **Changelog**

<!-- mms-check: type=changelog required=true blocking=true -->

CHANGELOG entry: null

## **Related issues**

<!-- mms-check: type=issue-link required=true -->

Refs: No tracking issue. Companion to
[MetaMask/metamask-extension#47400](MetaMask/metamask-extension#47400)
and [MetaMask/core#10892](MetaMask/core#10892).

## **Manual testing steps**

<!-- mms-check: type=manual-testing required=true -->

```gherkin
Feature: assets controller 20 price refresh

  Scenario: Money home pull-to-refresh updates the mUSD fiat value
    Given the app is built from this branch and unlocked on an account that can open Money home
    And Money home shows an mUSD balance

    When the user pulls to refresh on Money home
    Then the mUSD fiat value finishes loading
    And the refresh spinner clears

  Scenario: a zero-balance withdraw pay token gets a fiat rate
    Given a withdraw confirmation whose pay-with sheet lists a non-native token with a zero balance

    When the user selects that token as the pay token
    Then the confirmation shows the token with a fiat rate
    And the confirmation does not stay waiting on a price

  Scenario: the wallet asset list still shows balances and prices
    Given the app is unlocked on an account that holds tokens on Ethereum Mainnet

    When the user opens the home asset list
    Then symbols, balances, and fiat prices appear
```

## **Screenshots/Recordings**

<!-- mms-check: type=screenshot required=true -->

N/A — the screens stay the same. This PR swaps the price-refresh API and
bumps the controller.

### **Before**

N/A

### **After**

N/A

## **Pre-merge author checklist**

<!-- mms-check: type=checklist required=true -->

- [x] I've followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile
Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've completed the PR template to the best of my ability
- [x] I've included tests if applicable
- [x] I've documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [x] I've applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

#### Performance checks (if applicable)

- [x] I've tested on Android
  - Ideally on a mid-range device; emulator is acceptable
- [x] I've tested with a power user scenario
- Use these [power-user
SRPs](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/edit-v2/401401446401?draftShareId=9d77e1e1-4bdc-4be1-9ebb-ccd916988d93)
to import wallets with many accounts and tokens
- [x] I've instrumented key operations with Sentry traces for production
performance metrics
- See [`trace()`](/app/util/trace.ts) for usage and
[`addToken`](/app/components/Views/AddAsset/components/AddCustomToken/AddCustomToken.tsx#L274)
for an example

For performance guidelines and tooling, see the [Performance
Guide](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/400085549067/Performance+Guide+for+Engineers).

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> A major assets-controller bump plus a narrower price-refresh API could
affect mUSD and pay-token fiat display if syncAssetsPrices behaves
differently than the old getAssets path.
> 
> **Overview**
> Upgrades **`@metamask/assets-controller`** to **^20.0.0** (and
**`@metamask/transaction-pay-controller`** to **^30.3.0** with lockfile
churn) because v20 drops **`getAssets`**’s **`assetsForPriceUpdate`**
option in favor of **`syncAssetsPrices(assetIds)`** for forced
spot-price fetches.
> 
> **Money home** (`useRefreshMusdFiatRate`): pull-to-refresh now calls
**`syncAssetsPrices`** with the Monad **mUSD** CAIP-19 id instead of
**`getAssets`** with account, chain, **`forceUpdate`**, and price
filters. The selected-EVM-account guard, in-flight promise dedupe, and
logged/swallowed errors are unchanged.
> 
> **Withdraw/pay confirmations** (`useEnsurePayToken`): after
**`addCustomAsset`**, the best-effort fiat refresh uses
**`syncAssetsPrices([token CAIP-19])`** rather than account-scoped
**`getAssets`**. Registration and account-override behavior stay the
same.
> 
> Unit tests for both hooks now mock and assert **`syncAssetsPrices`**.
There is also unrelated markdown table column alignment in a PredictNext
contract doc.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b60afdc. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
LabinatorSolutions pushed a commit to LabinatorSolutions/metamask-extension that referenced this pull request Oct 29, 2026
…47400)

<!--
Please submit this PR as a draft initially.
Do not mark it as "Ready for review" until the template has been
completely filled out, and PR status checks have passed at least once.
-->

## **Description**

Bumps `@metamask/assets-controller` from `^19.1.0` to `^20.0.0` so
Extension picks up the 20.0.0 asset pipeline
([core#10892](MetaMask/core#10892)).

`20.0.0` changes how token metadata and prices are filled in:

- Stored metadata is fetched again when `symbol`, `name`, `decimals`,
`image`, `aggregators`, or `occurrences` is missing.
- A balance refresh prices a balance from the current response only when
that asset has no stored price, and it skips hidden assets. The price
poll still refreshes stored prices for held balances and custom assets,
and it skips metadata that has no balance.
- `DetectionMiddleware`, the `AssetsController:assetsDetected` event,
`detectedAssets` on `DataResponse`, and the `assetsForPriceUpdate`
option on `getAssets` are removed. An explicit price refresh goes
through `AssetsController:syncAssetsPrices`.

Extension already compiles against the remaining messenger surface, so
this PR only updates dependency versions and two E2E fixtures.
`@metamask/bridge-controller` (`^83.1.1`) and
`@metamask/transaction-pay-controller` (`^30.3.0`) move with it because
they depend on assets-controller 20.

Fixture updates:

- Perps withdraw mocks build ERC-20 asset ids from the EIP-55 address.
AssetsController 20 keys ERC-20 state by that checksummed id, and Pay
reads the same key. A lowercase seed left the checksummed entry with
metadata and no price, so the withdraw button stayed on its loading
spinner. Spot-price mocks match those ids case-insensitively.
- The spam-token cleanup fixture seeds `assetsInfo` with `occurrences`
and `image`, so those rows are complete metadata and the controller
leaves them in place.

## **Changelog**

CHANGELOG entry: null

<!--
## **Related issues**

Fixes:
-->

## **Manual testing steps**

1. Build and load this branch, then unlock a wallet that holds tokens on
Ethereum Mainnet.
2. Open the home asset list and confirm symbols, balances, and fiat
prices still appear.
3. Open a token whose stored metadata was missing an image or occurrence
count, refresh assets, and confirm the icon and name fill in.
4. Open Perps, start a withdraw, and confirm the pay-token price loads
and the withdraw button leaves the loading spinner.
5. Confirm a token that was previously hidden as spam stays out of the
asset list.

<!--
## **Screenshots/Recordings**

### **Before**

### **After**
-->

## **Pre-merge author checklist**

- [x] I've followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask
Extension Coding
Standards](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've completed the PR template to the best of my ability
- [x] I’ve included tests if applicable
- [x] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [x] I’ve applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> A major-version assets-controller bump can change how token metadata,
balances, and prices are keyed and synced across Pay, bridge, and the
wallet UI; risk is mitigated here by limited diff scope and targeted E2E
fixture fixes.
>
> **Overview**
> Upgrades **`@metamask/assets-controller`** from 19.x to **20.0.0**,
with aligned bumps to **`@metamask/bridge-controller`** (^83.1.1) and
**`@metamask/transaction-pay-controller`** (^30.3.0), plus the
corresponding **`yarn.lock`** transitive updates.
>
> E2E fixtures are adjusted for **AssetsController 20** behavior: ERC-20
state is keyed by **EIP-55 checksummed asset IDs**, so Perps withdraw
mocks now build asset IDs from hex addresses and match spot-price mocks
with **case-insensitive** lookups. The spam-token cleanup spec seeds
**`assetsInfo`** with **`occurrences`** and **`image`** so fixture state
matches what the new controller expects during cleanup tests.
>
> There are **no application source changes** in this PR—only dependency
versions and test/fixture updates.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ed54147. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants