Skip to content

chore: adds new initialize method and cleans constructor #5781

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/assets-controllers/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- Improve controller constructor by moving async logic to it's own method ([#5781](https://github.com/MetaMask/core/pull/5781))
- Updated `TokenListController` `fetchTokenList` method to bail if cache is valid ([#5804](https://github.com/MetaMask/core/pull/5804))
- also cleaned up internal state update logic
- Bump `@metamask/controller-utils` to `^11.9.0` ([#5812](https://github.com/MetaMask/core/pull/5812))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,9 @@ describe('MultichainBalancesController', () => {

it('stores balances when receiving new balances from the "AccountsController:accountBalancesUpdated" event', async () => {
const { controller, messenger } = setupController();

await controller.initialize();

const balanceUpdate = {
balances: {
[mockBtcAccount.id]: mockBalanceResult,
Expand Down Expand Up @@ -403,6 +406,8 @@ describe('MultichainBalancesController', () => {
},
});

await controller.initialize();

await waitForAllPromises();

expect(controller.state.balances[mockBtcAccount.id]).toStrictEqual(
Expand Down Expand Up @@ -573,6 +578,8 @@ describe('MultichainBalancesController', () => {
},
});

await controller.initialize();

mockSnapHandleRequest.mockReset();
mockListMultichainAccounts.mockReset();

Expand Down Expand Up @@ -642,4 +649,52 @@ describe('MultichainBalancesController', () => {
mockBalanceResult,
);
});

it('initializes by fetching balances for non-EVM accounts', async () => {
const { controller, mockSnapHandleRequest } = setupController({
mocks: {
listMultichainAccounts: [mockBtcAccount],
},
});

expect(controller.state.balances).toStrictEqual({});

await controller.initialize();
await waitForAllPromises();

expect(mockSnapHandleRequest).toHaveBeenCalled();
expect(controller.state.balances[mockBtcAccount.id]).toStrictEqual(
mockBalanceResult,
);
});

it('handles errors during initialization', async () => {
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation();

const initError = new Error('Test initialization error');

const { controller, mockListMultichainAccounts } = setupController({
mocks: {
listMultichainAccounts: [mockBtcAccount],
},
});

mockListMultichainAccounts.mockReturnValue([mockBtcAccount]);

const updateSpy = jest.spyOn(controller, 'updateBalance');
updateSpy.mockRejectedValue(initError);

await controller.initialize();
await waitForAllPromises();

expect(consoleErrorSpy).toHaveBeenCalledWith(
`Failed to fetch initial balances for account ${mockBtcAccount.id}:`,
initError,
);

expect(controller.state.balances).toStrictEqual({});

updateSpy.mockRestore();
consoleErrorSpy.mockRestore();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,6 @@ export class MultichainBalancesController extends BaseController<
},
});

// Fetch initial balances for all non-EVM accounts
for (const account of this.#listAccounts()) {
// Fetching the balance is asynchronous and we cannot use `await` here.
// eslint-disable-next-line no-void
void this.updateBalance(account.id);
}

this.messagingSystem.subscribe(
'AccountsController:accountRemoved',
(account: string) => this.#handleOnAccountRemoved(account),
Expand All @@ -187,6 +180,21 @@ export class MultichainBalancesController extends BaseController<
);
}

/**
* Initialize the controller by fetching initial balances for all non-EVM accounts.
* This method should be called after the controller is constructed.
*/
async initialize(): Promise<void> {
for (const account of this.#listAccounts()) {
this.updateBalance(account.id).catch((error) => {
console.error(
`Failed to fetch initial balances for account ${account.id}:`,
error,
);
});
}
}

/**
* Updates the balances for the given accounts.
*
Expand Down
4 changes: 4 additions & 0 deletions packages/multichain-transactions-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed

- Improve controller constructor by moving async logic to it's own method ([#5781](https://github.com/MetaMask/core/pull/5781))

## [1.0.0]

### Changed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ describe('MultichainTransactionsController', () => {

expect(
Object.keys(controller.state.nonEvmTransactions[mockSolAccount.id]),
).toHaveLength(4);
).toHaveLength(3);

expect(
controller.state.nonEvmTransactions[mockSolAccount.id][
Expand Down Expand Up @@ -951,4 +951,33 @@ describe('MultichainTransactionsController', () => {
transactions[1],
);
});

it('handles errors when initializing transactions for accounts', async () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
const { controller, mockSnapHandleRequest } = setupController({
mocks: {
listMultichainAccounts: [mockBtcAccount],
},
});

mockSnapHandleRequest.mockRejectedValueOnce(
new Error('Failed to fetch transactions'),
);

jest
.spyOn(controller, 'updateTransactionsForAccount')
.mockRejectedValueOnce(new Error('Failed to fetch transactions'));

await controller.initialize();
await waitForAllPromises();

expect(consoleSpy).toHaveBeenCalledWith(
`Failed to fetch initial transactions for account ${mockBtcAccount.id}:`,
expect.any(Error),
);

expect(controller.state).toStrictEqual({ nonEvmTransactions: {} });

consoleSpy.mockRestore();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -189,16 +189,6 @@ export class MultichainTransactionsController extends BaseController<
},
});

// Fetch initial transactions for all non-EVM accounts
for (const account of this.#listAccounts()) {
this.updateTransactionsForAccount(account.id).catch((error) => {
console.error(
`Failed to fetch initial transactions for account ${account.id}:`,
error,
);
});
}

this.messagingSystem.subscribe(
'AccountsController:accountAdded',
(account: InternalAccount) => this.#handleOnAccountAdded(account),
Expand All @@ -214,6 +204,21 @@ export class MultichainTransactionsController extends BaseController<
);
}

/**
* Initialize the controller by fetching initial transactions for all non-EVM accounts.
* This method should be called after the controller is constructed.
*/
async initialize(): Promise<void> {
for (const account of this.#listAccounts()) {
this.updateTransactionsForAccount(account.id).catch((error) => {
console.error(
`Failed to fetch initial transactions for account ${account.id}:`,
error,
);
});
}
}

/**
* Lists the multichain accounts coming from the `AccountsController`.
*
Expand Down
Loading