Skip to content
Open
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: 0 additions & 5 deletions eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -532,11 +532,6 @@
"count": 1
}
},
"packages/solana-wallet-snap/src/core/services/send/SendService.ts": {
"@typescript-eslint/no-unused-vars": {
"count": 1
}
},
"packages/solana-wallet-snap/src/core/services/send/SendSolBuilder.test.ts": {
"import-x/no-named-as-default": {
"count": 1
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 @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed

- 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))

## [5.0.0]

### Changed
Expand Down
2 changes: 1 addition & 1 deletion 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": "x1ofZt8S0KIVHIQv3AJyARRJNjs2dvQ8E44IW8mnugU=",
"shasum": "FsnRDiZzvrIkgP6+ieA6ti4GkrHHw5KYWxVWqTjyCnE=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
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 @@ -17,6 +17,7 @@ import {
SOLANA_MOCK_TOKEN_METADATA,
} from '../../test/mocks/asset-entities';
import { MOCK_SOLANA_KEYRING_ACCOUNT_0 } from '../../test/mocks/solana-keyring-accounts';
import type { AccountsService } from '../accounts/AccountsService';
import type { ConfigProvider } from '../config';
import type { SolanaConnection } from '../connection';
import { mockLogger } from '../mocks/logger';
Expand All @@ -35,6 +36,7 @@ describe('AssetsService', () => {
let mockConnection: SolanaConnection;
let mockConfigProvider: ConfigProvider;
let mockAssetsRepository: AssetsRepository;
let mockAccountsService: AccountsService;
let mockTokenApiClient: TokenApiClient;
let mockTokenPricesService: TokenPricesService;
let mockNftApiClient: NftApiClient;
Expand Down Expand Up @@ -81,11 +83,16 @@ describe('AssetsService', () => {
saveMany: jest.fn(),
} as unknown as AssetsRepository;

mockAccountsService = {
findById: jest.fn().mockResolvedValue(MOCK_SOLANA_KEYRING_ACCOUNT_0),
} as unknown as AccountsService;

assetsService = new AssetsService({
connection: mockConnection,
logger: mockLogger,
configProvider: mockConfigProvider,
assetsRepository: mockAssetsRepository,
accountsService: mockAccountsService,
tokenApiClient: mockTokenApiClient,
tokenPricesService: mockTokenPricesService,
cache: mockCache,
Expand Down Expand Up @@ -604,4 +611,81 @@ describe('AssetsService', () => {
expect(assets).toStrictEqual(MOCK_ASSET_ENTITIES);
});
});

describe('getAccountAssetByID', () => {
it('returns the matching asset when present', async () => {
jest
.spyOn(mockAssetsRepository, 'findByKeyringAccountId')
.mockResolvedValueOnce(MOCK_ASSET_ENTITIES);

const asset = await assetsService.getAccountAssetByID(
MOCK_SOLANA_KEYRING_ACCOUNT_0.id,
MOCK_ASSET_ENTITY_1.assetType,
);

expect(asset).toStrictEqual(MOCK_ASSET_ENTITY_1);
});

it('returns null when the asset is missing', async () => {
jest
.spyOn(mockAssetsRepository, 'findByKeyringAccountId')
.mockResolvedValueOnce([]);

const asset = await assetsService.getAccountAssetByID(
MOCK_SOLANA_KEYRING_ACCOUNT_0.id,
MOCK_ASSET_ENTITY_1.assetType,
);

expect(asset).toBeNull();
});
});

describe('getAccountAssetsByIDs', () => {
it('returns a record keyed by asset ID', async () => {
jest
.spyOn(mockAssetsRepository, 'findByKeyringAccountId')
.mockResolvedValueOnce(MOCK_ASSET_ENTITIES);

const assets = await assetsService.getAccountAssetsByIDs(
MOCK_SOLANA_KEYRING_ACCOUNT_0.id,
[MOCK_ASSET_ENTITY_0.assetType, MOCK_ASSET_ENTITY_1.assetType],
);

expect(assets).toStrictEqual({
[MOCK_ASSET_ENTITY_0.assetType]: MOCK_ASSET_ENTITY_0,
[MOCK_ASSET_ENTITY_1.assetType]: MOCK_ASSET_ENTITY_1,
});
});

it('returns null entries for missing assets', async () => {
jest
.spyOn(mockAssetsRepository, 'findByKeyringAccountId')
.mockResolvedValueOnce([MOCK_ASSET_ENTITY_0]);

const assets = await assetsService.getAccountAssetsByIDs(
MOCK_SOLANA_KEYRING_ACCOUNT_0.id,
[MOCK_ASSET_ENTITY_0.assetType, MOCK_ASSET_ENTITY_1.assetType],
);

expect(assets).toStrictEqual({
[MOCK_ASSET_ENTITY_0.assetType]: MOCK_ASSET_ENTITY_0,
[MOCK_ASSET_ENTITY_1.assetType]: null,
});
});
});

describe('getAccountAssetsByScope', () => {
it('filters account assets to the requested scope', async () => {
jest
.spyOn(mockAssetsRepository, 'findByKeyringAccountId')
.mockResolvedValueOnce(MOCK_ASSET_ENTITIES);

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

expect(assets).toStrictEqual(MOCK_ASSET_ENTITIES);
});
});
});
Loading
Loading