Skip to content

fix(accounts): dynamically enable Money account keyrings and service#29502

Merged
ccharly merged 9 commits into
mainfrom
cc/fix/money-keyring-dynamic-ff
May 6, 2026
Merged

fix(accounts): dynamically enable Money account keyrings and service#29502
ccharly merged 9 commits into
mainfrom
cc/fix/money-keyring-dynamic-ff

Conversation

@ccharly

@ccharly ccharly commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

Description

Keep the MoneyKeyring builder registered in the KeyringController so that if the feature flag gets enabled dynamically, the controller and keyring will get created dynamically too!

  • The money keyring state is never removed/cleared
  • When the flag goes from ON -> OFF and there was a Money account, it gets cleared
  • When the flag goes from OFF -> ON and there was no Money account, it gets created automatically

Changelog

CHANGELOG entry: N/A

Related issues

Fixes: TODO

Manual testing steps

Make sure to enable this in your .js.env:

DEBUG=metamask:money-account-controller

Here's a patch to get some logs:

diff --git a/app/core/Engine/controllers/money-account-controller-init.ts b/app/core/Engine/controllers/money-account-controller-init.ts
index c493253bed..b5d5f4b761 100644
--- a/app/core/Engine/controllers/money-account-controller-init.ts
+++ b/app/core/Engine/controllers/money-account-controller-init.ts
@@ -39,12 +39,14 @@ export const moneyAccountControllerInit: MessengerClientInitFunction<
           const { isUnlocked } = initMessenger.call(
             'KeyringController:getState',
           );
+            console.log('testing: Initializing money account due to FF on');
           // Check for the `KeyringController` to be unlocked, otherwise we won't be able
           // to create the Money keyring if it doesn't exist yet!
           if (isUnlocked) {
             // This call is idempotent, so it is safe to call even if the
             // controller is already initialized.
             await controller.init();
+          console.log('testing: Clearing money account state due to FF off');
           }
         } else if (!isEnabled && hasMoneyAccount) {
           // Clear state if we had a previous Money account and FF is off.
diff --git a/app/core/Engine/controllers/remote-feature-flag-controller-init.ts b/app/core/Engine/controllers/remote-feature-flag-controller-init.ts
index 2ab54cceae..2ac6fb26d9 100644
--- a/app/core/Engine/controllers/remote-feature-flag-controller-init.ts
+++ b/app/core/Engine/controllers/remote-feature-flag-controller-init.ts
@@ -45,9 +45,7 @@ export const remoteFeatureFlagControllerInit: MessengerClientInitFunction<
         distribution: getFeatureFlagAppDistribution(),
       },
     }),
-    fetchInterval: __DEV__
-      ? 1000
-      : AppConstants.FEATURE_FLAGS_API.DEFAULT_FETCH_INTERVAL,
+    fetchInterval: 1000,
   });

   if (disabled) {
@@ -61,6 +59,15 @@ export const remoteFeatureFlagControllerInit: MessengerClientInitFunction<
         Logger.log('Feature flags updated');
       })
       .catch((error) => Logger.log('Feature flags update failed: ', error));
