Skip to content
Draft
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
5 changes: 1 addition & 4 deletions eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -353,13 +353,10 @@
"count": 2
}
},
"packages/solana-wallet-snap/src/core/services/assets/AssetsService.ts": {
"packages/solana-wallet-snap/src/core/services/assets/adapters/SnapAssetsAdapter.ts": {
"@typescript-eslint/await-thenable": {
"count": 1
},
"@typescript-eslint/explicit-function-return-type": {
"count": 10
},
"no-unused-private-class-members": {
"count": 2
}
Expand Down
6 changes: 6 additions & 0 deletions packages/solana-wallet-snap/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add a read-only `CoreAssetsAdapter` and `mapControllerAsset` for AssetsController integration (wired unused until routing lands), including Core messenger plumbing (`coreMessenger`, `RemoteFeatureFlagsProvider`, `AssetsProvider`). Solana has no snap-owned assets, so the adapter does not fetch, persist, or publish balances, and the mapper does not derive associated token account addresses. ([#122](https://github.com/MetaMask/internal-snaps/pull/122))

### Changed

- Route Solana asset reads through `CoreAssetsAdapter` when the assets migration feature flag is active. Fetch and save become no-ops (Solana has no snap-owned assets), and `KeyringAccountMonitor` stops persisting balances from websocket notifications. ([#123](https://github.com/MetaMask/internal-snaps/pull/123))
- Extract Snap-owned assets domain logic into `SnapAssetsAdapter`; `AssetsService` is a thin facade that delegates metadata, market data, fetch, persist, and account asset reads through the adapter (no Core routing yet). ([#121](https://github.com/MetaMask/internal-snaps/pull/121))
- Align `AssetsService` read API with `snap-networks-utils` / AssetsController shapes by adding `getAccountAssetByID`, `getAccountAssetsByIDs`, `getAccountAssetsByScope`, and `getAccountAssets`, and routing Keyring and Send through them (still Snap-owned storage). ([#120](https://github.com/MetaMask/internal-snaps/pull/120))

## [6.0.0]
Expand Down
4 changes: 4 additions & 0 deletions packages/solana-wallet-snap/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,14 @@
},
"devDependencies": {
"@jest/globals": "^29.5.0",
"@metamask/assets-controller": "^13.0.0",
"@metamask/auto-changelog": "^6.1.1",
"@metamask/key-tree": "^10.1.1",
"@metamask/keyring-api": "^23.7.0",
"@metamask/keyring-snap-sdk": "^9.2.1",
"@metamask/messenger": "^2.0.0",
"@metamask/remote-feature-flag-controller": "^5.0.0",
"@metamask/snap-networks-utils": "^1.0.0",
"@metamask/snaps-cli": "^8.4.1",
"@metamask/snaps-jest": "^10.2.0",
"@metamask/snaps-sdk": "^11.2.0",
Expand Down
12 changes: 10 additions & 2 deletions packages/solana-wallet-snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/MetaMask/internal-snaps.git"
},
"source": {
"shasum": "YaPEFBNuMbbASorQCj4MFJKRSlqOjSOqJoOGUB9ET2I=",
"shasum": "SWB+3GxlGtesIJB2wxYfykU0SmJbn6oonAilJxUEqBk=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down Expand Up @@ -88,7 +88,15 @@
"snap_manageAccounts": {},
"snap_manageState": {},
"snap_dialog": {},
"snap_getPreferences": {}
"snap_getPreferences": {},
"endowment:messenger": {
"actions": [
"RemoteFeatureFlagController:getState",
"AssetsController:getAccountAssetByID",
"AssetsController:getAccountAssetsByIDs",
"AssetsController:getAccountAssetsByScope"
]
}
},
"platformVersion": "11.2.0",
"manifestVersion": "0.1"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import {
SNAPS_ASSETS_MIGRATION_FLAG_KEYS,
SnapsAssetsMigrationStage,
} from '@metamask/assets-controller';
import { KeyringEvent } from '@metamask/keyring-api';
import { emitSnapKeyringEvent } from '@metamask/keyring-snap-sdk';
import type { RemoteFeatureFlagsProvider } from '@metamask/snap-networks-utils';
import { cloneDeep } from 'lodash';

import type { ICache } from '../../caching/ICache';
import { InMemoryCache } from '../../caching/InMemoryCache';
import { MOCK_NFTS_LIST_RESPONSE_MAPPED } from '../../clients/nft-api/mocks/mockNftsListResponseMapped';
import type { NftApiClient } from '../../clients/nft-api/NftApiClient';
import type { TokenApiClient } from '../../clients/token-api-client/TokenApiClient';
import { Network } from '../../constants/solana';
import { KnownCaip19Id, Network } from '../../constants/solana';
import type { Serializable } from '../../serialization/types';
import {
MOCK_ASSET_ENTITIES,
Expand All @@ -24,6 +29,8 @@ import { mockLogger } from '../mocks/logger';
import { createMockConnection } from '../mocks/mockConnection';
import { MOCK_SOLANA_RPC_GET_TOKEN_ACCOUNTS_BY_OWNER_RESPONSE } from '../mocks/mockSolanaRpcResponses';
import type { TokenPricesService } from '../token-prices/TokenPrices';
import { CoreAssetsAdapter } from './adapters/CoreAssetsAdapter';
import { SnapAssetsAdapter } from './adapters/SnapAssetsAdapter';
import type { AssetsRepository } from './AssetsRepository';
import { AssetsService } from './AssetsService';

Expand All @@ -33,6 +40,9 @@ jest.mock('@metamask/keyring-snap-sdk', () => ({

describe('AssetsService', () => {
let assetsService: AssetsService;
let snapAssetsAdapter: SnapAssetsAdapter;
let coreAdapter: CoreAssetsAdapter;
let mockGetFeatureFlag: jest.Mock;
let mockConnection: SolanaConnection;
let mockConfigProvider: ConfigProvider;
let mockAssetsRepository: AssetsRepository;
Expand All @@ -42,6 +52,10 @@ describe('AssetsService', () => {
let mockNftApiClient: NftApiClient;
let mockCache: ICache<Serializable>;

const setMigrationStage = (stage: SnapsAssetsMigrationStage): void => {
mockGetFeatureFlag.mockResolvedValue({ stage });
};

beforeEach(() => {
jest.clearAllMocks();
mockConnection = createMockConnection();
Expand Down Expand Up @@ -87,7 +101,7 @@ describe('AssetsService', () => {
findById: jest.fn().mockResolvedValue(MOCK_SOLANA_KEYRING_ACCOUNT_0),
} as unknown as AccountsService;

assetsService = new AssetsService({
snapAssetsAdapter = new SnapAssetsAdapter({
connection: mockConnection,
logger: mockLogger,
configProvider: mockConfigProvider,
Expand All @@ -98,6 +112,27 @@ describe('AssetsService', () => {
cache: mockCache,
nftApiClient: mockNftApiClient,
});

coreAdapter = new CoreAssetsAdapter({
getAccountAssetByID: jest.fn().mockResolvedValue(null),
getAccountAssetsByIDs: jest.fn().mockResolvedValue({}),
getAccountAssetsByScope: jest.fn().mockResolvedValue({}),
findAccountById: mockAccountsService.findById.bind(mockAccountsService),
getActiveNetworks:
mockConfigProvider.getActiveNetworks.bind(mockConfigProvider),
});

mockGetFeatureFlag = jest.fn().mockResolvedValue({
stage: SnapsAssetsMigrationStage.Off,
});

assetsService = new AssetsService({
snapAdapter: snapAssetsAdapter,
coreAdapter,
remoteFeatureFlagsProvider: {
getFeatureFlag: mockGetFeatureFlag,
} as unknown as RemoteFeatureFlagsProvider,
});
});

describe('fetch', () => {
Expand Down Expand Up @@ -173,6 +208,45 @@ describe('AssetsService', () => {
});
});

describe('getAssetsMetadata', () => {
it('fetches token metadata from the token API client', async () => {
const tokenAssetTypes = [
MOCK_ASSET_ENTITY_1.assetType,
MOCK_ASSET_ENTITY_2.assetType,
];

const metadata = await assetsService.getAssetsMetadata(tokenAssetTypes);

expect(mockTokenApiClient.getTokensMetadata).toHaveBeenCalledWith(
tokenAssetTypes,
);
expect(metadata).toStrictEqual(SOLANA_MOCK_TOKEN_METADATA);
});
});

describe('fetchAssetsMarketData', () => {
it('delegates to the token prices service', async () => {
const assets = [
{
asset: MOCK_ASSET_ENTITY_0.assetType,
unit: MOCK_ASSET_ENTITY_0.assetType,
},
];
const expected = { [MOCK_ASSET_ENTITY_0.assetType]: {} };

jest
.spyOn(mockTokenPricesService, 'getMultipleTokensMarketData')
.mockResolvedValueOnce(expected as never);

const result = await assetsService.fetchAssetsMarketData(assets);

expect(
mockTokenPricesService.getMultipleTokensMarketData,
).toHaveBeenCalledWith(assets);
expect(result).toStrictEqual(expected);
});
});

describe('save', () => {
it('saves an asset', async () => {
const spy = jest
Expand Down Expand Up @@ -768,4 +842,122 @@ describe('AssetsService', () => {
).not.toHaveBeenCalled();
});
});

describe('assets migration', () => {
const accountId = MOCK_SOLANA_KEYRING_ACCOUNT_0.id;
const activeMigrationStage =
SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback;

it('routes getAccountAssetByID through Core when migration is active', async () => {
setMigrationStage(activeMigrationStage);
jest
.spyOn(coreAdapter, 'getAccountAssetByID')
.mockResolvedValue(MOCK_ASSET_ENTITY_0);

const asset = await assetsService.getAccountAssetByID(
accountId,
KnownCaip19Id.SolMainnet,
);

expect(coreAdapter.getAccountAssetByID).toHaveBeenCalledWith(
accountId,
KnownCaip19Id.SolMainnet,
);
expect(asset).toStrictEqual(MOCK_ASSET_ENTITY_0);
});

it('routes getAccountAssetsByIDs through Core when migration is active', async () => {
setMigrationStage(activeMigrationStage);
jest.spyOn(coreAdapter, 'getAccountAssetsByIDs').mockResolvedValue({
[KnownCaip19Id.SolMainnet]: MOCK_ASSET_ENTITY_0,
[KnownCaip19Id.UsdcMainnet]: MOCK_ASSET_ENTITY_1,
});

const results = await assetsService.getAccountAssetsByIDs(accountId, [
KnownCaip19Id.SolMainnet,
KnownCaip19Id.UsdcMainnet,
]);

expect(coreAdapter.getAccountAssetsByIDs).toHaveBeenCalledWith(
accountId,
[KnownCaip19Id.SolMainnet, KnownCaip19Id.UsdcMainnet],
);
expect(results[KnownCaip19Id.SolMainnet]).toStrictEqual(
MOCK_ASSET_ENTITY_0,
);
expect(results[KnownCaip19Id.UsdcMainnet]).toStrictEqual(
MOCK_ASSET_ENTITY_1,
);
});

it('routes getAccountAssetsByScope through Core when migration is active', async () => {
setMigrationStage(activeMigrationStage);
jest
.spyOn(coreAdapter, 'getAccountAssetsByScope')
.mockResolvedValue([MOCK_ASSET_ENTITY_0]);

const assets = await assetsService.getAccountAssetsByScope(
Network.Mainnet,
accountId,
);

expect(coreAdapter.getAccountAssetsByScope).toHaveBeenCalledWith(
Network.Mainnet,
accountId,
);
expect(assets).toStrictEqual([MOCK_ASSET_ENTITY_0]);
});

it('routes getAccountAssets through Core when migration is active', async () => {
setMigrationStage(activeMigrationStage);
jest
.spyOn(coreAdapter, 'getAccountAssets')
.mockResolvedValue([MOCK_ASSET_ENTITY_0]);

const assets = await assetsService.getAccountAssets(accountId);

expect(coreAdapter.getAccountAssets).toHaveBeenCalledWith(accountId);
expect(assets).toStrictEqual([MOCK_ASSET_ENTITY_0]);
});

it('returns no assets from fetch when migration is active', async () => {
setMigrationStage(activeMigrationStage);
const snapFetchSpy = jest.spyOn(snapAssetsAdapter, 'fetch');

const assets = await assetsService.fetch(MOCK_SOLANA_KEYRING_ACCOUNT_0);

expect(snapFetchSpy).not.toHaveBeenCalled();
expect(assets).toStrictEqual([]);
});

it('does not persist or emit when saveMany is called and migration is active', async () => {
setMigrationStage(activeMigrationStage);

await assetsService.saveMany([MOCK_ASSET_ENTITY_0]);

expect(mockAssetsRepository.saveMany).not.toHaveBeenCalled();
expect(emitSnapKeyringEvent).not.toHaveBeenCalled();
});

it('reports Core assets as active when the migration flag is on', async () => {
setMigrationStage(activeMigrationStage);

expect(await assetsService.isUsingCoreAssets()).toBe(true);
});

it('reports Core assets as inactive when the migration flag is off', async () => {
expect(await assetsService.isUsingCoreAssets()).toBe(false);
});

it('reads the Solana migration flag key', async () => {
setMigrationStage(activeMigrationStage);
jest.spyOn(coreAdapter, 'getAccountAssets').mockResolvedValue([]);

await assetsService.getAccountAssets(accountId);

expect(mockGetFeatureFlag).toHaveBeenCalledWith(
SNAPS_ASSETS_MIGRATION_FLAG_KEYS.solana,
);
});
});
});
Loading
Loading