@metamask-previews/money-account-upgrade-controller 3.0.2-preview-00a181c → 3.0.2-preview-cfd35b8dd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/MoneyAccountUpgradeController-method-action-types.cjs.map +1 -1
  3. package/dist/MoneyAccountUpgradeController-method-action-types.d.cts +4 -0
  4. package/dist/MoneyAccountUpgradeController-method-action-types.d.cts.map +1 -1
  5. package/dist/MoneyAccountUpgradeController-method-action-types.d.mts +4 -0
  6. package/dist/MoneyAccountUpgradeController-method-action-types.d.mts.map +1 -1
  7. package/dist/MoneyAccountUpgradeController-method-action-types.mjs.map +1 -1
  8. package/dist/MoneyAccountUpgradeController.cjs +194 -40
  9. package/dist/MoneyAccountUpgradeController.cjs.map +1 -1
  10. package/dist/MoneyAccountUpgradeController.d.cts +90 -18
  11. package/dist/MoneyAccountUpgradeController.d.cts.map +1 -1
  12. package/dist/MoneyAccountUpgradeController.d.mts +90 -18
  13. package/dist/MoneyAccountUpgradeController.d.mts.map +1 -1
  14. package/dist/MoneyAccountUpgradeController.mjs +195 -41
  15. package/dist/MoneyAccountUpgradeController.mjs.map +1 -1
  16. package/dist/errors.cjs +13 -1
  17. package/dist/errors.cjs.map +1 -1
  18. package/dist/errors.d.cts +8 -0
  19. package/dist/errors.d.cts.map +1 -1
  20. package/dist/errors.d.mts +8 -0
  21. package/dist/errors.d.mts.map +1 -1
  22. package/dist/errors.mjs +11 -0
  23. package/dist/errors.mjs.map +1 -1
  24. package/dist/index.cjs +2 -1
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +2 -2
  27. package/dist/index.d.cts.map +1 -1
  28. package/dist/index.d.mts +2 -2
  29. package/dist/index.d.mts.map +1 -1
  30. package/dist/index.mjs +1 -1
  31. package/dist/index.mjs.map +1 -1
  32. package/package.json +3 -1
@@ -3,9 +3,11 @@ import type { ControllerGetStateAction, ControllerStateChangedEvent } from "@met
3
3
  import { BaseController } from "@metamask/base-controller";
4
4
  import type { ChompApiServiceAssociateAddressAction, ChompApiServiceCreateIntentsAction, ChompApiServiceCreateUpgradeAction, ChompApiServiceGetAssociatedAddressesAction, ChompApiServiceGetIntentsByAddressAction, ChompApiServiceGetServiceDetailsAction, ChompApiServiceVerifyDelegationAction } from "@metamask/chomp-api-service";
5
5
  import type { DelegationControllerSignDelegationAction } from "@metamask/delegation-controller";
6
- import type { KeyringControllerSignEip7702AuthorizationAction, KeyringControllerSignPersonalMessageAction } from "@metamask/keyring-controller";
6
+ import type { KeyringControllerGetStateAction, KeyringControllerSignEip7702AuthorizationAction, KeyringControllerSignPersonalMessageAction, KeyringControllerState } from "@metamask/keyring-controller";
7
7
  import type { Messenger } from "@metamask/messenger";
8
+ import type { MoneyAccountVaultConfig } from "@metamask/money-account-utils";
8
9
  import type { NetworkControllerFindNetworkClientIdByChainIdAction, NetworkControllerGetNetworkClientByIdAction } from "@metamask/network-controller";
10
+ import type { FeatureFlags, RemoteFeatureFlagControllerGetStateAction, RemoteFeatureFlagControllerState } from "@metamask/remote-feature-flag-controller";
9
11
  import type { Hex } from "@metamask/utils";
10
12
  import type { MoneyAccountUpgradeControllerMethodActions } from "./MoneyAccountUpgradeController-method-action-types.cjs";
11
13
  export declare const controllerName = "MoneyAccountUpgradeController";
