diff --git a/packages/money-account-upgrade-controller/CHANGELOG.md b/packages/money-account-upgrade-controller/CHANGELOG.md new file mode 100644 index 00000000000..15294a254a7 --- /dev/null +++ b/packages/money-account-upgrade-controller/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 `MoneyAccountUpgradeController` with multi-step `upgradeAccount` method that orchestrates address association, EIP-7702 authorization, delegation verification, and intent registration via CHOMP + +[Unreleased]: https://github.com/MetaMask/core/ diff --git a/packages/money-account-upgrade-controller/LICENSE b/packages/money-account-upgrade-controller/LICENSE new file mode 100644 index 00000000000..fe29e78e0fe --- /dev/null +++ b/packages/money-account-upgrade-controller/LICENSE @@ -0,0 +1,21 @@ +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 +SOFTWARE. diff --git a/packages/money-account-upgrade-controller/README.md b/packages/money-account-upgrade-controller/README.md new file mode 100644 index 00000000000..dde58824dd1 --- /dev/null +++ b/packages/money-account-upgrade-controller/README.md @@ -0,0 +1,15 @@ +# `@metamask/money-account-upgrade-controller` + +MetaMask Money account upgrade controller. + +## Installation + +`yarn add @metamask/money-account-upgrade-controller` + +or + +`npm install @metamask/money-account-upgrade-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). diff --git a/packages/money-account-upgrade-controller/TODO.md b/packages/money-account-upgrade-controller/TODO.md new file mode 100644 index 00000000000..e86e1bbc404 --- /dev/null +++ b/packages/money-account-upgrade-controller/TODO.md @@ -0,0 +1,29 @@ +# MoneyAccountUpgradeController — Remaining Work + +## Step 0: Associate address + +- [ ] **Idempotency check**: `#associateAddress` currently always signs and submits. The CHOMP API returns 409 when already associated (which is handled as success), but we could skip the signing step entirely by checking state or querying CHOMP first. + +## Step 1: Submit authorization + +- [ ] **Fetch on-chain nonce**: The nonce is hardcoded to `0` (line 202). This needs to be replaced with an actual on-chain nonce fetch for the account — likely via an `eth_getTransactionCount` call or equivalent messenger action. CHOMP validates that the nonce matches. + +## Step 2: Verify delegation + +- [ ] **Caveat term encoding**: `#encodeCaveatTerms` does naive left-padded hex concatenation. Verify this matches the exact ABI encoding expected by the caveat enforcer contracts (may need proper ABI encoding via `@metamask/abi-utils` or similar). +- [ ] **Use `@metamask/smart-accounts-kit`**: The description mentions using `createDelegation` from `@metamask/smart-accounts-kit` to build the delegation. This package is not yet in the repo — once it lands, the delegation construction in `#verifyDelegation` should use it instead of manual assembly. +- [ ] **Import `ROOT_AUTHORITY` from `@metamask/delegation-controller`**: Currently defined locally as a constant. The delegation-controller has it but doesn't export it — once it's exported, import it instead. + +## Step 3: Save delegation + +- [ ] **Implement Authenticated User Storage save**: `#saveDelegation` is a stub (line 312-316). Needs the `@metamask/authenticated-user-storage` wrapper (PR currently open). Once available, save the signed delegation so CHOMP can read it at execution time via its internal VPC endpoint. + +## Step 4: Register intents + +- [ ] **Intent configuration**: The deposit/withdrawal intents are hardcoded with `mUSD` token symbol and `MAX_UINT256` allowance. These may need to come from config or be parameterised once requirements solidify. + +## General + +- [ ] **Resumability**: `upgradeAccount` runs all steps sequentially. If it fails mid-way and is retried, steps 0 and 2-4 will re-run from scratch. Consider checking persisted state at the start of each step to skip already-completed work (step 1 already does this via `getUpgrade`). +- [ ] **`MoneyAccountController:getMoneyAccount`**: This action is declared in `AllowedActions` but not currently used. It was included anticipating the controller may need to look up account details. Remove if not needed, or use it to validate the address before starting. +- [ ] **`#saveDelegation` unused `_chainId` parameter**: Will be needed once the stub is implemented — the storage call will likely need it. diff --git a/packages/money-account-upgrade-controller/jest.config.js b/packages/money-account-upgrade-controller/jest.config.js new file mode 100644 index 00000000000..ca084133399 --- /dev/null +++ b/packages/money-account-upgrade-controller/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/money-account-upgrade-controller/package.json b/packages/money-account-upgrade-controller/package.json new file mode 100644 index 00000000000..27c79e873d9 --- /dev/null +++ b/packages/money-account-upgrade-controller/package.json @@ -0,0 +1,79 @@ +{ + "name": "@metamask/money-account-upgrade-controller", + "version": "0.1.0", + "description": "MetaMask Money account upgrade controller", + "keywords": [ + "MetaMask", + "Ethereum" + ], + "homepage": "https://github.com/MetaMask/core/tree/main/packages/money-account-upgrade-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:all": "ts-bridge --project tsconfig.build.json --verbose --clean", + "build:docs": "typedoc", + "changelog:update": "../../scripts/update-changelog.sh @metamask/money-account-upgrade-controller", + "changelog:validate": "../../scripts/validate-changelog.sh @metamask/money-account-upgrade-controller", + "messenger-action-types:check": "tsx ../../packages/messenger-cli/src/cli.ts --check", + "messenger-action-types:generate": "tsx ../../packages/messenger-cli/src/cli.ts --generate", + "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-controller": "^9.0.1", + "@metamask/chomp-api-service": "^0.0.0", + "@metamask/delegation-controller": "^2.1.0", + "@metamask/keyring-controller": "^25.2.0", + "@metamask/messenger": "^1.1.1", + "@metamask/money-account-controller": "^0.1.0" + }, + "devDependencies": { + "@metamask/auto-changelog": "^3.4.4", + "@metamask/utils": "^11.9.0", + "@ts-bridge/cli": "^0.6.4", + "@types/jest": "^29.5.14", + "deepmerge": "^4.2.2", + "jest": "^29.2.5", + "ts-jest": "^29.2.5", + "tsx": "^4.20.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/money-account-upgrade-controller/src/MoneyAccountUpgradeController-method-action-types.ts b/packages/money-account-upgrade-controller/src/MoneyAccountUpgradeController-method-action-types.ts new file mode 100644 index 00000000000..bf1040d3d17 --- /dev/null +++ b/packages/money-account-upgrade-controller/src/MoneyAccountUpgradeController-method-action-types.ts @@ -0,0 +1,24 @@ +/** + * This file is auto generated. + * Do not edit manually. + */ + +import type { MoneyAccountUpgradeController } from './MoneyAccountUpgradeController'; + +/** + * Runs the full upgrade sequence for a Money Account. + * + * @param address - The Money Account address to upgrade. + * @param chainId - The target chain for the upgrade. + * @returns A promise that resolves when the upgrade is complete. + */ +export type MoneyAccountUpgradeControllerUpgradeAccountAction = { + type: `MoneyAccountUpgradeController:upgradeAccount`; + handler: MoneyAccountUpgradeController['upgradeAccount']; +}; + +/** + * Union of all MoneyAccountUpgradeController action types. + */ +export type MoneyAccountUpgradeControllerMethodActions = + MoneyAccountUpgradeControllerUpgradeAccountAction; diff --git a/packages/money-account-upgrade-controller/src/MoneyAccountUpgradeController.test.ts b/packages/money-account-upgrade-controller/src/MoneyAccountUpgradeController.test.ts new file mode 100644 index 00000000000..955b9b793b4 --- /dev/null +++ b/packages/money-account-upgrade-controller/src/MoneyAccountUpgradeController.test.ts @@ -0,0 +1,506 @@ +import { Messenger, MOCK_ANY_NAMESPACE } from '@metamask/messenger'; +import type { + MockAnyNamespace, + MessengerActions, + MessengerEvents, +} from '@metamask/messenger'; +import type { Hex } from '@metamask/utils'; + +import type { MoneyAccountUpgradeControllerMessenger } from '.'; +import { + MoneyAccountUpgradeController, + getDefaultMoneyAccountUpgradeControllerState, +} from '.'; +import type { UpgradeConfig } from './types'; + +const MOCK_ADDRESS = '0xabcdef1234567890abcdef1234567890abcdef12' as Hex; +const MOCK_CHAIN_ID = '0x1' as Hex; +const MOCK_SIGNATURE = + '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' + + '1b'; +const MOCK_DELEGATION_SIGNATURE = '0xdeadbeef' as Hex; +const MOCK_DELEGATION_HASH = '0xabcdef1234567890'; + +const MOCK_CONFIG: UpgradeConfig = { + delegateAddress: '0x1111111111111111111111111111111111111111' as Hex, + delegatorImplAddress: '0x2222222222222222222222222222222222222222' as Hex, + musdTokenAddress: '0x3333333333333333333333333333333333333333' as Hex, + vedaVaultAdapterAddress: '0x4444444444444444444444444444444444444444' as Hex, + erc20TransferAmountEnforcer: + '0x5555555555555555555555555555555555555555' as Hex, + redeemerEnforcer: '0x6666666666666666666666666666666666666666' as Hex, + valueLteEnforcer: '0x7777777777777777777777777777777777777777' as Hex, +}; + +type AllActions = MessengerActions; + +type AllEvents = MessengerEvents; + +type RootMessenger = Messenger; + +type Mocks = { + signPersonalMessage: jest.Mock; + signEip7702Authorization: jest.Mock; + associateAddress: jest.Mock; + createUpgrade: jest.Mock; + getUpgrade: jest.Mock; + verifyDelegation: jest.Mock; + createIntents: jest.Mock; + signDelegation: jest.Mock; + getMoneyAccount: jest.Mock; +}; + +function setup({ + state, +}: { + state?: Partial< + ReturnType + >; +} = {}): { + controller: MoneyAccountUpgradeController; + rootMessenger: RootMessenger; + messenger: MoneyAccountUpgradeControllerMessenger; + mocks: Mocks; +} { + const mocks: Mocks = { + signPersonalMessage: jest.fn().mockResolvedValue(MOCK_SIGNATURE), + signEip7702Authorization: jest.fn().mockResolvedValue(MOCK_SIGNATURE), + associateAddress: jest.fn().mockResolvedValue({ + profileId: 'profile-1', + address: MOCK_ADDRESS, + status: 'created', + }), + createUpgrade: jest.fn().mockResolvedValue({ + signerAddress: MOCK_ADDRESS, + status: 'created', + createdAt: '2026-04-10T00:00:00Z', + }), + getUpgrade: jest.fn().mockResolvedValue(null), + verifyDelegation: jest.fn().mockResolvedValue({ + valid: true, + delegationHash: MOCK_DELEGATION_HASH, + }), + createIntents: jest.fn().mockResolvedValue([]), + signDelegation: jest.fn().mockResolvedValue(MOCK_DELEGATION_SIGNATURE), + getMoneyAccount: jest.fn().mockReturnValue({ + id: 'account-1', + address: MOCK_ADDRESS, + }), + }; + + const rootMessenger = new Messenger({ + namespace: MOCK_ANY_NAMESPACE, + }); + + rootMessenger.registerActionHandler( + 'KeyringController:signPersonalMessage', + mocks.signPersonalMessage, + ); + rootMessenger.registerActionHandler( + 'KeyringController:signEip7702Authorization', + mocks.signEip7702Authorization, + ); + rootMessenger.registerActionHandler( + 'ChompApiService:associateAddress', + mocks.associateAddress, + ); + rootMessenger.registerActionHandler( + 'ChompApiService:createUpgrade', + mocks.createUpgrade, + ); + rootMessenger.registerActionHandler( + 'ChompApiService:getUpgrade', + mocks.getUpgrade, + ); + rootMessenger.registerActionHandler( + 'ChompApiService:verifyDelegation', + mocks.verifyDelegation, + ); + rootMessenger.registerActionHandler( + 'ChompApiService:createIntents', + mocks.createIntents, + ); + rootMessenger.registerActionHandler( + 'DelegationController:signDelegation', + mocks.signDelegation, + ); + rootMessenger.registerActionHandler( + 'MoneyAccountController:getMoneyAccount', + mocks.getMoneyAccount, + ); + + const messenger: MoneyAccountUpgradeControllerMessenger = new Messenger({ + namespace: 'MoneyAccountUpgradeController', + parent: rootMessenger, + }); + + rootMessenger.delegate({ + actions: [ + 'KeyringController:signPersonalMessage', + 'KeyringController:signEip7702Authorization', + 'ChompApiService:associateAddress', + 'ChompApiService:createUpgrade', + 'ChompApiService:getUpgrade', + 'ChompApiService:verifyDelegation', + 'ChompApiService:createIntents', + 'DelegationController:signDelegation', + 'MoneyAccountController:getMoneyAccount', + ], + events: [], + messenger, + }); + + const controller = new MoneyAccountUpgradeController({ + messenger, + state, + config: MOCK_CONFIG, + }); + + return { controller, rootMessenger, messenger, mocks }; +} + +describe('MoneyAccountUpgradeController', () => { + describe('constructor', () => { + it('initializes with default state when no state is provided', () => { + const { controller } = setup(); + + expect(controller.state).toStrictEqual( + getDefaultMoneyAccountUpgradeControllerState(), + ); + }); + + it('accepts initial state', () => { + const { controller } = setup({ + state: { + upgrades: { + [MOCK_ADDRESS]: { + step: 'associate-address', + chainId: MOCK_CHAIN_ID, + }, + }, + }, + }); + + expect(controller.state.upgrades[MOCK_ADDRESS]).toStrictEqual({ + step: 'associate-address', + chainId: MOCK_CHAIN_ID, + }); + }); + }); + + describe('upgradeAccount', () => { + it('runs the full upgrade sequence', async () => { + const { controller, mocks } = setup(); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + expect(mocks.signPersonalMessage).toHaveBeenCalledTimes(1); + expect(mocks.associateAddress).toHaveBeenCalledTimes(1); + expect(mocks.getUpgrade).toHaveBeenCalledTimes(1); + expect(mocks.signEip7702Authorization).toHaveBeenCalledTimes(1); + expect(mocks.createUpgrade).toHaveBeenCalledTimes(1); + expect(mocks.signDelegation).toHaveBeenCalledTimes(1); + expect(mocks.verifyDelegation).toHaveBeenCalledTimes(1); + expect(mocks.createIntents).toHaveBeenCalledTimes(1); + }); + + it('records final state as register-intents with delegationHash', async () => { + const { controller } = setup(); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + expect(controller.state.upgrades[MOCK_ADDRESS]).toStrictEqual({ + step: 'register-intents', + chainId: MOCK_CHAIN_ID, + delegationHash: MOCK_DELEGATION_HASH, + }); + }); + + it('is callable via the messenger', async () => { + const { rootMessenger } = setup(); + + expect( + await rootMessenger.call( + 'MoneyAccountUpgradeController:upgradeAccount', + MOCK_ADDRESS, + MOCK_CHAIN_ID, + ), + ).toBeUndefined(); + }); + }); + + describe('step 0: associate address', () => { + it('signs the authentication message and submits to CHOMP', async () => { + const { controller, mocks } = setup(); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + expect(mocks.signPersonalMessage).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.stringMatching(/^CHOMP Authentication \d+$/u), + from: MOCK_ADDRESS, + }), + ); + + expect(mocks.associateAddress).toHaveBeenCalledWith( + expect.objectContaining({ + signature: MOCK_SIGNATURE, + address: MOCK_ADDRESS, + timestamp: expect.stringMatching(/^\d+$/u), + }), + ); + }); + + it('updates state to associate-address after completion', async () => { + const { controller, mocks } = setup(); + + // Make subsequent steps fail so we can check state after step 0. + mocks.getUpgrade.mockRejectedValue(new Error('stop')); + + await expect( + controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID), + ).rejects.toThrow('stop'); + + expect(controller.state.upgrades[MOCK_ADDRESS]?.step).toBe( + 'associate-address', + ); + }); + }); + + describe('step 1: submit authorization', () => { + it('skips signing when CHOMP already has an upgrade record', async () => { + const { controller, mocks } = setup(); + + mocks.getUpgrade.mockResolvedValue({ + signerAddress: MOCK_ADDRESS, + status: 'upgraded', + createdAt: '2026-04-09T00:00:00Z', + }); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + expect(mocks.signEip7702Authorization).not.toHaveBeenCalled(); + expect(mocks.createUpgrade).not.toHaveBeenCalled(); + }); + + it('signs and submits an EIP-7702 authorization', async () => { + const { controller, mocks } = setup(); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + expect(mocks.signEip7702Authorization).toHaveBeenCalledWith({ + chainId: 1, + contractAddress: MOCK_CONFIG.delegatorImplAddress, + nonce: 0, + from: MOCK_ADDRESS, + }); + + expect(mocks.createUpgrade).toHaveBeenCalledWith( + expect.objectContaining({ + address: MOCK_ADDRESS, + chainId: MOCK_CHAIN_ID, + }), + ); + }); + + it('computes yParity=1 when v is 28', async () => { + const { controller, mocks } = setup(); + + const sigWithV28 = + '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' + + '1c'; + mocks.signEip7702Authorization.mockResolvedValue(sigWithV28); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + expect(mocks.createUpgrade).toHaveBeenCalledWith( + expect.objectContaining({ + v: 28, + yParity: 1, + }), + ); + }); + + it('parses signature components correctly', async () => { + const { controller, mocks } = setup(); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + expect(mocks.createUpgrade).toHaveBeenCalledWith( + expect.objectContaining({ + // r = first 66 chars (0x + 64 hex chars) + r: MOCK_SIGNATURE.slice(0, 66), + // s = 0x + next 64 hex chars + s: `0x${MOCK_SIGNATURE.slice(66, 130)}`, + // v = last 2 hex chars parsed as int + v: parseInt(MOCK_SIGNATURE.slice(130, 132), 16), + // yParity derived from v + yParity: + parseInt(MOCK_SIGNATURE.slice(130, 132), 16) - 27 === 0 ? 0 : 1, + }), + ); + }); + }); + + describe('step 2: verify delegation', () => { + it('builds a delegation with three caveats and verifies with CHOMP', async () => { + const { controller, mocks } = setup(); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + expect(mocks.signDelegation).toHaveBeenCalledWith({ + delegation: expect.objectContaining({ + delegate: MOCK_CONFIG.delegateAddress, + delegator: MOCK_ADDRESS, + caveats: expect.arrayContaining([ + expect.objectContaining({ + enforcer: MOCK_CONFIG.erc20TransferAmountEnforcer, + }), + expect.objectContaining({ + enforcer: MOCK_CONFIG.redeemerEnforcer, + }), + expect.objectContaining({ + enforcer: MOCK_CONFIG.valueLteEnforcer, + }), + ]), + }), + chainId: MOCK_CHAIN_ID, + }); + + expect(mocks.verifyDelegation).toHaveBeenCalledWith( + expect.objectContaining({ + signedDelegation: expect.objectContaining({ + delegate: MOCK_CONFIG.delegateAddress, + delegator: MOCK_ADDRESS, + signature: MOCK_DELEGATION_SIGNATURE, + }), + chainId: MOCK_CHAIN_ID, + }), + ); + }); + + it('includes exactly three caveats', async () => { + const { controller, mocks } = setup(); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + const { delegation } = mocks.signDelegation.mock.calls[0][0]; + expect(delegation.caveats).toHaveLength(3); + }); + + it('throws when delegation verification fails', async () => { + const { controller, mocks } = setup(); + + mocks.verifyDelegation.mockResolvedValue({ + valid: false, + errors: ['delegate mismatch'], + }); + + await expect( + controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID), + ).rejects.toThrow('Delegation verification failed: delegate mismatch'); + }); + + it('throws with unknown error when verification fails without error details', async () => { + const { controller, mocks } = setup(); + + mocks.verifyDelegation.mockResolvedValue({ + valid: false, + }); + + await expect( + controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID), + ).rejects.toThrow('Delegation verification failed: unknown error'); + }); + + it('stores delegationHash in state after successful verification', async () => { + const { controller } = setup(); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + expect(controller.state.upgrades[MOCK_ADDRESS]?.delegationHash).toBe( + MOCK_DELEGATION_HASH, + ); + }); + }); + + describe('step 3: save delegation (stub)', () => { + it('updates state to save-delegation', async () => { + const { controller, mocks } = setup(); + + // Make step 4 fail so we can check state after step 3. + mocks.createIntents.mockRejectedValue(new Error('stop')); + + await expect( + controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID), + ).rejects.toThrow('stop'); + + expect(controller.state.upgrades[MOCK_ADDRESS]?.step).toBe( + 'save-delegation', + ); + }); + }); + + describe('step 4: register intents', () => { + it('submits deposit and withdrawal intents', async () => { + const { controller, mocks } = setup(); + + await controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID); + + expect(mocks.createIntents).toHaveBeenCalledWith([ + expect.objectContaining({ + account: MOCK_ADDRESS, + delegationHash: MOCK_DELEGATION_HASH, + chainId: MOCK_CHAIN_ID, + metadata: expect.objectContaining({ type: 'cash-deposit' }), + }), + expect.objectContaining({ + account: MOCK_ADDRESS, + delegationHash: MOCK_DELEGATION_HASH, + chainId: MOCK_CHAIN_ID, + metadata: expect.objectContaining({ type: 'cash-withdrawal' }), + }), + ]); + }); + + it('throws if delegationHash is missing', async () => { + const { controller, mocks } = setup(); + + // Skip the verify step by making it not store a hash + mocks.verifyDelegation.mockResolvedValue({ + valid: true, + // No delegationHash returned + }); + + await expect( + controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID), + ).rejects.toThrow('Cannot register intents: no delegationHash found'); + }); + }); + + describe('error propagation', () => { + it('propagates signing errors', async () => { + const { controller, mocks } = setup(); + + mocks.signPersonalMessage.mockRejectedValue(new Error('signing failed')); + + await expect( + controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID), + ).rejects.toThrow('signing failed'); + }); + + it('propagates CHOMP API errors', async () => { + const { controller, mocks } = setup(); + + mocks.associateAddress.mockRejectedValue( + new Error("POST /v1/auth/address failed with status '500'"), + ); + + await expect( + controller.upgradeAccount(MOCK_ADDRESS, MOCK_CHAIN_ID), + ).rejects.toThrow("POST /v1/auth/address failed with status '500'"); + }); + }); +}); diff --git a/packages/money-account-upgrade-controller/src/MoneyAccountUpgradeController.ts b/packages/money-account-upgrade-controller/src/MoneyAccountUpgradeController.ts new file mode 100644 index 00000000000..f5b157bc0c5 --- /dev/null +++ b/packages/money-account-upgrade-controller/src/MoneyAccountUpgradeController.ts @@ -0,0 +1,390 @@ +import type { + ControllerGetStateAction, + ControllerStateChangeEvent, + StateMetadata, +} from '@metamask/base-controller'; +import { BaseController } from '@metamask/base-controller'; +import type { + ChompApiServiceAssociateAddressAction, + ChompApiServiceCreateIntentsAction, + ChompApiServiceCreateUpgradeAction, + ChompApiServiceGetUpgradeAction, + ChompApiServiceVerifyDelegationAction, + SignedDelegation, +} from '@metamask/chomp-api-service'; +import type { DelegationControllerSignDelegationAction } from '@metamask/delegation-controller'; +import type { + KeyringControllerSignEip7702AuthorizationAction, + KeyringControllerSignPersonalMessageAction, +} from '@metamask/keyring-controller'; +import type { Messenger } from '@metamask/messenger'; +import type { MoneyAccountControllerGetMoneyAccountAction } from '@metamask/money-account-controller'; +import type { Hex } from '@metamask/utils'; + +import type { MoneyAccountUpgradeControllerMethodActions } from './MoneyAccountUpgradeController-method-action-types'; +import type { AccountUpgradeEntry, UpgradeConfig } from './types'; + +export const controllerName = 'MoneyAccountUpgradeController'; + +// The root authority constant for top-level delegations. +const ROOT_AUTHORITY = + '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' as Hex; + +// Maximum uint256 — used as the allowance for the ERC20TransferAmountEnforcer. +const MAX_UINT256 = + '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' as Hex; + +export type MoneyAccountUpgradeControllerState = { + upgrades: Record; +}; + +const moneyAccountUpgradeControllerMetadata = { + upgrades: { + includeInDebugSnapshot: false, + includeInStateLogs: false, + persist: true, + usedInUi: false, + }, +} satisfies StateMetadata; + +export function getDefaultMoneyAccountUpgradeControllerState(): MoneyAccountUpgradeControllerState { + return { + upgrades: {}, + }; +} + +const MESSENGER_EXPOSED_METHODS = ['upgradeAccount'] as const; + +export type MoneyAccountUpgradeControllerGetStateAction = + ControllerGetStateAction< + typeof controllerName, + MoneyAccountUpgradeControllerState + >; + +export type MoneyAccountUpgradeControllerActions = + | MoneyAccountUpgradeControllerGetStateAction + | MoneyAccountUpgradeControllerMethodActions; + +type AllowedActions = + | ChompApiServiceAssociateAddressAction + | ChompApiServiceCreateUpgradeAction + | ChompApiServiceGetUpgradeAction + | ChompApiServiceVerifyDelegationAction + | ChompApiServiceCreateIntentsAction + | KeyringControllerSignPersonalMessageAction + | KeyringControllerSignEip7702AuthorizationAction + | DelegationControllerSignDelegationAction + | MoneyAccountControllerGetMoneyAccountAction; + +export type MoneyAccountUpgradeControllerStateChangeEvent = + ControllerStateChangeEvent< + typeof controllerName, + MoneyAccountUpgradeControllerState + >; + +export type MoneyAccountUpgradeControllerEvents = + MoneyAccountUpgradeControllerStateChangeEvent; + +type AllowedEvents = never; + +export type MoneyAccountUpgradeControllerMessenger = Messenger< + typeof controllerName, + MoneyAccountUpgradeControllerActions | AllowedActions, + MoneyAccountUpgradeControllerEvents | AllowedEvents +>; + +/** + * Controller that orchestrates the multi-step Money Account upgrade sequence. + */ +export class MoneyAccountUpgradeController extends BaseController< + typeof controllerName, + MoneyAccountUpgradeControllerState, + MoneyAccountUpgradeControllerMessenger +> { + readonly #config: UpgradeConfig; + + /** + * Constructor for the MoneyAccountUpgradeController. + * + * @param options - The options for constructing the controller. + * @param options.messenger - The messenger to use for inter-controller communication. + * @param options.state - The initial state of the controller. + * @param options.config - Contract addresses and configuration for the upgrade sequence. + */ + constructor({ + messenger, + state, + config, + }: { + messenger: MoneyAccountUpgradeControllerMessenger; + state?: Partial; + config: UpgradeConfig; + }) { + super({ + messenger, + metadata: moneyAccountUpgradeControllerMetadata, + name: controllerName, + state: { + ...getDefaultMoneyAccountUpgradeControllerState(), + ...state, + }, + }); + + this.#config = config; + + this.messenger.registerMethodActionHandlers( + this, + MESSENGER_EXPOSED_METHODS, + ); + } + + /** + * Runs the full upgrade sequence for a Money Account. Each step is + * idempotent — if the step has already been completed, it is skipped. + * + * @param address - The Money Account address to upgrade. + * @param chainId - The target chain for the upgrade. + */ + async upgradeAccount(address: Hex, chainId: Hex): Promise { + await this.#associateAddress(address); + await this.#submitAuthorization(address, chainId); + await this.#verifyDelegation(address, chainId); + await this.#saveDelegation(address, chainId); + await this.#registerIntents(address, chainId); + } + + /** + * Step 0: Associate the Money Account address with the user's CHOMP profile. + * + * Signs "CHOMP Authentication {timestamp}" via personal_sign and submits + * it to CHOMP. The API accepts 409 (already associated) as success. + * + * @param address - The Money Account address. + */ + async #associateAddress(address: Hex): Promise { + const timestamp = Date.now().toString(); + const message = `CHOMP Authentication ${timestamp}`; + + const signature = await this.messenger.call( + 'KeyringController:signPersonalMessage', + { data: message, from: address }, + ); + + await this.messenger.call('ChompApiService:associateAddress', { + signature, + timestamp, + address, + }); + + this.#updateUpgrade(address, { step: 'associate-address' }); + } + + /** + * Step 1: Sign and submit an EIP-7702 authorization to CHOMP. + * + * Skips if CHOMP already has an upgrade record for this address. + * + * @param address - The Money Account address. + * @param chainId - The target chain. + */ + async #submitAuthorization(address: Hex, chainId: Hex): Promise { + const existing = await this.messenger.call( + 'ChompApiService:getUpgrade', + address, + ); + + if (existing) { + this.#updateUpgrade(address, { step: 'submit-authorization', chainId }); + return; + } + + // TODO: Fetch on-chain nonce. Using 0 as placeholder. + const nonce = 0; + const chainIdDecimal = parseInt(chainId, 16); + + const signature = await this.messenger.call( + 'KeyringController:signEip7702Authorization', + { + chainId: chainIdDecimal, + contractAddress: this.#config.delegatorImplAddress, + nonce, + from: address, + }, + ); + + const sigR = signature.slice(0, 66); + const sigS = `0x${signature.slice(66, 130)}`; + const sigV = parseInt(signature.slice(130, 132), 16); + const yParity = sigV - 27 === 0 ? 0 : 1; + + await this.messenger.call('ChompApiService:createUpgrade', { + r: sigR, + s: sigS, + v: sigV, + yParity, + address, + chainId, + nonce: nonce.toString(), + }); + + this.#updateUpgrade(address, { step: 'submit-authorization', chainId }); + } + + /** + * Step 2: Build, sign, and verify a delegation with CHOMP. + * + * Constructs an unsigned delegation with three caveat enforcers + * (ERC20TransferAmount, Redeemer, ValueLte), signs it via the + * DelegationController, and verifies it with CHOMP. + * + * @param address - The Money Account address (delegator). + * @param chainId - The target chain. + */ + async #verifyDelegation(address: Hex, chainId: Hex): Promise { + const salt: Hex = `0x${Array.from( + // TODO: do I need to read this off of globalThis? + globalThis.crypto.getRandomValues(new Uint8Array(32)), + ) + .map((b) => b.toString(16).padStart(2, '0')) + .join('')}`; + + const delegation = { + delegate: this.#config.delegateAddress, + delegator: address, + authority: ROOT_AUTHORITY, + caveats: [ + { + enforcer: this.#config.erc20TransferAmountEnforcer, + terms: this.#encodeCaveatTerms( + MAX_UINT256, + this.#config.musdTokenAddress, + ), + args: '0x' as Hex, + }, + { + enforcer: this.#config.redeemerEnforcer, + terms: this.#encodeCaveatTerms(this.#config.vedaVaultAdapterAddress), + args: '0x' as Hex, + }, + { + enforcer: this.#config.valueLteEnforcer, + terms: + '0x0000000000000000000000000000000000000000000000000000000000000000' as Hex, + args: '0x' as Hex, + }, + ], + salt, + }; + + const signature: string = await this.messenger.call( + 'DelegationController:signDelegation', + { delegation, chainId }, + ); + + const signedDelegation: SignedDelegation = { + ...delegation, + signature: signature as Hex, + }; + + const result = await this.messenger.call( + 'ChompApiService:verifyDelegation', + { signedDelegation, chainId }, + ); + + if (!result.valid) { + throw new Error( + `Delegation verification failed: ${result.errors?.join(', ') ?? 'unknown error'}`, + ); + } + + this.#updateUpgrade(address, { + step: 'verify-delegation', + chainId, + delegationHash: result.delegationHash, + }); + } + + /** + * Step 3: Save the signed delegation to Authenticated User Storage. + * + * @param address - The Money Account address. + * @param _chainId - The target chain (unused in stub). + */ + async #saveDelegation(address: Hex, _chainId: Hex): Promise { + // TODO: Save delegation to Authenticated User Storage once the + // @metamask/authenticated-user-storage wrapper is available. + this.#updateUpgrade(address, { step: 'save-delegation' }); + } + + /** + * Step 4: Register intents with CHOMP so it begins monitoring the account. + * + * @param address - The Money Account address. + * @param chainId - The target chain. + */ + async #registerIntents(address: Hex, chainId: Hex): Promise { + const entry = this.state.upgrades[address]; + const delegationHash = entry?.delegationHash; + + if (!delegationHash) { + throw new Error( + 'Cannot register intents: no delegationHash found. Run verify-delegation first.', + ); + } + + await this.messenger.call('ChompApiService:createIntents', [ + { + account: address, + delegationHash: delegationHash as Hex, + chainId, + metadata: { + allowance: MAX_UINT256, + tokenSymbol: 'mUSD', + tokenAddress: this.#config.musdTokenAddress, + type: 'cash-deposit', + }, + }, + { + account: address, + delegationHash: delegationHash as Hex, + chainId, + metadata: { + allowance: MAX_UINT256, + tokenSymbol: 'mUSD', + tokenAddress: this.#config.musdTokenAddress, + type: 'cash-withdrawal', + }, + }, + ]); + + this.#updateUpgrade(address, { step: 'register-intents' }); + } + + /** + * Encodes caveat terms by concatenating hex values (ABI-style). + * + * @param values - The hex values to pack. + * @returns The concatenated hex string. + */ + #encodeCaveatTerms(...values: Hex[]): Hex { + return `0x${values.map((v) => v.slice(2).padStart(64, '0')).join('')}`; + } + + /** + * Merges an update into the upgrade entry for the given address. + * + * @param address - The account address. + * @param update - Fields to merge into the existing entry. + */ + #updateUpgrade( + address: Hex, + update: Partial & Pick, + ): void { + this.update((state) => { + state.upgrades[address] = { + ...state.upgrades[address], + ...update, + } as AccountUpgradeEntry; + }); + } +} diff --git a/packages/money-account-upgrade-controller/src/index.ts b/packages/money-account-upgrade-controller/src/index.ts new file mode 100644 index 00000000000..7be107296d6 --- /dev/null +++ b/packages/money-account-upgrade-controller/src/index.ts @@ -0,0 +1,15 @@ +export type { UpgradeConfig, UpgradeStep, AccountUpgradeEntry } from './types'; +export { + MoneyAccountUpgradeController, + controllerName, + getDefaultMoneyAccountUpgradeControllerState, +} from './MoneyAccountUpgradeController'; +export type { + MoneyAccountUpgradeControllerState, + MoneyAccountUpgradeControllerGetStateAction, + MoneyAccountUpgradeControllerActions, + MoneyAccountUpgradeControllerStateChangeEvent, + MoneyAccountUpgradeControllerEvents, + MoneyAccountUpgradeControllerMessenger, +} from './MoneyAccountUpgradeController'; +export type { MoneyAccountUpgradeControllerUpgradeAccountAction } from './MoneyAccountUpgradeController-method-action-types'; diff --git a/packages/money-account-upgrade-controller/src/types.ts b/packages/money-account-upgrade-controller/src/types.ts new file mode 100644 index 00000000000..ed75e1890ad --- /dev/null +++ b/packages/money-account-upgrade-controller/src/types.ts @@ -0,0 +1,44 @@ +import type { Hex } from '@metamask/utils'; + +/** + * Contract addresses and configuration required to perform the + * Money Account upgrade sequence. + */ +export type UpgradeConfig = { + /** CHOMP's delegate address — receives the delegation. */ + delegateAddress: Hex; + /** The EIP-7702 delegation target (EIP7702StatelessDeleGatorImpl). */ + delegatorImplAddress: Hex; + /** The mUSD token contract address. */ + musdTokenAddress: Hex; + /** The Veda vault adapter contract address. */ + vedaVaultAdapterAddress: Hex; + /** Address of the ERC20TransferAmountEnforcer caveat enforcer. */ + erc20TransferAmountEnforcer: Hex; + /** Address of the RedeemerEnforcer caveat enforcer. */ + redeemerEnforcer: Hex; + /** Address of the ValueLteEnforcer caveat enforcer. */ + valueLteEnforcer: Hex; +}; + +/** + * The discrete steps of the upgrade sequence, in order. + */ +export type UpgradeStep = + | 'associate-address' + | 'submit-authorization' + | 'verify-delegation' + | 'save-delegation' + | 'register-intents'; + +/** + * Persisted record tracking the progress of an individual account upgrade. + */ +export type AccountUpgradeEntry = { + /** The last successfully completed step. */ + step: UpgradeStep; + /** The chain the upgrade is targeting. */ + chainId: Hex; + /** The delegation hash returned by CHOMP after verify-delegation. */ + delegationHash?: string; +}; diff --git a/packages/money-account-upgrade-controller/tsconfig.build.json b/packages/money-account-upgrade-controller/tsconfig.build.json new file mode 100644 index 00000000000..1885ad844ba --- /dev/null +++ b/packages/money-account-upgrade-controller/tsconfig.build.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tsconfig.packages.build.json", + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist", + "rootDir": "./src" + }, + "references": [ + { "path": "../base-controller/tsconfig.build.json" }, + { "path": "../chomp-api-service/tsconfig.build.json" }, + { "path": "../delegation-controller/tsconfig.build.json" }, + { "path": "../keyring-controller/tsconfig.build.json" }, + { "path": "../messenger/tsconfig.build.json" }, + { "path": "../money-account-controller/tsconfig.build.json" } + ], + "include": ["../../types", "./src"] +} diff --git a/packages/money-account-upgrade-controller/tsconfig.json b/packages/money-account-upgrade-controller/tsconfig.json new file mode 100644 index 00000000000..84f2d5918d3 --- /dev/null +++ b/packages/money-account-upgrade-controller/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.packages.json", + "compilerOptions": { + "baseUrl": "./" + }, + "references": [ + { "path": "../base-controller" }, + { "path": "../chomp-api-service" }, + { "path": "../delegation-controller" }, + { "path": "../keyring-controller" }, + { "path": "../messenger" }, + { "path": "../money-account-controller" } + ], + "include": ["../../types", "./src"] +} diff --git a/packages/money-account-upgrade-controller/typedoc.json b/packages/money-account-upgrade-controller/typedoc.json new file mode 100644 index 00000000000..c9da015dbf8 --- /dev/null +++ b/packages/money-account-upgrade-controller/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 7c960fbabc4..286ba00f21a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3126,7 +3126,7 @@ __metadata: languageName: unknown linkType: soft -"@metamask/chomp-api-service@workspace:packages/chomp-api-service": +"@metamask/chomp-api-service@npm:^0.0.0, @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: @@ -3431,7 +3431,7 @@ __metadata: languageName: node linkType: hard -"@metamask/delegation-controller@workspace:packages/delegation-controller": +"@metamask/delegation-controller@npm:^2.1.0, @metamask/delegation-controller@workspace:packages/delegation-controller": version: 0.0.0-use.local resolution: "@metamask/delegation-controller@workspace:packages/delegation-controller" dependencies: @@ -4426,7 +4426,7 @@ __metadata: languageName: node linkType: hard -"@metamask/money-account-controller@workspace:packages/money-account-controller": +"@metamask/money-account-controller@npm:^0.1.0, @metamask/money-account-controller@workspace:packages/money-account-controller": version: 0.0.0-use.local resolution: "@metamask/money-account-controller@workspace:packages/money-account-controller" dependencies: @@ -4452,6 +4452,30 @@ __metadata: languageName: unknown linkType: soft +"@metamask/money-account-upgrade-controller@workspace:packages/money-account-upgrade-controller": + version: 0.0.0-use.local + resolution: "@metamask/money-account-upgrade-controller@workspace:packages/money-account-upgrade-controller" + dependencies: + "@metamask/auto-changelog": "npm:^3.4.4" + "@metamask/base-controller": "npm:^9.0.1" + "@metamask/chomp-api-service": "npm:^0.0.0" + "@metamask/delegation-controller": "npm:^2.1.0" + "@metamask/keyring-controller": "npm:^25.2.0" + "@metamask/messenger": "npm:^1.1.1" + "@metamask/money-account-controller": "npm:^0.1.0" + "@metamask/utils": "npm:^11.9.0" + "@ts-bridge/cli": "npm:^0.6.4" + "@types/jest": "npm:^29.5.14" + deepmerge: "npm:^4.2.2" + jest: "npm:^29.2.5" + ts-jest: "npm:^29.2.5" + tsx: "npm:^4.20.5" + typedoc: "npm:^0.25.13" + typedoc-plugin-missing-exports: "npm:^2.0.0" + typescript: "npm:~5.3.3" + languageName: unknown + linkType: soft + "@metamask/multichain-account-service@npm:^8.0.1, @metamask/multichain-account-service@workspace:packages/multichain-account-service": version: 0.0.0-use.local resolution: "@metamask/multichain-account-service@workspace:packages/multichain-account-service" @@ -11293,7 +11317,7 @@ __metadata: languageName: node linkType: hard -"jest@npm:^29.7.0": +"jest@npm:^29.2.5, jest@npm:^29.7.0": version: 29.7.0 resolution: "jest@npm:29.7.0" dependencies: