Skip to content

fix: guard RpcDataSource against invalid decimals to prevent NaN bala…#8781

Merged
salimtb merged 5 commits into
mainfrom
fix/rpc-datasource-invalid-decimals-guard
May 13, 2026
Merged

fix: guard RpcDataSource against invalid decimals to prevent NaN bala…#8781
salimtb merged 5 commits into
mainfrom
fix/rpc-datasource-invalid-decimals-guard

Conversation

@salimtb
Copy link
Copy Markdown
Contributor

@salimtb salimtb commented May 12, 2026

…nces

Two fixes that together stop entries like
eip155:4326/erc20:0x000…000: { amount: "NaN" } from leaking into assetsBalance.

  • #collectMetadataForBalances: only reuse existing native metadata when it has finite decimals (via new #hasValidDecimals helper). Empty name/symbol are still accepted, and decimals: 0 is valid. Bad state metadata (e.g. { decimals: null, name: '', symbol: '', type: 'native' }) is replaced by the chain-status stub so the pipeline resolves a usable decimals.

  • #convertToHumanReadable: defensively return '0' when decimals isn't a finite non-negative number or when rawBalance can't be parsed. Defaulting decimals to a fixed value (e.g. 18) would silently produce wrong amounts; '0' matches the existing safe fallback used in the error path.

Adds 7 tests covering the bug payload (decimals: null), NaN decimals, negative decimals, non-numeric raw balance, and the decimals: 0 / missing name/symbol valid cases.

Explanation

References

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
Touches balance formatting and native metadata selection in RpcDataSource, which can affect emitted assetsBalance/assetsInfo values across chains and accounts. Changes are defensive and well-tested but could alter behavior for edge-case metadata payloads.

Overview
Prevents RpcDataSource from emitting { amount: "NaN" } (or silently wrong '0') balances when native asset metadata in state contains invalid decimals.

Native metadata reuse is now gated by a new #hasValidDecimals (finite, non-negative; 0 allowed), otherwise falling back to the chain-status stub, and decimals selection no longer uses ??—a new #pickValidDecimals skips NaN/negative values so stale state can’t shadow valid pipeline metadata.

#convertToHumanReadable now returns '0' when decimals is invalid or the raw balance is unparsable, and the PR adds focused unit tests covering null/NaN/negative decimals and invalid raw balances (plus valid decimals: 0 cases).

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

salimtb added 2 commits May 12, 2026 19:25
…nces

Two fixes that together stop entries like
`eip155:4326/erc20:0x000…000: { amount: "NaN" }` from leaking into
`assetsBalance`.

- `#collectMetadataForBalances`: only reuse existing native metadata when
  it has finite `decimals` (via new `#hasValidDecimals` helper). Empty
  `name`/`symbol` are still accepted, and `decimals: 0` is valid. Bad
  state metadata (e.g. `{ decimals: null, name: '', symbol: '', type:
  'native' }`) is replaced by the chain-status stub so the pipeline
  resolves a usable `decimals`.

- `#convertToHumanReadable`: defensively return `'0'` when `decimals`
  isn't a finite non-negative number or when `rawBalance` can't be
  parsed. Defaulting decimals to a fixed value (e.g. 18) would silently
  produce wrong amounts; `'0'` matches the existing safe fallback used
  in the error path.

Adds 7 tests covering the bug payload (`decimals: null`), `NaN`
decimals, negative decimals, non-numeric raw balance, and the
`decimals: 0` / missing `name`/`symbol` valid cases.
@salimtb salimtb marked this pull request as ready for review May 12, 2026 22:17
@salimtb salimtb requested review from a team as code owners May 12, 2026 22:17
@salimtb salimtb temporarily deployed to default-branch May 12, 2026 22:17 — with GitHub Actions Inactive
Copy link
Copy Markdown

@cursor cursor Bot left a comment

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 and found 2 potential issues.

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 7e44e16. Configure here.

Comment thread packages/assets-controller/src/data-sources/RpcDataSource.ts
Comment thread packages/assets-controller/src/data-sources/RpcDataSource.ts
salimtb added 3 commits May 13, 2026 00:40
This update introduces a new helper method, `#pickValidDecimals`, to ensure that the first valid `decimals` value is selected from metadata sources, preventing stale `decimals: NaN` entries from shadowing valid values. The `#handleBalanceUpdate` method has been updated to utilize this helper, ensuring accurate balance calculations. Additionally, the changelog has been updated to reflect these changes and their implications for balance handling.
…lances

This update enhances the `#hasValidDecimals` guard to ensure that only finite and non-negative `decimals` values are accepted for balance calculations. It prevents stale metadata with negative decimals from affecting balance resolution, ensuring that the chain-status stub is used correctly. Additionally, tests have been added to verify this behavior, and the changelog has been updated accordingly.
This update refines the `#hasValidDecimals` method by consolidating the validation logic for asset metadata decimals into a single line. This change enhances code readability while maintaining the existing functionality that ensures only valid, non-negative decimals are accepted.
@salimtb salimtb added this pull request to the merge queue May 13, 2026
Merged via the queue into main with commit 11747b8 May 13, 2026
366 checks passed
@salimtb salimtb deleted the fix/rpc-datasource-invalid-decimals-guard branch May 13, 2026 08:18
pull Bot pushed a commit to Reality2byte/metamask-extension that referenced this pull request May 14, 2026
<!--
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**

patch assets controller 7.0.0

core PRs: 

- MetaMask/core#8789
- MetaMask/core#8781
- MetaMask/core#8786

<!--
Write a short description of the changes included in this pull request,
also include relevant motivation and context. Have in mind the following
questions:
1. What is the reason for the change?
2. What is the improvement/solution?
-->

## **Changelog**

<!--
If this PR is not End-User-Facing and should not show up in the
CHANGELOG, you can choose to either:
1. Write `CHANGELOG entry: null`
2. Label with `no-changelog`

If this PR is End-User-Facing, please write a short User-Facing
description in the past tense like:
`CHANGELOG entry: Added a new tab for users to see their NFTs`
`CHANGELOG entry: Fixed a bug that was causing some NFTs to flicker`

(This helps the Release Engineer do their job more quickly and
accurately)
-->

CHANGELOG entry:  patch assets controller 7.0.0

## **Related issues**

Fixes:

## **Manual testing steps**

1. Go to this page...
2.
3.

## **Screenshots/Recordings**

<!-- If applicable, add screenshots and/or recordings to visualize the
before and after of your change. -->

### **Before**

<!-- [screenshots/recordings] -->

### **After**

<!-- [screenshots/recordings] -->

## **Pre-merge author checklist**

- [ ] 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
- [ ] 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.




<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches token/native balance normalization and default asset metadata
keying; mistakes could lead to incorrect balances or duplicate/missing
asset entries in state.
> 
> **Overview**
> Applies a Yarn patch override for `@metamask/assets-controller@7.0.0`
and updates the lockfile to use the patched package.
> 
> The patch tightens `RpcDataSource` balance conversion by validating
`decimals` and raw balances (defaulting invalid values to `"0"`), and
only reuses existing asset metadata when it has valid `decimals` (with a
helper to pick the first valid decimals source).
> 
> It also standardizes default/native asset identifiers: `mUSD` defaults
now use an EIP-55 checksummed address and `DEFAULT_ASSET_METADATA` keys
are stored/queried as checksummed CAIP-19 IDs (no `.toLowerCase()`), and
`buildNativeAssetsFromConstant` now runs IDs through `normalizeAssetId`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
58b729d. 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