@@ -43,13 +45,72 @@ export type MoneyAccountUpgradeControllerState = {
43
45
  export declare function getDefaultMoneyAccountUpgradeControllerState(): MoneyAccountUpgradeControllerState;
44
46
  export type MoneyAccountUpgradeControllerGetStateAction = ControllerGetStateAction<typeof controllerName, MoneyAccountUpgradeControllerState>;
45
47
  export type MoneyAccountUpgradeControllerActions = MoneyAccountUpgradeControllerGetStateAction | MoneyAccountUpgradeControllerMethodActions;
46
- type AllowedActions = AuthenticatedUserStorageServiceCreateDelegationAction | AuthenticatedUserStorageServiceListDelegationsAction | ChompApiServiceAssociateAddressAction | ChompApiServiceCreateIntentsAction | ChompApiServiceCreateUpgradeAction | ChompApiServiceGetAssociatedAddressesAction | ChompApiServiceGetIntentsByAddressAction | ChompApiServiceGetServiceDetailsAction | ChompApiServiceVerifyDelegationAction | DelegationControllerSignDelegationAction | KeyringControllerSignEip7702AuthorizationAction | KeyringControllerSignPersonalMessageAction | NetworkControllerFindNetworkClientIdByChainIdAction | NetworkControllerGetNetworkClientByIdAction;
48
+ type AllowedActions = AuthenticatedUserStorageServiceCreateDelegationAction | AuthenticatedUserStorageServiceListDelegationsAction | ChompApiServiceAssociateAddressAction | ChompApiServiceCreateIntentsAction | ChompApiServiceCreateUpgradeAction | ChompApiServiceGetAssociatedAddressesAction | ChompApiServiceGetIntentsByAddressAction | ChompApiServiceGetServiceDetailsAction | ChompApiServiceVerifyDelegationAction | DelegationControllerSignDelegationAction | KeyringControllerGetStateAction | KeyringControllerSignEip7702AuthorizationAction | KeyringControllerSignPersonalMessageAction | NetworkControllerFindNetworkClientIdByChainIdAction | NetworkControllerGetNetworkClientByIdAction | RemoteFeatureFlagControllerGetStateAction;
47
49
  export type MoneyAccountUpgradeControllerStateChangedEvent = ControllerStateChangedEvent<typeof controllerName, MoneyAccountUpgradeControllerState>;
48
50
  export type MoneyAccountUpgradeControllerEvents = MoneyAccountUpgradeControllerStateChangedEvent;
49
- type AllowedEvents = never;
51
+ type AllowedEvents = ControllerStateChangedEvent<'KeyringController', KeyringControllerState> | ControllerStateChangedEvent<'RemoteFeatureFlagController', RemoteFeatureFlagControllerState>;
50
52
  export type MoneyAccountUpgradeControllerMessenger = Messenger<typeof controllerName, MoneyAccountUpgradeControllerActions | AllowedActions, MoneyAccountUpgradeControllerEvents | AllowedEvents>;
51
53
  /**
52
- * Controller that orchestrates the Money Account upgrade sequence.
54
+ * These hooks must be provided by the client - they provide functions that required to bootstrap
55
+ * the controller, which rely on client specific information.
56
+ */
57
+ export type MoneyAccountUpgradeControllerHooks = {
58
+ /**
59
+ * Whether the Money Account feature is enabled for this client.
60
+ *
61
+ * The controller will call the function with the current state of
62
+ * the remote feature flags. It gets caleld on every sync, and re-checked
63
+ * when the bootstrap `awaits`.
64
+ *
65
+ * The isEnabled function should re-read any client state it depends
66
+ * on (e.g. a version-gated flag, a "basic functionality" toggle) rather
67
+ * than caching it. Returning `false` after a successful bootstrap disarms
68
+ * the controller: `upgradeAccount` refuses to run until a later sync
69
+ * re-bootstraps.
70
+ */
71
+ isEnabled: (remoteFeatureFlags: FeatureFlags) => boolean;
72
+ /**
73
+ * An asynchronous client gate checked once per bootstrap run, before any
74
+ * network is added or external service is called — e.g. a fail-closed
75
+ * geolocation check. A run skipped here is forgotten and retried on the
76
+ * next sync trigger. If the function is not provided we assume the client is eligible.
77
+ */
78
+ isEligible?: () => Promise<boolean>;
79
+ /**
80
+ * Ensure the vault chain exists in the client's NetworkController before
81
+ * the bootstrap validates it. Adding a network is client-specific, so
82
+ * the controller awaits this before calling
83
+ * `NetworkController:findNetworkClientIdByChainId` consumers. Defaults to a
84
+ * no-op.
85
+ */
86
+ ensureChainConfigured?: (vaultConfig: MoneyAccountVaultConfig) => Promise<void>;
87
+ /**
88
+ * Called when a bootstrap run fails or cannot be scheduled. Receives a
89
+ * {@link MissingMoneyAccountVaultConfigError} (once per controller
90
+ * lifetime) when the enable flag is on but `moneyAccountVaultConfig` is
91
+ * unserved or malformed.
92
+ */
93
+ onBootstrapError?: (error: unknown) => void;
94
+ };
95
+ /**
96
+ * Controller that owns the Money Account upgrade sequence and its own
97
+ * bootstrap.
98
+ *
99
+ * After {@link MoneyAccountUpgradeController.init} is called, the controller watches
100
+ * `RemoteFeatureFlagController` and `KeyringController` state and bootstraps
101
+ * itself when:
102
+ *
103
+ * 1. the client's `isEnabled` hook returns `true` for the current flags,
104
+ * 2. the wallet is unlocked with an HD keyring,
105
+ * 3. the client's `isEligible` hook (if any) resolves `true`, and
106
+ * 4. the `moneyAccountVaultConfig` flag parses.
107
+ *
108
+ * The bootstrap awaits the client's `ensureChainConfigured` hook and then
109
+ * fetches CHOMP service details to get the upgrade config. We recheck points
110
+ * 1–2 when awaiting in the bootstrap so a lock or an `isEnabled` will stop the process.
111
+ *
112
+ * The bootstrap re-runs whenever the vault config changes.
113
+ * `isEnabled` going `false` disables the controller.
53
114
  */
54
115
  export declare class MoneyAccountUpgradeController extends BaseController<typeof controllerName, MoneyAccountUpgradeControllerState, MoneyAccountUpgradeControllerMessenger> {
55
116
  #private;
@@ -59,27 +120,31 @@ export declare class MoneyAccountUpgradeController extends BaseController<typeof
59
120
  * @param options - The options for constructing the controller.
60
121
  * @param options.messenger - The messenger to use for inter-controller communication.
61
122
  * @param options.state - The initial state, merged with the defaults.
123
+ * @param options.hooks - The client hooks for the bootstrap; see
124
+ * {@link MoneyAccountUpgradeControllerHooks}.
62
125
  */
63
- constructor({ messenger, state, }: {
126
+ constructor({ messenger, state, hooks, }: {
64
127
  messenger: MoneyAccountUpgradeControllerMessenger;
65
128
  state?: Partial<MoneyAccountUpgradeControllerState>;
129
+ hooks: MoneyAccountUpgradeControllerHooks;
66
130
  });
67
131
  /**
68
- * Fetches service details and validates the controller can operate on the
69
- * given chain. Resolves the Delegation Framework contract addresses for the
70
- * chain from `@metamask/delegation-deployments`.
132
+ * Start the controller's bootstrap: subscribe to the feature-flag and
133
+ * keyring triggers and run an initial sync. Call once, after all
134
+ * controllers and services the messenger reaches are constructed — this is
135
+ * the only method that may be called before the controller is bootstrapped,
136
+ * and it is the reason the constructor performs no messenger calls.
137
+ */
138
+ init(): void;
139
+ /**
140
+ * Re-evaluate the bootstrap checks against live state and schedule a
141
+ * bootstrap run when they are open and the vault config is new. Runs on
142
+ * every feature-flag and keyring state change.
71
143
  *
72
- * @param params - The parameters for initialization.
73
- * @param params.chainId - The chain to initialize for.
74
- * @param params.boringVaultAddress - The Veda boring vault contract
75
- * (vmUSD) for the given chain. Used as the withdrawal-side delegation
76
- * token. Supplied by the consumer until the CHOMP service-details API
77
- * exposes it.
144
+ * If sync fails a failure is reported through `onBootstrapError` and retried
145
+ * on the next trigger.
78
146
  */
79
- init({ chainId, boringVaultAddress, }: {
80
- chainId: Hex;
81
- boringVaultAddress: Hex;
82
- }): Promise<void>;
147
+ sync(): void;
83
148
  /**
84
149
  * Runs each step in the upgrade sequence in order. A step that reports
85
150
  * `'already-done'` is skipped without performing any action; a step that
@@ -94,6 +159,13 @@ export declare class MoneyAccountUpgradeController extends BaseController<typeof
94
159
  * active config no longer matches the recorded fingerprint, the sequence
95
160
  * re-runs.
96
161
  *
162
+ * A call that arrives while the bootstrap chain is still in flight —
163
+ * including runs scheduled while waiting — waits for it to settle rather
164
+ * than failing, so the upgrade always runs against the latest armed
165
+ * config. Scheduling a bootstrap for a changed vault config disarms the
166
+ * previous one, so it only throws when no bootstrap has armed a config:
167
+ * feature disabled, wallet locked, or the last bootstrap failed.
168
+ *
97
169
  * @param address - The Money Account address to upgrade.
98
170
  */
99
171
  upgradeAccount(address: Hex): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"MoneyAccountUpgradeController.d.cts","sourceRoot":"","sources":["../src/MoneyAccountUpgradeController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qDAAqD,EACrD,oDAAoD,EACrD,6CAA6C;AAC9C,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,qCAAqC,EACrC,kCAAkC,EAClC,kCAAkC,EAClC,2CAA2C,EAC3C,wCAAwC,EACxC,sCAAsC,EACtC,qCAAqC,EACtC,oCAAoC;AACrC,OAAO,KAAK,EAAE,wCAAwC,EAAE,wCAAwC;AAEhG,OAAO,KAAK,EACV,+CAA+C,EAC/C,0CAA0C,EAC3C,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EACV,mDAAmD,EACnD,2CAA2C,EAC5C,qCAAqC;AAEtC,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3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G;gBACS,EACV,SAAS,EACT,KAAK,GACN,EAAE;QACD,SAAS,EAAE,sCAAsC,CAAC;QAClD,KAAK,CAAC,EAAE,OAAO,CAAC,kCAAkC,CAAC,CAAC;KACrD;IAiBD;;;;;;;;;;;OAWG;IACG,IAAI,CAAC,EACT,OAAO,EACP,kBAAkB,GACnB,EAAE;QACD,OAAO,EAAE,GAAG,CAAC;QACb,kBAAkB,EAAE,GAAG,CAAC;KACzB,GAAG,OAAO,CAAC,IAAI,CAAC;IA6CjB;;;;;;;;;;;;;;;OAeG;IACG,cAAc,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;CAoClD"}
1
+ {"version":3,"file":"MoneyAccountUpgradeController.d.cts","sourceRoot":"","sources":["../src/MoneyAccountUpgradeController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qDAAqD,EACrD,oDAAoD,EACrD,6CAA6C;AAC9C,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,qCAAqC,EACrC,kCAAkC,EAClC,kCAAkC,EAClC,2CAA2C,EAC3C,wCAAwC,EACxC,sCAAsC,EACtC,qCAAqC,EACtC,oCAAoC;AACrC,OAAO,KAAK,EAAE,wCAAwC,EAAE,wCAAwC;AAGhG,OAAO,KAAK,EACV,+BAA+B,EAC/B,+CAA+C,EAC/C,0CAA0C,EAC1C,sBAAsB,EACvB,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAKrD,OAAO,KAAK,EAAE,uBAAuB,EAAE,sCAAsC;AAC7E,OAAO,KAAK,EACV,mDAAmD,EACnD,2CAA2C,EAC5C,qCAAqC;AACtC,OAAO,KAAK,EACV,YAAY,EACZ,yCAAyC,EACzC,gCAAgC,EACjC,iDAAiD;AAElD,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAM3C,OAAO,K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GG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C;;;;;;;;;;;;OAYG;IACH,SAAS,EAAE,CAAC,kBAAkB,EAAE,YAAY,KAAK,OAAO,CAAC;IAEzD;;;;;OAKG;IACH,UAAU,CAAC,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAEpC;;;;;;OAMG;IACH,qBAAqB,CAAC,EAAE,CACtB,WAAW,EAAE,uBAAuB,KACjC,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnB;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CAC7C,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,6BAA8B,SAAQ,cAAc,CAC/D,OAAO,cAAc,EACrB,kCAAkC,EAClC,sCAAsC,CACvC;;IAgCC;;;;;;;;OAQG;gBACS,EACV,SAAS,EACT,KAAK,EACL,KAAK,GACN,EAAE;QACD,SAAS,EAAE,sCAAsC,CAAC;QAClD,KAAK,CAAC,EAAE,OAAO,CAAC,kCAAkC,CAAC,CAAC;QACpD,KAAK,EAAE,kCAAkC,CAAC;KAC3C;IAuBD;;;;;;OAMG;IACH,IAAI,IAAI,IAAI;IAeZ;;;;;;;OAOG;IACH,IAAI,IAAI,IAAI;IAwMZ;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACG,cAAc,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;CA2ClD"}
@@ -3,9 +3,11 @@ import type { ControllerGetStateAction, ControllerStateChangedEvent } from "@met
3
3
  import { BaseController } from "@metamask/base-controller";
4
4
  import type { ChompApiServiceAssociateAddressAction, ChompApiServiceCreateIntentsAction, ChompApiServiceCreateUpgradeAction, ChompApiServiceGetAssociatedAddressesAction, ChompApiServiceGetIntentsByAddressAction, ChompApiServiceGetServiceDetailsAction, ChompApiServiceVerifyDelegationAction } from "@metamask/chomp-api-service";
5
5
  import type { DelegationControllerSignDelegationAction } from "@metamask/delegation-controller";
6
- import type { KeyringControllerSignEip7702AuthorizationAction, KeyringControllerSignPersonalMessageAction } from "@metamask/keyring-controller";
6
+ import type { KeyringControllerGetStateAction, KeyringControllerSignEip7702AuthorizationAction, KeyringControllerSignPersonalMessageAction, KeyringControllerState } from "@metamask/keyring-controller";
7
7
  import type { Messenger } from "@metamask/messenger";
8
+ import type { MoneyAccountVaultConfig } from "@metamask/money-account-utils";
8
9
  import type { NetworkControllerFindNetworkClientIdByChainIdAction, NetworkControllerGetNetworkClientByIdAction } from "@metamask/network-controller";
10
+ import type { FeatureFlags, RemoteFeatureFlagControllerGetStateAction, RemoteFeatureFlagControllerState } from "@metamask/remote-feature-flag-controller";
9
11
  import type { Hex } from "@metamask/utils";
10
12
  import type { MoneyAccountUpgradeControllerMethodActions } from "./MoneyAccountUpgradeController-method-action-types.mjs";
11
13
  export declare const controllerName = "MoneyAccountUpgradeController";
@@ -43,13 +45,72 @@ export type MoneyAccountUpgradeControllerState = {
43
45
  export declare function getDefaultMoneyAccountUpgradeControllerState(): MoneyAccountUpgradeControllerState;
44
46
  export type MoneyAccountUpgradeControllerGetStateAction = ControllerGetStateAction<typeof controllerName, MoneyAccountUpgradeControllerState>;
45
47
  export type MoneyAccountUpgradeControllerActions = MoneyAccountUpgradeControllerGetStateAction | MoneyAccountUpgradeControllerMethodActions;
46
- type AllowedActions = AuthenticatedUserStorageServiceCreateDelegationAction | AuthenticatedUserStorageServiceListDelegationsAction | ChompApiServiceAssociateAddressAction | ChompApiServiceCreateIntentsAction | ChompApiServiceCreateUpgradeAction | ChompApiServiceGetAssociatedAddressesAction | ChompApiServiceGetIntentsByAddressAction | ChompApiServiceGetServiceDetailsAction | ChompApiServiceVerifyDelegationAction | DelegationControllerSignDelegationAction | KeyringControllerSignEip7702AuthorizationAction | KeyringControllerSignPersonalMessageAction | NetworkControllerFindNetworkClientIdByChainIdAction | NetworkControllerGetNetworkClientByIdAction;
48
+ type AllowedActions = AuthenticatedUserStorageServiceCreateDelegationAction | AuthenticatedUserStorageServiceListDelegationsAction | ChompApiServiceAssociateAddressAction | ChompApiServiceCreateIntentsAction | ChompApiServiceCreateUpgradeAction | ChompApiServiceGetAssociatedAddressesAction | ChompApiServiceGetIntentsByAddressAction | ChompApiServiceGetServiceDetailsAction | ChompApiServiceVerifyDelegationAction | DelegationControllerSignDelegationAction | KeyringControllerGetStateAction | KeyringControllerSignEip7702AuthorizationAction | KeyringControllerSignPersonalMessageAction | NetworkControllerFindNetworkClientIdByChainIdAction | NetworkControllerGetNetworkClientByIdAction | RemoteFeatureFlagControllerGetStateAction;
47
49
  export type MoneyAccountUpgradeControllerStateChangedEvent = ControllerStateChangedEvent<typeof controllerName, MoneyAccountUpgradeControllerState>;
48
50
  export type MoneyAccountUpgradeControllerEvents = MoneyAccountUpgradeControllerStateChangedEvent;
49
- type AllowedEvents = never;
51
+ type AllowedEvents = ControllerStateChangedEvent<'KeyringController', KeyringControllerState> | ControllerStateChangedEvent<'RemoteFeatureFlagController', RemoteFeatureFlagControllerState>;
50
52
  export type MoneyAccountUpgradeControllerMessenger = Messenger<typeof controllerName, MoneyAccountUpgradeControllerActions | AllowedActions, MoneyAccountUpgradeControllerEvents | AllowedEvents>;
51
53
  /**
52
- * Controller that orchestrates the Money Account upgrade sequence.
54
+ * These hooks must be provided by the client - they provide functions that required to bootstrap
55
+ * the controller, which rely on client specific information.
56
+ */
57
+ export type MoneyAccountUpgradeControllerHooks = {
58
+ /**
59
+ * Whether the Money Account feature is enabled for this client.
60
+ *
61
+ * The controller will call the function with the current state of
62
+ * the remote feature flags. It gets caleld on every sync, and re-checked
63
+ * when the bootstrap `awaits`.
64
+ *
65
+ * The isEnabled function should re-read any client state it depends
66
+ * on (e.g. a version-gated flag, a "basic functionality" toggle) rather
67
+ * than caching it. Returning `false` after a successful bootstrap disarms
68
+ * the controller: `upgradeAccount` refuses to run until a later sync
69
+ * re-bootstraps.
70
+ */
71
+ isEnabled: (remoteFeatureFlags: FeatureFlags) => boolean;
72
+ /**
73
+ * An asynchronous client gate checked once per bootstrap run, before any
74
+ * network is added or external service is called — e.g. a fail-closed
75
+ * geolocation check. A run skipped here is forgotten and retried on the
76
+ * next sync trigger. If the function is not provided we assume the client is eligible.
77
+ */
78
+ isEligible?: () => Promise<boolean>;
79
+ /**
80
+ * Ensure the vault chain exists in the client's NetworkController before
81
+ * the bootstrap validates it. Adding a network is client-specific, so
82
+ * the controller awaits this before calling
83
+ * `NetworkController:findNetworkClientIdByChainId` consumers. Defaults to a
84
+ * no-op.
85
+ */
86
+ ensureChainConfigured?: (vaultConfig: MoneyAccountVaultConfig) => Promise<void>;
87
+ /**
88
+ * Called when a bootstrap run fails or cannot be scheduled. Receives a
89
+ * {@link MissingMoneyAccountVaultConfigError} (once per controller
90
+ * lifetime) when the enable flag is on but `moneyAccountVaultConfig` is
91
+ * unserved or malformed.
92
+ */
93
+ onBootstrapError?: (error: unknown) => void;
94
+ };
95
+ /**
96
+ * Controller that owns the Money Account upgrade sequence and its own
97
+ * bootstrap.
98
+ *
99
+ * After {@link MoneyAccountUpgradeController.init} is called, the controller watches
100
+ * `RemoteFeatureFlagController` and `KeyringController` state and bootstraps
101
+ * itself when:
102
+ *
103
+ * 1. the client's `isEnabled` hook returns `true` for the current flags,
104
+ * 2. the wallet is unlocked with an HD keyring,
105
+ * 3. the client's `isEligible` hook (if any) resolves `true`, and
106
+ * 4. the `moneyAccountVaultConfig` flag parses.
107
+ *
108
+ * The bootstrap awaits the client's `ensureChainConfigured` hook and then
109
+ * fetches CHOMP service details to get the upgrade config. We recheck points
110
+ * 1–2 when awaiting in the bootstrap so a lock or an `isEnabled` will stop the process.
111
+ *
112
+ * The bootstrap re-runs whenever the vault config changes.
113
+ * `isEnabled` going `false` disables the controller.
53
114
  */
54
115
  export declare class MoneyAccountUpgradeController extends BaseController<typeof controllerName, MoneyAccountUpgradeControllerState, MoneyAccountUpgradeControllerMessenger> {
55
116
  #private;
@@ -59,27 +120,31 @@ export declare class MoneyAccountUpgradeController extends BaseController<typeof
59
120
  * @param options - The options for constructing the controller.
60
121
  * @param options.messenger - The messenger to use for inter-controller communication.
61
122
  * @param options.state - The initial state, merged with the defaults.
123
+ * @param options.hooks - The client hooks for the bootstrap; see
124
+ * {@link MoneyAccountUpgradeControllerHooks}.
62
125
  */
63
- constructor({ messenger, state, }: {
126
+ constructor({ messenger, state, hooks, }: {
64
127
  messenger: MoneyAccountUpgradeControllerMessenger;
65
128
  state?: Partial<MoneyAccountUpgradeControllerState>;
129
+ hooks: MoneyAccountUpgradeControllerHooks;
66
130
  });
67
131
  /**
68
- * Fetches service details and validates the controller can operate on the
69
- * given chain. Resolves the Delegation Framework contract addresses for the
70
- * chain from `@metamask/delegation-deployments`.
132
+ * Start the controller's bootstrap: subscribe to the feature-flag and
133
+ * keyring triggers and run an initial sync. Call once, after all
134
+ * controllers and services the messenger reaches are constructed — this is
135
+ * the only method that may be called before the controller is bootstrapped,
136
+ * and it is the reason the constructor performs no messenger calls.
137
+ */
138
+ init(): void;
139
+ /**
140
+ * Re-evaluate the bootstrap checks against live state and schedule a
141
+ * bootstrap run when they are open and the vault config is new. Runs on
142
+ * every feature-flag and keyring state change.
71
143
  *
72
- * @param params - The parameters for initialization.
73
- * @param params.chainId - The chain to initialize for.
74
- * @param params.boringVaultAddress - The Veda boring vault contract
75
- * (vmUSD) for the given chain. Used as the withdrawal-side delegation
76
- * token. Supplied by the consumer until the CHOMP service-details API
77
- * exposes it.
144
+ * If sync fails a failure is reported through `onBootstrapError` and retried
145
+ * on the next trigger.
78
146
  */
79
- init({ chainId, boringVaultAddress, }: {
80
- chainId: Hex;
81
- boringVaultAddress: Hex;
82
- }): Promise<void>;
147
+ sync(): void;
83
148
  /**
84
149
  * Runs each step in the upgrade sequence in order. A step that reports
85
150
  * `'already-done'` is skipped without performing any action; a step that
@@ -94,6 +159,13 @@ export declare class MoneyAccountUpgradeController extends BaseController<typeof
94
159
  * active config no longer matches the recorded fingerprint, the sequence
95
160
  * re-runs.
96
161
  *
162
+ * A call that arrives while the bootstrap chain is still in flight —
163
+ * including runs scheduled while waiting — waits for it to settle rather
164
+ * than failing, so the upgrade always runs against the latest armed
165
+ * config. Scheduling a bootstrap for a changed vault config disarms the
166
+ * previous one, so it only throws when no bootstrap has armed a config:
167
+ * feature disabled, wallet locked, or the last bootstrap failed.
168
+ *
97
169
  * @param address - The Money Account address to upgrade.
98
170
  */
99
171
  upgradeAccount(address: Hex): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"MoneyAccountUpgradeController.d.mts","sourceRoot":"","sources":["../src/MoneyAccountUpgradeController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qDAAqD,EACrD,oDAAoD,EACrD,6CAA6C;AAC9C,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,qCAAqC,EACrC,kCAAkC,EAClC,kCAAkC,EAClC,2CAA2C,EAC3C,wCAAwC,EACxC,sCAAsC,EACtC,qCAAqC,EACtC,oCAAoC;AACrC,OAAO,KAAK,EAAE,wCAAwC,EAAE,wCAAwC;AAEhG,OAAO,KAAK,EACV,+CAA+C,EAC/C,0CAA0C,EAC3C,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EACV,mDAAmD,EACnD,2CAA2C,EAC5C,qCAAqC;AAEtC,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EAAE,0CAA0C,EAAE,gEAA+D;AAczH,eAAO,MAAM,cAAc,kCAAkC,CAAC;AAE9D;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC;;;;;OAKG;IACH,iBAAiB,EAAE,MAAM,CAAC;IAC1B,oEAAoE;IACpE,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,MAAM,MAAM,kCAAkC,GAAG;IAC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AC;KACzB,GAAG,OAAO,CAAC,IAAI,CAAC;IA6CjB;;;;;;;;;;;;;;;OAeG;IACG,cAAc,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;CAoClD"}
1
+ {"version":3,"file":"MoneyAccountUpgradeController.d.mts","sourceRoot":"","sources":["../src/MoneyAccountUpgradeController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qDAAqD,EACrD,oDAAoD,EACrD,6CAA6C;AAC9C,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,qCAAqC,EACrC,kCAAkC,EAClC,kCAAkC,EAClC,2CAA2C,EAC3C,wCAAwC,EACxC,sCAAsC,EACtC,qCAAqC,EACtC,oCAAoC;AACrC,OAAO,KAAK,EAAE,wCAAwC,EAAE,wCAAwC;AAGhG,OAAO,KAAK,EACV,+BAA+B,EAC/B,+CAA+C,EAC/C,0CAA0C,EAC1C,sBAAsB,EACvB,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAKrD,OAAO,KAAK,EAAE,uBAAuB,EAAE,sCAAsC;AAC7E,OAAO,KAAK,EACV,mDAAmD,EACnD,2CAA2C,EAC5C,qCAAqC;AACtC,OAAO,KAAK,EACV,YAAY,EACZ,yCAAyC,EACzC,gCAAgC,EACjC,iDAAiD;AAElD,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAM3C,OAAO,KAAK,EAAE,0CAA0C,EAAE,gEAA+D;AAczH,eAAO,MAAM,cAAc,kCAAkC,CAAC;AAE9D;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC;;;;;OAKG;IACH,iBAAiB,EAAE,MAAM,CAAC;IAC1B,oEAAoE;IACpE,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,MAAM,MAAM,kCAAkC,GAAG;IAC/C;;;OAG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,KACjC,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnB;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CAC7C,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,6BAA8B,SAAQ,cAAc,CAC/D,OAAO,cAAc,EACrB,kCAAkC,EAClC,sCAAsC,CACvC;;IAgCC;;;;;;;;OAQG;gBACS,EACV,SAAS,EACT,KAAK,EACL,KAAK,GACN,EAAE;QACD,SAAS,EAAE,sCAAsC,CAAC;QAClD,KAAK,CAAC,EAAE,OAAO,CAAC,kCAAkC,CAAC,CAAC;QACpD,KAAK,EAAE,kCAAkC,CAAC;KAC3C;IAuBD;;;;;;OAMG;IACH,IAAI,IAAI,IAAI;IAeZ;;;;;;;OAOG;IACH,IAAI,IAAI,IAAI;IAwMZ;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACG,cAAc,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;CA2ClD"}
@@ -9,11 +9,13 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _MoneyAccountUpgradeController_config, _MoneyAccountUpgradeController_steps;
12
+ var _MoneyAccountUpgradeController_instances, _MoneyAccountUpgradeController_config, _MoneyAccountUpgradeController_isEnabled, _MoneyAccountUpgradeController_isEligible, _MoneyAccountUpgradeController_ensureChainConfigured, _MoneyAccountUpgradeController_onBootstrapError, _MoneyAccountUpgradeController_initialized, _MoneyAccountUpgradeController_bootstrap, _MoneyAccountUpgradeController_bootstrappedConfig, _MoneyAccountUpgradeController_missingConfigReported, _MoneyAccountUpgradeController_steps, _MoneyAccountUpgradeController_isWalletReady, _MoneyAccountUpgradeController_areGatesOpen, _MoneyAccountUpgradeController_scheduleBootstrap, _MoneyAccountUpgradeController_forget, _MoneyAccountUpgradeController_reportMissingConfig, _MoneyAccountUpgradeController_applyVaultConfig;
13
13
  import { BaseController } from "@metamask/base-controller";
14
14
  import { DELEGATOR_CONTRACTS } from "@metamask/delegation-deployments";
15
+ import { KeyringTypes } from "@metamask/keyring-controller";
16
+ import { areMoneyAccountVaultConfigsEqual, getMoneyAccountVaultConfig } from "@metamask/money-account-utils";
15
17
  import { hexToNumber } from "@metamask/utils";
16
- import { MoneyAccountUpgradeStepError } from "./errors.mjs";
18
+ import { MissingMoneyAccountVaultConfigError, MoneyAccountUpgradeStepError } from "./errors.mjs";
17
19
  import { associateAddressStep } from "./steps/associate-address.mjs";
18
20
  import { buildDelegationStep } from "./steps/build-delegations.mjs";
19
21
  import { eip7702AuthorizationStep } from "./steps/eip-7702-authorization.mjs";
@@ -47,7 +49,24 @@ export function getDefaultMoneyAccountUpgradeControllerState() {
47
49
  }
48
50
  const MESSENGER_EXPOSED_METHODS = ['upgradeAccount'];
49
51
  /**
50
- * Controller that orchestrates the Money Account upgrade sequence.
52
+ * Controller that owns the Money Account upgrade sequence and its own
53
+ * bootstrap.
54
+ *
55
+ * After {@link MoneyAccountUpgradeController.init} is called, the controller watches
56
+ * `RemoteFeatureFlagController` and `KeyringController` state and bootstraps
57
+ * itself when:
58
+ *
59
+ * 1. the client's `isEnabled` hook returns `true` for the current flags,
60
+ * 2. the wallet is unlocked with an HD keyring,
61
+ * 3. the client's `isEligible` hook (if any) resolves `true`, and
62
+ * 4. the `moneyAccountVaultConfig` flag parses.
63
+ *
64
+ * The bootstrap awaits the client's `ensureChainConfigured` hook and then
65
+ * fetches CHOMP service details to get the upgrade config. We recheck points
66
+ * 1–2 when awaiting in the bootstrap so a lock or an `isEnabled` will stop the process.
67
+ *
68
+ * The bootstrap re-runs whenever the vault config changes.
69
+ * `isEnabled` going `false` disables the controller.
51
70
  */
52
71
  export class MoneyAccountUpgradeController extends BaseController {
53
72
  /**
@@ -56,8 +75,10 @@ export class MoneyAccountUpgradeController extends BaseController {
56
75
  * @param options - The options for constructing the controller.
57
76
  * @param options.messenger - The messenger to use for inter-controller communication.
58
77
  * @param options.state - The initial state, merged with the defaults.
78
+ * @param options.hooks - The client hooks for the bootstrap; see
79
+ * {@link MoneyAccountUpgradeControllerHooks}.
59
80
  */
60
- constructor({ messenger, state, }) {
81
+ constructor({ messenger, state, hooks, }) {
61
82
  super({
62
83
  messenger,
63
84
  metadata: moneyAccountUpgradeControllerMetadata,
@@ -67,55 +88,80 @@ export class MoneyAccountUpgradeController extends BaseController {
67
88
  ...state,
68
89
  },
69
90
  });
91
+ _MoneyAccountUpgradeController_instances.add(this);
70
92
  _MoneyAccountUpgradeController_config.set(this, void 0);
93
+ _MoneyAccountUpgradeController_isEnabled.set(this, void 0);
94
+ _MoneyAccountUpgradeController_isEligible.set(this, void 0);
95
+ _MoneyAccountUpgradeController_ensureChainConfigured.set(this, void 0);
96
+ _MoneyAccountUpgradeController_onBootstrapError.set(this, void 0);
97
+ _MoneyAccountUpgradeController_initialized.set(this, false);
98
+ _MoneyAccountUpgradeController_bootstrap.set(this, void 0);
99
+ _MoneyAccountUpgradeController_bootstrappedConfig.set(this, void 0);
100
+ _MoneyAccountUpgradeController_missingConfigReported.set(this, false);
71
101
  _MoneyAccountUpgradeController_steps.set(this, [
72
102
  associateAddressStep,
73
103
  eip7702AuthorizationStep,
74
104
  buildDelegationStep,
75
105
  registerIntentsStep,
76
106
  ]);
107
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_isEnabled, hooks.isEnabled, "f");
108
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_isEligible, hooks.isEligible ?? (async () => true), "f");
109
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_ensureChainConfigured, hooks.ensureChainConfigured ?? (async () => undefined), "f");
110
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_onBootstrapError, hooks.onBootstrapError ?? (() => undefined), "f");
77
111
  this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
78
112
  }
79
113
  /**
80
- * Fetches service details and validates the controller can operate on the
81
- * given chain. Resolves the Delegation Framework contract addresses for the
82
- * chain from `@metamask/delegation-deployments`.
83
- *
84
- * @param params - The parameters for initialization.
85
- * @param params.chainId - The chain to initialize for.
86
- * @param params.boringVaultAddress - The Veda boring vault contract
87
- * (vmUSD) for the given chain. Used as the withdrawal-side delegation
88
- * token. Supplied by the consumer until the CHOMP service-details API
89
- * exposes it.
114
+ * Start the controller's bootstrap: subscribe to the feature-flag and
115
+ * keyring triggers and run an initial sync. Call once, after all
116
+ * controllers and services the messenger reaches are constructed — this is
117
+ * the only method that may be called before the controller is bootstrapped,
118
+ * and it is the reason the constructor performs no messenger calls.
90
119
  */
91
- async init({ chainId, boringVaultAddress, }) {
92
- const contracts = DELEGATOR_CONTRACTS[DELEGATION_FRAMEWORK_VERSION][hexToNumber(chainId)];
93
- if (!contracts) {
94
- throw new Error(`Delegation Framework ${DELEGATION_FRAMEWORK_VERSION} is not deployed on chain ${chainId}`);
95
- }
96
- const response = await this.messenger.call('ChompApiService:getServiceDetails', [chainId]);
97
- const chain = response.chains[chainId];
98
- if (!chain) {
99
- throw new Error(`Chain ${chainId} not found in service details response`);
120
+ init() {
121
+ if (__classPrivateFieldGet(this, _MoneyAccountUpgradeController_initialized, "f")) {
122
+ return;
100
123
  }
101
- const { vedaProtocol } = chain.protocol;
102
- if (!vedaProtocol) {
103
- throw new Error(`vedaProtocol not found for chain ${chainId} in service details response`);
124
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_initialized, true, "f");
125
+ this.messenger.subscribe('RemoteFeatureFlagController:stateChanged', () => this.sync());
126
+ this.messenger.subscribe('KeyringController:stateChanged', () => this.sync());
127
+ this.sync();
128
+ }
129
+ /**
130
+ * Re-evaluate the bootstrap checks against live state and schedule a
131
+ * bootstrap run when they are open and the vault config is new. Runs on
132
+ * every feature-flag and keyring state change.
133
+ *
134
+ * If sync fails a failure is reported through `onBootstrapError` and retried
135
+ * on the next trigger.
136
+ */
137
+ sync() {
138
+ try {
139
+ const { remoteFeatureFlags } = this.messenger.call('RemoteFeatureFlagController:getState');
140
+ if (!__classPrivateFieldGet(this, _MoneyAccountUpgradeController_isEnabled, "f").call(this, remoteFeatureFlags)) {
141
+ // Disarm so a later `upgradeAccount` cannot run against a config
142
+ // armed while the feature was still enabled. Re-enabling re-runs the
143
+ // bootstrap from scratch.
144
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_config, undefined, "f");
145
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_bootstrappedConfig, undefined, "f");
146
+ return;
147
+ }
148
+ if (!__classPrivateFieldGet(this, _MoneyAccountUpgradeController_instances, "m", _MoneyAccountUpgradeController_isWalletReady).call(this)) {
149
+ return;
150
+ }
151
+ const vaultConfig = getMoneyAccountVaultConfig(remoteFeatureFlags);
152
+ if (!vaultConfig) {
153
+ __classPrivateFieldGet(this, _MoneyAccountUpgradeController_instances, "m", _MoneyAccountUpgradeController_reportMissingConfig).call(this);
154
+ return;
155
+ }
156
+ if (__classPrivateFieldGet(this, _MoneyAccountUpgradeController_bootstrappedConfig, "f") &&
157
+ areMoneyAccountVaultConfigsEqual(vaultConfig, __classPrivateFieldGet(this, _MoneyAccountUpgradeController_bootstrappedConfig, "f"))) {
158
+ return;
159
+ }
160
+ __classPrivateFieldGet(this, _MoneyAccountUpgradeController_instances, "m", _MoneyAccountUpgradeController_scheduleBootstrap).call(this, vaultConfig);
104
161
  }
105
- if (vedaProtocol.supportedTokens.length === 0) {
106
- throw new Error(`No supported tokens found for vedaProtocol on chain ${chainId}`);
162
+ catch (error) {
163
+ __classPrivateFieldGet(this, _MoneyAccountUpgradeController_onBootstrapError, "f").call(this, error);
107
164
  }
108
- __classPrivateFieldSet(this, _MoneyAccountUpgradeController_config, {
109
- chainId,
110
- delegateAddress: chain.autoDepositDelegate,
111
- musdTokenAddress: vedaProtocol.supportedTokens[0].tokenAddress,
112
- boringVaultAddress,
113
- vedaVaultAdapterAddress: vedaProtocol.adapterAddress,
114
- delegatorImplAddress: contracts.EIP7702StatelessDeleGatorImpl,
115
- erc20TransferAmountEnforcer: contracts.ERC20TransferAmountEnforcer,
116
- redeemerEnforcer: contracts.RedeemerEnforcer,
117
- valueLteEnforcer: contracts.ValueLteEnforcer,
118
- }, "f");
119
165
  }
120
166
  /**
121
167
  * Runs each step in the upgrade sequence in order. A step that reports
@@ -131,11 +177,25 @@ export class MoneyAccountUpgradeController extends BaseController {
131
177
  * active config no longer matches the recorded fingerprint, the sequence
132
178
  * re-runs.
133
179
  *
180
+ * A call that arrives while the bootstrap chain is still in flight —
181
+ * including runs scheduled while waiting — waits for it to settle rather
182
+ * than failing, so the upgrade always runs against the latest armed
183
+ * config. Scheduling a bootstrap for a changed vault config disarms the
184
+ * previous one, so it only throws when no bootstrap has armed a config:
185
+ * feature disabled, wallet locked, or the last bootstrap failed.
186
+ *
134
187
  * @param address - The Money Account address to upgrade.
135
188
  */
136
189
  async upgradeAccount(address) {
190
+ let bootstrap = __classPrivateFieldGet(this, _MoneyAccountUpgradeController_bootstrap, "f");
191
+ while (bootstrap) {
192
+ await bootstrap.catch(() => undefined);
193
+ // A newer run may have been chained on while we waited; wait for that
194
+ // one too, until the chain settles.
195
+ bootstrap = __classPrivateFieldGet(this, _MoneyAccountUpgradeController_bootstrap, "f") === bootstrap ? undefined : __classPrivateFieldGet(this, _MoneyAccountUpgradeController_bootstrap, "f");
196
+ }
137
197
  if (!__classPrivateFieldGet(this, _MoneyAccountUpgradeController_config, "f")) {
138
- throw new Error('MoneyAccountUpgradeController must be initialized via init() before upgradeAccount() can be called');
198
+ throw new Error('MoneyAccountUpgradeController is not bootstrapped: upgradeAccount() requires the feature flag on, the wallet unlocked, and a successful bootstrap');
139
199
  }
140
200
  const config = __classPrivateFieldGet(this, _MoneyAccountUpgradeController_config, "f");
141
201
  const accountKey = address.toLowerCase();
@@ -164,7 +224,101 @@ export class MoneyAccountUpgradeController extends BaseController {
164
224
  });
165
225
  }
166
226
  }
167
- _MoneyAccountUpgradeController_config = new WeakMap(), _MoneyAccountUpgradeController_steps = new WeakMap();
227
+ _MoneyAccountUpgradeController_config = new WeakMap(), _MoneyAccountUpgradeController_isEnabled = new WeakMap(), _MoneyAccountUpgradeController_isEligible = new WeakMap(), _MoneyAccountUpgradeController_ensureChainConfigured = new WeakMap(), _MoneyAccountUpgradeController_onBootstrapError = new WeakMap(), _MoneyAccountUpgradeController_initialized = new WeakMap(), _MoneyAccountUpgradeController_bootstrap = new WeakMap(), _MoneyAccountUpgradeController_bootstrappedConfig = new WeakMap(), _MoneyAccountUpgradeController_missingConfigReported = new WeakMap(), _MoneyAccountUpgradeController_steps = new WeakMap(), _MoneyAccountUpgradeController_instances = new WeakSet(), _MoneyAccountUpgradeController_isWalletReady = function _MoneyAccountUpgradeController_isWalletReady() {
228
+ const { isUnlocked, keyrings } = this.messenger.call('KeyringController:getState');
229
+ return (isUnlocked && keyrings.some((keyring) => keyring.type === KeyringTypes.hd));
230
+ }, _MoneyAccountUpgradeController_areGatesOpen = function _MoneyAccountUpgradeController_areGatesOpen() {
231
+ const { remoteFeatureFlags } = this.messenger.call('RemoteFeatureFlagController:getState');
232
+ return __classPrivateFieldGet(this, _MoneyAccountUpgradeController_isEnabled, "f").call(this, remoteFeatureFlags) && __classPrivateFieldGet(this, _MoneyAccountUpgradeController_instances, "m", _MoneyAccountUpgradeController_isWalletReady).call(this);
233
+ }, _MoneyAccountUpgradeController_scheduleBootstrap = function _MoneyAccountUpgradeController_scheduleBootstrap(vaultConfig) {
234
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_bootstrappedConfig, vaultConfig, "f");
235
+ // Scheduling means the served vault config no longer matches whatever is
236
+ // armed, so disarm now: until this run succeeds, `upgradeAccount` must
237
+ // wait for it (or refuse if it fails) rather than sign delegations
238
+ // against the superseded vault.
239
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_config, undefined, "f");
240
+ const run = async () => {
241
+ // The gates were checked when this run was scheduled, but it may start
242
+ // much later, chained behind an in-flight bootstrap. Eligibility comes
243
+ // after the gates so a disabled client also skips the (possibly
244
+ // external) eligibility lookup.
245
+ if (!__classPrivateFieldGet(this, _MoneyAccountUpgradeController_instances, "m", _MoneyAccountUpgradeController_areGatesOpen).call(this) || !(await __classPrivateFieldGet(this, _MoneyAccountUpgradeController_isEligible, "f").call(this))) {
246
+ __classPrivateFieldGet(this, _MoneyAccountUpgradeController_instances, "m", _MoneyAccountUpgradeController_forget).call(this, vaultConfig);
247
+ return;
248
+ }
249
+ await __classPrivateFieldGet(this, _MoneyAccountUpgradeController_ensureChainConfigured, "f").call(this, vaultConfig);
250
+ // Configuring the chain can suspend for a while, so re-check the gates
251
+ // before the external CHOMP call.
252
+ if (!__classPrivateFieldGet(this, _MoneyAccountUpgradeController_instances, "m", _MoneyAccountUpgradeController_areGatesOpen).call(this)) {
253
+ __classPrivateFieldGet(this, _MoneyAccountUpgradeController_instances, "m", _MoneyAccountUpgradeController_forget).call(this, vaultConfig);
254
+ return;
255
+ }
256
+ await __classPrivateFieldGet(this, _MoneyAccountUpgradeController_instances, "m", _MoneyAccountUpgradeController_applyVaultConfig).call(this, vaultConfig);
257
+ };
258
+ const bootstrap = __classPrivateFieldGet(this, _MoneyAccountUpgradeController_bootstrap, "f")
259
+ ? __classPrivateFieldGet(this, _MoneyAccountUpgradeController_bootstrap, "f").catch(() => undefined).then(run)
260
+ : run();
261
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_bootstrap, bootstrap, "f");
262
+ bootstrap.catch((error) => {
263
+ __classPrivateFieldGet(this, _MoneyAccountUpgradeController_onBootstrapError, "f").call(this, error);
264
+ __classPrivateFieldGet(this, _MoneyAccountUpgradeController_instances, "m", _MoneyAccountUpgradeController_forget).call(this, vaultConfig);
265
+ });
266
+ }, _MoneyAccountUpgradeController_forget = function _MoneyAccountUpgradeController_forget(vaultConfig) {
267
+ if (__classPrivateFieldGet(this, _MoneyAccountUpgradeController_bootstrappedConfig, "f") === vaultConfig) {
268
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_bootstrappedConfig, undefined, "f");
269
+ }
270
+ }, _MoneyAccountUpgradeController_reportMissingConfig = function _MoneyAccountUpgradeController_reportMissingConfig() {
271
+ if (!__classPrivateFieldGet(this, _MoneyAccountUpgradeController_missingConfigReported, "f")) {
272
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_missingConfigReported, true, "f");
273
+ __classPrivateFieldGet(this, _MoneyAccountUpgradeController_onBootstrapError, "f").call(this, new MissingMoneyAccountVaultConfigError());
274
+ }
275
+ }, _MoneyAccountUpgradeController_applyVaultConfig =
276
+ /**
277
+ * Fetches service details and validates the controller can operate on the
278
+ * vault's chain, arming the upgrade config `upgradeAccount` runs against.
279
+ * Resolves the Delegation Framework contract addresses for the chain from
280
+ * `@metamask/delegation-deployments`.
281
+ *
282
+ * @param vaultConfig - The vault config to arm; its `boringVault` is the
283
+ * withdrawal-side delegation token (vmUSD), supplied via the flag until
284
+ * the CHOMP service-details API exposes it.
285
+ */
286
+ async function _MoneyAccountUpgradeController_applyVaultConfig(vaultConfig) {
287
+ const { chainId, boringVault: boringVaultAddress } = vaultConfig;
288
+ const contracts = DELEGATOR_CONTRACTS[DELEGATION_FRAMEWORK_VERSION][hexToNumber(chainId)];
289
+ if (!contracts) {
290
+ throw new Error(`Delegation Framework ${DELEGATION_FRAMEWORK_VERSION} is not deployed on chain ${chainId}`);
291
+ }
292
+ const response = await this.messenger.call('ChompApiService:getServiceDetails', [chainId]);
293
+ const chain = response.chains[chainId];
294
+ if (!chain) {
295
+ throw new Error(`Chain ${chainId} not found in service details response`);
296
+ }
297
+ const { vedaProtocol } = chain.protocol;
298
+ if (!vedaProtocol) {
299
+ throw new Error(`vedaProtocol not found for chain ${chainId} in service details response`);
300
+ }
301
+ if (vedaProtocol.supportedTokens.length === 0) {
302
+ throw new Error(`No supported tokens found for vedaProtocol on chain ${chainId}`);
303
+ }
304
+ // A disarm (isEnabled flipping off) or a newer scheduled config during
305
+ // the CHOMP call supersedes this run: arming now would resurrect a config
306
+ // the controller just dropped, or briefly shadow the newer one.
307
+ if (__classPrivateFieldGet(this, _MoneyAccountUpgradeController_bootstrappedConfig, "f") !== vaultConfig) {
308
+ return;
309
+ }
310
+ __classPrivateFieldSet(this, _MoneyAccountUpgradeController_config, {
311
+ chainId,
312
+ delegateAddress: chain.autoDepositDelegate,
313
+ musdTokenAddress: vedaProtocol.supportedTokens[0].tokenAddress,
314
+ boringVaultAddress,
315
+ vedaVaultAdapterAddress: vedaProtocol.adapterAddress,
316
+ delegatorImplAddress: contracts.EIP7702StatelessDeleGatorImpl,
317
+ erc20TransferAmountEnforcer: contracts.ERC20TransferAmountEnforcer,
318
+ redeemerEnforcer: contracts.RedeemerEnforcer,
319
+ valueLteEnforcer: contracts.ValueLteEnforcer,
320
+ }, "f");
321
+ };
168
322
  /**
169
323
  * Derives a stable fingerprint of the config fields that define what
170
324
  * "upgraded" means for an account. A recorded upgrade is only trusted while