Skip to content

Commit d6a4c8f

Browse files
authored
feat: Add mm portfolio api - token search controller (#5142)
## Explanation <!-- Thanks for your contribution! Take a moment to answer these questions so that reviewers have the information they need to properly understand your changes: * What is the current state of things and why does it need to change? * What is the solution your changes offer and how does it work? * Are there any changes whose purpose might not obvious to those unfamiliar with the domain? * If your primary goal was to update one package but you found you had to update another one along the way, why did you do so? * If you had to upgrade a dependency, why did you do so? --> This is the introduction of metamask portfolio api's token search in the core monorepo. This will return values from Moralis intended to provide search functionality coming soon to the metamask mobile app. ## References <!-- Are there any issues that this pull request is tied to? Are there other links that reviewers should consult to understand these changes better? Are there client or consumer pull requests to adopt any breaking changes? For example: * Fixes #12345 * Related to #67890 --> [MMPD-1504](https://consensyssoftware.atlassian.net/browse/MMPD-1504) [MMPD-1526](https://consensyssoftware.atlassian.net/browse/MMPD-1526) ## Changelog <!-- If you're making any consumer-facing changes, list those changes here as if you were updating a changelog, using the template below as a guide. (CATEGORY is one of BREAKING, ADDED, CHANGED, DEPRECATED, REMOVED, or FIXED. For security-related issues, follow the Security Advisory process.) Please take care to name the exact pieces of the API you've added or changed (e.g. types, interfaces, functions, or methods). If there are any breaking changes, make sure to offer a solution for consumers to follow once they upgrade to the changes. Finally, if you're only making changes to development scripts or tests, you may replace the template below with "None". --> ### `@metamask/token-search-discovery-controller` - **ADDED**: TokenSearchDiscoveryController which fetches token search results from the metamask portfolio api - **ADDED**: TokenSearchApiService to handle portfolio API interactions for token search ## Checklist - [x] I've updated the test suite for new or updated code as appropriate - [x] I've updated documentation (JSDoc, Markdown, etc.) for new or updated code as appropriate - [x] I've highlighted breaking changes using the "BREAKING" category above as appropriate - [x] I've prepared draft pull requests for clients and consumer packages to resolve any breaking changes [MMPD-1504]: https://consensyssoftware.atlassian.net/browse/MMPD-1504?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
1 parent 52d1c16 commit d6a4c8f

21 files changed

+695
-4
lines changed

.github/CODEOWNERS

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@
3434
## Snaps Team
3535
/packages/rate-limit-controller @MetaMask/snaps-devs
3636

37+
## Portfolio Team
38+
/packages/token-search-discovery-controller @MetaMask/portfolio
39+
3740
## Wallet API Platform Team
3841
/packages/multichain @MetaMask/wallet-api-platform-engineers
3942
/packages/queued-request-controller @MetaMask/wallet-api-platform-engineers
@@ -100,3 +103,5 @@
100103
/packages/transaction-controller/CHANGELOG.md @MetaMask/confirmations @MetaMask/wallet-framework-engineers
101104
/packages/user-operation-controller/package.json @MetaMask/confirmations @MetaMask/wallet-framework-engineers
102105
/packages/user-operation-controller/CHANGELOG.md @MetaMask/confirmations @MetaMask/wallet-framework-engineers
106+
/packages/token-search-discovery-controller/package.json @MetaMask/portfolio @MetaMask/wallet-framework-engineers
107+
/packages/token-search-discovery-controller/CHANGELOG.md @MetaMask/portfolio @MetaMask/wallet-framework-engineers

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ Each package in this repository has its own README where you can find installati
5151
- [`@metamask/rate-limit-controller`](packages/rate-limit-controller)
5252
- [`@metamask/selected-network-controller`](packages/selected-network-controller)
5353
- [`@metamask/signature-controller`](packages/signature-controller)
54+
- [`@metamask/token-search-discovery-controller`](packages/token-search-discovery-controller)
5455
- [`@metamask/transaction-controller`](packages/transaction-controller)
5556
- [`@metamask/user-operation-controller`](packages/user-operation-controller)
5657

@@ -91,8 +92,10 @@ linkStyle default opacity:0.5
9192
profile_sync_controller(["@metamask/profile-sync-controller"]);
9293
queued_request_controller(["@metamask/queued-request-controller"]);
9394
rate_limit_controller(["@metamask/rate-limit-controller"]);
95+
remote_feature_flag_controller(["@metamask/remote-feature-flag-controller"]);
9496
selected_network_controller(["@metamask/selected-network-controller"]);
9597
signature_controller(["@metamask/signature-controller"]);
98+
token_search_discovery_controller(["@metamask/token-search-discovery-controller"]);
9699
transaction_controller(["@metamask/transaction-controller"]);
97100
user_operation_controller(["@metamask/user-operation-controller"]);
98101
accounts_controller --> base_controller;
@@ -164,6 +167,8 @@ linkStyle default opacity:0.5
164167
queued_request_controller --> network_controller;
165168
queued_request_controller --> selected_network_controller;
166169
rate_limit_controller --> base_controller;
170+
remote_feature_flag_controller --> base_controller;
171+
remote_feature_flag_controller --> controller_utils;
167172
selected_network_controller --> base_controller;
168173
selected_network_controller --> json_rpc_engine;
169174
selected_network_controller --> network_controller;
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Changelog
2+
3+
All notable changes to this project will be documented in this file.
4+
5+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7+
8+
## [Unreleased]
9+
10+
### Added
11+
12+
- Initial work to introduce the TokenSearchDiscoveryController ([#5142](https://github.com/MetaMask/core/pull/5142/))
13+
- This controller manages token search and discovery through the Portfolio API
14+
15+
[Unreleased]: https://github.com/MetaMask/core/
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
MIT License
2+
3+
Copyright (c) 2025 MetaMask
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# `@metamask/token-search-discovery-controller`
2+
3+
Manages token search and discovery through the Portfolio API.
4+
5+
## Installation
6+
7+
`yarn add @metamask/token-search-discovery-controller`
8+
9+
or
10+
11+
`npm install @metamask/token-search-discovery-controller`
12+
13+
## Contributing
14+
15+
This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* For a detailed explanation regarding each configuration property and type check, visit:
3+
* https://jestjs.io/docs/configuration
4+
*/
5+
6+
const merge = require('deepmerge');
7+
const path = require('path');
8+
9+
const baseConfig = require('../../jest.config.packages');
10+
11+
const displayName = path.basename(__dirname);
12+
13+
module.exports = merge(baseConfig, {
14+
// The display name when running multiple projects
15+
displayName,
16+
17+
// An object that configures minimum threshold enforcement for coverage results
18+
coverageThreshold: {
19+
global: {
20+
branches: 100,
21+
functions: 100,
22+
lines: 100,
23+
statements: 100,
24+
},
25+
},
26+
});
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
{
2+
"name": "@metamask/token-search-discovery-controller",
3+
"version": "0.0.0",
4+
"description": "Manages token search and discovery through the Portfolio API",
5+
"keywords": [
6+
"MetaMask",
7+
"Ethereum"
8+
],
9+
"homepage": "https://github.com/MetaMask/core/tree/main/packages/token-search-discovery-controller#readme",
10+
"bugs": {
11+
"url": "https://github.com/MetaMask/core/issues"
12+
},
13+
"repository": {
14+
"type": "git",
15+
"url": "https://github.com/MetaMask/core.git"
16+
},
17+
"license": "MIT",
18+
"sideEffects": false,
19+
"exports": {
20+
".": {
21+
"import": {
22+
"types": "./dist/index.d.mts",
23+
"default": "./dist/index.mjs"
24+
},
25+
"require": {
26+
"types": "./dist/index.d.cts",
27+
"default": "./dist/index.cjs"
28+
}
29+
},
30+
"./package.json": "./package.json"
31+
},
32+
"main": "./dist/index.cjs",
33+
"types": "./dist/index.d.cts",
34+
"files": [
35+
"dist/"
36+
],
37+
"scripts": {
38+
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
39+
"build:docs": "typedoc",
40+
"changelog:update": "../../scripts/update-changelog.sh @metamask/token-search-discovery-controller",
41+
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/token-search-discovery-controller",
42+
"publish:preview": "yarn npm publish --tag preview",
43+
"test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
44+
"test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
45+
"test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
46+
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch",
47+
"since-latest-release": "../../scripts/since-latest-release.sh"
48+
},
49+
"dependencies": {
50+
"@metamask/base-controller": "^7.1.1",
51+
"@metamask/utils": "^11.0.1"
52+
},
53+
"devDependencies": {
54+
"@metamask/auto-changelog": "^3.4.4",
55+
"@types/jest": "^27.4.1",
56+
"deepmerge": "^4.2.2",
57+
"jest": "^27.5.1",
58+
"ts-jest": "^27.1.4",
59+
"typedoc": "^0.24.8",
60+
"typedoc-plugin-missing-exports": "^2.0.0",
61+
"typescript": "~5.2.2"
62+
},
63+
"engines": {
64+
"node": "^18.18 || >=20"
65+
},
66+
"publishConfig": {
67+
"access": "public",
68+
"registry": "https://registry.npmjs.org/"
69+
}
70+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export { TokenSearchDiscoveryController } from './token-search-discovery-controller';
2+
export type { TokenSearchDiscoveryControllerState } from './token-search-discovery-controller';
3+
export type { TokenSearchResponseItem } from './types';
4+
5+
export { AbstractTokenSearchApiService } from './token-search-api-service/abstract-token-search-api-service';
6+
export { TokenSearchApiService } from './token-search-api-service/token-search-api-service';
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import type { TokenSearchParams, TokenSearchResponseItem } from '../types';
2+
3+
/**
4+
* Abstract class for fetching token search results.
5+
*/
6+
export abstract class AbstractTokenSearchApiService {
7+
/**
8+
* Fetches token search results from the portfolio API.
9+
*
10+
* @param tokenSearchParams - Optional search parameters including chains, name, and limit {@link TokenSearchParams}
11+
* @returns A promise resolving to an array of {@link TokenSearchResponseItem}
12+
*/
13+
abstract searchTokens(
14+
tokenSearchParams?: TokenSearchParams,
15+
): Promise<TokenSearchResponseItem[]>;
16+
}
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
import { TokenSearchApiService } from './token-search-api-service';
2+
3+
describe('TokenSearchApiService', () => {
4+
const baseUrl = 'https://test-api';
5+
let service: TokenSearchApiService;
6+
let mockFetch: jest.SpyInstance;
7+
8+
const mockResponses = {
9+
allParams: [
10+
{
11+
name: 'Token1',
12+
symbol: 'TK1',
13+
chainId: '1',
14+
tokenAddress: '0x1',
15+
usdPrice: 100,
16+
usdPricePercentChange: { oneDay: 10 },
17+
},
18+
{
19+
name: 'Token2',
20+
symbol: 'TK2',
21+
chainId: '1',
22+
tokenAddress: '0x2',
23+
usdPrice: 200,
24+
usdPricePercentChange: { oneDay: 20 },
25+
},
26+
],
27+
onlyChain: [
28+
{
29+
name: 'ChainToken',
30+
symbol: 'CTK',
31+
chainId: '1',
32+
tokenAddress: '0x3',
33+
usdPrice: 300,
34+
usdPricePercentChange: { oneDay: 30 },
35+
},
36+
],
37+
onlyName: [
38+
{
39+
name: 'NameMatch',
40+
symbol: 'NM',
41+
chainId: '1',
42+
tokenAddress: '0x4',
43+
usdPrice: 400,
44+
usdPricePercentChange: { oneDay: 40 },
45+
},
46+
],
47+
};
48+
49+
beforeEach(() => {
50+
service = new TokenSearchApiService(baseUrl);
51+
mockFetch = jest
52+
.spyOn(global, 'fetch')
53+
.mockResolvedValue(new Response(JSON.stringify([]), { status: 200 }));
54+
});
55+
56+
afterEach(() => {
57+
mockFetch.mockRestore();
58+
});
59+
60+
describe('constructor', () => {
61+
it('should throw if baseUrl is empty', () => {
62+
expect(() => new TokenSearchApiService('')).toThrow(
63+
'Portfolio API URL is not set',
64+
);
65+
});
66+
});
67+
68+
describe('searchTokens', () => {
69+
it.each([
70+
{
71+
params: { chains: ['1'], name: 'Test', limit: '10' },
72+
expectedUrl: new URL(
73+
`${baseUrl}/tokens-search/name?chains=1&name=Test&limit=10`,
74+
),
75+
},
76+
{
77+
params: { chains: ['1', '137'], name: 'Test' },
78+
expectedUrl: new URL(
79+
`${baseUrl}/tokens-search/name?chains=1%2C137&name=Test`,
80+
),
81+
},
82+
{
83+
params: { name: 'Test' },
84+
expectedUrl: new URL(`${baseUrl}/tokens-search/name?name=Test`),
85+
},
86+
{
87+
params: { chains: ['1'] },
88+
expectedUrl: new URL(`${baseUrl}/tokens-search/name?chains=1`),
89+
},
90+
{
91+
params: { limit: '20' },
92+
expectedUrl: new URL(`${baseUrl}/tokens-search/name?limit=20`),
93+
},
94+
{
95+
params: {},
96+
expectedUrl: new URL(`${baseUrl}/tokens-search/name`),
97+
},
98+
])(
99+
'should construct correct URL for params: $params',
100+
async ({ params, expectedUrl }) => {
101+
await service.searchTokens(params);
102+
expect(mockFetch.mock.calls[0][0].toString()).toBe(
103+
expectedUrl.toString(),
104+
);
105+
},
106+
);
107+
108+
it('should handle API errors', async () => {
109+
mockFetch.mockResolvedValueOnce(
110+
new Response('Server Error', { status: 500 }),
111+
);
112+
113+
await expect(service.searchTokens({})).rejects.toThrow(
114+
'Portfolio API request failed with status: 500',
115+
);
116+
});
117+
});
118+
119+
describe('searchTokens response handling', () => {
120+
it.each([
121+
{
122+
params: { chains: ['1'], name: 'Test', limit: '2' },
123+
mockResponse: mockResponses.allParams,
124+
description: 'all parameters',
125+
},
126+
{
127+
params: { chains: ['1'] },
128+
mockResponse: mockResponses.onlyChain,
129+
description: 'only chain parameter',
130+
},
131+
{
132+
params: { name: 'Name' },
133+
mockResponse: mockResponses.onlyName,
134+
description: 'only name parameter',
135+
},
136+
])(
137+
'should handle response correctly regardless of params',
138+
async ({ params, mockResponse }) => {
139+
mockFetch = jest
140+
.spyOn(global, 'fetch')
141+
.mockResolvedValue(
142+
new Response(JSON.stringify(mockResponse), { status: 200 }),
143+
);
144+
145+
const response = await service.searchTokens(params);
146+
147+
expect(response).toStrictEqual(mockResponse);
148+
},
149+
);
150+
});
151+
});

0 commit comments

Comments
 (0)