+    setInterval(() =>
+      controller
+        .updateRemoteFeatureFlags()
+        .then(() => {
+          Logger.log('Feature flags updated (interval)');
+        })
+        .catch((error) => Logger.log('Feature flags update failed: ', error))
+      , 10 * 1000
+    );
   }

   return {
diff --git a/app/lib/Money/feature-flags.ts b/app/lib/Money/feature-flags.ts
index 736ed109e0..464497e8dc 100644
--- a/app/lib/Money/feature-flags.ts
+++ b/app/lib/Money/feature-flags.ts
@@ -16,6 +16,7 @@ export function isMoneyAccountEnabled(
   const localFlag = process.env.MM_MONEY_ENABLE_MONEY_ACCOUNT === 'true';
   const remoteFlag =
     remoteFeatureFlags?.moneyEnableMoneyAccount as VersionGatedFeatureFlag;
+  console.log('testing: Remote Flag is:', remoteFlag, 'Local Flag is:', localFlag);

   return validatedVersionGatedFeatureFlag(remoteFlag) ?? localFlag;
 }
Feature: Money account feature flag handling (ON)

  Scenario: flag is ON
    Given the flag was OFF

    When the flag gets updated
    Then the Money account gets created automatically
    
Feature: Money account feature flag handling (OFF)

  Scenario: flag is OFF
    Given the flag was ON

    When the flag gets updated
    Then the Money account gets cleared automatically

If you enabled those extra logs (with the patch above), toggling ON/OFF should give you something like this:

$ yarn watch |& grep -E "metamask:money-account-controller|testing:"
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) DEBUG  metamask:money-account-controller Money keyring (entropy:01KQFS1XQNH0399NJM7EZEFWP7 - primary) account is: 0xad9d9f06da37139dd54fd48fda02cae244a590cb (b3961609-ef94-42ea-90fc-93149e185d56) +0ms
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": false, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Clearing money account state due to FF off
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Initializing money account due to FF on
 (NOBRIDGE) DEBUG  metamask:money-account-controller Money keyring (entropy:01KQFS1XQNH0399NJM7EZEFWP7) account created: 0xad9d9f06da37139dd54fd48fda02cae244a590cb (b3961609-ef94-42ea-90fc-93149e185d56) +26s
 (NOBRIDGE) DEBUG  metamask:money-account-controller Money keyring (entropy:01KQFS1XQNH0399NJM7EZEFWP7 - primary) account is: 0xad9d9f06da37139dd54fd48fda02cae244a590cb (b3961609-ef94-42ea-90fc-93149e185d56) +0ms
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": false, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Clearing money account state due to FF off
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": false, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": false, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Initializing money account due to FF on
 (NOBRIDGE) DEBUG  metamask:money-account-controller Money keyring (entropy:01KQFS1XQNH0399NJM7EZEFWP7) account created: 0xad9d9f06da37139dd54fd48fda02cae244a590cb (b3961609-ef94-42ea-90fc-93149e185d56) +1m
 (NOBRIDGE) DEBUG  metamask:money-account-controller Money keyring (entropy:01KQFS1XQNH0399NJM7EZEFWP7 - primary) account is: 0xad9d9f06da37139dd54fd48fda02cae244a590cb (b3961609-ef94-42ea-90fc-93149e185d56) +0ms
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
 (NOBRIDGE) LOG  testing: Remote Flag is: {"enabled": true, "minimumVersion": "0.0.0"} Local Flag is: false
  • We only re-init if there was no Money account AND the flag is ON
  • We only clear if there was a Money account AND the flag is OFF
  • We only do those steps once (not clearing twice, not calling init twice)

Screenshots/Recordings

Before

After

Pre-merge author checklist

Performance checks (if applicable)

  • I've tested on Android
    • Ideally on a mid-range device; emulator is acceptable
  • I've tested with a power user scenario
    • Use these power-user SRPs to import wallets with many accounts and tokens
  • I've instrumented key operations with Sentry traces for production performance metrics

For performance guidelines and tooling, see the Performance Guide.

Pre-merge reviewer checklist

  • I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed).
  • I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots.

Note

Medium Risk
Touches account/keyring initialization and wallet reset flows, so mistakes could create or wipe Money account state unexpectedly when feature flags change. Changes are scoped and covered by targeted unit tests, but still impact core account plumbing.

Overview
Money accounts are now managed dynamically based on remote feature-flag updates. MoneyAccountController subscribes to RemoteFeatureFlagController:stateChange during init and will init() when the flag turns on (only if the keyring is unlocked and no money accounts exist), or clearState() when the flag turns off (only if money accounts exist), with error logging on failures.

Keyring handling is made resilient to flag timing. The MoneyKeyring builder is now always registered in keyringControllerInit so vault deserialization can recognize the type even if the Money feature flag is disabled at that moment.

State clearing responsibilities are centralized. Engine.resetState now clears MoneyAccountController state, while AccountTreeInitService.clearState no longer clears money accounts. Tests were updated/added to assert these behaviors and the new init messenger wiring (getMoneyAccountControllerInitMessenger).

Reviewed by Cursor Bugbot for commit 9d427ea. Bugbot is set up for automated code reviews on this repo. Configure here.

@github-actions

Copy link
Copy Markdown
Contributor

CLA Signature Action: All authors have signed the CLA. You may need to manually re-run the blocking PR check if it doesn't pass in a few minutes.

@metamaskbotv2 metamaskbotv2 Bot added the team-accounts-framework Accounts team label Apr 29, 2026
Comment thread app/multichain-accounts/AccountTreeInitService/index.ts Outdated
@ccharly ccharly marked this pull request as ready for review May 1, 2026 12:53
@ccharly ccharly requested review from a team as code owners May 1, 2026 12:53

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit ee29ab2. Configure here.

