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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
],
"files": [],
"scripts": {
"build": "yarn workspaces foreach --all --no-private --parallel --interlaced --verbose run build",
"build": "yarn workspaces foreach --all --no-private --parallel --topological-dev --interlaced --verbose run build",
"build:clean": "yarn build:only-clean && yarn build",
"build:docs": "yarn workspaces foreach --all --no-private --parallel --interlaced --verbose run build:docs",
"build:only-clean": "rimraf -g 'packages/*/dist'",
Expand Down
4 changes: 4 additions & 0 deletions packages/solana-wallet-snap/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- Hardcode Solana fungible asset reads through `AssetsProvider` / `mapControllerAsset` (no migration-stage or remote feature-flag routing). Disable Snap fungible tracking in `fetch`/`save`/`saveMany` and account sync; Snap-owned NFT assets still use `SnapAssetsAdapter`.
- Wire Core messenger plumbing (`endowment:messenger`, `AssetsProvider`) into the Solana snap.
- Extract Snap-owned balance fetch/persist/read logic into `SnapAssetsAdapter`; `AssetsService` delegates account asset reads and saves 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 `getAccountAssetsForAllActiveScopes`, and routing Keyring, Send, send render, and `refreshSend` through them (still Snap-owned storage). ([#120](https://github.com/MetaMask/internal-snaps/pull/120))
- This package was migrated from [snap-solana-wallet](https://github.com/MetaMask/snap-solana-wallet). See the source repository for the original [changelog](https://github.com/MetaMask/snap-solana-wallet/blob/main/packages/snap/CHANGELOG.md). ([#72](https://github.com/MetaMask/internal-snaps/pull/72))

[Unreleased]: https://github.com/MetaMask/internal-snaps/
32 changes: 32 additions & 0 deletions packages/solana-wallet-snap/jest.setup.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,46 @@
import { jest } from '@jest/globals';
import type { SimulationUserOptions } from '@metamask/snaps-simulation';
import BigNumber from 'bignumber.js';
import dotenv from 'dotenv';

import { registerCoreAssetsControllerHandlers } from './src/core/test/helpers/registerCoreAssetsControllerHandlers';
import logger from './src/core/utils/logger';

dotenv.config();

// Lowest precision we ever go for: MicroLamports represented in Sol amount
BigNumber.config({ EXPONENTIAL_AT: 16 });

type SnapsTestEnvironment = {
installSnap: (
snapId?: string,
options?: { options?: SimulationUserOptions },
) => Promise<{
controllerMessenger: Parameters<
typeof registerCoreAssetsControllerHandlers
>[0];
}>;
};

const { snapsEnvironment } = globalThis as {
snapsEnvironment?: SnapsTestEnvironment;
};

if (snapsEnvironment) {
const originalInstallSnap =
snapsEnvironment.installSnap.bind(snapsEnvironment);
jest
.spyOn(snapsEnvironment, 'installSnap')
.mockImplementation(async (snapId, options = {}) => {
const installed = await originalInstallSnap(snapId, options);
registerCoreAssetsControllerHandlers(
installed.controllerMessenger,
options.options ?? {},
);
return installed;
});
}

// Mock the console methods
jest.spyOn(logger, 'log').mockImplementation(() => {
/* no-op */
Expand Down
3 changes: 3 additions & 0 deletions packages/solana-wallet-snap/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,13 @@
},
"devDependencies": {
"@jest/globals": "^29.5.0",
"@metamask/assets-controller": "^13.0.0",
"@metamask/auto-changelog": "^6.1.1",
"@metamask/key-tree": "9.1.2",
"@metamask/keyring-api": "^23.7.0",
"@metamask/keyring-snap-sdk": "^9.2.1",
"@metamask/messenger": "^2.0.0",
"@metamask/snap-networks-utils": "workspace:^",
"@metamask/snaps-cli": "^8.4.1",
"@metamask/snaps-jest": "^10.2.0",
"@metamask/snaps-sdk": "^11.2.0",
Expand Down
11 changes: 9 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": "ml2uYEdvkS+53VKce/0XkF/NIeewCD/1X9MbwndcV1M=",
"shasum": "8pC/CUT1b2BVxIsPy6IWJQ8SMrFeW13nBhWeWKriNUs=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down Expand Up @@ -88,7 +88,14 @@
"snap_manageAccounts": {},
"snap_manageState": {},
"snap_dialog": {},
"snap_getPreferences": {}
"snap_getPreferences": {},
"endowment:messenger": {
"actions": [
"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,4 +1,10 @@
import { assetsService, priceApiClient, state } from '../../../../snapContext';
import {
accountsService,
assetsService,
configProvider,
priceApiClient,
state,
} from '../../../../snapContext';
import { KnownCaip19Id } from '../../../constants/solana';
import { trackError } from '../../../utils/errors';
import {
Expand Down Expand Up @@ -33,9 +39,15 @@ jest.mock('../../../../features/send/Send', () => ({
}));

jest.mock('../../../../snapContext', () => ({
assetsService: {
accountsService: {
getAll: jest.fn(),
},
assetsService: {
getAccountAssetsByScope: jest.fn(),
},
configProvider: {
getActiveNetworks: jest.fn(),
},
priceApiClient: {
getMultipleSpotPrices: jest.fn(),
},
Expand All @@ -50,7 +62,13 @@ const setupTest = () => {
request: jest.fn(),
};

(assetsService.getAll as jest.Mock).mockResolvedValue([
(accountsService.getAll as jest.Mock).mockResolvedValue([
{ id: 'account-1' },
]);
(configProvider.getActiveNetworks as jest.Mock).mockResolvedValue([
'solana:mainnet',
]);
(assetsService.getAccountAssetsByScope as jest.Mock).mockResolvedValue([
{
assetType: KnownCaip19Id.SolMainnet,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ import type { OnCronjobHandler } from '@metamask/snaps-sdk';
import { DEFAULT_SEND_CONTEXT } from '../../../../features/send/render';
import { Send } from '../../../../features/send/Send';
import type { SendContext } from '../../../../features/send/types';
import { assetsService, priceApiClient, state } from '../../../../snapContext';
import {
assetsService,
configProvider,
priceApiClient,
state,
accountsService,
} from '../../../../snapContext';
import type { UnencryptedStateValue } from '../../../services/state/State';
import { trackError } from '../../../utils/errors';
import {
Expand All @@ -19,13 +25,25 @@ export const refreshSend: OnCronjobHandler = async () => {

logger.info(`Background event triggered`);

const [assets, mapInterfaceNameToId, preferences] = await Promise.all([
assetsService.getAll(),
state.getKey<UnencryptedStateValue['mapInterfaceNameToId']>(
'mapInterfaceNameToId',
),
getPreferences().catch(() => DEFAULT_SEND_CONTEXT.preferences),
]);
const [accounts, activeNetworks, mapInterfaceNameToId, preferences] =
await Promise.all([
accountsService.getAll(),
configProvider.getActiveNetworks(),
state.getKey<UnencryptedStateValue['mapInterfaceNameToId']>(
'mapInterfaceNameToId',
),
getPreferences().catch(() => DEFAULT_SEND_CONTEXT.preferences),
]);

const assets = (
await Promise.all(
accounts.flatMap((account) =>
activeNetworks.map((network) =>
assetsService.getAccountAssetsByScope(network, account.id),
),
),
)
).flat();

const assetTypes = assets.flatMap((asset) => asset.assetType);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ describe('SolanaKeyring', () => {
mockAssetsService = {
fetch: jest.fn().mockResolvedValue(MOCK_ASSET_ENTITIES),
saveMany: jest.fn(),
findByAccount: jest.fn(),
getAccountAssetsForAllActiveScopes: jest.fn(),
getAccountAssetsByIDs: jest.fn(),
getNativeAssetTypes: jest
.fn()
.mockReturnValue([KnownCaip19Id.SolMainnet]),
Expand Down Expand Up @@ -143,7 +144,7 @@ describe('SolanaKeyring', () => {
describe('getAccountAssets', () => {
it('calls the assets service', async () => {
jest
.spyOn(mockAssetsService, 'findByAccount')
.spyOn(mockAssetsService, 'getAccountAssetsForAllActiveScopes')
.mockResolvedValue(MOCK_ASSET_ENTITIES);

const result = await keyring.getAccountAssets(
Expand All @@ -158,10 +159,12 @@ describe('SolanaKeyring', () => {
});

it('removes token assets with zero balance', async () => {
jest.spyOn(mockAssetsService, 'findByAccount').mockResolvedValue([
MOCK_ASSET_ENTITY_1, // Token asset with non-zero balance
{ ...MOCK_ASSET_ENTITY_2, rawAmount: '0' }, // Token asset with zero balance
]);
jest
.spyOn(mockAssetsService, 'getAccountAssetsForAllActiveScopes')
.mockResolvedValue([
MOCK_ASSET_ENTITY_1, // Token asset with non-zero balance
{ ...MOCK_ASSET_ENTITY_2, rawAmount: '0' }, // Token asset with zero balance
]);

const result = await keyring.getAccountAssets(
MOCK_SOLANA_KEYRING_ACCOUNT_0.id,
Expand All @@ -171,10 +174,12 @@ describe('SolanaKeyring', () => {
});

it('keeps the native asset even if it has zero balance', async () => {
jest.spyOn(mockAssetsService, 'findByAccount').mockResolvedValue([
{ ...MOCK_ASSET_ENTITY_0, rawAmount: '0' }, // Native asset with zero balance
{ ...MOCK_ASSET_ENTITY_1, rawAmount: '0' }, // Token asset with zero balance
]);
jest
.spyOn(mockAssetsService, 'getAccountAssetsForAllActiveScopes')
.mockResolvedValue([
{ ...MOCK_ASSET_ENTITY_0, rawAmount: '0' }, // Native asset with zero balance
{ ...MOCK_ASSET_ENTITY_1, rawAmount: '0' }, // Token asset with zero balance
]);

const result = await keyring.getAccountAssets(
MOCK_SOLANA_KEYRING_ACCOUNT_0.id,
Expand Down Expand Up @@ -343,9 +348,9 @@ describe('SolanaKeyring', () => {
symbol: 4,
} as unknown as AssetEntity;

jest
.spyOn(mockAssetsService, 'findByAccount')
.mockResolvedValue([invalidAsset]);
jest.spyOn(mockAssetsService, 'getAccountAssetsByIDs').mockResolvedValue({
[KnownCaip19Id.SolMainnet]: invalidAsset,
});

await expect(
keyring.getAccountBalances(MOCK_SOLANA_KEYRING_ACCOUNT_1.id, [
Expand All @@ -355,10 +360,13 @@ describe('SolanaKeyring', () => {
});

it('removes token assets with zero balance', async () => {
jest.spyOn(mockAssetsService, 'findByAccount').mockResolvedValue([
MOCK_ASSET_ENTITY_1, // Token asset with non-zero balance
{ ...MOCK_ASSET_ENTITY_2, rawAmount: '0' }, // Token asset with zero balance
]);
jest.spyOn(mockAssetsService, 'getAccountAssetsByIDs').mockResolvedValue({
[MOCK_ASSET_ENTITY_1.assetType]: MOCK_ASSET_ENTITY_1,
[MOCK_ASSET_ENTITY_2.assetType]: {
...MOCK_ASSET_ENTITY_2,
rawAmount: '0',
},
});

const result = await keyring.getAccountBalances(
MOCK_SOLANA_KEYRING_ACCOUNT_0.id,
Expand All @@ -374,10 +382,16 @@ describe('SolanaKeyring', () => {
});

it('keeps the native asset even if it has zero balance', async () => {
jest.spyOn(mockAssetsService, 'findByAccount').mockResolvedValue([
{ ...MOCK_ASSET_ENTITY_0, rawAmount: '0' }, // Native asset with zero balance
{ ...MOCK_ASSET_ENTITY_1, rawAmount: '0' }, // Token asset with zero balance
]);
jest.spyOn(mockAssetsService, 'getAccountAssetsByIDs').mockResolvedValue({
[MOCK_ASSET_ENTITY_0.assetType]: {
...MOCK_ASSET_ENTITY_0,
rawAmount: '0',
},
[MOCK_ASSET_ENTITY_1.assetType]: {
...MOCK_ASSET_ENTITY_1,
rawAmount: '0',
},
});

const result = await keyring.getAccountBalances(
MOCK_SOLANA_KEYRING_ACCOUNT_0.id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -413,9 +413,10 @@ export class SolanaKeyring implements KeyringSnapRpc {
try {
validateRequest({ accountId }, ListAccountAssetsStruct);

const account = await this.getAccountOrThrow(accountId);
await this.getAccountOrThrow(accountId);

const assetEntities = await this.#assetsService.findByAccount(account);
const assetEntities =
await this.#assetsService.getAccountAssetsForAllActiveScopes(accountId);

const result = assetEntities
// Remove token assets with zero balance
Expand Down Expand Up @@ -448,10 +449,15 @@ export class SolanaKeyring implements KeyringSnapRpc {
try {
validateRequest({ accountId, assets }, GetAccountBalancesStruct);

const account = await this.getAccountOrThrow(accountId);
await this.getAccountOrThrow(accountId);

const assetsById = await this.#assetsService.getAccountAssetsByIDs(
accountId,
assets,
);

const assetsToUse = (await this.#assetsService.findByAccount(account))
.filter((asset) => assets.includes(asset.assetType))
const assetsToUse = Object.values(assetsById)
.filter((asset): asset is NonNullable<typeof asset> => asset !== null)
// Remove token assets with zero balance
.filter(
(asset) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,13 @@ export class AccountsSynchronizer {
const assets = (
await Promise.allSettled(
accountsToSync.map(async (account) =>
this.#assetsService.fetch(account),
this.#assetsService.getAccountAssetsForAllActiveScopes(account.id),
),
)
)
.map((item) => (item.status === 'fulfilled' ? item.value : []))
.flat();

await this.#assetsService.saveMany(assets);

const transactions =
await this.#transactionsService.fetchAssetsTransactions(assets, {
limit: 20,
Expand Down
Loading
Loading