From c4d76460cebd9a2f8d96fc6e5e1561c747dea666 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 5 Aug 2026 08:15:12 +0000 Subject: [PATCH 1/2] fix(tron-wallet-snap): update manifest shasum after rebase onto main Co-authored-by: Ulisses Ferreira --- packages/tron-wallet-snap/CHANGELOG.md | 1 - packages/tron-wallet-snap/package.json | 2 +- packages/tron-wallet-snap/snap.manifest.json | 2 +- yarn.lock | 4 ++-- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/tron-wallet-snap/CHANGELOG.md b/packages/tron-wallet-snap/CHANGELOG.md index 14fa407b..a10c6ddd 100644 --- a/packages/tron-wallet-snap/CHANGELOG.md +++ b/packages/tron-wallet-snap/CHANGELOG.md @@ -12,7 +12,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **BREAKING** Implement Keyring API v2 (`KeyringSnapRpc` interface): rename `listAccounts` → `getAccounts`, `listAccountAssets` → `getAccountAssets`, `listAccountTransactions` → `getAccountTransactions`; `getAccount` now throws instead of returning `undefined`; add `exportAccount` with hexadecimal private key export using `sensitive()` for redaction; remove v1-only methods `createAccount`, `discoverAccounts`, `filterAccountChains`, and `updateAccount`. ([#56](https://github.com/MetaMask/internal-snaps/pull/56)) - Add `bip44:discover` support to `createAccounts`: checks on-chain activity across all Tron networks before persisting; returns `[]` if no activity to signal end-of-discovery to the client. ([#56](https://github.com/MetaMask/internal-snaps/pull/56)) - Add `endowment:keyring` capabilities to manifest declaring the `tron:728126428` scope, hexadecimal private key export, and BIP-44 derivation strategies. ([#56](https://github.com/MetaMask/internal-snaps/pull/56)) -- Wire Core messenger endowment and instantiate `RemoteFeatureFlagsProvider` and `AssetsProvider` from `@metamask/snap-networks-utils` v1.0.0 (plumbing only; no Core routing yet). ### Fixed diff --git a/packages/tron-wallet-snap/package.json b/packages/tron-wallet-snap/package.json index 922e9242..80e93ce6 100644 --- a/packages/tron-wallet-snap/package.json +++ b/packages/tron-wallet-snap/package.json @@ -55,7 +55,7 @@ "@metamask/keyring-snap-sdk": "^9.2.1", "@metamask/messenger": "^2.0.0", "@metamask/remote-feature-flag-controller": "4.2.2", - "@metamask/snap-networks-utils": "workspace:^", + "@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", diff --git a/packages/tron-wallet-snap/snap.manifest.json b/packages/tron-wallet-snap/snap.manifest.json index 2d2e9bf9..d0e732b9 100644 --- a/packages/tron-wallet-snap/snap.manifest.json +++ b/packages/tron-wallet-snap/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/internal-snaps.git" }, "source": { - "shasum": "uocZF1RsEzCWGmRM3X3mMv42laNfJWpwVXOfNViikl8=", + "shasum": "geU/HB4DiYL7nfzl4H/b5S+2xUmrtCAoqvvoqMN2+qQ=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/yarn.lock b/yarn.lock index c0b103b1..de86c7ed 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3312,7 +3312,7 @@ __metadata: languageName: node linkType: hard -"@metamask/snap-networks-utils@workspace:^, @metamask/snap-networks-utils@workspace:packages/snap-networks-utils": +"@metamask/snap-networks-utils@npm:1.0.0, @metamask/snap-networks-utils@workspace:packages/snap-networks-utils": version: 0.0.0-use.local resolution: "@metamask/snap-networks-utils@workspace:packages/snap-networks-utils" dependencies: @@ -3787,7 +3787,7 @@ __metadata: "@metamask/keyring-snap-sdk": "npm:^9.2.1" "@metamask/messenger": "npm:^2.0.0" "@metamask/remote-feature-flag-controller": "npm:4.2.2" - "@metamask/snap-networks-utils": "workspace:^" + "@metamask/snap-networks-utils": "npm:1.0.0" "@metamask/snaps-cli": "npm:^8.4.1" "@metamask/snaps-jest": "npm:^10.2.0" "@metamask/snaps-sdk": "npm:^11.2.0" From ea6cdf431ea9364bc41492ac21df3239d3c77e15 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 5 Aug 2026 10:16:29 +0000 Subject: [PATCH 2/2] refactor(tron-wallet-snap): simplify AssetsService read routing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebase onto latest WPN-1497-messenger-plumbing and simplify asset read routing per review feedback: - Remove private provider indirection helpers; inline AssetsProvider calls - Route all asset reads (including snap-owned) by migration stage only - Use early return: Off → SnapAssetsAdapter, otherwise → AssetsProvider - Drop ReadAssetsControllerWithFallback try/catch fallback paths - Update tests to match unified controller read path Co-authored-by: Ulisses Ferreira --- packages/tron-wallet-snap/CHANGELOG.md | 7 +- packages/tron-wallet-snap/package.json | 7 +- packages/tron-wallet-snap/snap.manifest.json | 23 +- packages/tron-wallet-snap/src/context.ts | 2 + .../src/handlers/keyring/keyring.test.ts | 10 +- .../src/handlers/keyring/keyring.ts | 5 +- .../src/services/assets/AssetsService.test.ts | 903 +++++++++++++----- .../src/services/assets/AssetsService.ts | 177 +++- .../assets/adapters/SnapAssetsAdapter.ts | 188 ++-- .../assets/mapControllerAsset.test.ts | 84 ++ .../src/services/assets/mapControllerAsset.ts | 35 + .../src/types/core-messenger.ts | 5 + 12 files changed, 1105 insertions(+), 341 deletions(-) create mode 100644 packages/tron-wallet-snap/src/services/assets/mapControllerAsset.test.ts create mode 100644 packages/tron-wallet-snap/src/services/assets/mapControllerAsset.ts diff --git a/packages/tron-wallet-snap/CHANGELOG.md b/packages/tron-wallet-snap/CHANGELOG.md index a10c6ddd..36d23e9c 100644 --- a/packages/tron-wallet-snap/CHANGELOG.md +++ b/packages/tron-wallet-snap/CHANGELOG.md @@ -12,11 +12,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **BREAKING** Implement Keyring API v2 (`KeyringSnapRpc` interface): rename `listAccounts` → `getAccounts`, `listAccountAssets` → `getAccountAssets`, `listAccountTransactions` → `getAccountTransactions`; `getAccount` now throws instead of returning `undefined`; add `exportAccount` with hexadecimal private key export using `sensitive()` for redaction; remove v1-only methods `createAccount`, `discoverAccounts`, `filterAccountChains`, and `updateAccount`. ([#56](https://github.com/MetaMask/internal-snaps/pull/56)) - Add `bip44:discover` support to `createAccounts`: checks on-chain activity across all Tron networks before persisting; returns `[]` if no activity to signal end-of-discovery to the client. ([#56](https://github.com/MetaMask/internal-snaps/pull/56)) - Add `endowment:keyring` capabilities to manifest declaring the `tron:728126428` scope, hexadecimal private key export, and BIP-44 derivation strategies. ([#56](https://github.com/MetaMask/internal-snaps/pull/56)) +- Wire Core messenger endowment and instantiate `RemoteFeatureFlagsProvider` and `AssetsProvider` from `@metamask/snap-networks-utils` v1.0.0 (plumbing only; no Core routing yet). +- Route asset reads through the shared `AssetsProvider` from `@metamask/snap-networks-utils` using account-scoped `AssetsController:getAccountAssetByID`, `AssetsController:getAccountAssetsByIDs`, and `AssetsController:getAccountAssetsByScope` actions when the migration stage is not `Off`. Snap-owned assets remain synced by the Snap but are read through the same controller path as fungibles. Resolution order: remote feature flags → Off default. -### Fixed +### Changed -- Fix `bip44:discover` always failing due to `Network` enum being compiled bidirectionally by TypeScript when initialised from another enum's members, causing `Object.values(Network)` to include human-readable names (`"Mainnet"` etc.) alongside scope IDs; replaced enum initialisers with string literals so TypeScript emits a one-way mapping. ([#101](https://github.com/MetaMask/internal-snaps/pull/101)) -- Fix `submitRequest` returning a v1 `KeyringResponse` envelope `{ pending: false, result: ... }` instead of raw `Json`; the Keyring API v2 `SnapKeyring` calls the snap directly and expects unwrapped `Json` back. ([#105](https://github.com/MetaMask/internal-snaps/pull/105)) +- Update `snap.manifest.json` bundle shasum ([#82](https://github.com/MetaMask/internal-snaps/pull/82)) ## [2.0.0] diff --git a/packages/tron-wallet-snap/package.json b/packages/tron-wallet-snap/package.json index 80e93ce6..75bec324 100644 --- a/packages/tron-wallet-snap/package.json +++ b/packages/tron-wallet-snap/package.json @@ -47,6 +47,9 @@ "test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose", "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch" }, + "dependencies": { + "@metamask/snap-networks-utils": "workspace:^" + }, "devDependencies": { "@metamask/assets-controller": "^13.0.0", "@metamask/auto-changelog": "^6.1.1", @@ -55,12 +58,12 @@ "@metamask/keyring-snap-sdk": "^9.2.1", "@metamask/messenger": "^2.0.0", "@metamask/remote-feature-flag-controller": "4.2.2", - "@metamask/snap-networks-utils": "1.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", "@metamask/superstruct": "^3.4.1", - "@types/lodash": "^4.17.15", + "@types/lodash": "^4.14.191", "async-mutex": "^0.5.0", "bignumber.js": "^9.3.1", "concurrently": "^10.0.3", diff --git a/packages/tron-wallet-snap/snap.manifest.json b/packages/tron-wallet-snap/snap.manifest.json index d0e732b9..8d39f0b4 100644 --- a/packages/tron-wallet-snap/snap.manifest.json +++ b/packages/tron-wallet-snap/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/internal-snaps.git" }, "source": { - "shasum": "geU/HB4DiYL7nfzl4H/b5S+2xUmrtCAoqvvoqMN2+qQ=", + "shasum": "m1aV5aLS2glLsXdoHzUjoFUieyH4oUKiyzocw5VdWXY=", "location": { "npm": { "filePath": "dist/bundle.js", @@ -23,22 +23,7 @@ }, "initialPermissions": { "endowment:keyring": { - "allowedOrigins": ["https://portfolio.metamask.io"], - "capabilities": { - "scopes": ["tron:728126428"], - "privateKey": { - "exportFormats": [ - { - "encoding": "hexadecimal" - } - ] - }, - "bip44": { - "deriveIndex": true, - "deriveIndexRange": true, - "discover": true - } - } + "allowedOrigins": ["https://portfolio.metamask.io"] }, "snap_getBip32Entropy": [ { @@ -66,10 +51,10 @@ }, "endowment:messenger": { "actions": [ - "RemoteFeatureFlagController:getState", "AssetsController:getAccountAssetByID", "AssetsController:getAccountAssetsByIDs", - "AssetsController:getAccountAssetsByScope" + "AssetsController:getAccountAssetsByScope", + "RemoteFeatureFlagController:getState" ] } }, diff --git a/packages/tron-wallet-snap/src/context.ts b/packages/tron-wallet-snap/src/context.ts index ec9d12dd..a4e3df64 100644 --- a/packages/tron-wallet-snap/src/context.ts +++ b/packages/tron-wallet-snap/src/context.ts @@ -117,6 +117,8 @@ const assetsService = new AssetsService({ priceApiClient, tokenApiClient, snapClient, + coreMessenger, + assetsProvider, }); const transactionsService = new TransactionsService({ diff --git a/packages/tron-wallet-snap/src/handlers/keyring/keyring.test.ts b/packages/tron-wallet-snap/src/handlers/keyring/keyring.test.ts index 47fd5452..9a8a74f4 100644 --- a/packages/tron-wallet-snap/src/handlers/keyring/keyring.test.ts +++ b/packages/tron-wallet-snap/src/handlers/keyring/keyring.test.ts @@ -130,7 +130,10 @@ describe('KeyringHandler', () => { const result = await keyringHandler.submitRequest(request); - expect(result).toStrictEqual({ signature: '0xsignature123' }); + expect(result).toStrictEqual({ + pending: false, + result: { signature: '0xsignature123' }, + }); expect(mockAccountsService.findById).toHaveBeenCalledWith( mockAccount.id, ); @@ -221,7 +224,10 @@ describe('KeyringHandler', () => { const result = await keyringHandler.submitRequest(request); - expect(result).toStrictEqual({ signature: '0xsignature123' }); + expect(result).toStrictEqual({ + pending: false, + result: { signature: '0xsignature123' }, + }); // The request reaching confirmation keeps the dApp's original payload. expect( mockConfirmationHandler.handleKeyringRequest, diff --git a/packages/tron-wallet-snap/src/handlers/keyring/keyring.ts b/packages/tron-wallet-snap/src/handlers/keyring/keyring.ts index 2c9b0b43..cf388d0d 100644 --- a/packages/tron-wallet-snap/src/handlers/keyring/keyring.ts +++ b/packages/tron-wallet-snap/src/handlers/keyring/keyring.ts @@ -7,6 +7,7 @@ import type { CreateAccountOptions as KeyringBatchCreateAccountOptions, KeyringAccount, KeyringRequest, + KeyringResponse, Pagination, ResolvedAccountAddress, Transaction, @@ -395,8 +396,8 @@ export class KeyringHandler implements KeyringSnapRpc { } } - async submitRequest(request: KeyringRequest): Promise { - return this.#handleSubmitRequest(request); + async submitRequest(request: KeyringRequest): Promise { + return { pending: false, result: await this.#handleSubmitRequest(request) }; } #prepareRequestForConfirmation( diff --git a/packages/tron-wallet-snap/src/services/assets/AssetsService.test.ts b/packages/tron-wallet-snap/src/services/assets/AssetsService.test.ts index 549b55ec..5e185983 100644 --- a/packages/tron-wallet-snap/src/services/assets/AssetsService.test.ts +++ b/packages/tron-wallet-snap/src/services/assets/AssetsService.test.ts @@ -1,7 +1,14 @@ +import type { Asset, Caip19AssetId } from '@metamask/assets-controller'; +import { + SNAPS_ASSETS_MIGRATION_FLAG_KEYS, + SnapsAssetsMigrationStage, +} from '@metamask/assets-controller'; import type { KeyringAccount } from '@metamask/keyring-api'; import { KeyringEvent } from '@metamask/keyring-api'; import { emitSnapKeyringEvent } from '@metamask/keyring-snap-sdk'; +import { AssetsProvider } from '@metamask/snap-networks-utils'; +import { MOCK_EXCHANGE_RATES } from '../../clients/price-api/mocks/exchange-rates'; import type { PriceApiClient } from '../../clients/price-api/PriceApiClient'; import type { SpotPrices } from '../../clients/price-api/types'; import type { SnapClient } from '../../clients/snap/SnapClient'; @@ -9,9 +16,10 @@ import type { TokenApiClient } from '../../clients/token-api/TokenApiClient'; import type { AccountResources, TronHttpClient } from '../../clients/tron-http'; import { TrongridAccountNotFoundError } from '../../clients/trongrid/errors'; import type { TrongridApiClient } from '../../clients/trongrid/TrongridApiClient'; -import type { Trc20Balance, TronAccount } from '../../clients/trongrid/types'; -import { KnownCaip19Id, Network } from '../../constants'; +import type { TronAccount } from '../../clients/trongrid/types'; +import { KnownCaip19Id, Network, SNAP_OWNED_ASSETS } from '../../constants'; import type { AssetEntity } from '../../entities/assets'; +import type { CoreMessengerCaller } from '../../types/core-messenger'; import { mockLogger } from '../../utils/mockLogger'; import type { AssetsRepository } from './AssetsRepository'; import type { NativeCaipAssetType, TokenCaipAssetType } from './types'; @@ -51,6 +59,89 @@ jest.mock('@metamask/keyring-snap-sdk', () => ({ // eslint-disable-next-line @typescript-eslint/no-require-imports const { AssetsService } = require('./AssetsService'); +const TRON_FLAG_KEY = SNAPS_ASSETS_MIGRATION_FLAG_KEYS.tron; + +function createMessengerCallMock( + getState: () => unknown, + getAccountAssetByID: jest.Mock, + getAccountAssetsByIDs: jest.Mock = jest.fn().mockResolvedValue({}), + getAccountAssetsByScope: jest.Mock = jest.fn().mockResolvedValue({}), +): CoreMessengerCaller['call'] { + return async (actionType, ...args) => { + switch (actionType) { + case 'RemoteFeatureFlagController:getState': + return getState() as Awaited>; + case 'AssetsController:getAccountAssetByID': + return getAccountAssetByID(...args); + case 'AssetsController:getAccountAssetsByIDs': + return getAccountAssetsByIDs(...args); + case 'AssetsController:getAccountAssetsByScope': + return getAccountAssetsByScope(...args); + default: + return undefined; + } + }; +} + +function restoreMigrationStageEnv( + originalEnvironment: string | undefined, + originalStage: string | undefined, +): void { + /* eslint-disable n/no-process-env */ + if (originalEnvironment === undefined) { + delete process.env.ENVIRONMENT; + } else { + process.env.ENVIRONMENT = originalEnvironment; + } + delete process.env.TRON_ASSETS_MIGRATION_STAGE; + if (originalStage !== undefined) { + process.env.TRON_ASSETS_MIGRATION_STAGE = originalStage; + } + /* eslint-enable n/no-process-env */ +} + +function buildControllerAsset( + assetId: string, + amount: string, + metadata: { + symbol: string; + name: string; + decimals: number; + image?: string; + }, +): Asset { + return { + id: assetId as Asset['id'], + chainId: Network.Mainnet as Asset['chainId'], + balance: { amount }, + metadata: { + type: 'fungible', + symbol: metadata.symbol, + name: metadata.name, + decimals: metadata.decimals, + image: metadata.image, + }, + price: { price: 0, lastUpdated: 0 }, + fiatValue: 0, + } as Asset; +} + +/** + * Builds a SpotPrices map for test mocks. + * + * @param entries - Map of asset ID to price info. + * @returns SpotPrices object. + */ +const createSpotPrices = ( + entries: Record, +): SpotPrices => + Object.fromEntries( + Object.entries(entries).map(([key, value]) => [ + key, + { id: value.id, price: value.price }, + ]), + ); + const mockAccount: KeyringAccount = { id: 'test-account-id', address: 'TGJn1wnUYHJbvN88cynZbsAz2EMeZq73yx', @@ -72,22 +163,6 @@ const emptyAccountResources: AccountResources = { TotalEnergyWeight: 0, }; -/** - * Creates properly typed SpotPrices for tests. - * - * @param entries - Map of asset ID to price info. - * @returns SpotPrices object. - */ -const createSpotPrices = ( - entries: Record, -): SpotPrices => - Object.fromEntries( - Object.entries(entries).map(([key, value]) => [ - key, - { id: value.id, price: value.price }, - ]), - ); - /** * Creates a properly typed TronAccount for tests. * Uses snake_case property names to match Tron API response format. @@ -187,6 +262,8 @@ type WithAssetsServiceCallback = (payload: { >; mockTokenApiClient: jest.Mocked>; mockSnapClient: jest.Mocked>; + mockCoreMessenger: jest.Mocked; + setMigrationStage: (stage: SnapsAssetsMigrationStage) => void; }) => Promise | ReturnValue; /** @@ -259,6 +336,33 @@ async function withAssetsService( trackError: jest.fn().mockResolvedValue(undefined), }; + const mockGetAccountAssetByID = jest.fn(); + const mockGetAccountAssetsByIDs = jest.fn().mockResolvedValue({}); + const mockGetAccountAssetsByScope = jest.fn().mockResolvedValue({}); + let migrationStage = SnapsAssetsMigrationStage.Off; + const mockCoreMessenger: jest.Mocked = { + call: jest.fn().mockImplementation( + createMessengerCallMock( + () => ({ + remoteFeatureFlags: { + [TRON_FLAG_KEY]: { stage: migrationStage }, + }, + }), + mockGetAccountAssetByID, + mockGetAccountAssetsByIDs, + mockGetAccountAssetsByScope, + ), + ), + }; + + const setMigrationStage = (stage: SnapsAssetsMigrationStage): void => { + migrationStage = stage; + }; + + const assetsProvider = new AssetsProvider({ + messenger: mockCoreMessenger as never, + }); + const assetsService = new AssetsService({ logger: mockLogger, assetsRepository: mockAssetsRepository, @@ -268,6 +372,8 @@ async function withAssetsService( priceApiClient: mockPriceApiClient, tokenApiClient: mockTokenApiClient, snapClient: mockSnapClient, + coreMessenger: mockCoreMessenger, + assetsProvider, }); return await testFunction({ @@ -279,6 +385,8 @@ async function withAssetsService( mockPriceApiClient, mockTokenApiClient, mockSnapClient, + mockCoreMessenger, + setMigrationStage, }); } @@ -292,7 +400,9 @@ describe('AssetsService', () => { mockTrongridApiClient, mockTronHttpClient, mockPriceApiClient, + setMigrationStage, }) => { + setMigrationStage(SnapsAssetsMigrationStage.Off); mockTrongridApiClient.getAccountInfoByAddress.mockRejectedValue( new TrongridAccountNotFoundError(), ); @@ -330,10 +440,8 @@ describe('AssetsService', () => { expect(trxAsset).toBeDefined(); expect(trxAsset?.rawAmount).toBe('0'); - const expectedTrc20AssetType = `${String(Network.Mainnet)}/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t`; const trc20Asset = assets.find( - (asset: AssetEntity) => - asset.assetType === expectedTrc20AssetType, + (asset: AssetEntity) => asset.assetType === trc20AssetId, ); expect(trc20Asset).toBeDefined(); expect(trc20Asset?.rawAmount).toBe('24249143'); @@ -341,22 +449,23 @@ describe('AssetsService', () => { ); }); - it('returns zero TRX and resources when fallback also returns empty', async () => { + it('skips TRC20 fallback and returns protocol assets only when mode is controller', async () => { await withAssetsService( async ({ assetsService, mockTrongridApiClient, mockTronHttpClient, + setMigrationStage, }) => { + setMigrationStage( + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + ); mockTrongridApiClient.getAccountInfoByAddress.mockRejectedValue( new TrongridAccountNotFoundError(), ); mockTronHttpClient.getAccountResources.mockResolvedValue( emptyAccountResources, ); - mockTrongridApiClient.getTrc20BalancesByAddress.mockResolvedValue( - [], - ); const assets = await assetsService.fetchAssetsAndBalancesForAccount( Network.Mainnet, @@ -365,99 +474,74 @@ describe('AssetsService', () => { expect( mockTrongridApiClient.getTrc20BalancesByAddress, - ).toHaveBeenCalledWith(Network.Mainnet, mockAccount.address); - - const trxAsset = assets.find( - (asset: AssetEntity) => - asset.assetType === KnownCaip19Id.TrxMainnet, - ); - expect(trxAsset).toBeDefined(); - expect(trxAsset?.rawAmount).toBe('0'); - - const bandwidthAsset = assets.find( - (asset: AssetEntity) => - asset.assetType === KnownCaip19Id.BandwidthMainnet, - ); - const energyAsset = assets.find( - (asset: AssetEntity) => - asset.assetType === KnownCaip19Id.EnergyMainnet, - ); - expect(bandwidthAsset).toBeDefined(); - expect(energyAsset).toBeDefined(); + ).not.toHaveBeenCalled(); + expect( + assets.every((asset: AssetEntity) => + SNAP_OWNED_ASSETS.includes(asset.assetType), + ), + ).toBe(true); + expect( + assets.some( + (asset: AssetEntity) => + asset.assetType === KnownCaip19Id.TrxMainnet, + ), + ).toBe(false); }, ); }); - it('gracefully handles fallback endpoint failure', async () => { + it('returns protocol resources when inactive account has empty resources', async () => { await withAssetsService( async ({ assetsService, mockTrongridApiClient, mockTronHttpClient, + setMigrationStage, }) => { + setMigrationStage( + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + ); mockTrongridApiClient.getAccountInfoByAddress.mockRejectedValue( new TrongridAccountNotFoundError(), ); mockTronHttpClient.getAccountResources.mockResolvedValue( emptyAccountResources, ); - mockTrongridApiClient.getTrc20BalancesByAddress.mockRejectedValue( - new Error('Network error'), - ); const assets = await assetsService.fetchAssetsAndBalancesForAccount( Network.Mainnet, mockAccount, ); - const trxAsset = assets.find( - (asset: AssetEntity) => - asset.assetType === KnownCaip19Id.TrxMainnet, - ); - expect(trxAsset).toBeDefined(); - expect(trxAsset?.rawAmount).toBe('0'); - }, - ); - }); - - it('tracks fallback endpoint errors', async () => { - await withAssetsService( - async ({ - assetsService, - mockSnapClient, - mockTrongridApiClient, - mockTronHttpClient, - }) => { - const error = new Error('Network error'); + expect( + mockTrongridApiClient.getTrc20BalancesByAddress, + ).not.toHaveBeenCalled(); - mockTrongridApiClient.getAccountInfoByAddress.mockRejectedValue( - new Error('Account not found or no data returned'), - ); - mockTronHttpClient.getAccountResources.mockResolvedValue( - emptyAccountResources, - ); - mockTrongridApiClient.getTrc20BalancesByAddress.mockRejectedValue( - error, + const bandwidthAsset = assets.find( + (asset: AssetEntity) => + asset.assetType === KnownCaip19Id.BandwidthMainnet, ); - - await assetsService.fetchAssetsAndBalancesForAccount( - Network.Mainnet, - mockAccount, + const energyAsset = assets.find( + (asset: AssetEntity) => + asset.assetType === KnownCaip19Id.EnergyMainnet, ); - - expect(mockSnapClient.trackError).toHaveBeenCalledWith(error); + expect(bandwidthAsset).toBeDefined(); + expect(energyAsset).toBeDefined(); }, ); }); - it('filters out TRC20 tokens without price data from inactive account', async () => { + it('returns protocol assets when inactive account info fails', async () => { await withAssetsService( async ({ assetsService, mockTrongridApiClient, mockTronHttpClient, - mockPriceApiClient, + setMigrationStage, }) => { + setMigrationStage( + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + ); mockTrongridApiClient.getAccountInfoByAddress.mockRejectedValue( new TrongridAccountNotFoundError(), ); @@ -465,51 +549,34 @@ describe('AssetsService', () => { emptyAccountResources, ); - const trc20BalancesWithSpam: Trc20Balance[] = [ - { TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t: '24249143' }, // USDT - has price - { TSpamToken123456789: '1000000000' }, // Spam token - no price - ]; - mockTrongridApiClient.getTrc20BalancesByAddress.mockResolvedValue( - trc20BalancesWithSpam, - ); - - const usdtAssetId = `${String(Network.Mainnet)}/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t`; - mockPriceApiClient.getMultipleSpotPrices.mockResolvedValue( - createSpotPrices({ - [usdtAssetId]: { id: usdtAssetId, price: 1.0 }, - }), - ); - const assets = await assetsService.fetchAssetsAndBalancesForAccount( Network.Mainnet, mockAccount, ); - const usdtAssetType = `${String(Network.Mainnet)}/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t`; - const usdtAsset = assets.find( - (asset: AssetEntity) => asset.assetType === usdtAssetType, - ); - expect(usdtAsset).toBeDefined(); - - const spamAssetType = `${String(Network.Mainnet)}/trc20:TSpamToken123456789`; - const spamAsset = assets.find( - (asset: AssetEntity) => asset.assetType === spamAssetType, - ); - expect(spamAsset).toBeUndefined(); + expect(assets.length).toBeGreaterThan(0); + expect( + assets.every((asset: AssetEntity) => + SNAP_OWNED_ASSETS.includes(asset.assetType), + ), + ).toBe(true); }, ); }); }); describe('partial failure handling', () => { - it('uses fallback when account info fails even if resources succeed (inactive account)', async () => { + it('returns protocol assets when account info fails even if resources succeed (inactive account)', async () => { await withAssetsService( async ({ assetsService, mockTrongridApiClient, mockTronHttpClient, - mockPriceApiClient, + setMigrationStage, }) => { + setMigrationStage( + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + ); mockTrongridApiClient.getAccountInfoByAddress.mockRejectedValue( new TrongridAccountNotFoundError(), ); @@ -520,20 +587,6 @@ describe('AssetsService', () => { EnergyLimit: 0, }); - const trc20Balances = [ - { TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t: '100000' }, - ]; - mockTrongridApiClient.getTrc20BalancesByAddress.mockResolvedValue( - trc20Balances, - ); - - const trc20AssetId = `${String(Network.Mainnet)}/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t`; - mockPriceApiClient.getMultipleSpotPrices.mockResolvedValue( - createSpotPrices({ - [trc20AssetId]: { id: trc20AssetId, price: 1.0 }, - }), - ); - const assets = await assetsService.fetchAssetsAndBalancesForAccount( Network.Mainnet, mockAccount, @@ -541,20 +594,19 @@ describe('AssetsService', () => { expect( mockTrongridApiClient.getTrc20BalancesByAddress, - ).toHaveBeenCalledWith(Network.Mainnet, mockAccount.address); + ).not.toHaveBeenCalled(); + expect( + assets.every((asset: AssetEntity) => + SNAP_OWNED_ASSETS.includes(asset.assetType), + ), + ).toBe(true); - const trxAsset = assets.find( + const bandwidthAsset = assets.find( (asset: AssetEntity) => - asset.assetType === KnownCaip19Id.TrxMainnet, - ); - expect(trxAsset).toBeDefined(); - expect(trxAsset?.rawAmount).toBe('0'); - - const trc20Asset = assets.find( - (asset: AssetEntity) => asset.assetType === trc20AssetId, + asset.assetType === KnownCaip19Id.BandwidthMainnet, ); - expect(trc20Asset).toBeDefined(); - expect(trc20Asset?.rawAmount).toBe('100000'); + expect(bandwidthAsset).toBeDefined(); + expect(bandwidthAsset?.rawAmount).toBe('600'); }, ); }); @@ -565,7 +617,11 @@ describe('AssetsService', () => { assetsService, mockTrongridApiClient, mockTronHttpClient, + setMigrationStage, }) => { + setMigrationStage( + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + ); mockTrongridApiClient.getAccountInfoByAddress.mockResolvedValue( createMockTronAccount({ address: mockAccount.address, @@ -582,12 +638,12 @@ describe('AssetsService', () => { mockAccount, ); - const trxAsset = assets.find( - (asset: AssetEntity) => - asset.assetType === KnownCaip19Id.TrxMainnet, - ); - expect(trxAsset).toBeDefined(); - expect(trxAsset?.rawAmount).toBe('1000000'); + expect( + assets.some( + (asset: AssetEntity) => + asset.assetType === KnownCaip19Id.TrxMainnet, + ), + ).toBe(false); const bandwidthAsset = assets.find( (asset: AssetEntity) => @@ -598,38 +654,6 @@ describe('AssetsService', () => { }, ); }); - - it('tracks spot price errors', async () => { - await withAssetsService( - async ({ - assetsService, - mockSnapClient, - mockTrongridApiClient, - mockTronHttpClient, - mockPriceApiClient, - }) => { - const error = new Error('Spot price endpoint unavailable'); - - mockTrongridApiClient.getAccountInfoByAddress.mockResolvedValue( - createMockTronAccount({ - address: mockAccount.address, - balance: 1000000, - }), - ); - mockTronHttpClient.getAccountResources.mockResolvedValue( - emptyAccountResources, - ); - mockPriceApiClient.getMultipleSpotPrices.mockRejectedValue(error); - - await assetsService.fetchAssetsAndBalancesForAccount( - Network.Mainnet, - mockAccount, - ); - - expect(mockSnapClient.trackError).toHaveBeenCalledWith(error); - }, - ); - }); }); describe('bandwidth', () => { @@ -1518,7 +1542,6 @@ describe('AssetsService', () => { assets: { [mockAccount.id]: { added: expect.arrayContaining([ - KnownCaip19Id.TrxMainnet, KnownCaip19Id.EnergyMainnet, KnownCaip19Id.BandwidthMainnet, ]), @@ -1634,9 +1657,6 @@ describe('AssetsService', () => { [mockAccount.id]: savedAssets, }); - // If an asset is missing from the received list - // - emits the event 'notify:accountAssetListUpdated' with the asset in the 'removed' property - // - emits the event 'notify:accountBalancesUpdated' with the balance for the removed asset sets to 0 await assetsService.saveMany(updatedAssets); expect(mockAssetsRepository.saveMany).toHaveBeenCalledWith( @@ -1725,7 +1745,6 @@ describe('AssetsService', () => { assets: { [mockAccount.id]: { added: expect.arrayContaining([ - KnownCaip19Id.TrxMainnet, KnownCaip19Id.MaximumEnergyMainnet, KnownCaip19Id.MaximumBandwidthMainnet, ]), @@ -1786,7 +1805,6 @@ describe('AssetsService', () => { assets: { [mockAccount.id]: { added: expect.arrayContaining([ - KnownCaip19Id.TrxMainnet, KnownCaip19Id.TrxStakedForBandwidthMainnet, KnownCaip19Id.TrxStakedForEnergyMainnet, ]), @@ -1837,7 +1855,6 @@ describe('AssetsService', () => { assets: { [mockAccount.id]: { added: expect.arrayContaining([ - KnownCaip19Id.TrxMainnet, KnownCaip19Id.TrxReadyForWithdrawalMainnet, ]), removed: [], @@ -1915,7 +1932,6 @@ describe('AssetsService', () => { assets: { [mockAccount.id]: { added: expect.arrayContaining([ - KnownCaip19Id.TrxMainnet, KnownCaip19Id.EnergyMainnet, ]), removed: [], @@ -1992,7 +2008,6 @@ describe('AssetsService', () => { assets: { [mockAccount.id]: { added: expect.arrayContaining([ - KnownCaip19Id.TrxMainnet, KnownCaip19Id.BandwidthMainnet, ]), removed: [], @@ -2190,10 +2205,8 @@ describe('AssetsService', () => { assets: { [mockAccount.id]: { added: expect.arrayContaining([ - KnownCaip19Id.TrxMainnet, KnownCaip19Id.EnergyMainnet, KnownCaip19Id.BandwidthMainnet, - trc20AssetId, ]), removed: [], }, @@ -2269,7 +2282,6 @@ describe('AssetsService', () => { assets: { [mockAccount.id]: { added: expect.arrayContaining([ - KnownCaip19Id.TrxMainnet, KnownCaip19Id.TrxStakedForEnergyMainnet, ]), removed: [], @@ -2831,8 +2843,478 @@ describe('AssetsService', () => { }); }); + describe('getAssetsMetadata', () => { + it('resolves metadata for native, protocol, and token asset types', async () => { + await withAssetsService(async ({ assetsService, mockTokenApiClient }) => { + const trc20 = + `${Network.Mainnet}/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` as TokenCaipAssetType; + const trc10 = `${Network.Mainnet}/trc10:1002000` as TokenCaipAssetType; + + mockTokenApiClient.getTokensMetadata.mockResolvedValue({ + [trc20]: { + fungible: { symbol: 'USDT', name: 'Tether', decimals: 6 }, + }, + [trc10]: { + fungible: { symbol: 'T', name: 'Token', decimals: 0 }, + }, + } as never); + + const assetTypes = [ + KnownCaip19Id.TrxMainnet, + KnownCaip19Id.TrxStakedForBandwidthMainnet, + KnownCaip19Id.TrxStakedForEnergyMainnet, + KnownCaip19Id.TrxReadyForWithdrawalMainnet, + KnownCaip19Id.TrxInLockPeriodMainnet, + KnownCaip19Id.TrxStakingRewardsMainnet, + KnownCaip19Id.EnergyMainnet, + KnownCaip19Id.MaximumEnergyMainnet, + KnownCaip19Id.BandwidthMainnet, + KnownCaip19Id.MaximumBandwidthMainnet, + trc10, + trc20, + ]; + + const metadata = await assetsService.getAssetsMetadata(assetTypes); + + expect(metadata[KnownCaip19Id.TrxMainnet]?.symbol).toBe('TRX'); + expect(metadata[KnownCaip19Id.EnergyMainnet]?.symbol).toBe('ENERGY'); + expect(metadata[trc20]?.fungible?.symbol).toBe('USDT'); + expect(mockTokenApiClient.getTokensMetadata).toHaveBeenCalledWith([ + trc10, + trc20, + ]); + }); + }); + }); + + describe('assets migration mode', () => { + const accountId = mockAccount.id; + const fungibleAssetId = KnownCaip19Id.TrxMainnet; + const snapAssetId = KnownCaip19Id.EnergyMainnet; + + it('fetchAssetsAndBalancesForAccount returns fungibles when mode is snap', async () => { + await withAssetsService( + async ({ + assetsService, + mockTrongridApiClient, + mockTronHttpClient, + setMigrationStage, + }) => { + setMigrationStage(SnapsAssetsMigrationStage.Off); + mockTrongridApiClient.getAccountInfoByAddress.mockResolvedValue( + createMockTronAccount({ + address: mockAccount.address, + balance: 1_000_000, + }), + ); + mockTronHttpClient.getAccountResources.mockResolvedValue( + emptyAccountResources, + ); + + const assets = await assetsService.fetchAssetsAndBalancesForAccount( + Network.Mainnet, + mockAccount, + ); + + expect( + assets.some( + (asset: AssetEntity) => asset.assetType === fungibleAssetId, + ), + ).toBe(true); + }, + ); + }); + + it('fetchAssetsAndBalancesForAccount returns protocol assets only when mode is controller', async () => { + await withAssetsService( + async ({ + assetsService, + mockTrongridApiClient, + mockTronHttpClient, + setMigrationStage, + }) => { + setMigrationStage( + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + ); + mockTrongridApiClient.getAccountInfoByAddress.mockResolvedValue( + createMockTronAccount({ + address: mockAccount.address, + balance: 1_000_000, + trc20: [{ TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t: '1000' }], + }), + ); + mockTronHttpClient.getAccountResources.mockResolvedValue( + emptyAccountResources, + ); + + const assets = await assetsService.fetchAssetsAndBalancesForAccount( + Network.Mainnet, + mockAccount, + ); + + expect( + assets.every((asset: AssetEntity) => + SNAP_OWNED_ASSETS.includes(asset.assetType), + ), + ).toBe(true); + expect( + assets.some( + (asset: AssetEntity) => asset.assetType === fungibleAssetId, + ), + ).toBe(false); + }, + ); + }); + + it('routes snap-owned reads through the repository', async () => { + await withAssetsService( + async ({ assetsService, mockAssetsRepository, mockCoreMessenger }) => { + const snapAsset: AssetEntity = { + assetType: snapAssetId, + keyringAccountId: accountId, + network: Network.Mainnet, + symbol: 'ENERGY', + decimals: 0, + rawAmount: '100', + uiAmount: '100', + iconUrl: '', + }; + mockAssetsRepository.getByAccountIdAndAssetType.mockResolvedValue( + snapAsset, + ); + + const asset = await assetsService.getAccountAssetByID( + accountId, + snapAssetId, + ); + + expect(asset).toStrictEqual(snapAsset); + expect(mockCoreMessenger.call).not.toHaveBeenCalledWith( + 'AssetsController:getAccountAssetByID', + expect.anything(), + expect.anything(), + ); + }, + ); + }); + + it('routes fungible reads through AssetsController when mode is controller', async () => { + await withAssetsService(async ({ assetsService, mockCoreMessenger }) => { + mockCoreMessenger.call.mockImplementation( + createMessengerCallMock( + () => ({ + remoteFeatureFlags: { + [TRON_FLAG_KEY]: { + stage: + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + }, + }, + }), + jest.fn().mockResolvedValue( + buildControllerAsset(fungibleAssetId, '2000000', { + symbol: 'TRX', + name: 'TRON', + decimals: 6, + }), + ), + ), + ); + + const asset = await assetsService.getAccountAssetByID( + accountId, + fungibleAssetId, + ); + + expect(asset).toMatchObject({ + assetType: fungibleAssetId, + rawAmount: '2000000', + uiAmount: '2', + }); + }); + }); + + it('getAccountAssetsByIDs uses a single AssetsController:getAccountAssetsByIDs call for fungibles', async () => { + await withAssetsService(async ({ assetsService, mockCoreMessenger }) => { + const trx = KnownCaip19Id.TrxMainnet; + const usdt = `${Network.Mainnet}/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t`; + + mockCoreMessenger.call.mockImplementation( + createMessengerCallMock( + () => ({ + remoteFeatureFlags: { + [TRON_FLAG_KEY]: { + stage: + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + }, + }, + }), + jest.fn(), + jest.fn().mockImplementation(async () => { + return { + [trx as Caip19AssetId]: buildControllerAsset(trx, '1000000', { + symbol: 'TRX', + name: 'TRON', + decimals: 6, + }), + [usdt as Caip19AssetId]: buildControllerAsset(usdt, '500000', { + symbol: 'USDT', + name: 'Tether', + decimals: 6, + }), + }; + }), + ), + ); + + const results = await assetsService.getAccountAssetsByIDs(accountId, [ + trx, + usdt, + ]); + + expect(mockCoreMessenger.call).toHaveBeenCalledWith( + 'AssetsController:getAccountAssetsByIDs', + accountId, + [trx, usdt], + ); + expect(results[0]?.rawAmount).toBe('1000000'); + expect(results[1]?.rawAmount).toBe('500000'); + }); + }); + + it('getAccountAssetsByIDs batches snap-owned reads without calling AssetsController', async () => { + await withAssetsService( + async ({ assetsService, mockAssetsRepository, mockCoreMessenger }) => { + const snapAsset: AssetEntity = { + assetType: snapAssetId, + keyringAccountId: accountId, + network: Network.Mainnet, + symbol: 'ENERGY', + decimals: 0, + rawAmount: '100', + uiAmount: '100', + iconUrl: '', + }; + mockAssetsRepository.getByAccountIdAndAssetTypes.mockResolvedValue([ + snapAsset, + ]); + + const results = await assetsService.getAccountAssetsByIDs(accountId, [ + snapAssetId, + ]); + + expect(results[0]).toStrictEqual(snapAsset); + expect(mockCoreMessenger.call).not.toHaveBeenCalledWith( + 'AssetsController:getAccountAssetsByIDs', + expect.anything(), + expect.anything(), + ); + }, + ); + }); + + it('getAccountAssetsByIDs routes all asset IDs through AssetsController when mode is controller', async () => { + await withAssetsService( + async ({ assetsService, mockCoreMessenger }) => { + mockCoreMessenger.call.mockImplementation( + createMessengerCallMock( + () => ({ + remoteFeatureFlags: { + [TRON_FLAG_KEY]: { + stage: + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + }, + }, + }), + jest.fn(), + jest.fn().mockImplementation(async () => { + return { + [fungibleAssetId as Caip19AssetId]: buildControllerAsset( + fungibleAssetId, + '3000000', + { + symbol: 'TRX', + name: 'TRON', + decimals: 6, + }, + ), + [snapAssetId as Caip19AssetId]: buildControllerAsset( + snapAssetId, + '250', + { + symbol: 'ENERGY', + name: 'Energy', + decimals: 0, + }, + ), + }; + }), + ), + ); + + const results = await assetsService.getAccountAssetsByIDs(accountId, [ + fungibleAssetId, + snapAssetId, + ]); + + expect(results[0]?.rawAmount).toBe('3000000'); + expect(results[1]?.rawAmount).toBe('250'); + expect(mockCoreMessenger.call).toHaveBeenCalledWith( + 'AssetsController:getAccountAssetsByIDs', + accountId, + [fungibleAssetId, snapAssetId], + ); + }, + ); + }); + + it('getByKeyringAccountId reads from AssetsController when mode is controller', async () => { + await withAssetsService( + async ({ assetsService, mockCoreMessenger, setMigrationStage }) => { + setMigrationStage( + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + ); + + mockCoreMessenger.call.mockImplementation( + createMessengerCallMock( + () => ({ + remoteFeatureFlags: { + [TRON_FLAG_KEY]: { + stage: + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + }, + }, + }), + jest.fn(), + jest.fn(), + jest.fn().mockResolvedValue({ + [snapAssetId as Caip19AssetId]: buildControllerAsset( + snapAssetId, + '100', + { + symbol: 'ENERGY', + name: 'Energy', + decimals: 0, + }, + ), + }), + ), + ); + + const assets = await assetsService.getByKeyringAccountId(accountId); + + expect(mockCoreMessenger.call).toHaveBeenCalledWith( + 'AssetsController:getAccountAssetsByScope', + accountId, + Network.Mainnet, + ); + expect( + assets.some( + (asset: AssetEntity) => asset.assetType === snapAssetId, + ), + ).toBe(true); + expect( + assets.some( + (asset: AssetEntity) => asset.assetType === fungibleAssetId, + ), + ).toBe(false); + }, + ); + }); + + it('saveMany emits only snap-owned assets when mode is controller', async () => { + await withAssetsService( + async ({ assetsService, mockState, setMigrationStage }) => { + setMigrationStage( + SnapsAssetsMigrationStage.ReadAssetsControllerWithoutFallback, + ); + mockState.getKey.mockResolvedValue({}); + + const assets: AssetEntity[] = [ + { + assetType: fungibleAssetId, + keyringAccountId: accountId, + network: Network.Mainnet, + symbol: 'TRX', + decimals: 6, + rawAmount: '1000000', + uiAmount: '1', + iconUrl: '', + }, + { + assetType: snapAssetId, + keyringAccountId: accountId, + network: Network.Mainnet, + symbol: 'ENERGY', + decimals: 0, + rawAmount: '100', + uiAmount: '100', + iconUrl: '', + }, + ]; + + await assetsService.saveMany(assets); + + expect(emitSnapKeyringEvent).toHaveBeenCalledWith( + expect.anything(), + KeyringEvent.AccountAssetListUpdated, + { + assets: { + [accountId]: { + added: [snapAssetId], + removed: [], + }, + }, + }, + ); + }, + ); + }); + + it('ignores TRON_ASSETS_MIGRATION_STAGE in production', async () => { + /* eslint-disable n/no-process-env */ + const originalEnvironment = process.env.ENVIRONMENT; + const originalStage = process.env.TRON_ASSETS_MIGRATION_STAGE; + process.env.ENVIRONMENT = 'production'; + process.env.TRON_ASSETS_MIGRATION_STAGE = '2'; + /* eslint-enable n/no-process-env */ + + await withAssetsService( + async ({ assetsService, mockAssetsRepository, mockCoreMessenger }) => { + mockCoreMessenger.call.mockImplementation( + createMessengerCallMock( + () => ({ remoteFeatureFlags: {} }), + jest.fn(), + ), + ); + const snapAsset: AssetEntity = { + assetType: fungibleAssetId, + keyringAccountId: accountId, + network: Network.Mainnet, + symbol: 'TRX', + decimals: 6, + rawAmount: '1000000', + uiAmount: '1', + iconUrl: '', + }; + mockAssetsRepository.getByAccountIdAndAssetType.mockResolvedValue( + snapAsset, + ); + + const asset = await assetsService.getAccountAssetByID( + accountId, + fungibleAssetId, + ); + + expect(asset).toStrictEqual(snapAsset); + }, + ); + + restoreMigrationStageEnv(originalEnvironment, originalStage); + }); + }); + describe('facade delegation', () => { - it('delegates repository reads and market helpers to SnapAssetsAdapter', async () => { + it('delegates static helpers and empty batch reads to SnapAssetsAdapter', async () => { await withAssetsService( async ({ assetsService, mockAssetsRepository, mockPriceApiClient }) => { const asset: AssetEntity = { @@ -2843,18 +3325,15 @@ describe('AssetsService', () => { decimals: 6, rawAmount: '1', uiAmount: '1', + iconUrl: '', }; - mockAssetsRepository.getByAccountId.mockResolvedValue([asset]); mockAssetsRepository.getByAccountIdAndAssetTypes.mockResolvedValue([ asset, ]); - mockAssetsRepository.getByAccountIdAndAssetType.mockResolvedValue( - asset, + mockPriceApiClient.getFiatExchangeRates.mockResolvedValue( + MOCK_EXCHANGE_RATES, ); - mockPriceApiClient.getFiatExchangeRates.mockResolvedValue({ - usd: { value: 1 }, - }); mockPriceApiClient.getMultipleSpotPrices.mockResolvedValue( createSpotPrices({ [KnownCaip19Id.TrxMainnet]: { @@ -2868,39 +3347,17 @@ describe('AssetsService', () => { expect(AssetsService.isFiat('swift:0/iso4217:usd')).toBe(true); expect(AssetsService.hasChanged(asset, [])).toBe(true); expect(AssetsService.hasChanged(asset, [asset])).toBe(false); - expect( - await assetsService.getAccountAssets(mockAccount.id), - ).toStrictEqual([asset]); + await assetsService.getAccountAssetsByIDs(mockAccount.id, []), + ).toStrictEqual([]); expect( - await assetsService.getAccountAssetsByIDs(mockAccount.id, [ - KnownCaip19Id.TrxMainnet, + await assetsService.getMultipleTokensMarketData([ + { + asset: KnownCaip19Id.TrxMainnet, + unit: 'swift:0/iso4217:usd', + }, ]), - ).toStrictEqual([asset]); - expect( - await assetsService.getAccountAssetByID( - mockAccount.id, - KnownCaip19Id.TrxMainnet, - ), - ).toStrictEqual(asset); - const byKeyringAccountId = await assetsService.getByKeyringAccountId( - mockAccount.id, - ); - expect( - byKeyringAccountId.some( - (savedAsset) => savedAsset.assetType === KnownCaip19Id.TrxMainnet, - ), - ).toBe(true); - const marketData = await assetsService.getMultipleTokensMarketData([ - { - asset: KnownCaip19Id.TrxMainnet, - unit: 'swift:0/iso4217:usd', - }, - ]); - expect(marketData[KnownCaip19Id.TrxMainnet]).toBeDefined(); - expect(assetsService.cacheTtlsMilliseconds.historicalPrices).toBe( - 3600000, - ); + ).toBeDefined(); }, ); }); diff --git a/packages/tron-wallet-snap/src/services/assets/AssetsService.ts b/packages/tron-wallet-snap/src/services/assets/AssetsService.ts index 6ba8e4a3..3039fa84 100644 --- a/packages/tron-wallet-snap/src/services/assets/AssetsService.ts +++ b/packages/tron-wallet-snap/src/services/assets/AssetsService.ts @@ -1,32 +1,48 @@ +import { + SNAPS_ASSETS_MIGRATION_FLAG_KEYS, + SnapsAssetsMigrationStage, + getSnapsAssetsMigrationNamespace, + parseSnapsAssetsMigrationStage, +} from '@metamask/assets-controller'; +import type { Caip19AssetId } from '@metamask/assets-controller'; import type { KeyringAccount } from '@metamask/keyring-api'; +import type { AssetsProvider } from '@metamask/snap-networks-utils'; import type { AssetConversion, AssetMetadata, FungibleAssetMarketData, HistoricalPriceIntervals, } from '@metamask/snaps-sdk'; -import type { CaipAssetType } from '@metamask/utils'; +import type { CaipAssetType, CaipChainId, Json } from '@metamask/utils'; +import { parseCaipAssetType } from '@metamask/utils'; import type { PriceApiClient } from '../../clients/price-api/PriceApiClient'; import type { SnapClient } from '../../clients/snap/SnapClient'; import type { TokenApiClient } from '../../clients/token-api/TokenApiClient'; import type { TronHttpClient } from '../../clients/tron-http/TronHttpClient'; import type { TrongridApiClient } from '../../clients/trongrid/TrongridApiClient'; -import type { Network } from '../../constants'; +import { Network } from '../../constants'; import type { AssetEntity } from '../../entities/assets'; +import type { CoreMessengerCaller } from '../../types/core-messenger'; import type { ILogger } from '../../utils/logger'; import type { State, UnencryptedStateValue } from '../state/State'; import { SnapAssetsAdapter } from './adapters/SnapAssetsAdapter'; import type { AssetsRepository } from './AssetsRepository'; +import { mapControllerAsset } from './mapControllerAsset'; /** - * Assets domain facade. Currently delegates all behavior to SnapAssetsAdapter - * (legacy snap-owned reads/writes). Core adapter routing can be introduced later - * without changing callers. + * Assets migration stage used when no remote feature flag is set for the chain. + * Change this value to test Stage 0 / 1 / 2 locally. */ +const ASSETS_MIGRATION_STAGE = SnapsAssetsMigrationStage.Off; + export class AssetsService { readonly #snapAdapter: SnapAssetsAdapter; + readonly #assetsProvider: AssetsProvider; + + readonly #coreMessenger: CoreMessengerCaller; + readonly cacheTtlsMilliseconds: SnapAssetsAdapter['cacheTtlsMilliseconds']; constructor({ @@ -38,6 +54,8 @@ export class AssetsService { priceApiClient, tokenApiClient, snapClient, + coreMessenger, + assetsProvider, }: { logger: ILogger; assetsRepository: AssetsRepository; @@ -47,7 +65,12 @@ export class AssetsService { priceApiClient: PriceApiClient; tokenApiClient: TokenApiClient; snapClient: SnapClient; + coreMessenger: CoreMessengerCaller; + assetsProvider: AssetsProvider; }) { + this.#coreMessenger = coreMessenger; + this.#assetsProvider = assetsProvider; + this.#snapAdapter = new SnapAssetsAdapter({ logger, assetsRepository, @@ -57,10 +80,40 @@ export class AssetsService { priceApiClient, tokenApiClient, snapClient, + resolveMigrationStage: ( + chainId: string, + ): Promise => + this.#resolveMigrationStage(chainId), }); this.cacheTtlsMilliseconds = this.#snapAdapter.cacheTtlsMilliseconds; } + async #resolveMigrationStage( + chainId: string, + ): Promise { + const { remoteFeatureFlags } = await this.#coreMessenger.call( + 'RemoteFeatureFlagController:getState', + ); + + const namespace = getSnapsAssetsMigrationNamespace(chainId as CaipChainId); + + if (namespace) { + const flagKey = SNAPS_ASSETS_MIGRATION_FLAG_KEYS[namespace]; + + if (Object.hasOwn(remoteFeatureFlags, flagKey)) { + const remoteStage = parseSnapsAssetsMigrationStage( + remoteFeatureFlags[flagKey] as Json | undefined, + ); + + if (remoteStage !== undefined) { + return remoteStage; + } + } + } + + return ASSETS_MIGRATION_STAGE; + } + static isFiat(caipAssetId: CaipAssetType): boolean { return SnapAssetsAdapter.isFiat(caipAssetId); } @@ -69,22 +122,84 @@ export class AssetsService { return SnapAssetsAdapter.hasChanged(asset, assetsLookup); } - async getAccountAssets(accountId: string): Promise { - return this.#snapAdapter.getAccountAssets(accountId); + async getAccountAssetByID( + accountId: string, + assetId: string, + ): Promise { + const { chainId } = parseCaipAssetType(assetId as CaipAssetType); + const stage = await this.#resolveMigrationStage(chainId); + + if (stage === SnapsAssetsMigrationStage.Off) { + return this.#snapAdapter.getAccountAssetByID(accountId, assetId); + } + + const asset = await this.#assetsProvider.getAccountAssetByID( + accountId, + assetId as Caip19AssetId, + ); + + if (!asset) { + return null; + } + + return mapControllerAsset(accountId, asset); } async getAccountAssetsByIDs( accountId: string, - assetTypes: string[], + assetIds: string[], ): Promise<(AssetEntity | null)[]> { - return this.#snapAdapter.getAccountAssetsByIDs(accountId, assetTypes); + if (assetIds.length === 0) { + return []; + } + + const { chainId } = parseCaipAssetType(assetIds[0] as CaipAssetType); + const stage = await this.#resolveMigrationStage(chainId); + + if (stage === SnapsAssetsMigrationStage.Off) { + const results = await this.#snapAdapter.getAccountAssetsByIDs( + accountId, + assetIds, + ); + + return assetIds.map((assetId) => results[assetId] ?? null); + } + + const controllerAssets = await this.#assetsProvider.getAccountAssetsByIDs( + accountId, + assetIds as Caip19AssetId[], + ); + + return assetIds.map((assetId) => { + const controllerAsset = controllerAssets[assetId as Caip19AssetId]; + return controllerAsset + ? mapControllerAsset(accountId, controllerAsset) + : null; + }); } - async getAccountAssetByID( + async getAccountAssetsByScope( + scope: Network, accountId: string, - assetType: string, - ): Promise { - return this.#snapAdapter.getAccountAssetByID(accountId, assetType); + ): Promise { + const stage = await this.#resolveMigrationStage(scope); + + if (stage === SnapsAssetsMigrationStage.Off) { + return this.#snapAdapter.getAccountAssetsByScope(scope, accountId); + } + + const controllerAssets = await this.#assetsProvider.getAccountAssetsByScope( + scope, + accountId, + ); + + return Object.values(controllerAssets).map((asset) => + mapControllerAsset(accountId, asset), + ); + } + + async getByKeyringAccountId(accountId: string): Promise { + return this.getAccountAssetsByScope(Network.Mainnet, accountId); } async fetchAssetsAndBalancesForAccount( @@ -94,12 +209,6 @@ export class AssetsService { return this.#snapAdapter.fetchAssetsAndBalancesForAccount(scope, account); } - async getAssetsMetadata( - assetTypes: CaipAssetType[], - ): Promise> { - return this.#snapAdapter.getAssetsMetadata(assetTypes); - } - async saveMany(assets: AssetEntity[]): Promise { return this.#snapAdapter.saveMany(assets); } @@ -108,8 +217,15 @@ export class AssetsService { return this.#snapAdapter.getAll(); } - async getByKeyringAccountId(accountId: string): Promise { - return this.#snapAdapter.getByKeyringAccountId(accountId); + async getHistoricalPrice( + from: CaipAssetType, + to: CaipAssetType, + ): Promise<{ + intervals: HistoricalPriceIntervals; + updateTime: number; + expirationTime?: number; + }> { + return this.#snapAdapter.getHistoricalPrice(from, to); } async getMultipleTokenConversions( @@ -120,6 +236,12 @@ export class AssetsService { return this.#snapAdapter.getMultipleTokenConversions(conversions); } + async getAssetsMetadata( + assetTypes: CaipAssetType[], + ): Promise> { + return this.#snapAdapter.getAssetsMetadata(assetTypes); + } + async getMultipleTokensMarketData( assets: { asset: CaipAssetType; @@ -130,15 +252,6 @@ export class AssetsService { > { return this.#snapAdapter.getMultipleTokensMarketData(assets); } - - async getHistoricalPrice( - from: CaipAssetType, - to: CaipAssetType, - ): Promise<{ - intervals: HistoricalPriceIntervals; - updateTime: number; - expirationTime?: number; - }> { - return this.#snapAdapter.getHistoricalPrice(from, to); - } } + +export { SnapsAssetsMigrationStage }; diff --git a/packages/tron-wallet-snap/src/services/assets/adapters/SnapAssetsAdapter.ts b/packages/tron-wallet-snap/src/services/assets/adapters/SnapAssetsAdapter.ts index 0590aa2c..011fd657 100644 --- a/packages/tron-wallet-snap/src/services/assets/adapters/SnapAssetsAdapter.ts +++ b/packages/tron-wallet-snap/src/services/assets/adapters/SnapAssetsAdapter.ts @@ -1,3 +1,4 @@ +import { SnapsAssetsMigrationStage } from '@metamask/assets-controller'; import { KeyringEvent } from '@metamask/keyring-api'; import type { AccountAssetListUpdatedEvent, @@ -61,6 +62,7 @@ import { createPrefixedLogger } from '../../../utils/logger'; import type { ILogger } from '../../../utils/logger'; import type { State, UnencryptedStateValue } from '../../state/State'; import type { AssetsRepository } from '../AssetsRepository'; +import { isSnapOwnedAsset } from '../snapOwnedAssets'; import type { InLockPeriodCaipAssetType, NativeCaipAssetType, @@ -113,6 +115,10 @@ export class SnapAssetsAdapter { readonly #snapClient: SnapClient; + readonly #resolveMigrationStage: ( + chainId: string, + ) => Promise; + readonly cacheTtlsMilliseconds: { fiatExchangeRates: number; spotPrices: number; @@ -128,6 +134,7 @@ export class SnapAssetsAdapter { priceApiClient, tokenApiClient, snapClient, + resolveMigrationStage, }: { logger: ILogger; assetsRepository: AssetsRepository; @@ -137,6 +144,9 @@ export class SnapAssetsAdapter { priceApiClient: PriceApiClient; tokenApiClient: TokenApiClient; snapClient: SnapClient; + resolveMigrationStage: ( + chainId: string, + ) => Promise; }) { this.#logger = createPrefixedLogger(logger, '[🪙 SnapAssetsAdapter]'); this.#assetsRepository = assetsRepository; @@ -146,6 +156,7 @@ export class SnapAssetsAdapter { this.#priceApiClient = priceApiClient; this.#tokenApiClient = tokenApiClient; this.#snapClient = snapClient; + this.#resolveMigrationStage = resolveMigrationStage; const { cacheTtlsMilliseconds } = configProvider.get().priceApi; this.cacheTtlsMilliseconds = cacheTtlsMilliseconds; @@ -155,27 +166,31 @@ export class SnapAssetsAdapter { return caipAssetId.includes('swift:0/iso4217:'); } - async getAccountAssets(accountId: string): Promise { - return this.#assetsRepository.getByAccountId(accountId); + async #resolveStage(chainId: string): Promise { + return this.#resolveMigrationStage(chainId); } - async getAccountAssetsByIDs( + async getAccountAssetByID( accountId: string, - assetTypes: string[], - ): Promise<(AssetEntity | null)[]> { - return this.#assetsRepository.getByAccountIdAndAssetTypes( + assetId: string, + ): Promise { + return this.#assetsRepository.getByAccountIdAndAssetType( accountId, - assetTypes, + assetId, ); } - async getAccountAssetByID( + async getAccountAssetsByIDs( accountId: string, - assetType: string, - ): Promise { - return this.#assetsRepository.getByAccountIdAndAssetType( + assetIds: string[], + ): Promise> { + const assets = await this.#assetsRepository.getByAccountIdAndAssetTypes( accountId, - assetType, + assetIds, + ); + + return Object.fromEntries( + assetIds.map((assetId, index) => [assetId, assets[index] ?? null]), ); } @@ -208,6 +223,8 @@ export class SnapAssetsAdapter { scope, }); + const stage = await this.#resolveStage(scope); + const [ tronAccountInfoRequest, tronAccountResourcesRequest, @@ -226,18 +243,19 @@ export class SnapAssetsAdapter { ); } - const trc20BalancesFallback = isInactiveAccount - ? await this.#trongridApiClient - .getTrc20BalancesByAddress(scope, account.address) - .catch(async (error) => { - await this.#snapClient.trackError(error as Error); - this.#logger.warn( - 'Failed to fetch TRC20 balances for inactive account', - { error, account, scope }, - ); - return []; - }) - : []; + const trc20BalancesFallback = + stage === SnapsAssetsMigrationStage.Off && isInactiveAccount + ? await this.#trongridApiClient + .getTrc20BalancesByAddress(scope, account.address) + .catch(async (error) => { + await this.#snapClient.trackError(error as Error); + this.#logger.warn( + 'Failed to fetch TRC20 balances for inactive account', + { error, account, scope }, + ); + return []; + }) + : []; const accountData = this.#buildAccountData({ tronAccountInfoRequest, @@ -246,7 +264,10 @@ export class SnapAssetsAdapter { stakingRewardsRequest, }); - const rawAssets = this.#extractAssets(account, scope, accountData); + const rawAssets = + stage === SnapsAssetsMigrationStage.Off + ? this.#extractAssets(account, scope, accountData) + : this.#extractSnapOwnedAssets(account, scope, accountData); const assetTypes = rawAssets.map((asset) => asset.assetType); const priceableAssetTypes = this.#getPriceableAssetTypes(rawAssets); @@ -371,12 +392,22 @@ export class SnapAssetsAdapter { ): AssetEntity[] { return [ this.#extractNativeAsset(account, scope, data.nativeBalance), + ...this.#extractSnapOwnedAssets(account, scope, data), + ...this.#extractTrc10Assets(account, scope, data.trc10Balances), + ...this.#extractTrc20Assets(account, scope, data.trc20Balances), + ]; + } + + #extractSnapOwnedAssets( + account: KeyringAccount, + scope: Network, + data: NormalizedAccountData, + ): AssetEntity[] { + return [ ...this.#extractStakedNativeAssets(account, scope, data.stakedData), this.#extractReadyForWithdrawalAsset(account, scope, data.stakedData), this.#extractInLockPeriodAsset(account, scope, data.stakedData), this.#extractStakingRewardsAsset(account, scope, data.stakingRewards), - ...this.#extractTrc10Assets(account, scope, data.trc10Balances), - ...this.#extractTrc20Assets(account, scope, data.trc20Balances), ...this.#extractBandwidth({ account, scope, @@ -1261,6 +1292,19 @@ export class SnapAssetsAdapter { async saveMany(assets: AssetEntity[]): Promise { this.#logger.info('Saving assets', assets); + const stagesByNetwork = new Map(); + await Promise.all( + [...new Set(assets.map((asset) => asset.network))].map( + async (network) => { + stagesByNetwork.set(network, await this.#resolveStage(network)); + }, + ), + ); + + const shouldEmitAsset = (asset: AssetEntity): boolean => + (stagesByNetwork.get(asset.network) ?? SnapsAssetsMigrationStage.Off) === + SnapsAssetsMigrationStage.Off || isSnapOwnedAsset(asset.assetType); + const hasZeroAmount = (asset: AssetEntity): boolean => asset.rawAmount === '0' || asset.uiAmount === '0'; @@ -1268,6 +1312,14 @@ export class SnapAssetsAdapter { const isEssentialAsset = (asset: AssetEntity): boolean => ESSENTIAL_ASSETS.includes(asset.assetType); + const isProtectedAsset = (asset: AssetEntity): boolean => { + const stage = + stagesByNetwork.get(asset.network) ?? SnapsAssetsMigrationStage.Off; + return stage === SnapsAssetsMigrationStage.Off + ? isEssentialAsset(asset) + : isSnapOwnedAsset(asset.assetType); + }; + // Track only the account/network pairs refreshed in this run. // That prevents us from treating assets from untouched networks as disappeared. const syncedNetworksByAccount = assets.reduce>>( @@ -1292,7 +1344,17 @@ export class SnapAssetsAdapter { if ( !syncedNetworks?.has(savedAsset.network) || - isEssentialAsset(savedAsset) + isProtectedAsset(savedAsset) + ) { + return false; + } + + const stage = + stagesByNetwork.get(savedAsset.network) ?? + SnapsAssetsMigrationStage.Off; + if ( + stage !== SnapsAssetsMigrationStage.Off && + !isSnapOwnedAsset(savedAsset.assetType) ) { return false; } @@ -1320,23 +1382,23 @@ export class SnapAssetsAdapter { // snapshot entirely // 2. fold in the current assets to report additions and explicit zero-balance // removals in the same event - const assetListUpdatedPayload = disappearedAssets.reduce< - AccountAssetListUpdatedEvent['params']['assets'] - >( - (acc, asset) => ({ - ...acc, - [asset.keyringAccountId]: { - added: [...(acc[asset.keyringAccountId]?.added ?? [])], - removed: [ - ...(acc[asset.keyringAccountId]?.removed ?? []), - asset.assetType, - ], - }, - }), - {}, - ); + const assetListUpdatedPayload = disappearedAssets + .filter(shouldEmitAsset) + .reduce( + (acc, asset) => ({ + ...acc, + [asset.keyringAccountId]: { + added: [...(acc[asset.keyringAccountId]?.added ?? [])], + removed: [ + ...(acc[asset.keyringAccountId]?.removed ?? []), + asset.assetType, + ], + }, + }), + {}, + ); - for (const asset of assets) { + for (const asset of assets.filter(shouldEmitAsset)) { // Merge the current snapshot into the pre-seeded payload so each account // ends up with one consolidated added/removed diff. assetListUpdatedPayload[asset.keyringAccountId] = { @@ -1367,11 +1429,13 @@ export class SnapAssetsAdapter { // Emit synthetic zero-balance entries for disappeared assets so clients can // clear cached balances even when the backend omits zero-balance tokens // instead of returning them explicitly. - const removedAssetsWithZeroBalance = disappearedAssets.map((asset) => ({ - ...asset, - rawAmount: '0', - uiAmount: '0', - })); + const removedAssetsWithZeroBalance = disappearedAssets + .filter(shouldEmitAsset) + .map((asset) => ({ + ...asset, + rawAmount: '0', + uiAmount: '0', + })); const assetsToSave = [...assets, ...removedAssetsWithZeroBalance]; // Save assets using repository @@ -1379,9 +1443,10 @@ export class SnapAssetsAdapter { // Broadcast the current snapshot plus synthetic zero-balance removals so the // client can reconcile both visible assets and cached balances in one pass. - const balancesUpdatedPayload = assetsToSave.reduce< - AccountBalancesUpdatedEvent['params']['balances'] - >( + const balancesUpdatedPayload = [ + ...assets.filter(shouldEmitAsset), + ...removedAssetsWithZeroBalance, + ].reduce( (acc, asset) => ({ ...acc, [asset.keyringAccountId]: { @@ -1442,19 +1507,26 @@ export class SnapAssetsAdapter { } as AssetEntity; } - async getByKeyringAccountId( + async getAccountAssetsByScope( + scope: Network, keyringAccountId: string, ): Promise { const savedAssets = await this.#assetsRepository.getByAccountId(keyringAccountId); - /** - * Ensure the special assets are always present whether they have been synced or not. - * These are assets that should be visible to the user even with zero balance. - */ + const visibleSavedAssets = savedAssets.filter( + (asset) => asset.network === scope, + ); + const missingEssentialAssets: AssetEntity[] = []; for (const essentialAssetId of ESSENTIAL_ASSETS) { + const { chainId } = parseCaipAssetType(essentialAssetId as CaipAssetType); + + if ((chainId as Network) !== scope) { + continue; + } + const savedAsset = savedAssets.find( (asset) => (asset.assetType as string) === essentialAssetId, ); @@ -1468,7 +1540,7 @@ export class SnapAssetsAdapter { } } - return [...savedAssets, ...missingEssentialAssets]; + return [...visibleSavedAssets, ...missingEssentialAssets]; } /** diff --git a/packages/tron-wallet-snap/src/services/assets/mapControllerAsset.test.ts b/packages/tron-wallet-snap/src/services/assets/mapControllerAsset.test.ts new file mode 100644 index 00000000..852b6534 --- /dev/null +++ b/packages/tron-wallet-snap/src/services/assets/mapControllerAsset.test.ts @@ -0,0 +1,84 @@ +import type { Asset } from '@metamask/assets-controller'; +import type { CaipAssetType } from '@metamask/utils'; + +import { KnownCaip19Id, Network, TokenMetadata } from '../../constants'; +import { mapControllerAsset } from './mapControllerAsset'; + +describe('mapControllerAsset', () => { + const accountId = 'account-id'; + const knownAssetId = KnownCaip19Id.TrxMainnet; + const unknownAssetId = 'tron:728126428/trc20:unknown'; + + it('maps controller metadata when present', () => { + const asset = { + id: unknownAssetId, + chainId: Network.Mainnet, + balance: { amount: '1234567' }, + metadata: { + type: 'fungible', + symbol: 'TKN', + name: 'Token', + decimals: 6, + image: 'https://example.com/token.png', + }, + price: { price: 0, lastUpdated: 0 }, + fiatValue: 0, + } as unknown as Asset; + + expect(mapControllerAsset(accountId, asset)).toStrictEqual({ + assetType: unknownAssetId, + keyringAccountId: accountId, + network: Network.Mainnet, + symbol: 'TKN', + decimals: 6, + rawAmount: '1234567', + uiAmount: '1.234567', + iconUrl: 'https://example.com/token.png', + }); + }); + + it('falls back to TokenMetadata when controller metadata is missing', () => { + const asset = { + id: knownAssetId, + chainId: Network.Mainnet, + balance: { amount: '2000000' }, + metadata: { type: 'fungible', name: 'TRON' }, + price: { price: 0, lastUpdated: 0 }, + fiatValue: 0, + } as unknown as Asset; + + expect(mapControllerAsset(accountId, asset)).toStrictEqual({ + assetType: knownAssetId, + keyringAccountId: accountId, + network: Network.Mainnet, + symbol: TokenMetadata[knownAssetId].symbol, + decimals: TokenMetadata[knownAssetId].decimals, + rawAmount: '2000000', + uiAmount: '2', + iconUrl: TokenMetadata[knownAssetId].iconUrl, + }); + }); + + it('uses empty defaults when metadata is missing everywhere', () => { + const assetId = 'tron:728126428/trc20:missing' as CaipAssetType; + const asset = { + id: assetId, + chainId: Network.Mainnet, + balance: { amount: '42' }, + metadata: { type: 'fungible', name: 'Missing' }, + price: { price: 0, lastUpdated: 0 }, + fiatValue: 0, + } as unknown as Asset; + + expect(mapControllerAsset(accountId, asset)).toStrictEqual({ + assetType: assetId, + keyringAccountId: accountId, + network: Network.Mainnet, + symbol: '', + decimals: 0, + rawAmount: '42', + uiAmount: '42', + iconUrl: '', + }); + }); +}); diff --git a/packages/tron-wallet-snap/src/services/assets/mapControllerAsset.ts b/packages/tron-wallet-snap/src/services/assets/mapControllerAsset.ts new file mode 100644 index 00000000..6b09e488 --- /dev/null +++ b/packages/tron-wallet-snap/src/services/assets/mapControllerAsset.ts @@ -0,0 +1,35 @@ +import type { Asset } from '@metamask/assets-controller'; + +import { Network, TokenMetadata } from '../../constants'; +import type { AssetEntity } from '../../entities/assets'; +import { toUiAmount } from '../../utils/conversion'; + +/** + * Maps an AssetsController asset to the Snap's {@link AssetEntity} shape. + * + * @param accountId - Keyring account ID. + * @param asset - Asset returned by AssetsController. + * @returns Mapped asset entity. + */ +export function mapControllerAsset( + accountId: string, + asset: Asset, +): AssetEntity { + const assetId = asset.id; + const knownMetadata = TokenMetadata[assetId as keyof typeof TokenMetadata]; + const decimals = asset.metadata.decimals ?? knownMetadata?.decimals ?? 0; + const symbol = asset.metadata.symbol ?? knownMetadata?.symbol ?? ''; + const iconUrl = asset.metadata.image ?? knownMetadata?.iconUrl ?? ''; + const { amount } = asset.balance; + + return { + assetType: assetId, + keyringAccountId: accountId, + network: asset.chainId as Network, + symbol, + decimals, + rawAmount: amount, + uiAmount: toUiAmount(amount, decimals).toString(), + iconUrl, + } as AssetEntity; +} diff --git a/packages/tron-wallet-snap/src/types/core-messenger.ts b/packages/tron-wallet-snap/src/types/core-messenger.ts index 6090a068..54be9a9b 100644 --- a/packages/tron-wallet-snap/src/types/core-messenger.ts +++ b/packages/tron-wallet-snap/src/types/core-messenger.ts @@ -32,3 +32,8 @@ export type CoreMessengerMessenger = Messenger< * `endowment:messenger` / `getMessenger`. */ export type CoreMessenger = AsyncMessenger; + +/** + * Narrow dependency for services that only need to invoke Core actions. + */ +export type CoreMessengerCaller = Pick;