@metamask-previews/assets-controllers 64.0.0-preview-a5a6e357 → 64.0.0-preview-ef2405f
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.
- package/CHANGELOG.md +4 -0
- package/dist/MultichainAssetsController/MultichainAssetsController.cjs +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.cjs.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.mjs +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.mjs.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.cjs +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.cjs.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.mjs +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.mjs.map +1 -1
- package/dist/TokenBalancesController.cjs +2 -7
- package/dist/TokenBalancesController.cjs.map +1 -1
- package/dist/TokenBalancesController.d.cts.map +1 -1
- package/dist/TokenBalancesController.d.mts.map +1 -1
- package/dist/TokenBalancesController.mjs +2 -7
- package/dist/TokenBalancesController.mjs.map +1 -1
- package/dist/TokenDetectionController.cjs +6 -0
- package/dist/TokenDetectionController.cjs.map +1 -1
- package/dist/TokenDetectionController.d.cts +2 -1
- package/dist/TokenDetectionController.d.cts.map +1 -1
- package/dist/TokenDetectionController.d.mts +2 -1
- package/dist/TokenDetectionController.d.mts.map +1 -1
- package/dist/TokenDetectionController.mjs +6 -0
- package/dist/TokenDetectionController.mjs.map +1 -1
- package/dist/TokensController.cjs +2 -8
- package/dist/TokensController.cjs.map +1 -1
- package/dist/TokensController.d.cts.map +1 -1
- package/dist/TokensController.d.mts.map +1 -1
- package/dist/TokensController.mjs +2 -8
- package/dist/TokensController.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
7
7
|
|
8
8
|
## [Unreleased]
|
9
9
|
|
10
|
+
### Added
|
11
|
+
|
12
|
+
- **BREAKING:** Add event listener for `TransactionController:transactionConfirmed` on `TokenDetectionController` to trigger token detection ([#5859](https://github.com/MetaMask/core/pull/5859))
|
13
|
+
|
10
14
|
## [64.0.0]
|
11
15
|
|
12
16
|
### Added
|
@@ -68,7 +68,7 @@ class MultichainAssetsController extends base_controller_1.BaseController {
|
|
68
68
|
_MultichainAssetsController_controllerOperationMutex.set(this, new async_mutex_1.Mutex());
|
69
69
|
__classPrivateFieldSet(this, _MultichainAssetsController_snaps, {}, "f");
|
70
70
|
this.messagingSystem.subscribe('AccountsController:accountAdded', async (account) => await __classPrivateFieldGet(this, _MultichainAssetsController_instances, "m", _MultichainAssetsController_handleOnAccountAddedEvent).call(this, account));
|
71
|
-
this.messagingSystem.subscribe('AccountsController:accountRemoved', async (
|
71
|
+
this.messagingSystem.subscribe('AccountsController:accountRemoved', async ({ id }) => await __classPrivateFieldGet(this, _MultichainAssetsController_instances, "m", _MultichainAssetsController_handleOnAccountRemovedEvent).call(this, id));
|
72
72
|
this.messagingSystem.subscribe('AccountsController:accountAssetListUpdated', async (event) => await __classPrivateFieldGet(this, _MultichainAssetsController_instances, "m", _MultichainAssetsController_handleAccountAssetListUpdatedEvent).call(this, event));
|
73
73
|
__classPrivateFieldGet(this, _MultichainAssetsController_instances, "m", _MultichainAssetsController_registerMessageHandlers).call(this);
|
74
74
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"MultichainAssetsController.cjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/MultichainAssetsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAMA,+DAKmC;AACnC,uDAAyD;AAOzD,uEAA8D;AAW9D,uDAAoD;AACpD,2CAIyB;AAGzB,6CAAoC;AAEpC,uCAA4C;AAE5C,MAAM,cAAc,GAAG,4BAA4B,CAAC;AAqBpD;;;;;;;GAOG;AACH,SAAgB,yCAAyC;IACvD,OAAO,EAAE,cAAc,EAAE,EAAE,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,QAA2C;IAE3C,MAAM,WAAW,GAAG,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;IAE1C,IAAI;QACF,OAAO,MAAM,QAAQ,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;KACxC;YAAS;QACR,WAAW,EAAE,CAAC;KACf;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountAssetListUpdatedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerListMultichainAccountsAction,\n} from '@metamask/accounts-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n AccountAssetListUpdatedEventPayload,\n CaipAssetType,\n CaipAssetTypeOrId,\n} from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type {\n GetPermissions,\n PermissionConstraint,\n SubjectPermissions,\n} from '@metamask/permission-controller';\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n} from '@metamask/snaps-controllers';\nimport type { FungibleAssetMetadata, Snap, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport {\n isCaipAssetType,\n parseCaipAssetType,\n type CaipChainId,\n} from '@metamask/utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { MutexInterface } from 'async-mutex';\nimport { Mutex } from 'async-mutex';\n\nimport { getChainIdsCaveat } from './utils';\n\nconst controllerName = 'MultichainAssetsController';\n\nexport type MultichainAssetsControllerState = {\n assetsMetadata: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n accountsAssets: { [account: string]: CaipAssetType[] };\n};\n\n// Represents the response of the asset snap's onAssetLookup handler\nexport type AssetMetadataResponse = {\n assets: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n};\n\nexport type MultichainAssetsControllerAccountAssetListUpdatedEvent = {\n type: `${typeof controllerName}:accountAssetListUpdated`;\n payload: AccountsControllerAccountAssetListUpdatedEvent['payload'];\n};\n\n/**\n * Constructs the default {@link MultichainAssetsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link MultichainAssetsController} state.\n */\nexport function getDefaultMultichainAssetsControllerState(): MultichainAssetsControllerState {\n return { accountsAssets: {}, assetsMetadata: {} };\n}\n\nexport type MultichainAssetsControllerGetAssetMetadataAction = {\n type: `${typeof controllerName}:getAssetMetadata`;\n handler: MultichainAssetsController['getAssetMetadata'];\n};\n\n/**\n * Returns the state of the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n MultichainAssetsControllerState\n>;\n\n/**\n * Event emitted when the state of the {@link MultichainAssetsController} changes.\n */\nexport type MultichainAssetsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainAssetsControllerState\n >;\n\n/**\n * Actions exposed by the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerActions =\n | MultichainAssetsControllerGetStateAction\n | MultichainAssetsControllerGetAssetMetadataAction;\n\n/**\n * Events emitted by {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerEvents =\n | MultichainAssetsControllerStateChangeEvent\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n\n/**\n * A function executed within a mutually exclusive lock, with\n * a mutex releaser in its option bag.\n *\n * @param releaseLock - A function to release the lock.\n */\ntype MutuallyExclusiveCallback<Result> = ({\n releaseLock,\n}: {\n releaseLock: MutexInterface.Releaser;\n}) => Promise<Result>;\n\n/**\n * Actions that this controller is allowed to call.\n */\ntype AllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | AccountsControllerListMultichainAccountsAction;\n\n/**\n * Events that this controller is allowed to subscribe.\n */\ntype AllowedEvents =\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | AccountsControllerAccountAssetListUpdatedEvent;\n\n/**\n * Messenger type for the MultichainAssetsController.\n */\nexport type MultichainAssetsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n MultichainAssetsControllerActions | AllowedActions,\n MultichainAssetsControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * {@link MultichainAssetsController}'s metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst assetsControllerMetadata = {\n assetsMetadata: {\n persist: true,\n anonymous: false,\n },\n accountsAssets: {\n persist: true,\n anonymous: false,\n },\n};\n\n// TODO: make this controller extends StaticIntervalPollingController and update all assetsMetadata once a day.\n\nexport class MultichainAssetsController extends BaseController<\n typeof controllerName,\n MultichainAssetsControllerState,\n MultichainAssetsControllerMessenger\n> {\n // Mapping of CAIP-2 Chain ID to Asset Snaps.\n #snaps: Record<CaipChainId, Snap[]>;\n\n readonly #controllerOperationMutex = new Mutex();\n\n constructor({\n messenger,\n state = {},\n }: {\n messenger: MultichainAssetsControllerMessenger;\n state?: Partial<MultichainAssetsControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: assetsControllerMetadata,\n state: {\n ...getDefaultMultichainAssetsControllerState(),\n ...state,\n },\n });\n\n this.#snaps = {};\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n async (account) => await this.#handleOnAccountAddedEvent(account),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountRemoved',\n async (account) => await this.#handleOnAccountRemovedEvent(account),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountAssetListUpdated',\n async (event) => await this.#handleAccountAssetListUpdatedEvent(event),\n );\n\n this.#registerMessageHandlers();\n }\n\n async #handleAccountAssetListUpdatedEvent(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n return this.#withControllerLock(async () =>\n this.#handleAccountAssetListUpdated(event),\n );\n }\n\n async #handleOnAccountAddedEvent(account: InternalAccount) {\n return this.#withControllerLock(async () =>\n this.#handleOnAccountAdded(account),\n );\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n 'MultichainAssetsController:getAssetMetadata',\n this.getAssetMetadata.bind(this),\n );\n }\n\n /**\n * Returns the metadata for the given asset\n *\n * @param asset - The asset to get metadata for\n * @returns The metadata for the asset or undefined if not found.\n */\n getAssetMetadata(asset: CaipAssetType): FungibleAssetMetadata | undefined {\n return this.state.assetsMetadata[asset];\n }\n\n /**\n * Function to update the assets list for an account\n *\n * @param event - The list of assets to update\n */\n async #handleAccountAssetListUpdated(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n this.#assertControllerMutexIsLocked();\n\n const assetsForMetadataRefresh = new Set<CaipAssetType>([]);\n const accountsAndAssetsToUpdate: AccountAssetListUpdatedEventPayload['assets'] =\n {};\n for (const [accountId, { added, removed }] of Object.entries(\n event.assets,\n )) {\n if (added.length > 0 || removed.length > 0) {\n const existing = this.state.accountsAssets[accountId] || [];\n\n // In case accountsAndAssetsToUpdate event is fired with \"added\" assets that already exist, we don't want to add them again\n const filteredToBeAddedAssets = added.filter(\n (asset) => !existing.includes(asset) && isCaipAssetType(asset),\n );\n\n // In case accountsAndAssetsToUpdate event is fired with \"removed\" assets that don't exist, we don't want to remove them\n const filteredToBeRemovedAssets = removed.filter(\n (asset) => existing.includes(asset) && isCaipAssetType(asset),\n );\n\n if (\n filteredToBeAddedAssets.length > 0 ||\n filteredToBeRemovedAssets.length > 0\n ) {\n accountsAndAssetsToUpdate[accountId] = {\n added: filteredToBeAddedAssets,\n removed: filteredToBeRemovedAssets,\n };\n }\n\n for (const asset of existing) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeAddedAssets) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeRemovedAssets) {\n assetsForMetadataRefresh.delete(asset);\n }\n }\n }\n\n this.update((state) => {\n for (const [accountId, { added, removed }] of Object.entries(\n accountsAndAssetsToUpdate,\n )) {\n const assets = new Set([\n ...(state.accountsAssets[accountId] || []),\n ...added,\n ]);\n for (const asset of removed) {\n assets.delete(asset);\n }\n\n state.accountsAssets[accountId] = Array.from(assets);\n }\n });\n\n // Trigger fetching metadata for new assets\n await this.#refreshAssetsMetadata(Array.from(assetsForMetadataRefresh));\n\n this.messagingSystem.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: accountsAndAssetsToUpdate,\n });\n }\n\n /**\n * Checks for non-EVM accounts.\n *\n * @param account - The new account to be checked.\n * @returns True if the account is a non-EVM account, false otherwise.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) &&\n // Non-EVM accounts are backed by a Snap for now\n account.metadata.snap !== undefined\n );\n }\n\n /**\n * Handles changes when a new account has been added.\n *\n * @param account - The new account being added.\n */\n async #handleOnAccountAdded(account: InternalAccount): Promise<void> {\n if (!this.#isNonEvmAccount(account)) {\n // Nothing to do here for EVM accounts\n return;\n }\n this.#assertControllerMutexIsLocked();\n\n // Get assets list\n if (account.metadata.snap) {\n const assets = await this.#getAssetsList(\n account.id,\n account.metadata.snap.id,\n );\n await this.#refreshAssetsMetadata(assets);\n this.update((state) => {\n state.accountsAssets[account.id] = assets;\n });\n this.messagingSystem.publish(\n `${controllerName}:accountAssetListUpdated`,\n {\n assets: {\n [account.id]: {\n added: assets,\n removed: [],\n },\n },\n },\n );\n }\n }\n\n /**\n * Handles changes when a new account has been removed.\n *\n * @param accountId - The new account id being removed.\n */\n async #handleOnAccountRemovedEvent(accountId: string): Promise<void> {\n // Check if accountId is in accountsAssets and if it is, remove it\n if (this.state.accountsAssets[accountId]) {\n this.update((state) => {\n // TODO: We are not deleting the assetsMetadata because we will soon make this controller extends StaticIntervalPollingController\n // and update all assetsMetadata once a day.\n delete state.accountsAssets[accountId];\n });\n }\n }\n\n /**\n * Refreshes the assets snaps and metadata for the given list of assets\n *\n * @param assets - The assets to refresh\n */\n async #refreshAssetsMetadata(assets: CaipAssetType[]) {\n this.#assertControllerMutexIsLocked();\n\n const assetsWithoutMetadata: CaipAssetType[] = assets.filter(\n (asset) => !this.state.assetsMetadata[asset],\n );\n\n // Call the snap to get the metadata\n if (assetsWithoutMetadata.length > 0) {\n // Check if for every asset in assetsWithoutMetadata there is a snap in snaps by chainId else call getAssetSnaps\n if (\n !assetsWithoutMetadata.every((asset: CaipAssetType) => {\n const { chainId } = parseCaipAssetType(asset);\n return Boolean(this.#getAssetSnapFor(chainId));\n })\n ) {\n this.#snaps = this.#getAssetSnaps();\n }\n await this.#updateAssetsMetadata(assetsWithoutMetadata);\n }\n }\n\n /**\n * Updates the assets metadata for the given list of assets\n *\n * @param assets - The assets to update\n */\n async #updateAssetsMetadata(assets: CaipAssetType[]) {\n // Creates a mapping of scope to their respective assets list.\n const assetsByScope: Record<CaipChainId, CaipAssetType[]> = {};\n for (const asset of assets) {\n const { chainId } = parseCaipAssetType(asset);\n if (!assetsByScope[chainId]) {\n assetsByScope[chainId] = [];\n }\n assetsByScope[chainId].push(asset);\n }\n\n let newMetadata: Record<CaipAssetType, FungibleAssetMetadata> = {};\n for (const chainId of Object.keys(assetsByScope) as CaipChainId[]) {\n const assetsForChain = assetsByScope[chainId];\n // Now fetch metadata from the associated asset Snaps:\n const snap = this.#getAssetSnapFor(chainId);\n if (snap) {\n const metadata = await this.#getAssetsMetadataFrom(\n assetsForChain,\n snap.id,\n );\n newMetadata = {\n ...newMetadata,\n ...(metadata?.assets ?? {}),\n };\n }\n }\n this.update((state) => {\n state.assetsMetadata = {\n ...this.state.assetsMetadata,\n ...newMetadata,\n };\n });\n }\n\n /**\n * Creates a mapping of CAIP-2 Chain ID to Asset Snaps.\n *\n * @returns A mapping of CAIP-2 Chain ID to Asset Snaps.\n */\n #getAssetSnaps(): Record<CaipChainId, Snap[]> {\n const snaps: Record<CaipChainId, Snap[]> = {};\n const allSnaps = this.#getAllSnaps();\n const allPermissions = allSnaps.map((snap) =>\n this.#getSnapsPermissions(snap.id),\n );\n\n for (const [index, permission] of allPermissions.entries()) {\n let scopes;\n for (const singlePermissionConstraint of Object.values(permission)) {\n scopes = getChainIdsCaveat(singlePermissionConstraint);\n if (!scopes) {\n continue;\n }\n for (const scope of scopes as CaipChainId[]) {\n if (!snaps[scope]) {\n snaps[scope] = [];\n }\n snaps[scope].push(allSnaps[index]);\n }\n }\n }\n return snaps;\n }\n\n /**\n * Returns the first asset snap for the given scope\n *\n * @param scope - The scope to get the asset snap for\n * @returns The asset snap for the given scope\n */\n #getAssetSnapFor(scope: CaipChainId): Snap | undefined {\n const allSnaps = this.#snaps[scope];\n // Pick only the first one, we ignore the other Snaps if there are multiple candidates for now.\n return allSnaps?.[0]; // Will be undefined if there's no Snaps candidate for this scope.\n }\n\n /**\n * Returns all the asset snaps\n *\n * @returns All the asset snaps\n */\n #getAllSnaps(): Snap[] {\n // TODO: Use dedicated SnapController's action once available for this:\n return this.messagingSystem\n .call('SnapController:getAll')\n .filter((snap) => snap.enabled && !snap.blocked);\n }\n\n /**\n * Returns the permissions for the given origin\n *\n * @param origin - The origin to get the permissions for\n * @returns The permissions for the given origin\n */\n #getSnapsPermissions(\n origin: string,\n ): SubjectPermissions<PermissionConstraint> {\n return this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n ) as SubjectPermissions<PermissionConstraint>;\n }\n\n /**\n * Returns the metadata for the given assets\n *\n * @param assets - The assets to get metadata for\n * @param snapId - The snap ID to get metadata from\n * @returns The metadata for the assets\n */\n async #getAssetsMetadataFrom(\n assets: CaipAssetType[],\n snapId: string,\n ): Promise<AssetMetadataResponse | undefined> {\n try {\n return (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnAssetsLookup,\n request: {\n jsonrpc: '2.0',\n method: 'onAssetLookup',\n params: {\n assets,\n },\n },\n })) as Promise<AssetMetadataResponse>;\n } catch (error) {\n // Ignore\n console.error(error);\n return undefined;\n }\n }\n\n /**\n * Get assets list for an account\n *\n * @param accountId - AccountId to get assets for\n * @param snapId - Snap ID for the account\n * @returns list of assets\n */\n async #getAssetsList(\n accountId: string,\n snapId: string,\n ): Promise<CaipAssetTypeOrId[]> {\n return await this.#getClient(snapId).listAccountAssets(accountId);\n }\n\n /**\n * Gets a `KeyringClient` for a Snap.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getClient(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) =>\n (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n })) as Promise<Json>,\n });\n }\n\n /**\n * Assert that the controller mutex is locked.\n *\n * @throws If the controller mutex is not locked.\n */\n #assertControllerMutexIsLocked() {\n if (!this.#controllerOperationMutex.isLocked()) {\n throw new Error(\n 'MultichainAssetsControllerError - Attempt to update state',\n );\n }\n }\n\n /**\n * Lock the controller mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * This wrapper ensures that each mutable operation that interacts with the\n * controller and that changes its state is executed in a mutually exclusive way,\n * preventing unsafe concurrent access that could lead to unpredictable behavior.\n *\n * @param callback - The function to execute while the controller mutex is locked.\n * @returns The result of the function.\n */\n async #withControllerLock<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return withLock(this.#controllerOperationMutex, callback);\n }\n}\n\n/**\n * Lock the given mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * @param mutex - The mutex to lock.\n * @param callback - The function to execute while the mutex is locked.\n * @returns The result of the function.\n */\nasync function withLock<Result>(\n mutex: Mutex,\n callback: MutuallyExclusiveCallback<Result>,\n): Promise<Result> {\n const releaseLock = await mutex.acquire();\n\n try {\n return await callback({ releaseLock });\n } finally {\n releaseLock();\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"MultichainAssetsController.cjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/MultichainAssetsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAMA,+DAKmC;AACnC,uDAAyD;AAOzD,uEAA8D;AAW9D,uDAAoD;AACpD,2CAIyB;AAGzB,6CAAoC;AAEpC,uCAA4C;AAE5C,MAAM,cAAc,GAAG,4BAA4B,CAAC;AAqBpD;;;;;;;GAOG;AACH,SAAgB,yCAAyC;IACvD,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC;AACpD,CAAC;AAFD,8FAEC;AA8ED;;;;;;GAMG;AACH,MAAM,wBAAwB,GAAG;IAC/B,cAAc,EAAE;QACd,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,cAAc,EAAE;QACd,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AAEF,+GAA+G;AAE/G,MAAa,0BAA2B,SAAQ,gCAI/C;IAMC,YAAY,EACV,SAAS,EACT,KAAK,GAAG,EAAE,GAIX;QACC,KAAK,CAAC;YACJ,SAAS;YACT,IAAI,EAAE,cAAc;YACpB,QAAQ,EAAE,wBAAwB;YAClC,KAAK,EAAE;gBACL,GAAG,yCAAyC,EAAE;gBAC9C,GAAG,KAAK;aACT;SACF,CAAC,CAAC;;QApBL,6CAA6C;QAC7C,oDAAoC;QAE3B,+DAA4B,IAAI,mBAAK,EAAE,EAAC;QAmB/C,uBAAA,IAAI,qCAAU,EAAE,MAAA,CAAC;QAEjB,IAAI,CAAC,eAAe,CAAC,SAAS,CAC5B,iCAAiC,EACjC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,MAAM,uBAAA,IAAI,oGAA2B,MAA/B,IAAI,EAA4B,OAAO,CAAC,CAClE,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,SAAS,CAC5B,mCAAmC,EACnC,KAAK,EAAE,EAAE,E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;KACvB,CAAC,CAAC;AACL,CAAC;IAQC,IAAI,CAAC,uBAAA,IAAI,4DAA0B,CAAC,QAAQ,EAAE,EAAE;QAC9C,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;KACH;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,KAAK,yDACH,QAA2C;IAE3C,OAAO,QAAQ,CAAC,uBAAA,IAAI,4DAA0B,EAAE,QAAQ,CAAC,CAAC;AAC5D,CAAC;AAGH;;;;;;;;GAQG;AACH,KAAK,UAAU,QAAQ,CACrB,KAAY,EACZ,QAA2C;IAE3C,MAAM,WAAW,GAAG,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;IAE1C,IAAI;QACF,OAAO,MAAM,QAAQ,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;KACxC;YAAS;QACR,WAAW,EAAE,CAAC;KACf;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountAssetListUpdatedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerListMultichainAccountsAction,\n} from '@metamask/accounts-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n AccountAssetListUpdatedEventPayload,\n CaipAssetType,\n CaipAssetTypeOrId,\n} from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type {\n GetPermissions,\n PermissionConstraint,\n SubjectPermissions,\n} from '@metamask/permission-controller';\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n} from '@metamask/snaps-controllers';\nimport type { FungibleAssetMetadata, Snap, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport {\n isCaipAssetType,\n parseCaipAssetType,\n type CaipChainId,\n} from '@metamask/utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { MutexInterface } from 'async-mutex';\nimport { Mutex } from 'async-mutex';\n\nimport { getChainIdsCaveat } from './utils';\n\nconst controllerName = 'MultichainAssetsController';\n\nexport type MultichainAssetsControllerState = {\n assetsMetadata: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n accountsAssets: { [account: string]: CaipAssetType[] };\n};\n\n// Represents the response of the asset snap's onAssetLookup handler\nexport type AssetMetadataResponse = {\n assets: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n};\n\nexport type MultichainAssetsControllerAccountAssetListUpdatedEvent = {\n type: `${typeof controllerName}:accountAssetListUpdated`;\n payload: AccountsControllerAccountAssetListUpdatedEvent['payload'];\n};\n\n/**\n * Constructs the default {@link MultichainAssetsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link MultichainAssetsController} state.\n */\nexport function getDefaultMultichainAssetsControllerState(): MultichainAssetsControllerState {\n return { accountsAssets: {}, assetsMetadata: {} };\n}\n\nexport type MultichainAssetsControllerGetAssetMetadataAction = {\n type: `${typeof controllerName}:getAssetMetadata`;\n handler: MultichainAssetsController['getAssetMetadata'];\n};\n\n/**\n * Returns the state of the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n MultichainAssetsControllerState\n>;\n\n/**\n * Event emitted when the state of the {@link MultichainAssetsController} changes.\n */\nexport type MultichainAssetsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainAssetsControllerState\n >;\n\n/**\n * Actions exposed by the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerActions =\n | MultichainAssetsControllerGetStateAction\n | MultichainAssetsControllerGetAssetMetadataAction;\n\n/**\n * Events emitted by {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerEvents =\n | MultichainAssetsControllerStateChangeEvent\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n\n/**\n * A function executed within a mutually exclusive lock, with\n * a mutex releaser in its option bag.\n *\n * @param releaseLock - A function to release the lock.\n */\ntype MutuallyExclusiveCallback<Result> = ({\n releaseLock,\n}: {\n releaseLock: MutexInterface.Releaser;\n}) => Promise<Result>;\n\n/**\n * Actions that this controller is allowed to call.\n */\ntype AllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | AccountsControllerListMultichainAccountsAction;\n\n/**\n * Events that this controller is allowed to subscribe.\n */\ntype AllowedEvents =\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | AccountsControllerAccountAssetListUpdatedEvent;\n\n/**\n * Messenger type for the MultichainAssetsController.\n */\nexport type MultichainAssetsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n MultichainAssetsControllerActions | AllowedActions,\n MultichainAssetsControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * {@link MultichainAssetsController}'s metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst assetsControllerMetadata = {\n assetsMetadata: {\n persist: true,\n anonymous: false,\n },\n accountsAssets: {\n persist: true,\n anonymous: false,\n },\n};\n\n// TODO: make this controller extends StaticIntervalPollingController and update all assetsMetadata once a day.\n\nexport class MultichainAssetsController extends BaseController<\n typeof controllerName,\n MultichainAssetsControllerState,\n MultichainAssetsControllerMessenger\n> {\n // Mapping of CAIP-2 Chain ID to Asset Snaps.\n #snaps: Record<CaipChainId, Snap[]>;\n\n readonly #controllerOperationMutex = new Mutex();\n\n constructor({\n messenger,\n state = {},\n }: {\n messenger: MultichainAssetsControllerMessenger;\n state?: Partial<MultichainAssetsControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: assetsControllerMetadata,\n state: {\n ...getDefaultMultichainAssetsControllerState(),\n ...state,\n },\n });\n\n this.#snaps = {};\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n async (account) => await this.#handleOnAccountAddedEvent(account),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountRemoved',\n async ({ id }) => await this.#handleOnAccountRemovedEvent(id),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountAssetListUpdated',\n async (event) => await this.#handleAccountAssetListUpdatedEvent(event),\n );\n\n this.#registerMessageHandlers();\n }\n\n async #handleAccountAssetListUpdatedEvent(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n return this.#withControllerLock(async () =>\n this.#handleAccountAssetListUpdated(event),\n );\n }\n\n async #handleOnAccountAddedEvent(account: InternalAccount) {\n return this.#withControllerLock(async () =>\n this.#handleOnAccountAdded(account),\n );\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n 'MultichainAssetsController:getAssetMetadata',\n this.getAssetMetadata.bind(this),\n );\n }\n\n /**\n * Returns the metadata for the given asset\n *\n * @param asset - The asset to get metadata for\n * @returns The metadata for the asset or undefined if not found.\n */\n getAssetMetadata(asset: CaipAssetType): FungibleAssetMetadata | undefined {\n return this.state.assetsMetadata[asset];\n }\n\n /**\n * Function to update the assets list for an account\n *\n * @param event - The list of assets to update\n */\n async #handleAccountAssetListUpdated(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n this.#assertControllerMutexIsLocked();\n\n const assetsForMetadataRefresh = new Set<CaipAssetType>([]);\n const accountsAndAssetsToUpdate: AccountAssetListUpdatedEventPayload['assets'] =\n {};\n for (const [accountId, { added, removed }] of Object.entries(\n event.assets,\n )) {\n if (added.length > 0 || removed.length > 0) {\n const existing = this.state.accountsAssets[accountId] || [];\n\n // In case accountsAndAssetsToUpdate event is fired with \"added\" assets that already exist, we don't want to add them again\n const filteredToBeAddedAssets = added.filter(\n (asset) => !existing.includes(asset) && isCaipAssetType(asset),\n );\n\n // In case accountsAndAssetsToUpdate event is fired with \"removed\" assets that don't exist, we don't want to remove them\n const filteredToBeRemovedAssets = removed.filter(\n (asset) => existing.includes(asset) && isCaipAssetType(asset),\n );\n\n if (\n filteredToBeAddedAssets.length > 0 ||\n filteredToBeRemovedAssets.length > 0\n ) {\n accountsAndAssetsToUpdate[accountId] = {\n added: filteredToBeAddedAssets,\n removed: filteredToBeRemovedAssets,\n };\n }\n\n for (const asset of existing) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeAddedAssets) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeRemovedAssets) {\n assetsForMetadataRefresh.delete(asset);\n }\n }\n }\n\n this.update((state) => {\n for (const [accountId, { added, removed }] of Object.entries(\n accountsAndAssetsToUpdate,\n )) {\n const assets = new Set([\n ...(state.accountsAssets[accountId] || []),\n ...added,\n ]);\n for (const asset of removed) {\n assets.delete(asset);\n }\n\n state.accountsAssets[accountId] = Array.from(assets);\n }\n });\n\n // Trigger fetching metadata for new assets\n await this.#refreshAssetsMetadata(Array.from(assetsForMetadataRefresh));\n\n this.messagingSystem.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: accountsAndAssetsToUpdate,\n });\n }\n\n /**\n * Checks for non-EVM accounts.\n *\n * @param account - The new account to be checked.\n * @returns True if the account is a non-EVM account, false otherwise.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) &&\n // Non-EVM accounts are backed by a Snap for now\n account.metadata.snap !== undefined\n );\n }\n\n /**\n * Handles changes when a new account has been added.\n *\n * @param account - The new account being added.\n */\n async #handleOnAccountAdded(account: InternalAccount): Promise<void> {\n if (!this.#isNonEvmAccount(account)) {\n // Nothing to do here for EVM accounts\n return;\n }\n this.#assertControllerMutexIsLocked();\n\n // Get assets list\n if (account.metadata.snap) {\n const assets = await this.#getAssetsList(\n account.id,\n account.metadata.snap.id,\n );\n await this.#refreshAssetsMetadata(assets);\n this.update((state) => {\n state.accountsAssets[account.id] = assets;\n });\n this.messagingSystem.publish(\n `${controllerName}:accountAssetListUpdated`,\n {\n assets: {\n [account.id]: {\n added: assets,\n removed: [],\n },\n },\n },\n );\n }\n }\n\n /**\n * Handles changes when a new account has been removed.\n *\n * @param accountId - The new account id being removed.\n */\n async #handleOnAccountRemovedEvent(accountId: string): Promise<void> {\n // Check if accountId is in accountsAssets and if it is, remove it\n if (this.state.accountsAssets[accountId]) {\n this.update((state) => {\n // TODO: We are not deleting the assetsMetadata because we will soon make this controller extends StaticIntervalPollingController\n // and update all assetsMetadata once a day.\n delete state.accountsAssets[accountId];\n });\n }\n }\n\n /**\n * Refreshes the assets snaps and metadata for the given list of assets\n *\n * @param assets - The assets to refresh\n */\n async #refreshAssetsMetadata(assets: CaipAssetType[]) {\n this.#assertControllerMutexIsLocked();\n\n const assetsWithoutMetadata: CaipAssetType[] = assets.filter(\n (asset) => !this.state.assetsMetadata[asset],\n );\n\n // Call the snap to get the metadata\n if (assetsWithoutMetadata.length > 0) {\n // Check if for every asset in assetsWithoutMetadata there is a snap in snaps by chainId else call getAssetSnaps\n if (\n !assetsWithoutMetadata.every((asset: CaipAssetType) => {\n const { chainId } = parseCaipAssetType(asset);\n return Boolean(this.#getAssetSnapFor(chainId));\n })\n ) {\n this.#snaps = this.#getAssetSnaps();\n }\n await this.#updateAssetsMetadata(assetsWithoutMetadata);\n }\n }\n\n /**\n * Updates the assets metadata for the given list of assets\n *\n * @param assets - The assets to update\n */\n async #updateAssetsMetadata(assets: CaipAssetType[]) {\n // Creates a mapping of scope to their respective assets list.\n const assetsByScope: Record<CaipChainId, CaipAssetType[]> = {};\n for (const asset of assets) {\n const { chainId } = parseCaipAssetType(asset);\n if (!assetsByScope[chainId]) {\n assetsByScope[chainId] = [];\n }\n assetsByScope[chainId].push(asset);\n }\n\n let newMetadata: Record<CaipAssetType, FungibleAssetMetadata> = {};\n for (const chainId of Object.keys(assetsByScope) as CaipChainId[]) {\n const assetsForChain = assetsByScope[chainId];\n // Now fetch metadata from the associated asset Snaps:\n const snap = this.#getAssetSnapFor(chainId);\n if (snap) {\n const metadata = await this.#getAssetsMetadataFrom(\n assetsForChain,\n snap.id,\n );\n newMetadata = {\n ...newMetadata,\n ...(metadata?.assets ?? {}),\n };\n }\n }\n this.update((state) => {\n state.assetsMetadata = {\n ...this.state.assetsMetadata,\n ...newMetadata,\n };\n });\n }\n\n /**\n * Creates a mapping of CAIP-2 Chain ID to Asset Snaps.\n *\n * @returns A mapping of CAIP-2 Chain ID to Asset Snaps.\n */\n #getAssetSnaps(): Record<CaipChainId, Snap[]> {\n const snaps: Record<CaipChainId, Snap[]> = {};\n const allSnaps = this.#getAllSnaps();\n const allPermissions = allSnaps.map((snap) =>\n this.#getSnapsPermissions(snap.id),\n );\n\n for (const [index, permission] of allPermissions.entries()) {\n let scopes;\n for (const singlePermissionConstraint of Object.values(permission)) {\n scopes = getChainIdsCaveat(singlePermissionConstraint);\n if (!scopes) {\n continue;\n }\n for (const scope of scopes as CaipChainId[]) {\n if (!snaps[scope]) {\n snaps[scope] = [];\n }\n snaps[scope].push(allSnaps[index]);\n }\n }\n }\n return snaps;\n }\n\n /**\n * Returns the first asset snap for the given scope\n *\n * @param scope - The scope to get the asset snap for\n * @returns The asset snap for the given scope\n */\n #getAssetSnapFor(scope: CaipChainId): Snap | undefined {\n const allSnaps = this.#snaps[scope];\n // Pick only the first one, we ignore the other Snaps if there are multiple candidates for now.\n return allSnaps?.[0]; // Will be undefined if there's no Snaps candidate for this scope.\n }\n\n /**\n * Returns all the asset snaps\n *\n * @returns All the asset snaps\n */\n #getAllSnaps(): Snap[] {\n // TODO: Use dedicated SnapController's action once available for this:\n return this.messagingSystem\n .call('SnapController:getAll')\n .filter((snap) => snap.enabled && !snap.blocked);\n }\n\n /**\n * Returns the permissions for the given origin\n *\n * @param origin - The origin to get the permissions for\n * @returns The permissions for the given origin\n */\n #getSnapsPermissions(\n origin: string,\n ): SubjectPermissions<PermissionConstraint> {\n return this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n ) as SubjectPermissions<PermissionConstraint>;\n }\n\n /**\n * Returns the metadata for the given assets\n *\n * @param assets - The assets to get metadata for\n * @param snapId - The snap ID to get metadata from\n * @returns The metadata for the assets\n */\n async #getAssetsMetadataFrom(\n assets: CaipAssetType[],\n snapId: string,\n ): Promise<AssetMetadataResponse | undefined> {\n try {\n return (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnAssetsLookup,\n request: {\n jsonrpc: '2.0',\n method: 'onAssetLookup',\n params: {\n assets,\n },\n },\n })) as Promise<AssetMetadataResponse>;\n } catch (error) {\n // Ignore\n console.error(error);\n return undefined;\n }\n }\n\n /**\n * Get assets list for an account\n *\n * @param accountId - AccountId to get assets for\n * @param snapId - Snap ID for the account\n * @returns list of assets\n */\n async #getAssetsList(\n accountId: string,\n snapId: string,\n ): Promise<CaipAssetTypeOrId[]> {\n return await this.#getClient(snapId).listAccountAssets(accountId);\n }\n\n /**\n * Gets a `KeyringClient` for a Snap.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getClient(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) =>\n (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n })) as Promise<Json>,\n });\n }\n\n /**\n * Assert that the controller mutex is locked.\n *\n * @throws If the controller mutex is not locked.\n */\n #assertControllerMutexIsLocked() {\n if (!this.#controllerOperationMutex.isLocked()) {\n throw new Error(\n 'MultichainAssetsControllerError - Attempt to update state',\n );\n }\n }\n\n /**\n * Lock the controller mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * This wrapper ensures that each mutable operation that interacts with the\n * controller and that changes its state is executed in a mutually exclusive way,\n * preventing unsafe concurrent access that could lead to unpredictable behavior.\n *\n * @param callback - The function to execute while the controller mutex is locked.\n * @returns The result of the function.\n */\n async #withControllerLock<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return withLock(this.#controllerOperationMutex, callback);\n }\n}\n\n/**\n * Lock the given mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * @param mutex - The mutex to lock.\n * @param callback - The function to execute while the mutex is locked.\n * @returns The result of the function.\n */\nasync function withLock<Result>(\n mutex: Mutex,\n callback: MutuallyExclusiveCallback<Result>,\n): Promise<Result> {\n const releaseLock = await mutex.acquire();\n\n try {\n return await callback({ releaseLock });\n } finally {\n releaseLock();\n }\n}\n"]}
|
@@ -64,7 +64,7 @@ export class MultichainAssetsController extends BaseController {
|
|
64
64
|
_MultichainAssetsController_controllerOperationMutex.set(this, new Mutex());
|
65
65
|
__classPrivateFieldSet(this, _MultichainAssetsController_snaps, {}, "f");
|
66
66
|
this.messagingSystem.subscribe('AccountsController:accountAdded', async (account) => await __classPrivateFieldGet(this, _MultichainAssetsController_instances, "m", _MultichainAssetsController_handleOnAccountAddedEvent).call(this, account));
|
67
|
-
this.messagingSystem.subscribe('AccountsController:accountRemoved', async (
|
67
|
+
this.messagingSystem.subscribe('AccountsController:accountRemoved', async ({ id }) => await __classPrivateFieldGet(this, _MultichainAssetsController_instances, "m", _MultichainAssetsController_handleOnAccountRemovedEvent).call(this, id));
|
68
68
|
this.messagingSystem.subscribe('AccountsController:accountAssetListUpdated', async (event) => await __classPrivateFieldGet(this, _MultichainAssetsController_instances, "m", _MultichainAssetsController_handleAccountAssetListUpdatedEvent).call(this, event));
|
69
69
|
__classPrivateFieldGet(this, _MultichainAssetsController_instances, "m", _MultichainAssetsController_registerMessageHandlers).call(this);
|
70
70
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"MultichainAssetsController.mjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/MultichainAssetsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAMA,OAAO,EACL,cAAc,EAIf,kCAAkC;AACnC,OAAO,EAAE,gBAAgB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C,QAAQ,EAAE,EAAE;QAC9C,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;KACH;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,KAAK,yDACH,QAA2C;IAE3C,OAAO,QAAQ,CAAC,uBAAA,IAAI,4DAA0B,EAAE,QAAQ,CAAC,CAAC;AAC5D,CAAC;AAGH;;;;;;;;GAQG;AACH,KAAK,UAAU,QAAQ,CACrB,KAAY,EACZ,QAA2C;IAE3C,MAAM,WAAW,GAAG,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;IAE1C,IAAI;QACF,OAAO,MAAM,QAAQ,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;KACxC;YAAS;QACR,WAAW,EAAE,CAAC;KACf;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountAssetListUpdatedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerListMultichainAccountsAction,\n} from '@metamask/accounts-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n AccountAssetListUpdatedEventPayload,\n CaipAssetType,\n CaipAssetTypeOrId,\n} from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type {\n GetPermissions,\n PermissionConstraint,\n SubjectPermissions,\n} from '@metamask/permission-controller';\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n} from '@metamask/snaps-controllers';\nimport type { FungibleAssetMetadata, Snap, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport {\n isCaipAssetType,\n parseCaipAssetType,\n type CaipChainId,\n} from '@metamask/utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { MutexInterface } from 'async-mutex';\nimport { Mutex } from 'async-mutex';\n\nimport { getChainIdsCaveat } from './utils';\n\nconst controllerName = 'MultichainAssetsController';\n\nexport type MultichainAssetsControllerState = {\n assetsMetadata: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n accountsAssets: { [account: string]: CaipAssetType[] };\n};\n\n// Represents the response of the asset snap's onAssetLookup handler\nexport type AssetMetadataResponse = {\n assets: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n};\n\nexport type MultichainAssetsControllerAccountAssetListUpdatedEvent = {\n type: `${typeof controllerName}:accountAssetListUpdated`;\n payload: AccountsControllerAccountAssetListUpdatedEvent['payload'];\n};\n\n/**\n * Constructs the default {@link MultichainAssetsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link MultichainAssetsController} state.\n */\nexport function getDefaultMultichainAssetsControllerState(): MultichainAssetsControllerState {\n return { accountsAssets: {}, assetsMetadata: {} };\n}\n\nexport type MultichainAssetsControllerGetAssetMetadataAction = {\n type: `${typeof controllerName}:getAssetMetadata`;\n handler: MultichainAssetsController['getAssetMetadata'];\n};\n\n/**\n * Returns the state of the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n MultichainAssetsControllerState\n>;\n\n/**\n * Event emitted when the state of the {@link MultichainAssetsController} changes.\n */\nexport type MultichainAssetsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainAssetsControllerState\n >;\n\n/**\n * Actions exposed by the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerActions =\n | MultichainAssetsControllerGetStateAction\n | MultichainAssetsControllerGetAssetMetadataAction;\n\n/**\n * Events emitted by {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerEvents =\n | MultichainAssetsControllerStateChangeEvent\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n\n/**\n * A function executed within a mutually exclusive lock, with\n * a mutex releaser in its option bag.\n *\n * @param releaseLock - A function to release the lock.\n */\ntype MutuallyExclusiveCallback<Result> = ({\n releaseLock,\n}: {\n releaseLock: MutexInterface.Releaser;\n}) => Promise<Result>;\n\n/**\n * Actions that this controller is allowed to call.\n */\ntype AllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | AccountsControllerListMultichainAccountsAction;\n\n/**\n * Events that this controller is allowed to subscribe.\n */\ntype AllowedEvents =\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | AccountsControllerAccountAssetListUpdatedEvent;\n\n/**\n * Messenger type for the MultichainAssetsController.\n */\nexport type MultichainAssetsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n MultichainAssetsControllerActions | AllowedActions,\n MultichainAssetsControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * {@link MultichainAssetsController}'s metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst assetsControllerMetadata = {\n assetsMetadata: {\n persist: true,\n anonymous: false,\n },\n accountsAssets: {\n persist: true,\n anonymous: false,\n },\n};\n\n// TODO: make this controller extends StaticIntervalPollingController and update all assetsMetadata once a day.\n\nexport class MultichainAssetsController extends BaseController<\n typeof controllerName,\n MultichainAssetsControllerState,\n MultichainAssetsControllerMessenger\n> {\n // Mapping of CAIP-2 Chain ID to Asset Snaps.\n #snaps: Record<CaipChainId, Snap[]>;\n\n readonly #controllerOperationMutex = new Mutex();\n\n constructor({\n messenger,\n state = {},\n }: {\n messenger: MultichainAssetsControllerMessenger;\n state?: Partial<MultichainAssetsControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: assetsControllerMetadata,\n state: {\n ...getDefaultMultichainAssetsControllerState(),\n ...state,\n },\n });\n\n this.#snaps = {};\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n async (account) => await this.#handleOnAccountAddedEvent(account),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountRemoved',\n async (account) => await this.#handleOnAccountRemovedEvent(account),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountAssetListUpdated',\n async (event) => await this.#handleAccountAssetListUpdatedEvent(event),\n );\n\n this.#registerMessageHandlers();\n }\n\n async #handleAccountAssetListUpdatedEvent(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n return this.#withControllerLock(async () =>\n this.#handleAccountAssetListUpdated(event),\n );\n }\n\n async #handleOnAccountAddedEvent(account: InternalAccount) {\n return this.#withControllerLock(async () =>\n this.#handleOnAccountAdded(account),\n );\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n 'MultichainAssetsController:getAssetMetadata',\n this.getAssetMetadata.bind(this),\n );\n }\n\n /**\n * Returns the metadata for the given asset\n *\n * @param asset - The asset to get metadata for\n * @returns The metadata for the asset or undefined if not found.\n */\n getAssetMetadata(asset: CaipAssetType): FungibleAssetMetadata | undefined {\n return this.state.assetsMetadata[asset];\n }\n\n /**\n * Function to update the assets list for an account\n *\n * @param event - The list of assets to update\n */\n async #handleAccountAssetListUpdated(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n this.#assertControllerMutexIsLocked();\n\n const assetsForMetadataRefresh = new Set<CaipAssetType>([]);\n const accountsAndAssetsToUpdate: AccountAssetListUpdatedEventPayload['assets'] =\n {};\n for (const [accountId, { added, removed }] of Object.entries(\n event.assets,\n )) {\n if (added.length > 0 || removed.length > 0) {\n const existing = this.state.accountsAssets[accountId] || [];\n\n // In case accountsAndAssetsToUpdate event is fired with \"added\" assets that already exist, we don't want to add them again\n const filteredToBeAddedAssets = added.filter(\n (asset) => !existing.includes(asset) && isCaipAssetType(asset),\n );\n\n // In case accountsAndAssetsToUpdate event is fired with \"removed\" assets that don't exist, we don't want to remove them\n const filteredToBeRemovedAssets = removed.filter(\n (asset) => existing.includes(asset) && isCaipAssetType(asset),\n );\n\n if (\n filteredToBeAddedAssets.length > 0 ||\n filteredToBeRemovedAssets.length > 0\n ) {\n accountsAndAssetsToUpdate[accountId] = {\n added: filteredToBeAddedAssets,\n removed: filteredToBeRemovedAssets,\n };\n }\n\n for (const asset of existing) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeAddedAssets) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeRemovedAssets) {\n assetsForMetadataRefresh.delete(asset);\n }\n }\n }\n\n this.update((state) => {\n for (const [accountId, { added, removed }] of Object.entries(\n accountsAndAssetsToUpdate,\n )) {\n const assets = new Set([\n ...(state.accountsAssets[accountId] || []),\n ...added,\n ]);\n for (const asset of removed) {\n assets.delete(asset);\n }\n\n state.accountsAssets[accountId] = Array.from(assets);\n }\n });\n\n // Trigger fetching metadata for new assets\n await this.#refreshAssetsMetadata(Array.from(assetsForMetadataRefresh));\n\n this.messagingSystem.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: accountsAndAssetsToUpdate,\n });\n }\n\n /**\n * Checks for non-EVM accounts.\n *\n * @param account - The new account to be checked.\n * @returns True if the account is a non-EVM account, false otherwise.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) &&\n // Non-EVM accounts are backed by a Snap for now\n account.metadata.snap !== undefined\n );\n }\n\n /**\n * Handles changes when a new account has been added.\n *\n * @param account - The new account being added.\n */\n async #handleOnAccountAdded(account: InternalAccount): Promise<void> {\n if (!this.#isNonEvmAccount(account)) {\n // Nothing to do here for EVM accounts\n return;\n }\n this.#assertControllerMutexIsLocked();\n\n // Get assets list\n if (account.metadata.snap) {\n const assets = await this.#getAssetsList(\n account.id,\n account.metadata.snap.id,\n );\n await this.#refreshAssetsMetadata(assets);\n this.update((state) => {\n state.accountsAssets[account.id] = assets;\n });\n this.messagingSystem.publish(\n `${controllerName}:accountAssetListUpdated`,\n {\n assets: {\n [account.id]: {\n added: assets,\n removed: [],\n },\n },\n },\n );\n }\n }\n\n /**\n * Handles changes when a new account has been removed.\n *\n * @param accountId - The new account id being removed.\n */\n async #handleOnAccountRemovedEvent(accountId: string): Promise<void> {\n // Check if accountId is in accountsAssets and if it is, remove it\n if (this.state.accountsAssets[accountId]) {\n this.update((state) => {\n // TODO: We are not deleting the assetsMetadata because we will soon make this controller extends StaticIntervalPollingController\n // and update all assetsMetadata once a day.\n delete state.accountsAssets[accountId];\n });\n }\n }\n\n /**\n * Refreshes the assets snaps and metadata for the given list of assets\n *\n * @param assets - The assets to refresh\n */\n async #refreshAssetsMetadata(assets: CaipAssetType[]) {\n this.#assertControllerMutexIsLocked();\n\n const assetsWithoutMetadata: CaipAssetType[] = assets.filter(\n (asset) => !this.state.assetsMetadata[asset],\n );\n\n // Call the snap to get the metadata\n if (assetsWithoutMetadata.length > 0) {\n // Check if for every asset in assetsWithoutMetadata there is a snap in snaps by chainId else call getAssetSnaps\n if (\n !assetsWithoutMetadata.every((asset: CaipAssetType) => {\n const { chainId } = parseCaipAssetType(asset);\n return Boolean(this.#getAssetSnapFor(chainId));\n })\n ) {\n this.#snaps = this.#getAssetSnaps();\n }\n await this.#updateAssetsMetadata(assetsWithoutMetadata);\n }\n }\n\n /**\n * Updates the assets metadata for the given list of assets\n *\n * @param assets - The assets to update\n */\n async #updateAssetsMetadata(assets: CaipAssetType[]) {\n // Creates a mapping of scope to their respective assets list.\n const assetsByScope: Record<CaipChainId, CaipAssetType[]> = {};\n for (const asset of assets) {\n const { chainId } = parseCaipAssetType(asset);\n if (!assetsByScope[chainId]) {\n assetsByScope[chainId] = [];\n }\n assetsByScope[chainId].push(asset);\n }\n\n let newMetadata: Record<CaipAssetType, FungibleAssetMetadata> = {};\n for (const chainId of Object.keys(assetsByScope) as CaipChainId[]) {\n const assetsForChain = assetsByScope[chainId];\n // Now fetch metadata from the associated asset Snaps:\n const snap = this.#getAssetSnapFor(chainId);\n if (snap) {\n const metadata = await this.#getAssetsMetadataFrom(\n assetsForChain,\n snap.id,\n );\n newMetadata = {\n ...newMetadata,\n ...(metadata?.assets ?? {}),\n };\n }\n }\n this.update((state) => {\n state.assetsMetadata = {\n ...this.state.assetsMetadata,\n ...newMetadata,\n };\n });\n }\n\n /**\n * Creates a mapping of CAIP-2 Chain ID to Asset Snaps.\n *\n * @returns A mapping of CAIP-2 Chain ID to Asset Snaps.\n */\n #getAssetSnaps(): Record<CaipChainId, Snap[]> {\n const snaps: Record<CaipChainId, Snap[]> = {};\n const allSnaps = this.#getAllSnaps();\n const allPermissions = allSnaps.map((snap) =>\n this.#getSnapsPermissions(snap.id),\n );\n\n for (const [index, permission] of allPermissions.entries()) {\n let scopes;\n for (const singlePermissionConstraint of Object.values(permission)) {\n scopes = getChainIdsCaveat(singlePermissionConstraint);\n if (!scopes) {\n continue;\n }\n for (const scope of scopes as CaipChainId[]) {\n if (!snaps[scope]) {\n snaps[scope] = [];\n }\n snaps[scope].push(allSnaps[index]);\n }\n }\n }\n return snaps;\n }\n\n /**\n * Returns the first asset snap for the given scope\n *\n * @param scope - The scope to get the asset snap for\n * @returns The asset snap for the given scope\n */\n #getAssetSnapFor(scope: CaipChainId): Snap | undefined {\n const allSnaps = this.#snaps[scope];\n // Pick only the first one, we ignore the other Snaps if there are multiple candidates for now.\n return allSnaps?.[0]; // Will be undefined if there's no Snaps candidate for this scope.\n }\n\n /**\n * Returns all the asset snaps\n *\n * @returns All the asset snaps\n */\n #getAllSnaps(): Snap[] {\n // TODO: Use dedicated SnapController's action once available for this:\n return this.messagingSystem\n .call('SnapController:getAll')\n .filter((snap) => snap.enabled && !snap.blocked);\n }\n\n /**\n * Returns the permissions for the given origin\n *\n * @param origin - The origin to get the permissions for\n * @returns The permissions for the given origin\n */\n #getSnapsPermissions(\n origin: string,\n ): SubjectPermissions<PermissionConstraint> {\n return this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n ) as SubjectPermissions<PermissionConstraint>;\n }\n\n /**\n * Returns the metadata for the given assets\n *\n * @param assets - The assets to get metadata for\n * @param snapId - The snap ID to get metadata from\n * @returns The metadata for the assets\n */\n async #getAssetsMetadataFrom(\n assets: CaipAssetType[],\n snapId: string,\n ): Promise<AssetMetadataResponse | undefined> {\n try {\n return (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnAssetsLookup,\n request: {\n jsonrpc: '2.0',\n method: 'onAssetLookup',\n params: {\n assets,\n },\n },\n })) as Promise<AssetMetadataResponse>;\n } catch (error) {\n // Ignore\n console.error(error);\n return undefined;\n }\n }\n\n /**\n * Get assets list for an account\n *\n * @param accountId - AccountId to get assets for\n * @param snapId - Snap ID for the account\n * @returns list of assets\n */\n async #getAssetsList(\n accountId: string,\n snapId: string,\n ): Promise<CaipAssetTypeOrId[]> {\n return await this.#getClient(snapId).listAccountAssets(accountId);\n }\n\n /**\n * Gets a `KeyringClient` for a Snap.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getClient(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) =>\n (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n })) as Promise<Json>,\n });\n }\n\n /**\n * Assert that the controller mutex is locked.\n *\n * @throws If the controller mutex is not locked.\n */\n #assertControllerMutexIsLocked() {\n if (!this.#controllerOperationMutex.isLocked()) {\n throw new Error(\n 'MultichainAssetsControllerError - Attempt to update state',\n );\n }\n }\n\n /**\n * Lock the controller mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * This wrapper ensures that each mutable operation that interacts with the\n * controller and that changes its state is executed in a mutually exclusive way,\n * preventing unsafe concurrent access that could lead to unpredictable behavior.\n *\n * @param callback - The function to execute while the controller mutex is locked.\n * @returns The result of the function.\n */\n async #withControllerLock<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return withLock(this.#controllerOperationMutex, callback);\n }\n}\n\n/**\n * Lock the given mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * @param mutex - The mutex to lock.\n * @param callback - The function to execute while the mutex is locked.\n * @returns The result of the function.\n */\nasync function withLock<Result>(\n mutex: Mutex,\n callback: MutuallyExclusiveCallback<Result>,\n): Promise<Result> {\n const releaseLock = await mutex.acquire();\n\n try {\n return await callback({ releaseLock });\n } finally {\n releaseLock();\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"MultichainAssetsController.mjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/MultichainAssetsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAMA,OAAO,EACL,cAAc,EAIf,kCAAkC;AACnC,OAAO,EAAE,gBAAgB,EAAE,8BAA8B;AAOzD,OAAO,EAAE,aAAa,EAAE,sCAAsC;AAW9D,OAAO,EAAE,WAAW,EAAE,8BAA8B;AACpD,OAAO,EACL,eAAe,EACf,kBAAkB,EAEnB,wBAAwB;AAGzB,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,iBAAiB,EAAE,oBAAgB;AAE5C,MAAM,cAAc,GAAG,4BAA4B,CAAC;AAqBpD;;;;;;;GAOG;AACH,MAAM,UAAU,yCAAyC;IACvD,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC;AACpD,CAAC;AA8ED;;;;;;GAMG;AACH,MAAM,wBAAwB,GAAG;IAC/B,cAAc,EAAE;QACd,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,cAAc,EAAE;QACd,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AAEF,+GAA+G;AAE/G,MAAM,OAAO,0BAA2B,SAAQ,cAI/C;IAMC,YAAY,EACV,SAAS,EACT,KAAK,GAAG,EAAE,GAIX;QACC,KAAK,CAAC;YACJ,SAAS;YACT,IAAI,EAAE,cAAc;YACpB,QAAQ,E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AAc;IAEd,OAAO,MAAM,uBAAA,IAAI,oFAAW,MAAf,IAAI,EAAY,MAAM,CAAC,CAAC,iBAAiB,CAAC,SAAS,CAAC,CAAC;AACpE,CAAC,yFAQU,MAAc;IACvB,OAAO,IAAI,aAAa,CAAC;QACvB,IAAI,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CACtC,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,8BAA8B,EAAE;YAC/D,MAAM,EAAE,MAAgB;YACxB,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,WAAW,CAAC,gBAAgB;YACrC,OAAO;SACR,CAAC,CAAkB;KACvB,CAAC,CAAC;AACL,CAAC;IAQC,IAAI,CAAC,uBAAA,IAAI,4DAA0B,CAAC,QAAQ,EAAE,EAAE;QAC9C,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;KACH;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,KAAK,yDACH,QAA2C;IAE3C,OAAO,QAAQ,CAAC,uBAAA,IAAI,4DAA0B,EAAE,QAAQ,CAAC,CAAC;AAC5D,CAAC;AAGH;;;;;;;;GAQG;AACH,KAAK,UAAU,QAAQ,CACrB,KAAY,EACZ,QAA2C;IAE3C,MAAM,WAAW,GAAG,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;IAE1C,IAAI;QACF,OAAO,MAAM,QAAQ,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;KACxC;YAAS;QACR,WAAW,EAAE,CAAC;KACf;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountAssetListUpdatedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerListMultichainAccountsAction,\n} from '@metamask/accounts-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n AccountAssetListUpdatedEventPayload,\n CaipAssetType,\n CaipAssetTypeOrId,\n} from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type {\n GetPermissions,\n PermissionConstraint,\n SubjectPermissions,\n} from '@metamask/permission-controller';\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n} from '@metamask/snaps-controllers';\nimport type { FungibleAssetMetadata, Snap, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport {\n isCaipAssetType,\n parseCaipAssetType,\n type CaipChainId,\n} from '@metamask/utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { MutexInterface } from 'async-mutex';\nimport { Mutex } from 'async-mutex';\n\nimport { getChainIdsCaveat } from './utils';\n\nconst controllerName = 'MultichainAssetsController';\n\nexport type MultichainAssetsControllerState = {\n assetsMetadata: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n accountsAssets: { [account: string]: CaipAssetType[] };\n};\n\n// Represents the response of the asset snap's onAssetLookup handler\nexport type AssetMetadataResponse = {\n assets: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n};\n\nexport type MultichainAssetsControllerAccountAssetListUpdatedEvent = {\n type: `${typeof controllerName}:accountAssetListUpdated`;\n payload: AccountsControllerAccountAssetListUpdatedEvent['payload'];\n};\n\n/**\n * Constructs the default {@link MultichainAssetsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link MultichainAssetsController} state.\n */\nexport function getDefaultMultichainAssetsControllerState(): MultichainAssetsControllerState {\n return { accountsAssets: {}, assetsMetadata: {} };\n}\n\nexport type MultichainAssetsControllerGetAssetMetadataAction = {\n type: `${typeof controllerName}:getAssetMetadata`;\n handler: MultichainAssetsController['getAssetMetadata'];\n};\n\n/**\n * Returns the state of the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n MultichainAssetsControllerState\n>;\n\n/**\n * Event emitted when the state of the {@link MultichainAssetsController} changes.\n */\nexport type MultichainAssetsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainAssetsControllerState\n >;\n\n/**\n * Actions exposed by the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerActions =\n | MultichainAssetsControllerGetStateAction\n | MultichainAssetsControllerGetAssetMetadataAction;\n\n/**\n * Events emitted by {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerEvents =\n | MultichainAssetsControllerStateChangeEvent\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n\n/**\n * A function executed within a mutually exclusive lock, with\n * a mutex releaser in its option bag.\n *\n * @param releaseLock - A function to release the lock.\n */\ntype MutuallyExclusiveCallback<Result> = ({\n releaseLock,\n}: {\n releaseLock: MutexInterface.Releaser;\n}) => Promise<Result>;\n\n/**\n * Actions that this controller is allowed to call.\n */\ntype AllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | AccountsControllerListMultichainAccountsAction;\n\n/**\n * Events that this controller is allowed to subscribe.\n */\ntype AllowedEvents =\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | AccountsControllerAccountAssetListUpdatedEvent;\n\n/**\n * Messenger type for the MultichainAssetsController.\n */\nexport type MultichainAssetsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n MultichainAssetsControllerActions | AllowedActions,\n MultichainAssetsControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * {@link MultichainAssetsController}'s metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst assetsControllerMetadata = {\n assetsMetadata: {\n persist: true,\n anonymous: false,\n },\n accountsAssets: {\n persist: true,\n anonymous: false,\n },\n};\n\n// TODO: make this controller extends StaticIntervalPollingController and update all assetsMetadata once a day.\n\nexport class MultichainAssetsController extends BaseController<\n typeof controllerName,\n MultichainAssetsControllerState,\n MultichainAssetsControllerMessenger\n> {\n // Mapping of CAIP-2 Chain ID to Asset Snaps.\n #snaps: Record<CaipChainId, Snap[]>;\n\n readonly #controllerOperationMutex = new Mutex();\n\n constructor({\n messenger,\n state = {},\n }: {\n messenger: MultichainAssetsControllerMessenger;\n state?: Partial<MultichainAssetsControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: assetsControllerMetadata,\n state: {\n ...getDefaultMultichainAssetsControllerState(),\n ...state,\n },\n });\n\n this.#snaps = {};\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n async (account) => await this.#handleOnAccountAddedEvent(account),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountRemoved',\n async ({ id }) => await this.#handleOnAccountRemovedEvent(id),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountAssetListUpdated',\n async (event) => await this.#handleAccountAssetListUpdatedEvent(event),\n );\n\n this.#registerMessageHandlers();\n }\n\n async #handleAccountAssetListUpdatedEvent(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n return this.#withControllerLock(async () =>\n this.#handleAccountAssetListUpdated(event),\n );\n }\n\n async #handleOnAccountAddedEvent(account: InternalAccount) {\n return this.#withControllerLock(async () =>\n this.#handleOnAccountAdded(account),\n );\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n 'MultichainAssetsController:getAssetMetadata',\n this.getAssetMetadata.bind(this),\n );\n }\n\n /**\n * Returns the metadata for the given asset\n *\n * @param asset - The asset to get metadata for\n * @returns The metadata for the asset or undefined if not found.\n */\n getAssetMetadata(asset: CaipAssetType): FungibleAssetMetadata | undefined {\n return this.state.assetsMetadata[asset];\n }\n\n /**\n * Function to update the assets list for an account\n *\n * @param event - The list of assets to update\n */\n async #handleAccountAssetListUpdated(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n this.#assertControllerMutexIsLocked();\n\n const assetsForMetadataRefresh = new Set<CaipAssetType>([]);\n const accountsAndAssetsToUpdate: AccountAssetListUpdatedEventPayload['assets'] =\n {};\n for (const [accountId, { added, removed }] of Object.entries(\n event.assets,\n )) {\n if (added.length > 0 || removed.length > 0) {\n const existing = this.state.accountsAssets[accountId] || [];\n\n // In case accountsAndAssetsToUpdate event is fired with \"added\" assets that already exist, we don't want to add them again\n const filteredToBeAddedAssets = added.filter(\n (asset) => !existing.includes(asset) && isCaipAssetType(asset),\n );\n\n // In case accountsAndAssetsToUpdate event is fired with \"removed\" assets that don't exist, we don't want to remove them\n const filteredToBeRemovedAssets = removed.filter(\n (asset) => existing.includes(asset) && isCaipAssetType(asset),\n );\n\n if (\n filteredToBeAddedAssets.length > 0 ||\n filteredToBeRemovedAssets.length > 0\n ) {\n accountsAndAssetsToUpdate[accountId] = {\n added: filteredToBeAddedAssets,\n removed: filteredToBeRemovedAssets,\n };\n }\n\n for (const asset of existing) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeAddedAssets) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeRemovedAssets) {\n assetsForMetadataRefresh.delete(asset);\n }\n }\n }\n\n this.update((state) => {\n for (const [accountId, { added, removed }] of Object.entries(\n accountsAndAssetsToUpdate,\n )) {\n const assets = new Set([\n ...(state.accountsAssets[accountId] || []),\n ...added,\n ]);\n for (const asset of removed) {\n assets.delete(asset);\n }\n\n state.accountsAssets[accountId] = Array.from(assets);\n }\n });\n\n // Trigger fetching metadata for new assets\n await this.#refreshAssetsMetadata(Array.from(assetsForMetadataRefresh));\n\n this.messagingSystem.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: accountsAndAssetsToUpdate,\n });\n }\n\n /**\n * Checks for non-EVM accounts.\n *\n * @param account - The new account to be checked.\n * @returns True if the account is a non-EVM account, false otherwise.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) &&\n // Non-EVM accounts are backed by a Snap for now\n account.metadata.snap !== undefined\n );\n }\n\n /**\n * Handles changes when a new account has been added.\n *\n * @param account - The new account being added.\n */\n async #handleOnAccountAdded(account: InternalAccount): Promise<void> {\n if (!this.#isNonEvmAccount(account)) {\n // Nothing to do here for EVM accounts\n return;\n }\n this.#assertControllerMutexIsLocked();\n\n // Get assets list\n if (account.metadata.snap) {\n const assets = await this.#getAssetsList(\n account.id,\n account.metadata.snap.id,\n );\n await this.#refreshAssetsMetadata(assets);\n this.update((state) => {\n state.accountsAssets[account.id] = assets;\n });\n this.messagingSystem.publish(\n `${controllerName}:accountAssetListUpdated`,\n {\n assets: {\n [account.id]: {\n added: assets,\n removed: [],\n },\n },\n },\n );\n }\n }\n\n /**\n * Handles changes when a new account has been removed.\n *\n * @param accountId - The new account id being removed.\n */\n async #handleOnAccountRemovedEvent(accountId: string): Promise<void> {\n // Check if accountId is in accountsAssets and if it is, remove it\n if (this.state.accountsAssets[accountId]) {\n this.update((state) => {\n // TODO: We are not deleting the assetsMetadata because we will soon make this controller extends StaticIntervalPollingController\n // and update all assetsMetadata once a day.\n delete state.accountsAssets[accountId];\n });\n }\n }\n\n /**\n * Refreshes the assets snaps and metadata for the given list of assets\n *\n * @param assets - The assets to refresh\n */\n async #refreshAssetsMetadata(assets: CaipAssetType[]) {\n this.#assertControllerMutexIsLocked();\n\n const assetsWithoutMetadata: CaipAssetType[] = assets.filter(\n (asset) => !this.state.assetsMetadata[asset],\n );\n\n // Call the snap to get the metadata\n if (assetsWithoutMetadata.length > 0) {\n // Check if for every asset in assetsWithoutMetadata there is a snap in snaps by chainId else call getAssetSnaps\n if (\n !assetsWithoutMetadata.every((asset: CaipAssetType) => {\n const { chainId } = parseCaipAssetType(asset);\n return Boolean(this.#getAssetSnapFor(chainId));\n })\n ) {\n this.#snaps = this.#getAssetSnaps();\n }\n await this.#updateAssetsMetadata(assetsWithoutMetadata);\n }\n }\n\n /**\n * Updates the assets metadata for the given list of assets\n *\n * @param assets - The assets to update\n */\n async #updateAssetsMetadata(assets: CaipAssetType[]) {\n // Creates a mapping of scope to their respective assets list.\n const assetsByScope: Record<CaipChainId, CaipAssetType[]> = {};\n for (const asset of assets) {\n const { chainId } = parseCaipAssetType(asset);\n if (!assetsByScope[chainId]) {\n assetsByScope[chainId] = [];\n }\n assetsByScope[chainId].push(asset);\n }\n\n let newMetadata: Record<CaipAssetType, FungibleAssetMetadata> = {};\n for (const chainId of Object.keys(assetsByScope) as CaipChainId[]) {\n const assetsForChain = assetsByScope[chainId];\n // Now fetch metadata from the associated asset Snaps:\n const snap = this.#getAssetSnapFor(chainId);\n if (snap) {\n const metadata = await this.#getAssetsMetadataFrom(\n assetsForChain,\n snap.id,\n );\n newMetadata = {\n ...newMetadata,\n ...(metadata?.assets ?? {}),\n };\n }\n }\n this.update((state) => {\n state.assetsMetadata = {\n ...this.state.assetsMetadata,\n ...newMetadata,\n };\n });\n }\n\n /**\n * Creates a mapping of CAIP-2 Chain ID to Asset Snaps.\n *\n * @returns A mapping of CAIP-2 Chain ID to Asset Snaps.\n */\n #getAssetSnaps(): Record<CaipChainId, Snap[]> {\n const snaps: Record<CaipChainId, Snap[]> = {};\n const allSnaps = this.#getAllSnaps();\n const allPermissions = allSnaps.map((snap) =>\n this.#getSnapsPermissions(snap.id),\n );\n\n for (const [index, permission] of allPermissions.entries()) {\n let scopes;\n for (const singlePermissionConstraint of Object.values(permission)) {\n scopes = getChainIdsCaveat(singlePermissionConstraint);\n if (!scopes) {\n continue;\n }\n for (const scope of scopes as CaipChainId[]) {\n if (!snaps[scope]) {\n snaps[scope] = [];\n }\n snaps[scope].push(allSnaps[index]);\n }\n }\n }\n return snaps;\n }\n\n /**\n * Returns the first asset snap for the given scope\n *\n * @param scope - The scope to get the asset snap for\n * @returns The asset snap for the given scope\n */\n #getAssetSnapFor(scope: CaipChainId): Snap | undefined {\n const allSnaps = this.#snaps[scope];\n // Pick only the first one, we ignore the other Snaps if there are multiple candidates for now.\n return allSnaps?.[0]; // Will be undefined if there's no Snaps candidate for this scope.\n }\n\n /**\n * Returns all the asset snaps\n *\n * @returns All the asset snaps\n */\n #getAllSnaps(): Snap[] {\n // TODO: Use dedicated SnapController's action once available for this:\n return this.messagingSystem\n .call('SnapController:getAll')\n .filter((snap) => snap.enabled && !snap.blocked);\n }\n\n /**\n * Returns the permissions for the given origin\n *\n * @param origin - The origin to get the permissions for\n * @returns The permissions for the given origin\n */\n #getSnapsPermissions(\n origin: string,\n ): SubjectPermissions<PermissionConstraint> {\n return this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n ) as SubjectPermissions<PermissionConstraint>;\n }\n\n /**\n * Returns the metadata for the given assets\n *\n * @param assets - The assets to get metadata for\n * @param snapId - The snap ID to get metadata from\n * @returns The metadata for the assets\n */\n async #getAssetsMetadataFrom(\n assets: CaipAssetType[],\n snapId: string,\n ): Promise<AssetMetadataResponse | undefined> {\n try {\n return (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnAssetsLookup,\n request: {\n jsonrpc: '2.0',\n method: 'onAssetLookup',\n params: {\n assets,\n },\n },\n })) as Promise<AssetMetadataResponse>;\n } catch (error) {\n // Ignore\n console.error(error);\n return undefined;\n }\n }\n\n /**\n * Get assets list for an account\n *\n * @param accountId - AccountId to get assets for\n * @param snapId - Snap ID for the account\n * @returns list of assets\n */\n async #getAssetsList(\n accountId: string,\n snapId: string,\n ): Promise<CaipAssetTypeOrId[]> {\n return await this.#getClient(snapId).listAccountAssets(accountId);\n }\n\n /**\n * Gets a `KeyringClient` for a Snap.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getClient(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) =>\n (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n })) as Promise<Json>,\n });\n }\n\n /**\n * Assert that the controller mutex is locked.\n *\n * @throws If the controller mutex is not locked.\n */\n #assertControllerMutexIsLocked() {\n if (!this.#controllerOperationMutex.isLocked()) {\n throw new Error(\n 'MultichainAssetsControllerError - Attempt to update state',\n );\n }\n }\n\n /**\n * Lock the controller mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * This wrapper ensures that each mutable operation that interacts with the\n * controller and that changes its state is executed in a mutually exclusive way,\n * preventing unsafe concurrent access that could lead to unpredictable behavior.\n *\n * @param callback - The function to execute while the controller mutex is locked.\n * @returns The result of the function.\n */\n async #withControllerLock<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return withLock(this.#controllerOperationMutex, callback);\n }\n}\n\n/**\n * Lock the given mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * @param mutex - The mutex to lock.\n * @param callback - The function to execute while the mutex is locked.\n * @returns The result of the function.\n */\nasync function withLock<Result>(\n mutex: Mutex,\n callback: MutuallyExclusiveCallback<Result>,\n): Promise<Result> {\n const releaseLock = await mutex.acquire();\n\n try {\n return await callback({ releaseLock });\n } finally {\n releaseLock();\n }\n}\n"]}
|
@@ -59,7 +59,7 @@ class MultichainBalancesController extends base_controller_1.BaseController {
|
|
59
59
|
// eslint-disable-next-line no-void
|
60
60
|
void this.updateBalance(account.id);
|
61
61
|
}
|
62
|
-
this.messagingSystem.subscribe('AccountsController:accountRemoved', (
|
62
|
+
this.messagingSystem.subscribe('AccountsController:accountRemoved', ({ id }) => __classPrivateFieldGet(this, _MultichainBalancesController_instances, "m", _MultichainBalancesController_handleOnAccountRemoved).call(this, id));
|
63
63
|
this.messagingSystem.subscribe('AccountsController:accountBalancesUpdated', (balanceUpdate) => __classPrivateFieldGet(this, _MultichainBalancesController_instances, "m", _MultichainBalancesController_handleOnAccountBalancesUpdated).call(this, balanceUpdate));
|
64
64
|
this.messagingSystem.subscribe('MultichainAssetsController:accountAssetListUpdated', async ({ assets }) => {
|
65
65
|
const newAccountAssets = Object.entries(assets).map(([accountId, { added }]) => ({
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"MultichainBalancesController.cjs","sourceRoot":"","sources":["../../src/MultichainBalancesController/MultichainBalancesController.ts"],"names":[],"mappings":";;;;;;;;;AAMA,+DAKmC;AACnC,uDAAyD;AAQzD,uEAA8D;AAG9D,uDAAoD;AASpD,MAAM,cAAc,GAAG,8BAA8B,CAAC;AAgBtD;;;;;;;GAOG;AACH,SAAgB,2CAA2C;IACzD,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC;AAC1B,CAAC;AAFD,kGAEC;AA4DD;;;;;;GAMG;AACH,MAAM,0BAA0B,GAAG;IACjC,QAAQ,EAAE;QACR,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AAEF;;;GAGG;AACH,MAAa,4BAA6B,SAAQ,gCAIjD;IACC,YAAY,EACV,SAAS,EACT,KAAK,GAAG,EAAE,GAIX;QACC,KAAK,CAAC;YACJ,SAAS;YACT,IAAI,EAAE,cAAc;YACpB,QAAQ,EAAE,0BAA0B;YACpC,KAAK,EAAE;gBACL,GAAG,2CAA2C,EAAE;gBAChD,GAAG,KAAK;aACT;SACF,CAAC,CAAC;;QAEH,kDAAkD;QAClD,KAAK,MAAM,OAAO,IAAI,uBAAA,IAAI,2FAAc,MAAlB,IAAI,CAAgB,EAAE;YAC1C,uEAAuE;YACvE,mCAAmC;YACnC,KAAK,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;SACrC;QAED,IAAI,CAAC,eAAe,CAAC,SAAS,CAC5B,mCAAmC,EACnC,CAAC,OAAe,EAAE,EAAE,CAAC,uBAAA,IAAI,qGAAwB,MAA5B,IAAI,EAAyB,OAAO,CAAC,CAC3D,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,SAAS,CAC5B,2CAA2C,EAC3C,CAAC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,CAAC,IAAI,CAAC,8BAA8B,EAAE;YAC/D,MAAM,EAAE,MAAgB;YACxB,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,yBAAW,CAAC,gBAAgB;YACrC,OAAO;SACR,CAAC,CAAkB;KACvB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerListMultichainAccountsAction,\n AccountsControllerAccountBalancesUpdatesEvent,\n} from '@metamask/accounts-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n Balance,\n CaipAssetType,\n AccountBalancesUpdatedEventPayload,\n} from '@metamask/keyring-api';\nimport type { KeyringControllerGetStateAction } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n MultichainAssetsControllerGetStateAction,\n MultichainAssetsControllerAccountAssetListUpdatedEvent,\n} from '../MultichainAssetsController';\n\nconst controllerName = 'MultichainBalancesController';\n\n/**\n * State used by the {@link MultichainBalancesController} to cache account balances.\n */\nexport type MultichainBalancesControllerState = {\n balances: {\n [account: string]: {\n [asset: string]: {\n amount: string;\n unit: string;\n };\n };\n };\n};\n\n/**\n * Constructs the default {@link MultichainBalancesController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link MultichainBalancesController} state.\n */\nexport function getDefaultMultichainBalancesControllerState(): MultichainBalancesControllerState {\n return { balances: {} };\n}\n\n/**\n * Returns the state of the {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n MultichainBalancesControllerState\n >;\n\n/**\n * Event emitted when the state of the {@link MultichainBalancesController} changes.\n */\nexport type MultichainBalancesControllerStateChange =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainBalancesControllerState\n >;\n\n/**\n * Actions exposed by the {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerActions =\n MultichainBalancesControllerGetStateAction;\n\n/**\n * Events emitted by {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerEvents =\n MultichainBalancesControllerStateChange;\n\n/**\n * Actions that this controller is allowed to call.\n */\ntype AllowedActions =\n | HandleSnapRequest\n | AccountsControllerListMultichainAccountsAction\n | MultichainAssetsControllerGetStateAction\n | KeyringControllerGetStateAction;\n\n/**\n * Events that this controller is allowed to subscribe.\n */\ntype AllowedEvents =\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | AccountsControllerAccountBalancesUpdatesEvent\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n/**\n * Messenger type for the MultichainBalancesController.\n */\nexport type MultichainBalancesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n MultichainBalancesControllerActions | AllowedActions,\n MultichainBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * {@link MultichainBalancesController}'s metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst balancesControllerMetadata = {\n balances: {\n persist: true,\n anonymous: false,\n },\n};\n\n/**\n * The MultichainBalancesController is responsible for fetching and caching account\n * balances.\n */\nexport class MultichainBalancesController extends BaseController<\n typeof controllerName,\n MultichainBalancesControllerState,\n MultichainBalancesControllerMessenger\n> {\n constructor({\n messenger,\n state = {},\n }: {\n messenger: MultichainBalancesControllerMessenger;\n state?: Partial<MultichainBalancesControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: balancesControllerMetadata,\n state: {\n ...getDefaultMultichainBalancesControllerState(),\n ...state,\n },\n });\n\n // Fetch initial balances for all non-EVM accounts\n for (const account of this.#listAccounts()) {\n // Fetching the balance is asynchronous and we cannot use `await` here.\n // eslint-disable-next-line no-void\n void this.updateBalance(account.id);\n }\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRemoved',\n (account: string) => this.#handleOnAccountRemoved(account),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountBalancesUpdated',\n (balanceUpdate: AccountBalancesUpdatedEventPayload) =>\n this.#handleOnAccountBalancesUpdated(balanceUpdate),\n );\n\n this.messagingSystem.subscribe(\n 'MultichainAssetsController:accountAssetListUpdated',\n async ({ assets }) => {\n const newAccountAssets = Object.entries(assets).map(\n ([accountId, { added }]) => ({\n accountId,\n assets: [...added],\n }),\n );\n await this.#handleOnAccountAssetListUpdated(newAccountAssets);\n },\n );\n }\n\n /**\n * Updates the balances for the given accounts.\n *\n * @param accounts - The accounts to update the balances for.\n */\n async #handleOnAccountAssetListUpdated(\n accounts: {\n accountId: string;\n assets: CaipAssetType[];\n }[],\n ): Promise<void> {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n\n if (!isUnlocked) {\n return;\n }\n const balancesToUpdate: MultichainBalancesControllerState['balances'] = {};\n\n for (const { accountId, assets } of accounts) {\n const account = this.#getAccount(accountId);\n if (account.metadata.snap) {\n const accountBalance = await this.#getBalances(\n account.id,\n account.metadata.snap.id,\n assets,\n );\n balancesToUpdate[accountId] = accountBalance;\n }\n }\n\n if (Object.keys(balancesToUpdate).length === 0) {\n return;\n }\n\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n for (const [accountId, accountBalances] of Object.entries(\n balancesToUpdate,\n )) {\n if (\n !state.balances[accountId] ||\n Object.keys(state.balances[accountId]).length === 0\n ) {\n state.balances[accountId] = accountBalances;\n } else {\n for (const assetId in accountBalances) {\n if (!state.balances[accountId][assetId]) {\n state.balances[accountId][assetId] = accountBalances[assetId];\n }\n }\n }\n }\n });\n }\n\n /**\n * Updates the balances of one account. This method doesn't return\n * anything, but it updates the state of the controller.\n *\n * @param accountId - The account ID.\n * @param assets - The list of asset types for this account to upadte.\n */\n async #updateBalance(\n accountId: string,\n assets: CaipAssetType[],\n ): Promise<void> {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n\n if (!isUnlocked) {\n return;\n }\n\n try {\n const account = this.#getAccount(accountId);\n\n if (account.metadata.snap) {\n const accountBalance = await this.#getBalances(\n account.id,\n account.metadata.snap.id,\n assets,\n );\n\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n state.balances[accountId] = accountBalance;\n });\n }\n } catch (error) {\n // FIXME: Maybe we shouldn't catch all errors here since this method is also being\n // used in the public methods. This means if something else uses `updateBalance` it\n // won't be able to catch and gets the error itself...\n console.error(\n `Failed to fetch balances for account ${accountId}:`,\n error,\n );\n }\n }\n\n /**\n * Updates the balances of one account. This method doesn't return\n * anything, but it updates the state of the controller.\n *\n * @param accountId - The account ID.\n */\n async updateBalance(accountId: string): Promise<void> {\n await this.#updateBalance(accountId, this.#listAccountAssets(accountId));\n }\n\n /**\n * Lists the multichain accounts coming from the `AccountsController`.\n *\n * @returns A list of multichain accounts.\n */\n #listMultichainAccounts(): InternalAccount[] {\n return this.messagingSystem.call(\n 'AccountsController:listMultichainAccounts',\n );\n }\n\n /**\n * Lists the accounts that we should get balances for.\n *\n * @returns A list of accounts that we should get balances for.\n */\n #listAccounts(): InternalAccount[] {\n const accounts = this.#listMultichainAccounts();\n return accounts.filter((account) => this.#isNonEvmAccount(account));\n }\n\n /**\n * Lists the accounts assets.\n *\n * @param accountId - The account ID.\n * @returns The list of assets for this account, returns an empty list if none.\n */\n #listAccountAssets(accountId: string): CaipAssetType[] {\n // TODO: Add an action `MultichainAssetsController:getAccountAssets` maybe?\n const assetsState = this.messagingSystem.call(\n 'MultichainAssetsController:getState',\n );\n\n return assetsState.accountsAssets[accountId] ?? [];\n }\n\n /**\n * Get a non-EVM account from its ID.\n *\n * @param accountId - The account ID.\n * @returns The non-EVM account.\n */\n #getAccount(accountId: string): InternalAccount {\n const account: InternalAccount | undefined = this.#listAccounts().find(\n (multichainAccount) => multichainAccount.id === accountId,\n );\n\n if (!account) {\n throw new Error(`Unknown account: ${accountId}`);\n }\n\n return account;\n }\n\n /**\n * Checks for non-EVM accounts.\n *\n * @param account - The new account to be checked.\n * @returns True if the account is a non-EVM account, false otherwise.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) &&\n // Non-EVM accounts are backed by a Snap for now\n account.metadata.snap !== undefined\n );\n }\n\n /**\n * Handles balance updates received from the AccountsController.\n *\n * @param balanceUpdate - The balance update event containing new balances.\n */\n #handleOnAccountBalancesUpdated(\n balanceUpdate: AccountBalancesUpdatedEventPayload,\n ): void {\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n Object.entries(balanceUpdate.balances).forEach(\n ([accountId, assetBalances]) => {\n if (accountId in state.balances) {\n Object.assign(state.balances[accountId], assetBalances);\n }\n },\n );\n });\n }\n\n /**\n * Handles changes when a new account has been removed.\n *\n * @param accountId - The account ID being removed.\n */\n async #handleOnAccountRemoved(accountId: string): Promise<void> {\n if (accountId in this.state.balances) {\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n delete state.balances[accountId];\n });\n }\n }\n\n /**\n * Get the balances for an account.\n *\n * @param accountId - ID of the account to get balances for.\n * @param snapId - ID of the Snap which manages the account.\n * @param assetTypes - Array of asset types to get balances for.\n * @returns A map of asset types to balances.\n */\n async #getBalances(\n accountId: string,\n snapId: string,\n assetTypes: CaipAssetType[],\n ): Promise<Record<CaipAssetType, Balance>> {\n return await this.#getClient(snapId).getAccountBalances(\n accountId,\n assetTypes,\n );\n }\n\n /**\n * Gets a `KeyringClient` for a Snap.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getClient(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) =>\n (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n })) as Promise<Json>,\n });\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"MultichainBalancesController.cjs","sourceRoot":"","sources":["../../src/MultichainBalancesController/MultichainBalancesController.ts"],"names":[],"mappings":";;;;;;;;;AAMA,+DAKmC;AACnC,uDAAyD;AAQzD,uEAA8D;AAG9D,uDAAoD;AASpD,MAAM,cAAc,GAAG,8BAA8B,CAAC;AAgBtD;;;;;;;GAOG;AACH,SAAgB,2CAA2C;IACzD,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC;AAC1B,CAAC;AAFD,kGAEC;AA4DD;;;;;;GAMG;AACH,MAAM,0BAA0B,GAAG;IACjC,QAAQ,EAAE;QACR,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AAEF;;;GAGG;AACH,MAAa,4BAA6B,SAAQ,gCAIjD;IACC,YAAY,EACV,SAAS,EACT,KAAK,GAAG,EAAE,GAIX;QACC,KAAK,CAAC;YACJ,SAAS;YACT,IAAI,EAAE,cAAc;YACpB,QAAQ,EAAE,0BAA0B;YACpC,KAAK,EAAE;gBACL,GAAG,2CAA2C,EAAE;gBAChD,GAAG,KAAK;aACT;SACF,CAAC,CAAC;;QAEH,kDAAkD;QAClD,KAAK,MAAM,OAAO,IAAI,uBAAA,IAAI,2FAAc,MAAlB,IAAI,CAAgB,EAAE;YAC1C,uEAAuE;YACvE,mCAAmC;YACnC,KAAK,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;SACrC;QAED,IAAI,CAAC,eAAe,CAAC,SAAS,CAC5B,mCAAmC,EACnC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,uBAAA,IAAI,qGAAwB,MAA5B,I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I,mCAAa,CAAC;QACvB,IAAI,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CACtC,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,8BAA8B,EAAE;YAC/D,MAAM,EAAE,MAAgB;YACxB,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,yBAAW,CAAC,gBAAgB;YACrC,OAAO;SACR,CAAC,CAAkB;KACvB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerListMultichainAccountsAction,\n AccountsControllerAccountBalancesUpdatesEvent,\n} from '@metamask/accounts-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n Balance,\n CaipAssetType,\n AccountBalancesUpdatedEventPayload,\n} from '@metamask/keyring-api';\nimport type { KeyringControllerGetStateAction } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n MultichainAssetsControllerGetStateAction,\n MultichainAssetsControllerAccountAssetListUpdatedEvent,\n} from '../MultichainAssetsController';\n\nconst controllerName = 'MultichainBalancesController';\n\n/**\n * State used by the {@link MultichainBalancesController} to cache account balances.\n */\nexport type MultichainBalancesControllerState = {\n balances: {\n [account: string]: {\n [asset: string]: {\n amount: string;\n unit: string;\n };\n };\n };\n};\n\n/**\n * Constructs the default {@link MultichainBalancesController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link MultichainBalancesController} state.\n */\nexport function getDefaultMultichainBalancesControllerState(): MultichainBalancesControllerState {\n return { balances: {} };\n}\n\n/**\n * Returns the state of the {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n MultichainBalancesControllerState\n >;\n\n/**\n * Event emitted when the state of the {@link MultichainBalancesController} changes.\n */\nexport type MultichainBalancesControllerStateChange =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainBalancesControllerState\n >;\n\n/**\n * Actions exposed by the {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerActions =\n MultichainBalancesControllerGetStateAction;\n\n/**\n * Events emitted by {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerEvents =\n MultichainBalancesControllerStateChange;\n\n/**\n * Actions that this controller is allowed to call.\n */\ntype AllowedActions =\n | HandleSnapRequest\n | AccountsControllerListMultichainAccountsAction\n | MultichainAssetsControllerGetStateAction\n | KeyringControllerGetStateAction;\n\n/**\n * Events that this controller is allowed to subscribe.\n */\ntype AllowedEvents =\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | AccountsControllerAccountBalancesUpdatesEvent\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n/**\n * Messenger type for the MultichainBalancesController.\n */\nexport type MultichainBalancesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n MultichainBalancesControllerActions | AllowedActions,\n MultichainBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * {@link MultichainBalancesController}'s metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst balancesControllerMetadata = {\n balances: {\n persist: true,\n anonymous: false,\n },\n};\n\n/**\n * The MultichainBalancesController is responsible for fetching and caching account\n * balances.\n */\nexport class MultichainBalancesController extends BaseController<\n typeof controllerName,\n MultichainBalancesControllerState,\n MultichainBalancesControllerMessenger\n> {\n constructor({\n messenger,\n state = {},\n }: {\n messenger: MultichainBalancesControllerMessenger;\n state?: Partial<MultichainBalancesControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: balancesControllerMetadata,\n state: {\n ...getDefaultMultichainBalancesControllerState(),\n ...state,\n },\n });\n\n // Fetch initial balances for all non-EVM accounts\n for (const account of this.#listAccounts()) {\n // Fetching the balance is asynchronous and we cannot use `await` here.\n // eslint-disable-next-line no-void\n void this.updateBalance(account.id);\n }\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRemoved',\n ({ id }) => this.#handleOnAccountRemoved(id),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountBalancesUpdated',\n (balanceUpdate: AccountBalancesUpdatedEventPayload) =>\n this.#handleOnAccountBalancesUpdated(balanceUpdate),\n );\n\n this.messagingSystem.subscribe(\n 'MultichainAssetsController:accountAssetListUpdated',\n async ({ assets }) => {\n const newAccountAssets = Object.entries(assets).map(\n ([accountId, { added }]) => ({\n accountId,\n assets: [...added],\n }),\n );\n await this.#handleOnAccountAssetListUpdated(newAccountAssets);\n },\n );\n }\n\n /**\n * Updates the balances for the given accounts.\n *\n * @param accounts - The accounts to update the balances for.\n */\n async #handleOnAccountAssetListUpdated(\n accounts: {\n accountId: string;\n assets: CaipAssetType[];\n }[],\n ): Promise<void> {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n\n if (!isUnlocked) {\n return;\n }\n const balancesToUpdate: MultichainBalancesControllerState['balances'] = {};\n\n for (const { accountId, assets } of accounts) {\n const account = this.#getAccount(accountId);\n if (account.metadata.snap) {\n const accountBalance = await this.#getBalances(\n account.id,\n account.metadata.snap.id,\n assets,\n );\n balancesToUpdate[accountId] = accountBalance;\n }\n }\n\n if (Object.keys(balancesToUpdate).length === 0) {\n return;\n }\n\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n for (const [accountId, accountBalances] of Object.entries(\n balancesToUpdate,\n )) {\n if (\n !state.balances[accountId] ||\n Object.keys(state.balances[accountId]).length === 0\n ) {\n state.balances[accountId] = accountBalances;\n } else {\n for (const assetId in accountBalances) {\n if (!state.balances[accountId][assetId]) {\n state.balances[accountId][assetId] = accountBalances[assetId];\n }\n }\n }\n }\n });\n }\n\n /**\n * Updates the balances of one account. This method doesn't return\n * anything, but it updates the state of the controller.\n *\n * @param accountId - The account ID.\n * @param assets - The list of asset types for this account to upadte.\n */\n async #updateBalance(\n accountId: string,\n assets: CaipAssetType[],\n ): Promise<void> {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n\n if (!isUnlocked) {\n return;\n }\n\n try {\n const account = this.#getAccount(accountId);\n\n if (account.metadata.snap) {\n const accountBalance = await this.#getBalances(\n account.id,\n account.metadata.snap.id,\n assets,\n );\n\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n state.balances[accountId] = accountBalance;\n });\n }\n } catch (error) {\n // FIXME: Maybe we shouldn't catch all errors here since this method is also being\n // used in the public methods. This means if something else uses `updateBalance` it\n // won't be able to catch and gets the error itself...\n console.error(\n `Failed to fetch balances for account ${accountId}:`,\n error,\n );\n }\n }\n\n /**\n * Updates the balances of one account. This method doesn't return\n * anything, but it updates the state of the controller.\n *\n * @param accountId - The account ID.\n */\n async updateBalance(accountId: string): Promise<void> {\n await this.#updateBalance(accountId, this.#listAccountAssets(accountId));\n }\n\n /**\n * Lists the multichain accounts coming from the `AccountsController`.\n *\n * @returns A list of multichain accounts.\n */\n #listMultichainAccounts(): InternalAccount[] {\n return this.messagingSystem.call(\n 'AccountsController:listMultichainAccounts',\n );\n }\n\n /**\n * Lists the accounts that we should get balances for.\n *\n * @returns A list of accounts that we should get balances for.\n */\n #listAccounts(): InternalAccount[] {\n const accounts = this.#listMultichainAccounts();\n return accounts.filter((account) => this.#isNonEvmAccount(account));\n }\n\n /**\n * Lists the accounts assets.\n *\n * @param accountId - The account ID.\n * @returns The list of assets for this account, returns an empty list if none.\n */\n #listAccountAssets(accountId: string): CaipAssetType[] {\n // TODO: Add an action `MultichainAssetsController:getAccountAssets` maybe?\n const assetsState = this.messagingSystem.call(\n 'MultichainAssetsController:getState',\n );\n\n return assetsState.accountsAssets[accountId] ?? [];\n }\n\n /**\n * Get a non-EVM account from its ID.\n *\n * @param accountId - The account ID.\n * @returns The non-EVM account.\n */\n #getAccount(accountId: string): InternalAccount {\n const account: InternalAccount | undefined = this.#listAccounts().find(\n (multichainAccount) => multichainAccount.id === accountId,\n );\n\n if (!account) {\n throw new Error(`Unknown account: ${accountId}`);\n }\n\n return account;\n }\n\n /**\n * Checks for non-EVM accounts.\n *\n * @param account - The new account to be checked.\n * @returns True if the account is a non-EVM account, false otherwise.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) &&\n // Non-EVM accounts are backed by a Snap for now\n account.metadata.snap !== undefined\n );\n }\n\n /**\n * Handles balance updates received from the AccountsController.\n *\n * @param balanceUpdate - The balance update event containing new balances.\n */\n #handleOnAccountBalancesUpdated(\n balanceUpdate: AccountBalancesUpdatedEventPayload,\n ): void {\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n Object.entries(balanceUpdate.balances).forEach(\n ([accountId, assetBalances]) => {\n if (accountId in state.balances) {\n Object.assign(state.balances[accountId], assetBalances);\n }\n },\n );\n });\n }\n\n /**\n * Handles changes when a new account has been removed.\n *\n * @param accountId - The account ID being removed.\n */\n async #handleOnAccountRemoved(accountId: string): Promise<void> {\n if (accountId in this.state.balances) {\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n delete state.balances[accountId];\n });\n }\n }\n\n /**\n * Get the balances for an account.\n *\n * @param accountId - ID of the account to get balances for.\n * @param snapId - ID of the Snap which manages the account.\n * @param assetTypes - Array of asset types to get balances for.\n * @returns A map of asset types to balances.\n */\n async #getBalances(\n accountId: string,\n snapId: string,\n assetTypes: CaipAssetType[],\n ): Promise<Record<CaipAssetType, Balance>> {\n return await this.#getClient(snapId).getAccountBalances(\n accountId,\n assetTypes,\n );\n }\n\n /**\n * Gets a `KeyringClient` for a Snap.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getClient(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) =>\n (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n })) as Promise<Json>,\n });\n }\n}\n"]}
|
@@ -55,7 +55,7 @@ export class MultichainBalancesController extends BaseController {
|
|
55
55
|
// eslint-disable-next-line no-void
|
56
56
|
void this.updateBalance(account.id);
|
57
57
|
}
|
58
|
-
this.messagingSystem.subscribe('AccountsController:accountRemoved', (
|
58
|
+
this.messagingSystem.subscribe('AccountsController:accountRemoved', ({ id }) => __classPrivateFieldGet(this, _MultichainBalancesController_instances, "m", _MultichainBalancesController_handleOnAccountRemoved).call(this, id));
|
59
59
|
this.messagingSystem.subscribe('AccountsController:accountBalancesUpdated', (balanceUpdate) => __classPrivateFieldGet(this, _MultichainBalancesController_instances, "m", _MultichainBalancesController_handleOnAccountBalancesUpdated).call(this, balanceUpdate));
|
60
60
|
this.messagingSystem.subscribe('MultichainAssetsController:accountAssetListUpdated', async ({ assets }) => {
|
61
61
|
const newAccountAssets = Object.entries(assets).map(([accountId, { added }]) => ({
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"MultichainBalancesController.mjs","sourceRoot":"","sources":["../../src/MultichainBalancesController/MultichainBalancesController.ts"],"names":[],"mappings":";;;;;;AAMA,OAAO,EACL,cAAc,EAIf,kCAAkC;AACnC,OAAO,EAAE,gBAAgB,EAAE,8BAA8B;AAQzD,OAAO,EAAE,aAAa,EAAE,sCAAsC;AAG9D,OAAO,EAAE,WAAW,EAAE,8BAA8B;AASpD,MAAM,cAAc,GAAG,8BAA8B,CAAC;AAgBtD;;;;;;;GAOG;AACH,MAAM,UAAU,2CAA2C;IACzD,OAAO,EAAE,QAAQ,EAAE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EAAE,aAAa,CAAC,EAAE,EAAE;YAC7B,IAAI,SAAS,IAAI,KAAK,CAAC,QAAQ,EAAE;gBAC/B,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,aAAa,CAAC,CAAC;aACzD;QACH,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,KAAK,+DAAyB,SAAiB;IAC7C,IAAI,SAAS,IAAI,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE;QACpC,IAAI,CAAC,MAAM,CAAC,CAAC,KAA+C,EAAE,EAAE;YAC9D,OAAO,KAAK,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;QACnC,CAAC,CAAC,CAAC;KACJ;AACH,CAAC;AAED;;;;;;;GAOG;AACH,KAAK,oDACH,SAAiB,EACjB,MAAc,EACd,UAA2B;IAE3B,OAAO,MAAM,uBAAA,IAAI,wFAAW,MAAf,IAAI,EAAY,MAAM,CAAC,CAAC,kBAAkB,CACrD,SAAS,EACT,UAAU,CACX,CAAC;AACJ,CAAC,6FAQU,MAAc;IACvB,OAAO,IAAI,aAAa,CAAC;QACvB,IAAI,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CACtC,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,8BAA8B,EAAE;YAC/D,MAAM,EAAE,MAAgB;YACxB,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,WAAW,CAAC,gBAAgB;YACrC,OAAO;SACR,CAAC,CAAkB;KACvB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerListMultichainAccountsAction,\n AccountsControllerAccountBalancesUpdatesEvent,\n} from '@metamask/accounts-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n Balance,\n CaipAssetType,\n AccountBalancesUpdatedEventPayload,\n} from '@metamask/keyring-api';\nimport type { KeyringControllerGetStateAction } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n MultichainAssetsControllerGetStateAction,\n MultichainAssetsControllerAccountAssetListUpdatedEvent,\n} from '../MultichainAssetsController';\n\nconst controllerName = 'MultichainBalancesController';\n\n/**\n * State used by the {@link MultichainBalancesController} to cache account balances.\n */\nexport type MultichainBalancesControllerState = {\n balances: {\n [account: string]: {\n [asset: string]: {\n amount: string;\n unit: string;\n };\n };\n };\n};\n\n/**\n * Constructs the default {@link MultichainBalancesController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link MultichainBalancesController} state.\n */\nexport function getDefaultMultichainBalancesControllerState(): MultichainBalancesControllerState {\n return { balances: {} };\n}\n\n/**\n * Returns the state of the {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n MultichainBalancesControllerState\n >;\n\n/**\n * Event emitted when the state of the {@link MultichainBalancesController} changes.\n */\nexport type MultichainBalancesControllerStateChange =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainBalancesControllerState\n >;\n\n/**\n * Actions exposed by the {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerActions =\n MultichainBalancesControllerGetStateAction;\n\n/**\n * Events emitted by {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerEvents =\n MultichainBalancesControllerStateChange;\n\n/**\n * Actions that this controller is allowed to call.\n */\ntype AllowedActions =\n | HandleSnapRequest\n | AccountsControllerListMultichainAccountsAction\n | MultichainAssetsControllerGetStateAction\n | KeyringControllerGetStateAction;\n\n/**\n * Events that this controller is allowed to subscribe.\n */\ntype AllowedEvents =\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | AccountsControllerAccountBalancesUpdatesEvent\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n/**\n * Messenger type for the MultichainBalancesController.\n */\nexport type MultichainBalancesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n MultichainBalancesControllerActions | AllowedActions,\n MultichainBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * {@link MultichainBalancesController}'s metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst balancesControllerMetadata = {\n balances: {\n persist: true,\n anonymous: false,\n },\n};\n\n/**\n * The MultichainBalancesController is responsible for fetching and caching account\n * balances.\n */\nexport class MultichainBalancesController extends BaseController<\n typeof controllerName,\n MultichainBalancesControllerState,\n MultichainBalancesControllerMessenger\n> {\n constructor({\n messenger,\n state = {},\n }: {\n messenger: MultichainBalancesControllerMessenger;\n state?: Partial<MultichainBalancesControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: balancesControllerMetadata,\n state: {\n ...getDefaultMultichainBalancesControllerState(),\n ...state,\n },\n });\n\n // Fetch initial balances for all non-EVM accounts\n for (const account of this.#listAccounts()) {\n // Fetching the balance is asynchronous and we cannot use `await` here.\n // eslint-disable-next-line no-void\n void this.updateBalance(account.id);\n }\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRemoved',\n (account: string) => this.#handleOnAccountRemoved(account),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountBalancesUpdated',\n (balanceUpdate: AccountBalancesUpdatedEventPayload) =>\n this.#handleOnAccountBalancesUpdated(balanceUpdate),\n );\n\n this.messagingSystem.subscribe(\n 'MultichainAssetsController:accountAssetListUpdated',\n async ({ assets }) => {\n const newAccountAssets = Object.entries(assets).map(\n ([accountId, { added }]) => ({\n accountId,\n assets: [...added],\n }),\n );\n await this.#handleOnAccountAssetListUpdated(newAccountAssets);\n },\n );\n }\n\n /**\n * Updates the balances for the given accounts.\n *\n * @param accounts - The accounts to update the balances for.\n */\n async #handleOnAccountAssetListUpdated(\n accounts: {\n accountId: string;\n assets: CaipAssetType[];\n }[],\n ): Promise<void> {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n\n if (!isUnlocked) {\n return;\n }\n const balancesToUpdate: MultichainBalancesControllerState['balances'] = {};\n\n for (const { accountId, assets } of accounts) {\n const account = this.#getAccount(accountId);\n if (account.metadata.snap) {\n const accountBalance = await this.#getBalances(\n account.id,\n account.metadata.snap.id,\n assets,\n );\n balancesToUpdate[accountId] = accountBalance;\n }\n }\n\n if (Object.keys(balancesToUpdate).length === 0) {\n return;\n }\n\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n for (const [accountId, accountBalances] of Object.entries(\n balancesToUpdate,\n )) {\n if (\n !state.balances[accountId] ||\n Object.keys(state.balances[accountId]).length === 0\n ) {\n state.balances[accountId] = accountBalances;\n } else {\n for (const assetId in accountBalances) {\n if (!state.balances[accountId][assetId]) {\n state.balances[accountId][assetId] = accountBalances[assetId];\n }\n }\n }\n }\n });\n }\n\n /**\n * Updates the balances of one account. This method doesn't return\n * anything, but it updates the state of the controller.\n *\n * @param accountId - The account ID.\n * @param assets - The list of asset types for this account to upadte.\n */\n async #updateBalance(\n accountId: string,\n assets: CaipAssetType[],\n ): Promise<void> {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n\n if (!isUnlocked) {\n return;\n }\n\n try {\n const account = this.#getAccount(accountId);\n\n if (account.metadata.snap) {\n const accountBalance = await this.#getBalances(\n account.id,\n account.metadata.snap.id,\n assets,\n );\n\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n state.balances[accountId] = accountBalance;\n });\n }\n } catch (error) {\n // FIXME: Maybe we shouldn't catch all errors here since this method is also being\n // used in the public methods. This means if something else uses `updateBalance` it\n // won't be able to catch and gets the error itself...\n console.error(\n `Failed to fetch balances for account ${accountId}:`,\n error,\n );\n }\n }\n\n /**\n * Updates the balances of one account. This method doesn't return\n * anything, but it updates the state of the controller.\n *\n * @param accountId - The account ID.\n */\n async updateBalance(accountId: string): Promise<void> {\n await this.#updateBalance(accountId, this.#listAccountAssets(accountId));\n }\n\n /**\n * Lists the multichain accounts coming from the `AccountsController`.\n *\n * @returns A list of multichain accounts.\n */\n #listMultichainAccounts(): InternalAccount[] {\n return this.messagingSystem.call(\n 'AccountsController:listMultichainAccounts',\n );\n }\n\n /**\n * Lists the accounts that we should get balances for.\n *\n * @returns A list of accounts that we should get balances for.\n */\n #listAccounts(): InternalAccount[] {\n const accounts = this.#listMultichainAccounts();\n return accounts.filter((account) => this.#isNonEvmAccount(account));\n }\n\n /**\n * Lists the accounts assets.\n *\n * @param accountId - The account ID.\n * @returns The list of assets for this account, returns an empty list if none.\n */\n #listAccountAssets(accountId: string): CaipAssetType[] {\n // TODO: Add an action `MultichainAssetsController:getAccountAssets` maybe?\n const assetsState = this.messagingSystem.call(\n 'MultichainAssetsController:getState',\n );\n\n return assetsState.accountsAssets[accountId] ?? [];\n }\n\n /**\n * Get a non-EVM account from its ID.\n *\n * @param accountId - The account ID.\n * @returns The non-EVM account.\n */\n #getAccount(accountId: string): InternalAccount {\n const account: InternalAccount | undefined = this.#listAccounts().find(\n (multichainAccount) => multichainAccount.id === accountId,\n );\n\n if (!account) {\n throw new Error(`Unknown account: ${accountId}`);\n }\n\n return account;\n }\n\n /**\n * Checks for non-EVM accounts.\n *\n * @param account - The new account to be checked.\n * @returns True if the account is a non-EVM account, false otherwise.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) &&\n // Non-EVM accounts are backed by a Snap for now\n account.metadata.snap !== undefined\n );\n }\n\n /**\n * Handles balance updates received from the AccountsController.\n *\n * @param balanceUpdate - The balance update event containing new balances.\n */\n #handleOnAccountBalancesUpdated(\n balanceUpdate: AccountBalancesUpdatedEventPayload,\n ): void {\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n Object.entries(balanceUpdate.balances).forEach(\n ([accountId, assetBalances]) => {\n if (accountId in state.balances) {\n Object.assign(state.balances[accountId], assetBalances);\n }\n },\n );\n });\n }\n\n /**\n * Handles changes when a new account has been removed.\n *\n * @param accountId - The account ID being removed.\n */\n async #handleOnAccountRemoved(accountId: string): Promise<void> {\n if (accountId in this.state.balances) {\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n delete state.balances[accountId];\n });\n }\n }\n\n /**\n * Get the balances for an account.\n *\n * @param accountId - ID of the account to get balances for.\n * @param snapId - ID of the Snap which manages the account.\n * @param assetTypes - Array of asset types to get balances for.\n * @returns A map of asset types to balances.\n */\n async #getBalances(\n accountId: string,\n snapId: string,\n assetTypes: CaipAssetType[],\n ): Promise<Record<CaipAssetType, Balance>> {\n return await this.#getClient(snapId).getAccountBalances(\n accountId,\n assetTypes,\n );\n }\n\n /**\n * Gets a `KeyringClient` for a Snap.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getClient(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) =>\n (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n })) as Promise<Json>,\n });\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"MultichainBalancesController.mjs","sourceRoot":"","sources":["../../src/MultichainBalancesController/MultichainBalancesController.ts"],"names":[],"mappings":";;;;;;AAMA,OAAO,EACL,cAAc,EAIf,kCAAkC;AACnC,OAAO,EAAE,gBAAgB,EAAE,8BAA8B;AAQzD,OAAO,EAAE,aAAa,EAAE,sCAAsC;A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ControllerListMultichainAccountsAction,\n AccountsControllerAccountBalancesUpdatesEvent,\n} from '@metamask/accounts-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n Balance,\n CaipAssetType,\n AccountBalancesUpdatedEventPayload,\n} from '@metamask/keyring-api';\nimport type { KeyringControllerGetStateAction } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n MultichainAssetsControllerGetStateAction,\n MultichainAssetsControllerAccountAssetListUpdatedEvent,\n} from '../MultichainAssetsController';\n\nconst controllerName = 'MultichainBalancesController';\n\n/**\n * State used by the {@link MultichainBalancesController} to cache account balances.\n */\nexport type MultichainBalancesControllerState = {\n balances: {\n [account: string]: {\n [asset: string]: {\n amount: string;\n unit: string;\n };\n };\n };\n};\n\n/**\n * Constructs the default {@link MultichainBalancesController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link MultichainBalancesController} state.\n */\nexport function getDefaultMultichainBalancesControllerState(): MultichainBalancesControllerState {\n return { balances: {} };\n}\n\n/**\n * Returns the state of the {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n MultichainBalancesControllerState\n >;\n\n/**\n * Event emitted when the state of the {@link MultichainBalancesController} changes.\n */\nexport type MultichainBalancesControllerStateChange =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainBalancesControllerState\n >;\n\n/**\n * Actions exposed by the {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerActions =\n MultichainBalancesControllerGetStateAction;\n\n/**\n * Events emitted by {@link MultichainBalancesController}.\n */\nexport type MultichainBalancesControllerEvents =\n MultichainBalancesControllerStateChange;\n\n/**\n * Actions that this controller is allowed to call.\n */\ntype AllowedActions =\n | HandleSnapRequest\n | AccountsControllerListMultichainAccountsAction\n | MultichainAssetsControllerGetStateAction\n | KeyringControllerGetStateAction;\n\n/**\n * Events that this controller is allowed to subscribe.\n */\ntype AllowedEvents =\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | AccountsControllerAccountBalancesUpdatesEvent\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n/**\n * Messenger type for the MultichainBalancesController.\n */\nexport type MultichainBalancesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n MultichainBalancesControllerActions | AllowedActions,\n MultichainBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * {@link MultichainBalancesController}'s metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst balancesControllerMetadata = {\n balances: {\n persist: true,\n anonymous: false,\n },\n};\n\n/**\n * The MultichainBalancesController is responsible for fetching and caching account\n * balances.\n */\nexport class MultichainBalancesController extends BaseController<\n typeof controllerName,\n MultichainBalancesControllerState,\n MultichainBalancesControllerMessenger\n> {\n constructor({\n messenger,\n state = {},\n }: {\n messenger: MultichainBalancesControllerMessenger;\n state?: Partial<MultichainBalancesControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: balancesControllerMetadata,\n state: {\n ...getDefaultMultichainBalancesControllerState(),\n ...state,\n },\n });\n\n // Fetch initial balances for all non-EVM accounts\n for (const account of this.#listAccounts()) {\n // Fetching the balance is asynchronous and we cannot use `await` here.\n // eslint-disable-next-line no-void\n void this.updateBalance(account.id);\n }\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRemoved',\n ({ id }) => this.#handleOnAccountRemoved(id),\n );\n this.messagingSystem.subscribe(\n 'AccountsController:accountBalancesUpdated',\n (balanceUpdate: AccountBalancesUpdatedEventPayload) =>\n this.#handleOnAccountBalancesUpdated(balanceUpdate),\n );\n\n this.messagingSystem.subscribe(\n 'MultichainAssetsController:accountAssetListUpdated',\n async ({ assets }) => {\n const newAccountAssets = Object.entries(assets).map(\n ([accountId, { added }]) => ({\n accountId,\n assets: [...added],\n }),\n );\n await this.#handleOnAccountAssetListUpdated(newAccountAssets);\n },\n );\n }\n\n /**\n * Updates the balances for the given accounts.\n *\n * @param accounts - The accounts to update the balances for.\n */\n async #handleOnAccountAssetListUpdated(\n accounts: {\n accountId: string;\n assets: CaipAssetType[];\n }[],\n ): Promise<void> {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n\n if (!isUnlocked) {\n return;\n }\n const balancesToUpdate: MultichainBalancesControllerState['balances'] = {};\n\n for (const { accountId, assets } of accounts) {\n const account = this.#getAccount(accountId);\n if (account.metadata.snap) {\n const accountBalance = await this.#getBalances(\n account.id,\n account.metadata.snap.id,\n assets,\n );\n balancesToUpdate[accountId] = accountBalance;\n }\n }\n\n if (Object.keys(balancesToUpdate).length === 0) {\n return;\n }\n\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n for (const [accountId, accountBalances] of Object.entries(\n balancesToUpdate,\n )) {\n if (\n !state.balances[accountId] ||\n Object.keys(state.balances[accountId]).length === 0\n ) {\n state.balances[accountId] = accountBalances;\n } else {\n for (const assetId in accountBalances) {\n if (!state.balances[accountId][assetId]) {\n state.balances[accountId][assetId] = accountBalances[assetId];\n }\n }\n }\n }\n });\n }\n\n /**\n * Updates the balances of one account. This method doesn't return\n * anything, but it updates the state of the controller.\n *\n * @param accountId - The account ID.\n * @param assets - The list of asset types for this account to upadte.\n */\n async #updateBalance(\n accountId: string,\n assets: CaipAssetType[],\n ): Promise<void> {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n\n if (!isUnlocked) {\n return;\n }\n\n try {\n const account = this.#getAccount(accountId);\n\n if (account.metadata.snap) {\n const accountBalance = await this.#getBalances(\n account.id,\n account.metadata.snap.id,\n assets,\n );\n\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n state.balances[accountId] = accountBalance;\n });\n }\n } catch (error) {\n // FIXME: Maybe we shouldn't catch all errors here since this method is also being\n // used in the public methods. This means if something else uses `updateBalance` it\n // won't be able to catch and gets the error itself...\n console.error(\n `Failed to fetch balances for account ${accountId}:`,\n error,\n );\n }\n }\n\n /**\n * Updates the balances of one account. This method doesn't return\n * anything, but it updates the state of the controller.\n *\n * @param accountId - The account ID.\n */\n async updateBalance(accountId: string): Promise<void> {\n await this.#updateBalance(accountId, this.#listAccountAssets(accountId));\n }\n\n /**\n * Lists the multichain accounts coming from the `AccountsController`.\n *\n * @returns A list of multichain accounts.\n */\n #listMultichainAccounts(): InternalAccount[] {\n return this.messagingSystem.call(\n 'AccountsController:listMultichainAccounts',\n );\n }\n\n /**\n * Lists the accounts that we should get balances for.\n *\n * @returns A list of accounts that we should get balances for.\n */\n #listAccounts(): InternalAccount[] {\n const accounts = this.#listMultichainAccounts();\n return accounts.filter((account) => this.#isNonEvmAccount(account));\n }\n\n /**\n * Lists the accounts assets.\n *\n * @param accountId - The account ID.\n * @returns The list of assets for this account, returns an empty list if none.\n */\n #listAccountAssets(accountId: string): CaipAssetType[] {\n // TODO: Add an action `MultichainAssetsController:getAccountAssets` maybe?\n const assetsState = this.messagingSystem.call(\n 'MultichainAssetsController:getState',\n );\n\n return assetsState.accountsAssets[accountId] ?? [];\n }\n\n /**\n * Get a non-EVM account from its ID.\n *\n * @param accountId - The account ID.\n * @returns The non-EVM account.\n */\n #getAccount(accountId: string): InternalAccount {\n const account: InternalAccount | undefined = this.#listAccounts().find(\n (multichainAccount) => multichainAccount.id === accountId,\n );\n\n if (!account) {\n throw new Error(`Unknown account: ${accountId}`);\n }\n\n return account;\n }\n\n /**\n * Checks for non-EVM accounts.\n *\n * @param account - The new account to be checked.\n * @returns True if the account is a non-EVM account, false otherwise.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) &&\n // Non-EVM accounts are backed by a Snap for now\n account.metadata.snap !== undefined\n );\n }\n\n /**\n * Handles balance updates received from the AccountsController.\n *\n * @param balanceUpdate - The balance update event containing new balances.\n */\n #handleOnAccountBalancesUpdated(\n balanceUpdate: AccountBalancesUpdatedEventPayload,\n ): void {\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n Object.entries(balanceUpdate.balances).forEach(\n ([accountId, assetBalances]) => {\n if (accountId in state.balances) {\n Object.assign(state.balances[accountId], assetBalances);\n }\n },\n );\n });\n }\n\n /**\n * Handles changes when a new account has been removed.\n *\n * @param accountId - The account ID being removed.\n */\n async #handleOnAccountRemoved(accountId: string): Promise<void> {\n if (accountId in this.state.balances) {\n this.update((state: Draft<MultichainBalancesControllerState>) => {\n delete state.balances[accountId];\n });\n }\n }\n\n /**\n * Get the balances for an account.\n *\n * @param accountId - ID of the account to get balances for.\n * @param snapId - ID of the Snap which manages the account.\n * @param assetTypes - Array of asset types to get balances for.\n * @returns A map of asset types to balances.\n */\n async #getBalances(\n accountId: string,\n snapId: string,\n assetTypes: CaipAssetType[],\n ): Promise<Record<CaipAssetType, Balance>> {\n return await this.#getClient(snapId).getAccountBalances(\n accountId,\n assetTypes,\n );\n }\n\n /**\n * Gets a `KeyringClient` for a Snap.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getClient(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) =>\n (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n })) as Promise<Json>,\n });\n }\n}\n"]}
|
@@ -132,7 +132,7 @@ class TokenBalancesController extends (0, polling_controller_1.StaticIntervalPol
|
|
132
132
|
// Subscribe to network state changes
|
133
133
|
this.messagingSystem.subscribe('NetworkController:stateChange', __classPrivateFieldGet(this, _TokenBalancesController_instances, "m", _TokenBalancesController_onNetworkStateChange).bind(this));
|
134
134
|
// subscribe to account removed event to cleanup stale balances
|
135
|
-
this.messagingSystem.subscribe('AccountsController:accountRemoved', (
|
135
|
+
this.messagingSystem.subscribe('AccountsController:accountRemoved', ({ address }) => __classPrivateFieldGet(this, _TokenBalancesController_instances, "m", _TokenBalancesController_handleOnAccountRemoved).call(this, address));
|
136
136
|
}
|
137
137
|
/**
|
138
138
|
* Polls for erc20 token balances.
|
@@ -230,12 +230,7 @@ _TokenBalancesController_queryMultipleAccounts = new WeakMap(), _TokenBalancesCo
|
|
230
230
|
});
|
231
231
|
}
|
232
232
|
}
|
233
|
-
}, _TokenBalancesController_handleOnAccountRemoved = function _TokenBalancesController_handleOnAccountRemoved(
|
234
|
-
const accounts = this.messagingSystem.call('AccountsController:listAccounts');
|
235
|
-
const accountAddress = accounts.find((account) => account.id === accountId)?.address;
|
236
|
-
if (!accountAddress) {
|
237
|
-
return;
|
238
|
-
}
|
233
|
+
}, _TokenBalancesController_handleOnAccountRemoved = function _TokenBalancesController_handleOnAccountRemoved(accountAddress) {
|
239
234
|
this.update((state) => {
|
240
235
|
delete state.tokenBalances[accountAddress];
|
241
236
|
});
|