Repository navigation
fix(assets-controller): remove assetsForPriceUpdate - #10892
Conversation
6bd258b to
508bcdf
Compare
c22b626 to
1b0ec3b
Compare
1b0ec3b to
3c57fb6
Compare
juanmigdr
left a comment
There was a problem hiding this comment.
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 () => { |
There was a problem hiding this comment.
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.
| 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); | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
I don't fully understand the need for these 2 loops.
- why are we going through both state & response?
- surely both loops should use the identical branching logic?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
But that's outside of this PR
c703900 to
c43bca4
Compare
5bf9cab to
ad7c31d
Compare
29c1be6 to
cc592fc
Compare
Co-authored-by: Cursor <cursoragent@cursor.com>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ 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) | ||
| ); | ||
| } |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit ff066f4. Configure here.
There was a problem hiding this comment.
Not an issue. Better to just re-fetch
| hasText(metadata.symbol) && | ||
| hasText(metadata.name) && | ||
| isFiniteNonNegative(metadata.decimals) && | ||
| hasText(metadata.image) && | ||
| Array.isArray(metadata.aggregators) && | ||
| isFiniteNonNegative(metadata.occurrences) |
There was a problem hiding this comment.
nit - future - this seems like it can be schema validated (e.g. @metamask/superstruct or zod.
…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 -->
…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 -->


Explanation
https://consensyssoftware.atlassian.net/browse/ASSETS-3924
getAssetsused to take anassetsForPriceUpdatelist, andDetectionMiddlewarewrotedetectedAssetssoTokenDataSourceandPriceDataSourceknew 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:
PriceDataSourceprices 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.TokenDataSourcefetches 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.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 callsPriceDataSource.fetchAssetPricesdirectly (bypassing the freshness cache), merges intoassetsPrice, and does not run the balance pipeline.setSelectedCurrencyuses it after invalidating the price cache, passing every asset id currently inassetsBalance.Breaking for
@metamask/assets-controllerconsumers:assetsForPriceUpdateis removed fromDataRequest/getAssetsoptions. CallsyncAssetsPricesinstead.DetectionMiddlewareandDetectionMiddlewareOptionsare no longer exported.FastFetchSources,UpdateSources, andWsUpdateSourcesno longer takedetectionMiddleware.References
No linked issue. Client adoption PRs are not open yet.
Checklist
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-controllerpicks tokens for metadata and prices after balances return.DetectionMiddlewareis removed, along withdetectedAssetson pipeline responses and theAssetsController:assetsDetectedevent.getAssetsno longer acceptsassetsForPriceUpdate.TokenDataSourceandPriceDataSourceeach 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 whenimageis 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 asAssetsController:syncAssetsPrices, force-fetching spot prices outside the balance pipeline (used for explicit lists andsetSelectedCurrencyafter cache invalidation). Startup and network-switch flows drop the extra price-onlygetAssetspass; 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 (
syncAssetsPricesreplacesassetsForPriceUpdate; stop wiringDetectionMiddleware).Reviewed by Cursor Bugbot for commit ff066f4. Bugbot is set up for automated code reviews on this repo. Configure here.