Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/assets-controllers/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- JWT token is included in `Authorization: Bearer <token>` header when provided
- Backward compatible: token parameter is optional and APIs work without authentication

### Fixed

- `TokenBalancesController`: state inconsistency by ensuring all account addresses are stored in lowercase format ([#7216](https://github.com/MetaMask/core/pull/7216))

## [91.0.0]

### Changed
Expand Down
50 changes: 47 additions & 3 deletions packages/assets-controllers/src/TokenBalancesController.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { deriveStateFromMetadata } from '@metamask/base-controller';
import { toHex } from '@metamask/controller-utils';
import { toChecksumHexAddress, toHex } from '@metamask/controller-utils';
import type { InternalAccount } from '@metamask/keyring-internal-api';
import {
Messenger,
Expand All @@ -11,9 +11,11 @@ import {
import type { NetworkState } from '@metamask/network-controller';
import type { PreferencesState } from '@metamask/preferences-controller';
import { CHAIN_IDS } from '@metamask/transaction-controller';
import type { Hex } from '@metamask/utils';
import BN from 'bn.js';
import { useFakeTimers } from 'sinon';

import { mockAPI_accountsAPI_MultichainAccountBalances } from './__fixtures__/account-api-v4-mocks';
import * as multicall from './multicall';
import { RpcBalanceFetcher } from './rpc-service/rpc-balance-fetcher';
import type {
Expand Down Expand Up @@ -4278,6 +4280,7 @@ describe('TokenBalancesController', () => {
ok: true,
json: () => Promise.resolve([]),
});
const originalFetch = global.fetch;
global.fetch = mockGlobalFetch;

// Create controller with accountsApiChainIds to enable AccountsApi fetcher
Expand Down Expand Up @@ -4312,8 +4315,7 @@ describe('TokenBalancesController', () => {
supportsSpy.mockRestore();
fetchSpy.mockRestore();
mockedSafelyExecuteWithTimeout.mockRestore();
// @ts-expect-error - deleting global fetch for test cleanup
delete global.fetch;
global.fetch = originalFetch;
});
});

Expand Down Expand Up @@ -5216,6 +5218,48 @@ describe('TokenBalancesController', () => {
});
});

describe('TokenBalancesController - AccountsAPI integration', () => {
const accountAddress = '0x393a8d3f7710047324d369a7cb368c0570c335b8';
const checksumAccountAddress = toChecksumHexAddress(accountAddress) as Hex;
const chainId = '0x89';

const arrange = () => {
const mockAccountsAPI =
mockAPI_accountsAPI_MultichainAccountBalances(accountAddress);

const account = createMockInternalAccount({ address: accountAddress });

const { controller } = setupController({
config: {
accountsApiChainIds: () => [chainId], // Enable Accounts API for this chain
allowExternalServices: () => true,
},
listAccounts: [account],
});

return {
mockAccountsAPI,
controller,
};
};

it('calls Accounts API and stores data with lowercased account address', async () => {
const { mockAccountsAPI, controller } = arrange();

await controller.updateBalances({
chainIds: [chainId],
queryAllAccounts: true,
});

expect(controller.state.tokenBalances[accountAddress]).toBeDefined();
expect(
controller.state.tokenBalances[checksumAccountAddress],
).toBeUndefined();

expect(mockAccountsAPI.isDone()).toBe(true);
});
});

describe('metadata', () => {
it('includes expected state in debug snapshots', () => {
const { controller } = setupController();
Expand Down
11 changes: 6 additions & 5 deletions packages/assets-controllers/src/TokenBalancesController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -756,17 +756,18 @@ export class TokenBalancesController extends StaticIntervalPollingController<{
// Update with actual fetched balances only if the value has changed
aggregated.forEach(({ success, value, account, token, chainId }) => {
if (success && value !== undefined) {
// Ensure all accounts we add/update are in lower-case
const lowerCaseAccount = account.toLowerCase() as ChecksumAddress;
const newBalance = toHex(value);
const tokenAddress = checksum(token);
const currentBalance =
d.tokenBalances[account as ChecksumAddress]?.[chainId]?.[
tokenAddress
];
d.tokenBalances[lowerCaseAccount]?.[chainId]?.[tokenAddress];

// Only update if the balance has actually changed
if (currentBalance !== newBalance) {
((d.tokenBalances[account as ChecksumAddress] ??= {})[chainId] ??=
{})[tokenAddress] = newBalance;
((d.tokenBalances[lowerCaseAccount] ??= {})[chainId] ??= {})[
tokenAddress
] = newBalance;
}
}
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import type { Hex } from '@metamask/utils';
import nock from 'nock';

export const mockResponse_accountsAPI_MultichainAccountBalances = (
accountAddress: Hex,
) => ({
count: 8,
balances: [
{
object: 'token',
address: '0x0000000000000000000000000000000000000000',
symbol: 'MATIC',
name: 'MATIC',
type: 'native',
decimals: 18,
chainId: 137,
balance: '168.699548832017288710',
accountAddress: `eip155:137:${accountAddress}`,
},
{
object: 'token',
address: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174',
name: 'USD Coin (PoS)',
symbol: 'USDC',
decimals: 6,
balance: '8.174688',
chainId: 137,
accountAddress: `eip155:137:${accountAddress}`,
},
{
object: 'token',
address: '0x53e0bca35ec356bd5dddfebbd1fc0fd03fabad39',
name: 'ChainLink Token',
symbol: 'LINK',
decimals: 18,
balance: '0.000734044925209136',
chainId: 137,
accountAddress: `eip155:137:${accountAddress}`,
},
{
object: 'token',
address: '0x6d80113e533a2c0fe82eabd35f1875dcea89ea97',
name: 'Aave Polygon WMATIC',
symbol: 'aPolWMATIC',
decimals: 18,
balance: '1.001966754893761781',
chainId: 137,
accountAddress: `eip155:137:${accountAddress}`,
},
],
unprocessedNetworks: [],
});

export const mockAPI_accountsAPI_MultichainAccountBalances = (
accountAddress: Hex,
) =>
nock('https://accounts.api.cx.metamask.io/v4/multiaccount/balances')
.get('')
.query({
accountAddresses: `eip155:137:${accountAddress}`,
})
.reply(
200,
mockResponse_accountsAPI_MultichainAccountBalances(accountAddress),
);
Loading