Skip to content

Commit

Permalink
feat: Add mm portfolio api - token search controller (#5142)
Browse files Browse the repository at this point in the history
## 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
  • Loading branch information
Bigshmow authored Jan 17, 2025
1 parent 52d1c16 commit d6a4c8f
Show file tree
Hide file tree
Showing 21 changed files with 695 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
## Snaps Team
/packages/rate-limit-controller @MetaMask/snaps-devs

## Portfolio Team
/packages/token-search-discovery-controller @MetaMask/portfolio

## Wallet API Platform Team
/packages/multichain @MetaMask/wallet-api-platform-engineers
/packages/queued-request-controller @MetaMask/wallet-api-platform-engineers
Expand Down Expand Up @@ -100,3 +103,5 @@
/packages/transaction-controller/CHANGELOG.md @MetaMask/confirmations @MetaMask/wallet-framework-engineers
/packages/user-operation-controller/package.json @MetaMask/confirmations @MetaMask/wallet-framework-engineers
/packages/user-operation-controller/CHANGELOG.md @MetaMask/confirmations @MetaMask/wallet-framework-engineers
/packages/token-search-discovery-controller/package.json @MetaMask/portfolio @MetaMask/wallet-framework-engineers
/packages/token-search-discovery-controller/CHANGELOG.md @MetaMask/portfolio @MetaMask/wallet-framework-engineers
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Each package in this repository has its own README where you can find installati
- [`@metamask/rate-limit-controller`](packages/rate-limit-controller)
- [`@metamask/selected-network-controller`](packages/selected-network-controller)
- [`@metamask/signature-controller`](packages/signature-controller)
- [`@metamask/token-search-discovery-controller`](packages/token-search-discovery-controller)
- [`@metamask/transaction-controller`](packages/transaction-controller)
- [`@metamask/user-operation-controller`](packages/user-operation-controller)

Expand Down Expand Up @@ -91,8 +92,10 @@ linkStyle default opacity:0.5
profile_sync_controller(["@metamask/profile-sync-controller"]);
queued_request_controller(["@metamask/queued-request-controller"]);
rate_limit_controller(["@metamask/rate-limit-controller"]);
remote_feature_flag_controller(["@metamask/remote-feature-flag-controller"]);
selected_network_controller(["@metamask/selected-network-controller"]);
signature_controller(["@metamask/signature-controller"]);
token_search_discovery_controller(["@metamask/token-search-discovery-controller"]);
transaction_controller(["@metamask/transaction-controller"]);
user_operation_controller(["@metamask/user-operation-controller"]);
accounts_controller --> base_controller;
Expand Down Expand Up @@ -164,6 +167,8 @@ linkStyle default opacity:0.5
queued_request_controller --> network_controller;
queued_request_controller --> selected_network_controller;
rate_limit_controller --> base_controller;
remote_feature_flag_controller --> base_controller;
remote_feature_flag_controller --> controller_utils;
selected_network_controller --> base_controller;
selected_network_controller --> json_rpc_engine;
selected_network_controller --> network_controller;
Expand Down
15 changes: 15 additions & 0 deletions packages/token-search-discovery-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Initial work to introduce the TokenSearchDiscoveryController ([#5142](https://github.com/MetaMask/core/pull/5142/))
- This controller manages token search and discovery through the Portfolio API

[Unreleased]: https://github.com/MetaMask/core/
20 changes: 20 additions & 0 deletions packages/token-search-discovery-controller/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
MIT License

Copyright (c) 2025 MetaMask

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
15 changes: 15 additions & 0 deletions packages/token-search-discovery-controller/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# `@metamask/token-search-discovery-controller`

Manages token search and discovery through the Portfolio API.

## Installation

`yarn add @metamask/token-search-discovery-controller`

or

`npm install @metamask/token-search-discovery-controller`

## Contributing

This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
26 changes: 26 additions & 0 deletions packages/token-search-discovery-controller/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/

const merge = require('deepmerge');
const path = require('path');

const baseConfig = require('../../jest.config.packages');

const displayName = path.basename(__dirname);

module.exports = merge(baseConfig, {
// The display name when running multiple projects
displayName,

// An object that configures minimum threshold enforcement for coverage results
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
});
70 changes: 70 additions & 0 deletions packages/token-search-discovery-controller/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"name": "@metamask/token-search-discovery-controller",
"version": "0.0.0",
"description": "Manages token search and discovery through the Portfolio API",
"keywords": [
"MetaMask",
"Ethereum"
],
"homepage": "https://github.com/MetaMask/core/tree/main/packages/token-search-discovery-controller#readme",
"bugs": {
"url": "https://github.com/MetaMask/core/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/MetaMask/core.git"
},
"license": "MIT",
"sideEffects": false,
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./package.json": "./package.json"
},
"main": "./dist/index.cjs",
"types": "./dist/index.d.cts",
"files": [
"dist/"
],
"scripts": {
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
"build:docs": "typedoc",
"changelog:update": "../../scripts/update-changelog.sh @metamask/token-search-discovery-controller",
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/token-search-discovery-controller",
"publish:preview": "yarn npm publish --tag preview",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
"test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
"test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch",
"since-latest-release": "../../scripts/since-latest-release.sh"
},
"dependencies": {
"@metamask/base-controller": "^7.1.1",
"@metamask/utils": "^11.0.1"
},
"devDependencies": {
"@metamask/auto-changelog": "^3.4.4",
"@types/jest": "^27.4.1",
"deepmerge": "^4.2.2",
"jest": "^27.5.1",
"ts-jest": "^27.1.4",
"typedoc": "^0.24.8",
"typedoc-plugin-missing-exports": "^2.0.0",
"typescript": "~5.2.2"
},
"engines": {
"node": "^18.18 || >=20"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}
6 changes: 6 additions & 0 deletions packages/token-search-discovery-controller/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export { TokenSearchDiscoveryController } from './token-search-discovery-controller';
export type { TokenSearchDiscoveryControllerState } from './token-search-discovery-controller';
export type { TokenSearchResponseItem } from './types';

export { AbstractTokenSearchApiService } from './token-search-api-service/abstract-token-search-api-service';
export { TokenSearchApiService } from './token-search-api-service/token-search-api-service';
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { TokenSearchParams, TokenSearchResponseItem } from '../types';

/**
* Abstract class for fetching token search results.
*/
export abstract class AbstractTokenSearchApiService {
/**
* Fetches token search results from the portfolio API.
*
* @param tokenSearchParams - Optional search parameters including chains, name, and limit {@link TokenSearchParams}
* @returns A promise resolving to an array of {@link TokenSearchResponseItem}
*/
abstract searchTokens(
tokenSearchParams?: TokenSearchParams,
): Promise<TokenSearchResponseItem[]>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { TokenSearchApiService } from './token-search-api-service';

describe('TokenSearchApiService', () => {
const baseUrl = 'https://test-api';
let service: TokenSearchApiService;
let mockFetch: jest.SpyInstance;

const mockResponses = {
allParams: [
{
name: 'Token1',
symbol: 'TK1',
chainId: '1',
tokenAddress: '0x1',
usdPrice: 100,
usdPricePercentChange: { oneDay: 10 },
},
{
name: 'Token2',
symbol: 'TK2',
chainId: '1',
tokenAddress: '0x2',
usdPrice: 200,
usdPricePercentChange: { oneDay: 20 },
},
],
onlyChain: [
{
name: 'ChainToken',
symbol: 'CTK',
chainId: '1',
tokenAddress: '0x3',
usdPrice: 300,
usdPricePercentChange: { oneDay: 30 },
},
],
onlyName: [
{
name: 'NameMatch',
symbol: 'NM',
chainId: '1',
tokenAddress: '0x4',
usdPrice: 400,
usdPricePercentChange: { oneDay: 40 },
},
],
};

beforeEach(() => {
service = new TokenSearchApiService(baseUrl);
mockFetch = jest
.spyOn(global, 'fetch')
.mockResolvedValue(new Response(JSON.stringify([]), { status: 200 }));
});

afterEach(() => {
mockFetch.mockRestore();
});

describe('constructor', () => {
it('should throw if baseUrl is empty', () => {
expect(() => new TokenSearchApiService('')).toThrow(
'Portfolio API URL is not set',
);
});
});

describe('searchTokens', () => {
it.each([
{
params: { chains: ['1'], name: 'Test', limit: '10' },
expectedUrl: new URL(
`${baseUrl}/tokens-search/name?chains=1&name=Test&limit=10`,
),
},
{
params: { chains: ['1', '137'], name: 'Test' },
expectedUrl: new URL(
`${baseUrl}/tokens-search/name?chains=1%2C137&name=Test`,
),
},
{
params: { name: 'Test' },
expectedUrl: new URL(`${baseUrl}/tokens-search/name?name=Test`),
},
{
params: { chains: ['1'] },
expectedUrl: new URL(`${baseUrl}/tokens-search/name?chains=1`),
},
{
params: { limit: '20' },
expectedUrl: new URL(`${baseUrl}/tokens-search/name?limit=20`),
},
{
params: {},
expectedUrl: new URL(`${baseUrl}/tokens-search/name`),
},
])(
'should construct correct URL for params: $params',
async ({ params, expectedUrl }) => {
await service.searchTokens(params);
expect(mockFetch.mock.calls[0][0].toString()).toBe(
expectedUrl.toString(),
);
},
);

it('should handle API errors', async () => {
mockFetch.mockResolvedValueOnce(
new Response('Server Error', { status: 500 }),
);

await expect(service.searchTokens({})).rejects.toThrow(
'Portfolio API request failed with status: 500',
);
});
});

describe('searchTokens response handling', () => {
it.each([
{
params: { chains: ['1'], name: 'Test', limit: '2' },
mockResponse: mockResponses.allParams,
description: 'all parameters',
},
{
params: { chains: ['1'] },
mockResponse: mockResponses.onlyChain,
description: 'only chain parameter',
},
{
params: { name: 'Name' },
mockResponse: mockResponses.onlyName,
description: 'only name parameter',
},
])(
'should handle response correctly regardless of params',
async ({ params, mockResponse }) => {
mockFetch = jest
.spyOn(global, 'fetch')
.mockResolvedValue(
new Response(JSON.stringify(mockResponse), { status: 200 }),
);

const response = await service.searchTokens(params);

expect(response).toStrictEqual(mockResponse);
},
);
});
});
Loading

0 comments on commit d6a4c8f

Please sign in to comment.