Skip to content

feat(assets-controllers): store the source of each NFT - #11106

Merged
juanmigdr merged 10 commits into
mainfrom
chore/store-if-nft-was-manually-imported
Oct 27, 2026
Merged

juanmigdr merged 10 commits into
mainfrom
chore/store-if-nft-was-manually-imported

Conversation

@juanmigdr

@juanmigdr juanmigdr commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Explanation

NFT state did not record how an NFT was added, so clients and other controllers could not treat manual imports, dapp suggestions and auto-detected NFTs differently (for example, to avoid removing NFTs the user added themselves).

Nft now has an optional source field (Source.Custom for a manual import, Source.Dapp for a dapp suggestion, Source.Detected for auto-detection). It is stored when the NFT is created and is kept stable afterwards:

  • Auto-detection never overwrites a stored source (a manually imported or dapp-suggested NFT stays that way when it is detected again).
  • A dapp suggestion upgrades a detected NFT, and a manual import overrides any other source. Nothing overwrites a manual import.
  • NFTs added before this change have no source (origin unknown). There is no backfill or migration.
  • onNftAdded is not called when an existing NFT is only updated to record its source, so analytics do not report a false "NFT added".
  • Source is now exported from the package entry point. The default source for addNft, addNfts and addNftVerifyOwnership stays Source.Custom, so callers that refresh existing NFTs should pass Source.Detected.

References

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

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

Medium Risk
Changes NFT state shape and merge logic in a widely used controller; the field is optional and backward compatible, but callers must pass the right source on refresh to avoid mis-labeling.

Overview
Adds an optional source field on Nft (custom, dapp, detected) so clients can tell manual imports, dapp suggestions, and auto-detection apart. Source is exported from @metamask/assets-controllers for use with addNft, addNfts, and addNftVerifyOwnership (default Source.Custom; refresh flows should pass Source.Detected).

NftController now sets source on create and applies precedence on re-add: Detected never overwrites an existing source, dapp can upgrade from detected, and manual import wins over everything. Legacy NFTs without source stay unset until a qualifying add. Docs/changelog describe the rules; tests cover storage, upgrades, skips, and package export.

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

Clients cannot tell user-imported NFTs apart from detected or dapp-suggested ones. Store that distinction when an NFT is added through the manual import flow.
@juanmigdr
juanmigdr requested review from a team as code owners October 27, 2026 03:24
@juanmigdr
juanmigdr enabled auto-merge October 27, 2026 03:25

@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 1cca0e7. Configure here.