'MoneyAccountController: error handling RemoteFeatureFlagController state change',
);
}
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Race condition in async flag handler can orphan money accounts

Low Severity

The async subscription callback has no guard against concurrent execution. If the flag toggles ON→OFF rapidly: (1) the first callback starts await controller.init(), (2) the second callback reads hasMoneyAccount as false (init not complete) and enters neither branch. When init() resolves, a money account exists but the flag is OFF — an inconsistent state that won't self-correct until another flag change event fires.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ee29ab2. Configure here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO that's super unlikely to happen, plus, restarting the app will, anyway, fix the state. WDYT @gantunesr?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the flag toggles ON→OFF rapidly

This is not a possible scenario in production. The flag has been designated as a "kill switch" therefore this is not a concern

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is a non-reversible change

gantunesr
gantunesr previously approved these changes May 5, 2026

@gantunesr gantunesr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Left a minor comment and did not have time to manually test it

shane-t
shane-t previously approved these changes May 6, 2026
@github-actions

github-actions Bot commented May 6, 2026

Copy link
Copy Markdown
Contributor

🔍 Smart E2E Test Selection

  • Selected E2E tags: SmokeAccounts, SmokeWalletPlatform, SmokeMoney, SmokeConfirmations
  • Selected Performance tags: @PerformanceLogin
  • Risk Level: high
  • AI Confidence: 80%
click to see 🤖 AI reasoning details

E2E Test Selection:

The PR makes several interconnected changes to the MoneyAccountController and KeyringController initialization:

  1. KeyringController (Phase 2 - Critical): The MoneyKeyring builder is now ALWAYS registered unconditionally, regardless of the feature flag. Previously it was gated behind isMoneyAccountEnabled. This is a behavioral change to a Phase 2 (foundational) controller that affects vault deserialization and keyring initialization. Any regression here could affect wallet unlock/lock flows and account management.

  2. MoneyAccountController init: Now subscribes to RemoteFeatureFlagController:stateChange to reactively enable/disable Money accounts. This adds a new messenger subscription pattern and uses a new init messenger with access to KeyringController and RemoteFeatureFlagController state.

  3. Engine.resetState: Now explicitly calls MoneyAccountController.clearState() during wallet reset. This affects the wallet reset/wipe flow.

  4. AccountTreeInitService: Removed MoneyAccountController.clearState() from its clearState() method — responsibility moved to Engine.resetState and the reactive subscription.

  5. New init messenger: getMoneyAccountControllerInitMessenger provides scoped access to RemoteFeatureFlagController and KeyringController actions/events.

Tag Selection Rationale:

  • SmokeAccounts: KeyringController changes (always registering MoneyKeyring) affect account creation, import, and vault deserialization. The wallet reset flow (Engine.resetState) also affects account management.
  • SmokeWalletPlatform: Engine.resetState changes affect wallet lifecycle. Multi-SRP architecture is touched by KeyringController changes.
  • SmokeMoney: The MoneyAccountController init changes directly affect the Money/Card feature — reactive feature flag handling, state clearing, and account initialization.
  • SmokeConfirmations: Money account deposits involve on-chain transactions; the MoneyKeyring is used for signing Money account transactions. Changes to keyring initialization could affect confirmation flows.

Performance Test Selection:
The KeyringController initialization change (MoneyKeyring builder now always registered unconditionally) could have a minor impact on wallet unlock/login performance since an additional keyring builder is always registered. The @PerformanceLogin tag covers password entry, biometric unlock, session restoration, and time to wallet ready state — all of which go through KeyringController initialization. This is a conservative selection given the Phase 2 controller change.

View GitHub Actions results

@sonarqubecloud

sonarqubecloud Bot commented May 6, 2026

Copy link
Copy Markdown

@ccharly ccharly added this pull request to the merge queue May 6, 2026
@ccharly ccharly removed this pull request from the merge queue due to a manual request May 6, 2026
@ccharly ccharly added this pull request to the merge queue May 6, 2026
Merged via the queue into main with commit a6572a0 May 6, 2026
100 checks passed
@ccharly ccharly deleted the cc/fix/money-keyring-dynamic-ff branch May 6, 2026 15:40
@github-actions github-actions Bot locked and limited conversation to collaborators May 6, 2026
@metamaskbotv2 metamaskbotv2 Bot added the release-7.77.0 Issue or pull request that will be included in release 7.77.0 label May 6, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release-7.77.0 Issue or pull request that will be included in release 7.77.0 size-M team-accounts-framework Accounts team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants