diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 7da370ce3fe..d7de5a8aef5 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -39,6 +39,7 @@ ## Earn Team /packages/earn-controller @MetaMask/earn +/packages/chomp-api-service @MetaMask/earn ## Social AI Team /packages/ai-controllers @MetaMask/social-ai @@ -226,3 +227,5 @@ /packages/social-controllers/CHANGELOG.md @MetaMask/social-ai @MetaMask/core-platform /packages/money-account-controller/package.json @MetaMask/accounts-engineers @MetaMask/core-platform /packages/money-account-controller/CHANGELOG.md @MetaMask/accounts-engineers @MetaMask/core-platform +/packages/chomp-api-service/package.json @MetaMask/accounts-engineers @MetaMask/core-platform +/packages/chomp-api-service/CHANGELOG.md @MetaMask/accounts-engineers @MetaMask/core-platform diff --git a/README.md b/README.md index 352fec4e6ec..7e2e6fb75f1 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ Each package in this repository has its own README where you can find installati - [`@metamask/bridge-status-controller`](packages/bridge-status-controller) - [`@metamask/build-utils`](packages/build-utils) - [`@metamask/chain-agnostic-permission`](packages/chain-agnostic-permission) +- [`@metamask/chomp-api-service`](packages/chomp-api-service) - [`@metamask/claims-controller`](packages/claims-controller) - [`@metamask/client-controller`](packages/client-controller) - [`@metamask/compliance-controller`](packages/compliance-controller) @@ -123,6 +124,7 @@ linkStyle default opacity:0.5 bridge_status_controller(["@metamask/bridge-status-controller"]); build_utils(["@metamask/build-utils"]); chain_agnostic_permission(["@metamask/chain-agnostic-permission"]); + chomp_api_service(["@metamask/chomp-api-service"]); claims_controller(["@metamask/claims-controller"]); client_controller(["@metamask/client-controller"]); compliance_controller(["@metamask/compliance-controller"]); @@ -274,6 +276,9 @@ linkStyle default opacity:0.5 bridge_status_controller --> transaction_controller; chain_agnostic_permission --> controller_utils; chain_agnostic_permission --> permission_controller; + chomp_api_service --> base_data_service; + chomp_api_service --> controller_utils; + chomp_api_service --> messenger; claims_controller --> base_controller; claims_controller --> controller_utils; claims_controller --> keyring_controller; diff --git a/packages/chomp-api-service/CHANGELOG.md b/packages/chomp-api-service/CHANGELOG.md new file mode 100644 index 00000000000..c050ac9419d --- /dev/null +++ b/packages/chomp-api-service/CHANGELOG.md @@ -0,0 +1,14 @@ +# 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 + +- Add `ChompApiService` ([#8361](https://github.com/MetaMask/core/pull/8413)) + +[Unreleased]: https://github.com/MetaMask/core/ diff --git a/packages/chomp-api-service/LICENSE b/packages/chomp-api-service/LICENSE new file mode 100644 index 00000000000..c8a0ff6be3a --- /dev/null +++ b/packages/chomp-api-service/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2026 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 diff --git a/packages/chomp-api-service/README.md b/packages/chomp-api-service/README.md new file mode 100644 index 00000000000..a12245d8d5f --- /dev/null +++ b/packages/chomp-api-service/README.md @@ -0,0 +1,15 @@ +# `@metamask/chom-api-service` + +Chomp API data service. + +## Installation + +`yarn add @metamask/chom-api-service` + +or + +`npm install @metamask/chom-api-service` + +## Contributing + +This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme). diff --git a/packages/chomp-api-service/jest.config.js b/packages/chomp-api-service/jest.config.js new file mode 100644 index 00000000000..ca084133399 --- /dev/null +++ b/packages/chomp-api-service/jest.config.js @@ -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, + }, + }, +}); diff --git a/packages/chomp-api-service/package.json b/packages/chomp-api-service/package.json new file mode 100644 index 00000000000..203f007a605 --- /dev/null +++ b/packages/chomp-api-service/package.json @@ -0,0 +1,76 @@ +{ + "name": "@metamask/chomp-api-service", + "version": "0.0.0", + "description": "Data service for the Chomp API", + "keywords": [ + "MetaMask", + "Ethereum" + ], + "homepage": "https://github.com/MetaMask/core/tree/main/packages/chomp-api-service#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:all": "ts-bridge --project tsconfig.build.json --verbose --clean", + "build:docs": "typedoc", + "changelog:update": "../../scripts/update-changelog.sh @metamask/chomp-api-service", + "changelog:validate": "../../scripts/validate-changelog.sh @metamask/chomp-api-service", + "since-latest-release": "../../scripts/since-latest-release.sh", + "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" + }, + "dependencies": { + "@metamask/base-data-service": "^0.1.1", + "@metamask/controller-utils": "^11.20.0", + "@metamask/messenger": "^1.1.1", + "@metamask/superstruct": "^3.1.0", + "@metamask/utils": "^11.9.0", + "@tanstack/query-core": "^4.43.0" + }, + "devDependencies": { + "@metamask/auto-changelog": "^3.4.4", + "@ts-bridge/cli": "^0.6.4", + "@types/jest": "^29.5.14", + "deepmerge": "^4.2.2", + "jest": "^29.7.0", + "nock": "^13.3.1", + "ts-jest": "^29.2.5", + "typedoc": "^0.25.13", + "typedoc-plugin-missing-exports": "^2.0.0", + "typescript": "~5.3.3" + }, + "engines": { + "node": "^18.18 || >=20" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + } +} diff --git a/packages/chomp-api-service/src/chomp-api-service-method-action-types.ts b/packages/chomp-api-service/src/chomp-api-service-method-action-types.ts new file mode 100644 index 00000000000..87454e3759d --- /dev/null +++ b/packages/chomp-api-service/src/chomp-api-service-method-action-types.ts @@ -0,0 +1,74 @@ +/** + * This file is auto generated. + * Do not edit manually. + */ + +import type { ChompApiService } from './chomp-api-service'; + +/** + * Associates an address with a CHOMP profile via POST /v1/auth/address. + */ +export type ChompApiServiceAssociateAddressAction = { + type: `ChompApiService:associateAddress`; + handler: ChompApiService['associateAddress']; +}; + +/** + * Creates an account upgrade via POST /v1/account-upgrade. + */ +export type ChompApiServiceCreateUpgradeAction = { + type: `ChompApiService:createUpgrade`; + handler: ChompApiService['createUpgrade']; +}; + +/** + * Fetches the upgrade record for an address via GET /v1/account-upgrade/:address. + */ +export type ChompApiServiceGetUpgradeAction = { + type: `ChompApiService:getUpgrade`; + handler: ChompApiService['getUpgrade']; +}; + +/** + * Verifies a delegation via POST /v1/intent/verify-delegation. + */ +export type ChompApiServiceVerifyDelegationAction = { + type: `ChompApiService:verifyDelegation`; + handler: ChompApiService['verifyDelegation']; +}; + +/** + * Submits intents via POST /v1/intent. + */ +export type ChompApiServiceCreateIntentsAction = { + type: `ChompApiService:createIntents`; + handler: ChompApiService['createIntents']; +}; + +/** + * Fetches intents by address via GET /v1/intent/account/:address. + */ +export type ChompApiServiceGetIntentsByAddressAction = { + type: `ChompApiService:getIntentsByAddress`; + handler: ChompApiService['getIntentsByAddress']; +}; + +/** + * Creates a withdrawal for card spend flows. + */ +export type ChompApiServiceCreateWithdrawalAction = { + type: `ChompApiService:createWithdrawal`; + handler: ChompApiService['createWithdrawal']; +}; + +/** + * Union of all ChompApiService action types. + */ +export type ChompApiServiceMethodActions = + | ChompApiServiceAssociateAddressAction + | ChompApiServiceCreateUpgradeAction + | ChompApiServiceGetUpgradeAction + | ChompApiServiceVerifyDelegationAction + | ChompApiServiceCreateIntentsAction + | ChompApiServiceGetIntentsByAddressAction + | ChompApiServiceCreateWithdrawalAction; diff --git a/packages/chomp-api-service/src/chomp-api-service.test.ts b/packages/chomp-api-service/src/chomp-api-service.test.ts new file mode 100644 index 00000000000..0c79cc63076 --- /dev/null +++ b/packages/chomp-api-service/src/chomp-api-service.test.ts @@ -0,0 +1,525 @@ +import { DEFAULT_MAX_RETRIES } from '@metamask/controller-utils'; +import { Messenger, MOCK_ANY_NAMESPACE } from '@metamask/messenger'; +import type { + MockAnyNamespace, + MessengerActions, + MessengerEvents, +} from '@metamask/messenger'; +import nock from 'nock'; + +import type { ChompApiServiceMessenger } from './chomp-api-service'; +import { ChompApiService } from './chomp-api-service'; + +const BASE_URL = 'https://api.chomp.example.com'; +const MOCK_TOKEN = 'mock-jwt-token'; + +describe('ChompApiService', () => { + describe('associateAddress', () => { + it('sends a POST with auth headers and returns the response on 201', async () => { + nock(BASE_URL) + .post('/v1/auth/address', { + signature: '0x123', + timestamp: '2026-01-01T00:00:00Z', + address: '0xabc', + }) + .matchHeader('Authorization', `Bearer ${MOCK_TOKEN}`) + .matchHeader('Content-Type', 'application/json') + .reply(201, { + profileId: 'p1', + address: '0xabc', + status: 'created', + }); + const { rootMessenger } = createService(); + + const result = await rootMessenger.call( + 'ChompApiService:associateAddress', + { + signature: '0x123', + timestamp: '2026-01-01T00:00:00Z', + address: '0xabc', + }, + ); + + expect(result).toStrictEqual({ + profileId: 'p1', + address: '0xabc', + status: 'created', + }); + }); + + it('returns the response on 409 without throwing', async () => { + nock(BASE_URL).post('/v1/auth/address').reply(409, { + profileId: 'p1', + address: '0xabc', + status: 'already_associated', + }); + const { service } = createService(); + + const result = await service.associateAddress({ + signature: '0x123', + timestamp: '2026-01-01T00:00:00Z', + address: '0xabc', + }); + + expect(result).toStrictEqual({ + profileId: 'p1', + address: '0xabc', + status: 'already_associated', + }); + }); + + it('throws on non-201/409 status', async () => { + nock(BASE_URL) + .post('/v1/auth/address') + .times(DEFAULT_MAX_RETRIES + 1) + .reply(500); + const { service } = createService(); + + await expect( + service.associateAddress({ + signature: '0x123', + timestamp: '2026-01-01T00:00:00Z', + address: '0xabc', + }), + ).rejects.toThrow("POST /v1/auth/address failed with status '500'"); + }); + + it('throws on malformed response', async () => { + nock(BASE_URL) + .post('/v1/auth/address') + .reply(201, JSON.stringify({ missing: 'fields' })); + const { service } = createService(); + + await expect( + service.associateAddress({ + signature: '0x123', + timestamp: '2026-01-01T00:00:00Z', + address: '0xabc', + }), + ).rejects.toThrow('At path: profileId -- Expected a string'); + }); + }); + + describe('createUpgrade', () => { + const upgradeRequest = { + r: '0x1', + s: '0x2', + v: 27, + yParity: 0, + address: '0xabc', + chainId: '1', + nonce: '0', + }; + + const upgradeResponse = { + signerAddress: '0xdef', + status: 'pending', + createdAt: '2026-01-01T00:00:00Z', + }; + + it('sends a POST with auth headers and returns the response', async () => { + nock(BASE_URL) + .post('/v1/account-upgrade', upgradeRequest) + .matchHeader('Authorization', `Bearer ${MOCK_TOKEN}`) + .reply(200, upgradeResponse); + const { rootMessenger } = createService(); + + const result = await rootMessenger.call( + 'ChompApiService:createUpgrade', + upgradeRequest, + ); + + expect(result).toStrictEqual(upgradeResponse); + }); + + it('throws on non-OK status', async () => { + nock(BASE_URL) + .post('/v1/account-upgrade') + .times(DEFAULT_MAX_RETRIES + 1) + .reply(500); + const { service } = createService(); + + await expect(service.createUpgrade(upgradeRequest)).rejects.toThrow( + "POST /v1/account-upgrade failed with status '500'", + ); + }); + + it('throws on malformed response', async () => { + nock(BASE_URL) + .post('/v1/account-upgrade') + .reply(200, JSON.stringify({ bad: 'data' })); + const { service } = createService(); + + await expect(service.createUpgrade(upgradeRequest)).rejects.toThrow( + 'At path: signerAddress -- Expected a string', + ); + }); + }); + + describe('getUpgrade', () => { + const upgradeRecord = { + signerAddress: '0xdef', + status: 'pending', + createdAt: '2026-01-01T00:00:00Z', + }; + + it('sends a GET with auth headers and returns the upgrade record', async () => { + nock(BASE_URL) + .get('/v1/account-upgrade/0xabc') + .matchHeader('Authorization', `Bearer ${MOCK_TOKEN}`) + .reply(200, upgradeRecord); + const { rootMessenger } = createService(); + + const result = await rootMessenger.call( + 'ChompApiService:getUpgrade', + '0xabc', + ); + + expect(result).toStrictEqual(upgradeRecord); + }); + + it('returns null on 404', async () => { + nock(BASE_URL).get('/v1/account-upgrade/0xabc').reply(404); + const { service } = createService(); + + const result = await service.getUpgrade('0xabc'); + + expect(result).toBeNull(); + }); + + it('throws on non-OK/non-404 status', async () => { + nock(BASE_URL) + .get('/v1/account-upgrade/0xabc') + .times(DEFAULT_MAX_RETRIES + 1) + .reply(500); + const { service } = createService(); + + await expect(service.getUpgrade('0xabc')).rejects.toThrow( + "Get upgrade request failed with status '500'", + ); + }); + + it('throws on malformed response', async () => { + nock(BASE_URL) + .get('/v1/account-upgrade/0xabc') + .reply(200, JSON.stringify({ bad: 'data' })); + const { service } = createService(); + + await expect(service.getUpgrade('0xabc')).rejects.toThrow( + 'At path: signerAddress -- Expected a string', + ); + }); + }); + + describe('verifyDelegation', () => { + const delegationRequest = { + signedDelegation: { + delegate: '0x1' as const, + delegator: '0x2' as const, + authority: '0x3' as const, + caveats: [], + salt: '0x4' as const, + signature: '0x5' as const, + }, + chainId: '0x1' as const, + }; + + it('sends a POST with auth headers and returns the response', async () => { + nock(BASE_URL) + .post('/v1/intent/verify-delegation', delegationRequest) + .matchHeader('Authorization', `Bearer ${MOCK_TOKEN}`) + .reply(200, { valid: true, delegationHash: '0xhash123' }); + const { rootMessenger } = createService(); + + const result = await rootMessenger.call( + 'ChompApiService:verifyDelegation', + delegationRequest, + ); + + expect(result).toStrictEqual({ + valid: true, + delegationHash: '0xhash123', + }); + }); + + it('returns errors when delegation is invalid', async () => { + nock(BASE_URL) + .post('/v1/intent/verify-delegation') + .reply(200, { valid: false, errors: ['bad signature'] }); + const { service } = createService(); + + const result = await service.verifyDelegation(delegationRequest); + + expect(result).toStrictEqual({ + valid: false, + errors: ['bad signature'], + }); + }); + + it('throws on non-OK status', async () => { + nock(BASE_URL) + .post('/v1/intent/verify-delegation') + .times(DEFAULT_MAX_RETRIES + 1) + .reply(400); + const { service } = createService(); + + await expect(service.verifyDelegation(delegationRequest)).rejects.toThrow( + "POST /v1/intent/verify-delegation failed with status '400'", + ); + }); + + it('throws on malformed response', async () => { + nock(BASE_URL) + .post('/v1/intent/verify-delegation') + .reply(200, JSON.stringify({ bad: 'data' })); + const { service } = createService(); + + await expect(service.verifyDelegation(delegationRequest)).rejects.toThrow( + 'At path: valid -- Expected a value of type `boolean`', + ); + }); + }); + + describe('createIntents', () => { + const intentRequest = [ + { + account: '0xabc' as const, + delegationHash: '0xdef' as const, + chainId: '0x1' as const, + metadata: { + allowance: '0xff' as const, + tokenSymbol: 'USDC', + tokenAddress: '0x123' as const, + type: 'cash-deposit' as const, + }, + }, + ]; + + const intentResponse = [ + { + delegationHash: '0xdef', + metadata: { + allowance: '0xff', + tokenSymbol: 'USDC', + tokenAddress: '0x123', + type: 'cash-deposit', + }, + createdAt: '2026-01-01T00:00:00Z', + }, + ]; + + it('sends a POST with auth headers and returns the response array', async () => { + nock(BASE_URL) + .post('/v1/intent', intentRequest) + .matchHeader('Authorization', `Bearer ${MOCK_TOKEN}`) + .reply(201, intentResponse); + const { rootMessenger } = createService(); + + const result = await rootMessenger.call( + 'ChompApiService:createIntents', + intentRequest, + ); + + expect(result).toStrictEqual(intentResponse); + }); + + it('throws on non-OK status', async () => { + nock(BASE_URL) + .post('/v1/intent') + .times(DEFAULT_MAX_RETRIES + 1) + .reply(409); + const { service } = createService(); + + await expect(service.createIntents(intentRequest)).rejects.toThrow( + "POST /v1/intent failed with status '409'", + ); + }); + + it('throws on malformed response', async () => { + nock(BASE_URL) + .post('/v1/intent') + .reply(201, JSON.stringify([{ bad: 'data' }])); + const { service } = createService(); + + await expect(service.createIntents(intentRequest)).rejects.toThrow( + 'At path: 0.delegationHash -- Expected a string', + ); + }); + }); + + describe('getIntentsByAddress', () => { + const intentsResponse = [ + { + account: '0xabc', + delegationHash: '0xdef', + chainId: '0x1', + status: 'active', + metadata: { + allowance: '0xff', + tokenAddress: '0x123', + tokenSymbol: 'USDC', + type: 'deposit', + }, + }, + ]; + + it('sends a GET with auth headers and returns the intents array', async () => { + nock(BASE_URL) + .get('/v1/intent/account/0xabc') + .matchHeader('Authorization', `Bearer ${MOCK_TOKEN}`) + .reply(200, intentsResponse); + const { rootMessenger } = createService(); + + const result = await rootMessenger.call( + 'ChompApiService:getIntentsByAddress', + '0xabc', + ); + + expect(result).toStrictEqual(intentsResponse); + }); + + it('returns an empty array when no intents exist', async () => { + nock(BASE_URL).get('/v1/intent/account/0xabc').reply(200, []); + const { service } = createService(); + + const result = await service.getIntentsByAddress('0xabc'); + + expect(result).toStrictEqual([]); + }); + + it('throws on non-OK status', async () => { + nock(BASE_URL) + .get('/v1/intent/account/0xabc') + .times(DEFAULT_MAX_RETRIES + 1) + .reply(500); + const { service } = createService(); + + await expect(service.getIntentsByAddress('0xabc')).rejects.toThrow( + "Get intents request failed with status '500'", + ); + }); + + it('throws on malformed response', async () => { + nock(BASE_URL) + .get('/v1/intent/account/0xabc') + .reply(200, JSON.stringify([{ bad: 'data' }])); + const { service } = createService(); + + await expect(service.getIntentsByAddress('0xabc')).rejects.toThrow( + 'At path: 0.account -- Expected a string', + ); + }); + }); + + describe('createWithdrawal', () => { + const withdrawalRequest = { + chainId: '0x1' as const, + amount: '1000000', + account: '0xabc' as const, + }; + + it('sends a POST with auth headers and returns the response', async () => { + nock(BASE_URL) + .post('/v1/withdrawal', withdrawalRequest) + .matchHeader('Authorization', `Bearer ${MOCK_TOKEN}`) + .reply(200, { success: true }); + const { rootMessenger } = createService(); + + const result = await rootMessenger.call( + 'ChompApiService:createWithdrawal', + withdrawalRequest, + ); + + expect(result).toStrictEqual({ success: true }); + }); + + it('throws on non-OK status', async () => { + nock(BASE_URL) + .post('/v1/withdrawal') + .times(DEFAULT_MAX_RETRIES + 1) + .reply(400); + const { service } = createService(); + + await expect(service.createWithdrawal(withdrawalRequest)).rejects.toThrow( + "POST /v1/withdrawal failed with status '400'", + ); + }); + + it('throws on malformed response', async () => { + nock(BASE_URL) + .post('/v1/withdrawal') + .reply(200, JSON.stringify({ success: false })); + const { service } = createService(); + + await expect(service.createWithdrawal(withdrawalRequest)).rejects.toThrow( + 'At path: success -- Expected the literal `true`', + ); + }); + }); +}); + +/** + * The type of the messenger populated with all external actions and events + * required by the service under test. + */ +type RootMessenger = Messenger< + MockAnyNamespace, + MessengerActions, + MessengerEvents +>; + +/** + * Constructs the messenger populated with all external actions and events + * required by the service under test. + * + * @returns The root messenger. + */ +function createRootMessenger(): RootMessenger { + return new Messenger({ namespace: MOCK_ANY_NAMESPACE }); +} + +/** + * Constructs the messenger for the service under test. + * + * @param rootMessenger - The root messenger, with all external actions and + * events required by the controller's messenger. + * @returns The service-specific messenger. + */ +function createServiceMessenger( + rootMessenger: RootMessenger, +): ChompApiServiceMessenger { + return new Messenger({ + namespace: 'ChompApiService', + parent: rootMessenger, + }); +} + +/** + * Constructs the service under test. + * + * @param args - The arguments to this function. + * @param args.options - The options that the service constructor takes. All are + * optional and will be filled in with defaults as needed (including + * `messenger`). + * @returns The new service, root messenger, and service messenger. + */ +function createService({ + options = {}, +}: { + options?: Partial[0]>; +} = {}): { + service: ChompApiService; + rootMessenger: RootMessenger; + messenger: ChompApiServiceMessenger; +} { + const rootMessenger = createRootMessenger(); + const messenger = createServiceMessenger(rootMessenger); + const service = new ChompApiService({ + baseUrl: BASE_URL, + getAccessToken: async (): Promise => MOCK_TOKEN, + messenger, + ...options, + }); + + return { service, rootMessenger, messenger }; +} diff --git a/packages/chomp-api-service/src/chomp-api-service.ts b/packages/chomp-api-service/src/chomp-api-service.ts new file mode 100644 index 00000000000..ffe34f79e09 --- /dev/null +++ b/packages/chomp-api-service/src/chomp-api-service.ts @@ -0,0 +1,433 @@ +import { BaseDataService } from '@metamask/base-data-service'; +import type { + DataServiceCacheUpdatedEvent, + DataServiceGranularCacheUpdatedEvent, + DataServiceInvalidateQueriesAction, +} from '@metamask/base-data-service'; +import type { + CreateServicePolicyOptions, + ServicePolicy, +} from '@metamask/controller-utils'; +import { createServicePolicy, HttpError } from '@metamask/controller-utils'; +import type { Messenger } from '@metamask/messenger'; +import { + array, + boolean, + create, + enums, + literal, + optional, + string, + type, +} from '@metamask/superstruct'; +import type { QueryClientConfig } from '@tanstack/query-core'; + +import type { ChompApiServiceMethodActions } from './chomp-api-service-method-action-types'; +import type { + AssociateAddressRequest, + AssociateAddressResponse, + CreateUpgradeRequest, + CreateUpgradeResponse, + CreateWithdrawalRequest, + CreateWithdrawalResponse, + GetUpgradeResponse, + IntentEntry, + SendIntentRequest, + SendIntentResponse, + VerifyDelegationRequest, + VerifyDelegationResponse, +} from './types'; + +// === GENERAL === + +/** + * The name of the {@link ChompApiService}, used to namespace the service's + * actions and events. + */ +export const serviceName = 'ChompApiService'; + +// === MESSENGER === + +/** + * All of the methods within {@link ChompApiService} that are exposed via the + * messenger. + */ +const MESSENGER_EXPOSED_METHODS = [ + 'associateAddress', + 'createUpgrade', + 'getUpgrade', + 'verifyDelegation', + 'createIntents', + 'getIntentsByAddress', + 'createWithdrawal', +] as const; + +/** + * Invalidates cached queries for {@link ChompApiService}. + */ +export type ChompApiServiceInvalidateQueriesAction = + DataServiceInvalidateQueriesAction; + +/** + * Actions that {@link ChompApiService} exposes to other consumers. + */ +export type ChompApiServiceActions = + | ChompApiServiceMethodActions + | ChompApiServiceInvalidateQueriesAction; + +/** + * Actions from other messengers that {@link ChompApiService} calls. + */ +type AllowedActions = never; + +/** + * Published when {@link ChompApiService}'s cache is updated. + */ +export type ChompApiServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent< + typeof serviceName +>; + +/** + * Published when a key within {@link ChompApiService}'s cache is updated. + */ +export type ChompApiServiceGranularCacheUpdatedEvent = + DataServiceGranularCacheUpdatedEvent; + +/** + * Events that {@link ChompApiService} exposes to other consumers. + */ +export type ChompApiServiceEvents = + | ChompApiServiceCacheUpdatedEvent + | ChompApiServiceGranularCacheUpdatedEvent; + +/** + * Events from other messengers that {@link ChompApiService} subscribes to. + */ +type AllowedEvents = never; + +/** + * The messenger which is restricted to actions and events accessed by + * {@link ChompApiService}. + */ +export type ChompApiServiceMessenger = Messenger< + typeof serviceName, + ChompApiServiceActions | AllowedActions, + ChompApiServiceEvents | AllowedEvents +>; + +// === RESPONSE VALIDATION === + +const AssociateAddressResponseStruct = type({ + profileId: string(), + address: string(), + status: string(), +}); + +const UpgradeResponseStruct = type({ + signerAddress: string(), + status: string(), + createdAt: string(), +}); + +const VerifyDelegationResponseStruct = type({ + valid: boolean(), + delegationHash: optional(string()), + errors: optional(array(string())), +}); + +const SendIntentResponseArrayStruct = array( + type({ + delegationHash: string(), + metadata: type({ + allowance: string(), + tokenSymbol: string(), + tokenAddress: string(), + type: enums(['cash-deposit', 'cash-withdrawal']), + }), + createdAt: string(), + }), +); + +const IntentEntryArrayStruct = array( + type({ + account: string(), + delegationHash: string(), + chainId: string(), + status: enums(['active', 'revoked']), + metadata: type({ + allowance: string(), + tokenAddress: string(), + tokenSymbol: string(), + type: enums(['deposit', 'withdraw']), + }), + }), +); + +const CreateWithdrawalResponseStruct = type({ + success: literal(true), +}); + +// === SERVICE DEFINITION === + +/** + * This service is responsible for communicating with the CHOMP API. + * + * All requests are authenticated via JWT Bearer tokens obtained from the + * `getAccessToken` callback provided at construction time. + */ +export class ChompApiService extends BaseDataService< + typeof serviceName, + ChompApiServiceMessenger +> { + readonly #baseUrl: string; + + readonly #getAccessToken: () => Promise; + + readonly #mutationPolicy: ServicePolicy; + + /** + * Constructs a new ChompApiService. + * + * @param args - The constructor arguments. + * @param args.messenger - The messenger suited for this service. + * @param args.baseUrl - The base URL of the CHOMP API. + * @param args.getAccessToken - An async callback that returns a valid JWT + * access token for authenticating requests. + * @param args.queryClientConfig - Configuration for the underlying TanStack + * Query client. + * @param args.policyOptions - Options to pass to `createServicePolicy`. + */ + constructor({ + messenger, + baseUrl, + getAccessToken, + queryClientConfig = {}, + policyOptions = {}, + }: { + messenger: ChompApiServiceMessenger; + baseUrl: string; + getAccessToken: () => Promise; + queryClientConfig?: QueryClientConfig; + policyOptions?: CreateServicePolicyOptions; + }) { + super({ + name: serviceName, + messenger, + queryClientConfig, + policyOptions, + }); + + this.#baseUrl = baseUrl; + this.#getAccessToken = getAccessToken; + this.#mutationPolicy = createServicePolicy(policyOptions); + + this.messenger.registerMethodActionHandlers( + this, + MESSENGER_EXPOSED_METHODS, + ); + } + + /** + * Builds the standard headers for an authenticated CHOMP API request. + * + * @returns Headers including Authorization and Content-Type. + */ + async #authHeaders(): Promise> { + const token = await this.#getAccessToken(); + return { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }; + } + + /** + * Makes an authenticated POST request to the CHOMP API. + * + * @param path - The URL path relative to the base URL. + * @param body - The request body to serialize as JSON. + * @param acceptedStatuses - HTTP status codes that should be returned rather + * than treated as errors (e.g. 409 for conflict). + * @returns The raw fetch Response. + */ + async #postJson( + path: string, + body: unknown, + acceptedStatuses: number[] = [], + ): Promise { + const headers = await this.#authHeaders(); + return this.#mutationPolicy.execute(async () => { + const response = await fetch(new URL(path, this.#baseUrl), { + method: 'POST', + headers, + body: JSON.stringify(body), + }); + + if (!response.ok && !acceptedStatuses.includes(response.status)) { + throw new HttpError( + response.status, + `POST ${path} failed with status '${response.status}'`, + ); + } + + return response; + }); + } + + /** + * Associates an address with a CHOMP profile. + * + * POST /v1/auth/address + * + * @param request - The association request containing signature, timestamp, + * and address. + * @returns The profile association result. Returns on both 201 and 409. + */ + async associateAddress( + request: AssociateAddressRequest, + ): Promise { + const response = await this.#postJson('/v1/auth/address', request, [409]); + const json = await response.json(); + return create(json, AssociateAddressResponseStruct); + } + + /** + * Creates an account upgrade request. + * + * POST /v1/account-upgrade + * + * @param request - The upgrade request containing signature components and + * chain details. + * @returns The upgrade result. + */ + async createUpgrade( + request: CreateUpgradeRequest, + ): Promise { + const response = await this.#postJson('/v1/account-upgrade', request); + const json = await response.json(); + return create(json, UpgradeResponseStruct); + } + + /** + * Fetches the upgrade record for a given address. + * + * GET /v1/account-upgrade/:address + * + * @param address - The address to look up. + * @returns The upgrade record, or null if not found. + */ + async getUpgrade(address: string): Promise { + const jsonResponse = await this.fetchQuery({ + queryKey: [`${this.name}:getUpgrade`, address], + queryFn: async () => { + const headers = await this.#authHeaders(); + const response = await fetch( + new URL(`/v1/account-upgrade/${address}`, this.#baseUrl), + { headers }, + ); + + if (response.status === 404) { + return null; + } + + if (!response.ok) { + throw new HttpError( + response.status, + `Get upgrade request failed with status '${response.status}'`, + ); + } + + return response.json(); + }, + }); + + if (jsonResponse === null) { + return null; + } + + return create(jsonResponse, UpgradeResponseStruct); + } + + /** + * Verifies a delegation signature. + * + * POST /v1/intent/verify-delegation + * + * @param request - The delegation verification request. + * @returns The verification result including validity and optional errors. + */ + async verifyDelegation( + request: VerifyDelegationRequest, + ): Promise { + const response = await this.#postJson( + '/v1/intent/verify-delegation', + request, + ); + const json = await response.json(); + return create(json, VerifyDelegationResponseStruct); + } + + /** + * Submits one or more intents to the CHOMP API. + * + * POST /v1/intent + * + * @param intents - The array of intents to submit. + * @returns The array of intent responses. + */ + async createIntents( + intents: SendIntentRequest[], + ): Promise { + const response = await this.#postJson('/v1/intent', intents); + const json = await response.json(); + return create(json, SendIntentResponseArrayStruct) as SendIntentResponse[]; + } + + /** + * Fetches intents associated with a given address. + * + * GET /v1/intent/account/:address + * + * @param address - The address to look up intents for. + * @returns The array of intents for the address. + */ + async getIntentsByAddress(address: string): Promise { + const jsonResponse = await this.fetchQuery({ + queryKey: [`${this.name}:getIntentsByAddress`, address], + queryFn: async () => { + const headers = await this.#authHeaders(); + const response = await fetch( + new URL(`/v1/intent/account/${address}`, this.#baseUrl), + { headers }, + ); + + if (!response.ok) { + throw new HttpError( + response.status, + `Get intents request failed with status '${response.status}'`, + ); + } + + return response.json(); + }, + }); + + return create(jsonResponse, IntentEntryArrayStruct) as IntentEntry[]; + } + + /** + * Creates a withdrawal for card spend flows. + * + * POST /v1/withdrawal + * + * @param request - The withdrawal request containing chainId, amount + * (decimal or hex string), and account address. + * @returns The withdrawal result. + */ + async createWithdrawal( + request: CreateWithdrawalRequest, + ): Promise { + const response = await this.#postJson('/v1/withdrawal', request); + const json = await response.json(); + return create(json, CreateWithdrawalResponseStruct); + } +} diff --git a/packages/chomp-api-service/src/index.ts b/packages/chomp-api-service/src/index.ts new file mode 100644 index 00000000000..f38958ca3cd --- /dev/null +++ b/packages/chomp-api-service/src/index.ts @@ -0,0 +1,36 @@ +export { ChompApiService } from './chomp-api-service'; +export type { + ChompApiServiceMessenger, + ChompApiServiceActions, + ChompApiServiceEvents, + ChompApiServiceInvalidateQueriesAction, + ChompApiServiceCacheUpdatedEvent, + ChompApiServiceGranularCacheUpdatedEvent, +} from './chomp-api-service'; +export type { + ChompApiServiceAssociateAddressAction, + ChompApiServiceCreateUpgradeAction, + ChompApiServiceGetUpgradeAction, + ChompApiServiceVerifyDelegationAction, + ChompApiServiceCreateIntentsAction, + ChompApiServiceGetIntentsByAddressAction, + ChompApiServiceCreateWithdrawalAction, +} from './chomp-api-service-method-action-types'; +export type { + AssociateAddressRequest, + AssociateAddressResponse, + CreateUpgradeRequest, + CreateUpgradeResponse, + CreateWithdrawalRequest, + CreateWithdrawalResponse, + DelegationCaveat, + GetUpgradeResponse, + IntentEntry, + IntentMetadataRequest, + IntentMetadataResponse, + SendIntentRequest, + SendIntentResponse, + SignedDelegation, + VerifyDelegationRequest, + VerifyDelegationResponse, +} from './types'; diff --git a/packages/chomp-api-service/src/types.ts b/packages/chomp-api-service/src/types.ts new file mode 100644 index 00000000000..382e7bc5280 --- /dev/null +++ b/packages/chomp-api-service/src/types.ts @@ -0,0 +1,127 @@ +import type { Hex } from '@metamask/utils'; + +// === COMMON TYPES === + +export type DelegationCaveat = { + enforcer: Hex; + terms: Hex; + args: Hex; +}; + +export type SignedDelegation = { + delegate: Hex; + delegator: Hex; + authority: Hex; + caveats: DelegationCaveat[]; + salt: Hex; + signature: Hex; +}; + +// === REQUEST TYPES === + +export type AssociateAddressRequest = { + signature: string; + timestamp: string; + address: string; +}; + +export type CreateUpgradeRequest = { + r: string; + s: string; + v: number; + yParity: number; + address: string; + chainId: string; + nonce: string; +}; + +export type VerifyDelegationRequest = { + signedDelegation: SignedDelegation; + chainId: Hex; +}; + +export type IntentMetadataRequest = { + allowance: Hex; + tokenSymbol: string; + tokenAddress: Hex; + type: 'cash-deposit' | 'cash-withdrawal'; +}; + +export type SendIntentRequest = { + account: Hex; + delegationHash: Hex; + chainId: Hex; + metadata: IntentMetadataRequest; +}; + +export type CreateWithdrawalRequest = { + chainId: Hex; + /** Decimal integer or 0x-prefixed hex string representing the amount. */ + amount: string; + account: Hex; +}; + +// === RESPONSE TYPES === + +export type AssociateAddressResponse = { + profileId: string; + address: string; + status: string; +}; + +export type CreateUpgradeResponse = { + signerAddress: string; + status: string; + createdAt: string; +}; + +/** + * The upgrade record returned by GET /v1/account-upgrade/:address. + */ +export type GetUpgradeResponse = { + signerAddress: string; + status: string; + createdAt: string; +}; + +export type VerifyDelegationResponse = { + valid: boolean; + delegationHash?: string; + errors?: string[]; +}; + +export type IntentMetadataResponse = { + allowance: Hex; + tokenSymbol: string; + tokenAddress: Hex; + type: 'cash-deposit' | 'cash-withdrawal'; +}; + +export type SendIntentResponse = { + delegationHash: string; + metadata: IntentMetadataResponse; + createdAt: string; +}; + +/** + * The shape returned by GET /v1/intent/account/:address for each intent. + * + * Note: the metadata `type` uses 'deposit' | 'withdraw' here, whereas the + * create-intent endpoint uses 'cash-deposit' | 'cash-withdrawal'. + */ +export type IntentEntry = { + account: Hex; + delegationHash: Hex; + chainId: Hex; + status: 'active' | 'revoked'; + metadata: { + allowance: Hex; + tokenAddress: Hex; + tokenSymbol: string; + type: 'deposit' | 'withdraw'; + }; +}; + +export type CreateWithdrawalResponse = { + success: true; +}; diff --git a/packages/chomp-api-service/tsconfig.build.json b/packages/chomp-api-service/tsconfig.build.json new file mode 100644 index 00000000000..c468e8dd1f5 --- /dev/null +++ b/packages/chomp-api-service/tsconfig.build.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.packages.build.json", + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist", + "rootDir": "./src" + }, + "references": [ + { "path": "../messenger/tsconfig.build.json" }, + { "path": "../controller-utils/tsconfig.build.json" }, + { "path": "../base-data-service/tsconfig.build.json" } + ], + "include": ["../../types", "./src"] +} diff --git a/packages/chomp-api-service/tsconfig.json b/packages/chomp-api-service/tsconfig.json new file mode 100644 index 00000000000..203994e1c3c --- /dev/null +++ b/packages/chomp-api-service/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.packages.json", + "compilerOptions": { + "baseUrl": "./" + }, + "references": [ + { "path": "../messenger" }, + { "path": "../controller-utils" }, + { "path": "../base-data-service" } + ], + "include": ["../../types", "./src"] +} diff --git a/packages/chomp-api-service/typedoc.json b/packages/chomp-api-service/typedoc.json new file mode 100644 index 00000000000..c9da015dbf8 --- /dev/null +++ b/packages/chomp-api-service/typedoc.json @@ -0,0 +1,7 @@ +{ + "entryPoints": ["./src/index.ts"], + "excludePrivate": true, + "hideGenerator": true, + "out": "docs", + "tsconfig": "./tsconfig.build.json" +} diff --git a/yarn.lock b/yarn.lock index 5feef62cd40..7c960fbabc4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3126,6 +3126,29 @@ __metadata: languageName: unknown linkType: soft +"@metamask/chomp-api-service@workspace:packages/chomp-api-service": + version: 0.0.0-use.local + resolution: "@metamask/chomp-api-service@workspace:packages/chomp-api-service" + dependencies: + "@metamask/auto-changelog": "npm:^3.4.4" + "@metamask/base-data-service": "npm:^0.1.1" + "@metamask/controller-utils": "npm:^11.20.0" + "@metamask/messenger": "npm:^1.1.1" + "@metamask/superstruct": "npm:^3.1.0" + "@metamask/utils": "npm:^11.9.0" + "@tanstack/query-core": "npm:^4.43.0" + "@ts-bridge/cli": "npm:^0.6.4" + "@types/jest": "npm:^29.5.14" + deepmerge: "npm:^4.2.2" + jest: "npm:^29.7.0" + nock: "npm:^13.3.1" + ts-jest: "npm:^29.2.5" + typedoc: "npm:^0.25.13" + typedoc-plugin-missing-exports: "npm:^2.0.0" + typescript: "npm:~5.3.3" + languageName: unknown + linkType: soft + "@metamask/claims-controller@workspace:packages/claims-controller": version: 0.0.0-use.local resolution: "@metamask/claims-controller@workspace:packages/claims-controller"