-
-
Notifications
You must be signed in to change notification settings - Fork 201
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
- Loading branch information
Showing
21 changed files
with
695 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}, | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; |
16 changes: 16 additions & 0 deletions
16
...ch-discovery-controller/src/token-search-api-service/abstract-token-search-api-service.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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[]>; | ||
} |
151 changes: 151 additions & 0 deletions
151
...search-discovery-controller/src/token-search-api-service/token-search-api-service.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}, | ||
); | ||
}); | ||
}); |
Oops, something went wrong.