@juanmigdr juanmigdr changed the title feat(assets-controllers): record when an NFT was manually imported feat(assets-controllers): store the source of each NFT Oct 27, 2026
@juanmigdr
juanmigdr added this pull request to the merge queue Oct 27, 2026
Merged via the queue into main with commit 12cd144 Oct 27, 2026
58 checks passed
@juanmigdr
juanmigdr deleted the chore/store-if-nft-was-manually-imported branch October 27, 2026 16:29
Naz-Ovh pushed a commit to 0x-fork/metamask-core that referenced this pull request Oct 28, 2026
…am (MetaMask#8237)

## Explanation

**Current state:** `NftDetectionController` only ever *adds* NFTs
returned by the NFT API (it filters out `isSpam: true` tokens before
`addNfts`). If an NFT was detected and stored while it was considered
legitimate, and the backend later reclassifies it as spam, it stays in
the user's local state forever, so users keep seeing NFTs that are now
known to be spam.

**Solution:** During detection, for each API page we now look at tokens
where `isSpam === true`. If that contract/tokenId already exists in
`allNfts[userAddress][chainId]`, we remove it via a new `removeNft`
callback. This runs before the existing add step, which is unchanged.

Details:
- Matching is by checksummed contract address (case-insensitive) plus
`tokenId`, on the chain reported by the spam entry.
- A spam entry is skipped when it has no `chainId`, is not present in
state (wrong chain or tokenId), or its chain has no configured network
client (`NetworkController:findNetworkClientIdByChainId` throws; this is
caught so detection continues).
- `toHex` from `@metamask/controller-utils` is used to normalize
`chainId` to the hex form used as state keys.
- NFTs the user added themselves are never removed. Removal only applies
to NFTs whose stored `source` is `detected` or unset. NFTs with a
`custom` (manual import) or `dapp` (approved dapp suggestion) source are
skipped. This relies on the `source` field introduced in MetaMask#11106, so this
PR should merge after it. NFTs added before sources were recorded have
no `source` and remain removable.
- Removal uses `removeNft`, so the NFT is not added to `ignoredNfts`; if
the API later stops flagging it as spam, detection can add it back as
`detected`.

**Breaking change:** the `NftDetectionController` constructor now
requires `removeNft: NftController['removeNft']`. Consumers must pass
`removeNft: nftController.removeNft.bind(nftController)`. This is
documented in the `@metamask/assets-controllers` changelog.

**Tests:** added coverage for the removal happy path, the source-based
exemption (custom and dapp kept; detected and unset removed; mixed
batch), no-op cases (no chainId, not in state, wrong chain/tokenId), an
unknown network, and the case where all requested chain IDs are filtered
out (e.g. `0x0`), so `addNfts([])` runs without hitting the API.

## References

- https://consensyssoftware.atlassian.net/browse/ASSETS-4116
- Related: MetaMask#10811 (closed)

## Checklist

- [x] I've updated the test suite for new or updated code as appropriate
- [x] I've updated documentation (JSDoc, Markdown, etc.) for new or
updated code as appropriate
- [x] I've communicated my changes to consumers by [updating changelogs
for packages I've
changed](https://github.com/MetaMask/core/tree/main/docs/processes/updating-changelogs.md)
- [ ] I've introduced [breaking
changes](https://github.com/MetaMask/core/tree/main/docs/processes/breaking-changes.md)
in this PR and have prepared draft pull requests for clients and
consumer packages to resolve them

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking constructor change for all integrators, plus automatic
deletion of wallet NFT state—mitigated by source-based exemptions and
guarded network resolution.
> 
> **Overview**
> **`NftDetectionController` now drops NFTs from local state when the
NFT API flags them as spam during detection**, instead of only ignoring
spam on add. For each API page, tokens with `isSpam: true` are matched
against existing `allNfts` (contract + `tokenId` on the reported chain)
and removed via a new required **`removeNft`** callback.
> 
> **BREAKING:** callers must pass `removeNft` (e.g.
`nftController.removeNft.bind(nftController)`). **Manually imported
(`custom`) and dapp-approved NFTs are never auto-removed**; only
`detected` or legacy entries without `source` can be removed. Removal is
skipped when `chainId` is missing, the NFT is not in state, or the chain
has no network client.
> 
> Changelog and broad test coverage document the behavior (mixed
sources, no-ops, unknown networks, all chains filtered out).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9101d57. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Prithpal Sooriya <prithpal.sooriya@consensys.net>
Co-authored-by: Cursor <cursoragent@cursor.com>
darkwing pushed a commit to darkwing/metamask-mobile that referenced this pull request Oct 29, 2026
…T source (MetaMask#38283)

## **Description**

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

Two changes are landing in `@metamask/assets-controllers` and this PR
adapts the client to them:

1. [MetaMask/core#8237](MetaMask/core#8237)
(breaking): `NftDetectionController` now requires a `removeNft` option.
During detection, an NFT already in state that the NFT API now flags as
spam is removed automatically. NFTs whose stored source is `custom` or
`dapp` are never auto-removed.
2. [MetaMask/core#11106](MetaMask/core#11106):
each NFT in `NftController` state now records how it was added
(`Nft.source`: `custom`, `dapp` or `detected`), and `Source` is exported
from the package.

Changes in this PR:

- `nft-detection-controller-init.ts` passes `removeNft:
nftController.removeNft.bind(nftController)` (`NftController` is already
resolved there, so no ordering change).
- `AddCustomCollectible` (the manual import flow) now passes `source:
Source.Custom` explicitly instead of relying on the default.
- The two "Refresh metadata" callers (`NftGridItemBottomSheet`,
`NftGridItemActionSheet`) now pass `source: Source.Detected`. Without
it, the default `Source.Custom` would mark refreshed detected NFTs as
manual imports, which would also protect them from spam removal.
`Source.Detected` never overwrites a stored source.
- Tests updated for the three callers and the detection controller init.

**Dependency:** both core PRs are merged and released in
`@metamask/assets-controllers@113.0.0`, which this PR bumps to
(`^113.0.0`). Verified with the real package: the touched test files and
the full type check pass.

Known behavior notes:

- `removeNft` does not add the NFT to the ignored list, so if the
backend later un-spams it, detection can re-add it (unlike the user's
"Hide" action).
- NFTs added before core records `source` have none and can still be
auto-removed.
- An open NFT details screen is a route-param snapshot, so a removed NFT
can stay on screen until the user leaves it.

## **Changelog**

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

CHANGELOG entry: Spam NFTs already in your wallet are now removed
automatically when detected

## **Related issues**

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

Fixes:
[ASSETS-4116](https://consensyssoftware.atlassian.net/browse/ASSETS-4116)
Refs: MetaMask/core#8237,
MetaMask/core#11106

## **Manual testing steps**

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

Requires the app built against the released (or locally linked)
`@metamask/assets-controllers` containing both core PRs.

```gherkin
Feature: NFT source and spam auto-removal

  Scenario: user imports an NFT manually
    Given the user is on the Add NFT screen with a valid contract address and token ID
    When user confirms the import
    Then the NFT appears in the list
    And its state entry has source "custom"

  Scenario: user refreshes metadata on a detected NFT
    Given a detected NFT is in the list
    When user opens its options and taps "Refresh metadata"
    Then its source stays "detected"

  Scenario: a detected NFT is later flagged as spam
    Given a detected NFT is in the list
    And the NFT API now returns that NFT with isSpam true
    When NFT detection runs
    Then the NFT disappears from the list

  Scenario: a manually imported NFT is flagged as spam
    Given a manually imported NFT is in the list
    And the NFT API now returns that NFT with isSpam true
    When NFT detection runs
    Then the NFT stays in the list
```

## **Screenshots/Recordings**

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

### **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
- [ ] 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)

- [ ] I've tested on Android
  - Ideally on a mid-range device; emulator is acceptable
- [ ] 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
- [ ] 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.


[ASSETS-4116]:
https://consensyssoftware.atlassian.net/browse/ASSETS-4116?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes wallet NFT state and removal rules during detection; incorrect
source tagging could remove wanted NFTs or leave spam, though scope is
limited to NFT flows and covered by tests.
> 
> **Overview**
> Bumps **`@metamask/assets-controllers`** to **^113.0.0** and adapts
the mobile client so NFT detection can **auto-remove spam NFTs** already
in the wallet, while **manual and dapp imports stay protected**.
> 
> **Engine:** `NftDetectionController` init now passes **`removeNft`**
from `NftController` (required by the new controller API).
> 
> **UI:** Manual import (`AddCustomCollectible`) passes
**`Source.Custom`**. **Refresh metadata** in the NFT grid action sheet
and bottom sheet passes **`Source.Detected`** so a refresh does not
overwrite a detected NFT’s source with the default (which would block
spam cleanup).
> 
> Changelog notes that **spam NFTs already in the wallet are removed
automatically when detected**. Tests assert the new `addNft` options and
detection init wiring.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6c98c84. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
bschorchit pushed a commit to bschorchit/metamask-extension that referenced this pull request Oct 29, 2026
…T source (MetaMask#47436)

## **Description**

> Depends on `@metamask/assets-controllers` 113.0.0 (released), which
contains [core#8237](MetaMask/core#8237) and
[core#11106](MetaMask/core#11106). The
dependency is bumped in this PR (`package.json`, `yarn.lock`, LavaMoat
policies).

Adapts the extension to two changes in `@metamask/assets-controllers`:

1. **core#8237 (breaking):** `NftDetectionController` requires a
`removeNft` option. During detection, an NFT already in state that the
API now returns as spam is removed (only if its stored source is
`detected` or unset; `custom` and `dapp` are never auto-removed). It is
not added to `ignoredNfts`, so it can come back if un-spammed.
2. **core#11106:** each NFT records a `source` (`custom`, `dapp`,
`detected`). `addNft`, `addNfts` and `addNftVerifyOwnership` default to
`Source.Custom` when it is omitted, so any caller that is not a manual
import must pass a source explicitly.

Changes:

- `nft-detection-controller-init.ts`: pass `removeNft` (same lazy
`NftController` getter as `addNfts`).
- `metamask-controller.js` `getApi`: `addNft` and
`addNftVerifyOwnership` are only called from the UI import flow, so they
now pass `Source.Custom` explicitly (same as the default, now explicit).
- `metamask-controller.js` `_updateNFTOwnership`: after a confirmed
contract interaction, NFTs transferred to the selected account are added
from the receipt logs. This is an automatic add (not a manual import),
so it now passes `Source.Detected`. Without it, the default `Custom`
would exempt these NFTs from spam removal.
- Tests for the init wiring and the three call sites.

Behavior notes for reviewers:

- The `_updateNFTOwnership` change is extension-specific (mobile has no
equivalent). NFTs added there are now spam-removable, and the `NftAdded`
event reports `source: 'detected'` instead of `'custom'` for them.
- There is no refresh-metadata `addNft` caller in the extension (mobile
had two); ownership refreshes use `checkAndUpdate*OwnershipStatus`,
which keeps the stored source.
- If an NFT is auto-removed while its details page is open, the page
redirects home (no NFT in state, no token).

Reference:
[metamask-mobile#38283](MetaMask/metamask-mobile#38283).

## **Changelog**

CHANGELOG entry: Spam NFTs already in your wallet are now removed
automatically when detected

## **Related issues**

Fixes:
[ASSETS-4116](https://consensyssoftware.atlassian.net/browse/ASSETS-4116)

Related: [core#8237](MetaMask/core#8237),
[core#11106](MetaMask/core#11106),
[metamask-mobile#38283](MetaMask/metamask-mobile#38283)

## **Manual testing steps**

1. Run the extension with NFT detection enabled and an account that
holds a detected NFT.
2. Make the NFT API flag that NFT as spam (or use a test account with a
known spam NFT already in state) and wait for the next detection run.
3. Verify the NFT disappears from the NFTs tab.
4. Import an NFT manually (NFTs tab > Import NFT) that the API flags as
spam, and run detection again. Verify it is not removed.
5. Open an NFT's details page, then trigger its removal as above. Verify
you are returned to the home screen.
6. Mint or buy an NFT through a dapp. Verify it appears after the
transaction confirms.

<!--
## **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).
- [ ] I've completed the PR template to the best of my ability
- [x] I’ve included tests if applicable
- [ ] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [ ] 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.


[ASSETS-4116]:
https://consensyssoftware.atlassian.net/browse/ASSETS-4116?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes NFT add/remove behavior and spam handling in wallet state;
wrong source tagging could remove user-imported NFTs or leave spam in
place.
> 
> **Overview**
> Bumps **`@metamask/assets-controllers`** to **113.0.0** (with LavaMoat
policy updates) and adapts the extension to NFT spam auto-removal and
per-NFT **`source`** tracking.
> 
> **`NftDetectionController`** init now passes **`removeNft`** into
**`NftController`**, matching the new required option so detection can
drop spam NFTs that were added as detected (not manual imports).
> 
> **`metamask-controller`** sets **`Source.Custom`** on UI **`addNft`**
/ **`addNftVerifyOwnership`** API paths, and **`Source.Detected`** when
NFTs are added from transaction receipt logs in
**`_updateNFTOwnership`**, so auto-added NFTs stay eligible for spam
removal instead of inheriting the default custom exemption.
> 
> Tests cover init delegation and the three source call sites.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
475d84c. 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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants