Skip to content

Commit

Permalink
feat: add accountAdded and accountRemoved events (#4496)
Browse files Browse the repository at this point in the history
## Explanation

This PR adds the following events to the `AccountsController`,
`accountAdded` and `accountRemoved`.

<!--
Thanks for your contribution! Take a moment to answer these questions so
that reviewers have the information they need to properly understand
your changes:

* What is the current state of things and why does it need to change?
* What is the solution your changes offer and how does it work?
* Are there any changes whose purpose might not obvious to those
unfamiliar with the domain?
* If your primary goal was to update one package but you found you had
to update another one along the way, why did you do so?
* If you had to upgrade a dependency, why did you do so?
-->

## References

<!--
Are there any issues that this pull request is tied to? Are there other
links that reviewers should consult to understand these changes better?

For example:

* Fixes #12345
* Related to #67890
-->

## Changelog

<!--
If you're making any consumer-facing changes, list those changes here as
if you were updating a changelog, using the template below as a guide.

(CATEGORY is one of BREAKING, ADDED, CHANGED, DEPRECATED, REMOVED, or
FIXED. For security-related issues, follow the Security Advisory
process.)

Please take care to name the exact pieces of the API you've added or
changed (e.g. types, interfaces, functions, or methods).

If there are any breaking changes, make sure to offer a solution for
consumers to follow once they upgrade to the changes.

Finally, if you're only making changes to development scripts or tests,
you may replace the template below with "None".
-->

### `@metamask/accounts-controller`

- **ADDED**: Adds `accountAdded` and `accountRemoved` events. 

## Checklist

- [x] I've updated the test suite for new or updated code as appropriate
- [x] I've updated documentation (JSDoc, Markdown, etc.) for new or
updated code as appropriate
- [ ] I've highlighted breaking changes using the "BREAKING" category
above as appropriate

---------

Co-authored-by: Charly Chevalier <charly.chevalier@consensys.net>
  • Loading branch information
montelaidev and ccharly authored Jul 3, 2024
1 parent cb11300 commit 5bc1150
Show file tree
Hide file tree
Showing 3 changed files with 119 additions and 3 deletions.
88 changes: 88 additions & 0 deletions packages/accounts-controller/src/AccountsController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,50 @@ describe('AccountsController', () => {
]);
expect(accountsController.getSelectedAccount().id).toBe(mockAccount.id);
});

it('publishes accountAdded event', async () => {
const messenger = buildMessenger();
const messengerSpy = jest.spyOn(messenger, 'publish');
mockUUID
.mockReturnValueOnce(mockAccount.id) // call to check if its a new account
.mockReturnValueOnce(mockAccount2.id) // call to check if its a new account
.mockReturnValueOnce(mockAccount2.id); // call to add account

setupAccountsController({
initialState: {
internalAccounts: {
accounts: {
[mockAccount.id]: mockAccount,
},
selectedAccount: mockAccount.id,
},
},
messenger,
});

const mockNewKeyringState = {
isUnlocked: true,
keyrings: [
{
type: KeyringTypes.hd,
accounts: [mockAccount.address, mockAccount2.address],
},
],
};

messenger.publish(
'KeyringController:stateChange',
mockNewKeyringState,
[],
);

// First call is 'KeyringController:stateChange'
expect(messengerSpy).toHaveBeenNthCalledWith(
2,
'AccountsController:accountAdded',
setLastSelectedAsAny(mockAccount2),
);
});
});

describe('deleting account', () => {
Expand Down Expand Up @@ -1155,6 +1199,50 @@ describe('AccountsController', () => {
currentTime,
);
});

it('publishes accountRemoved event', async () => {
const messenger = buildMessenger();
const messengerSpy = jest.spyOn(messenger, 'publish');
mockUUID
.mockReturnValueOnce(mockAccount.id) // call to check if its a new account
.mockReturnValueOnce(mockAccount2.id) // call to check if its a new account
.mockReturnValueOnce(mockAccount2.id); // call to add account

setupAccountsController({
initialState: {
internalAccounts: {
accounts: {
[mockAccount.id]: mockAccount,
[mockAccount3.id]: mockAccount3,
},
selectedAccount: mockAccount.id,
},
},
messenger,
});

const mockNewKeyringState = {
isUnlocked: true,
keyrings: [
{
type: KeyringTypes.hd,
accounts: [mockAccount.address, mockAccount2.address],
},
],
};
messenger.publish(
'KeyringController:stateChange',
mockNewKeyringState,
[],
);

// First call is 'KeyringController:stateChange'
expect(messengerSpy).toHaveBeenNthCalledWith(
2,
'AccountsController:accountRemoved',
mockAccount3.id,
);
});
});

it('handle keyring reinitialization', async () => {
Expand Down
32 changes: 29 additions & 3 deletions packages/accounts-controller/src/AccountsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ import {

const controllerName = 'AccountsController';

export type AccountId = string;

export type AccountsControllerState = {
internalAccounts: {
accounts: Record<string, InternalAccount>;
accounts: Record<AccountId, InternalAccount>;
selectedAccount: string; // id of the selected account
};
};
Expand Down Expand Up @@ -137,12 +139,24 @@ export type AccountsControllerSelectedEvmAccountChangeEvent = {
payload: [InternalAccount];
};

export type AccountsControllerAccountAddedEvent = {
type: `${typeof controllerName}:accountAdded`;
payload: [InternalAccount];
};

export type AccountsControllerAccountRemovedEvent = {
type: `${typeof controllerName}:accountRemoved`;
payload: [AccountId];
};

export type AllowedEvents = SnapStateChange | KeyringControllerStateChangeEvent;

export type AccountsControllerEvents =
| AccountsControllerChangeEvent
| AccountsControllerSelectedAccountChangeEvent
| AccountsControllerSelectedEvmAccountChangeEvent;
| AccountsControllerSelectedEvmAccountChangeEvent
| AccountsControllerAccountAddedEvent
| AccountsControllerAccountRemovedEvent;

export type AccountsControllerMessenger = RestrictedControllerMessenger<
typeof controllerName,
Expand Down Expand Up @@ -951,7 +965,7 @@ export class AccountsController extends BaseController<
Object.values(accountsState),
);

accountsState[newAccount.id] = {
const newAccountWithUpdatedMetadata = {
...newAccount,
metadata: {
...newAccount.metadata,
Expand All @@ -960,6 +974,12 @@ export class AccountsController extends BaseController<
lastSelected: isFirstAccount ? this.#getLastSelectedIndex() : 0,
},
};
accountsState[newAccount.id] = newAccountWithUpdatedMetadata;

this.messagingSystem.publish(
'AccountsController:accountAdded',
newAccountWithUpdatedMetadata,
);

return accountsState;
}
Expand Down Expand Up @@ -988,6 +1008,12 @@ export class AccountsController extends BaseController<
accountId: string,
): AccountsControllerState['internalAccounts']['accounts'] {
delete accountsState[accountId];

this.messagingSystem.publish(
'AccountsController:accountRemoved',
accountId,
);

return accountsState;
}

Expand Down
2 changes: 2 additions & 0 deletions packages/accounts-controller/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export type {
AccountsControllerChangeEvent,
AccountsControllerSelectedAccountChangeEvent,
AccountsControllerSelectedEvmAccountChangeEvent,
AccountsControllerAccountAddedEvent,
AccountsControllerAccountRemovedEvent,
AccountsControllerEvents,
AccountsControllerMessenger,
} from './AccountsController';
Expand Down

0 comments on commit 5bc1150

Please sign in to comment.