Skip to content

Commit

Permalink
feat: add NetworkController NetworkConfiguration actions and events (#…
Browse files Browse the repository at this point in the history
…4698)

## Explanation

This adds and exposes some new actions and events inside the network
controller.

Events:
- `NetworkController:networkRemoved`

Actions
- `NetworkController:updateNetwork`
- `NetworkController:addNetwork`
- `NetworkController:removeNetwork`

These will be used for the network syncing feature (see references)

## References

https://consensyssoftware.atlassian.net/browse/NOTIFY-1089

## 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/network-controller`

- **ADDED**: **(BREAKING)** add new event
`NetworkController:networkRemoved`
- **ADDED**: **(BREAKING)** add new actions
`NetworkController:addNetwork`; `NetworkController:removeNetwork`;
`NetworkController:updateNetwork`

## 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
- [x] I've highlighted breaking changes using the "BREAKING" category
above as appropriate

---------

Co-authored-by: Elliot Winkler <[email protected]>
  • Loading branch information
Prithpal-Sooriya and mcmire authored Nov 29, 2024
1 parent e2cdac9 commit 9857fad
Show file tree
Hide file tree
Showing 3 changed files with 214 additions and 2 deletions.
58 changes: 56 additions & 2 deletions packages/network-controller/src/NetworkController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,13 +413,23 @@ export type NetworkControllerNetworkAddedEvent = {
payload: [networkConfiguration: NetworkConfiguration];
};

/**
* `networkRemoved` is published after a network configuration is removed from the
* network configuration registry and once the network clients have been removed.
*/
export type NetworkControllerNetworkRemovedEvent = {
type: 'NetworkController:networkRemoved';
payload: [networkConfiguration: NetworkConfiguration];
};

export type NetworkControllerEvents =
| NetworkControllerStateChangeEvent
| NetworkControllerNetworkWillChangeEvent
| NetworkControllerNetworkDidChangeEvent
| NetworkControllerInfuraIsBlockedEvent
| NetworkControllerInfuraIsUnblockedEvent
| NetworkControllerNetworkAddedEvent;
| NetworkControllerNetworkAddedEvent
| NetworkControllerNetworkRemovedEvent;

export type NetworkControllerGetStateAction = ControllerGetStateAction<
typeof controllerName,
Expand Down Expand Up @@ -477,6 +487,21 @@ export type NetworkControllerGetNetworkConfigurationByNetworkClientId = {
handler: NetworkController['getNetworkConfigurationByNetworkClientId'];
};

export type NetworkControllerAddNetworkAction = {
type: 'NetworkController:addNetwork';
handler: NetworkController['addNetwork'];
};

export type NetworkControllerRemoveNetworkAction = {
type: 'NetworkController:removeNetwork';
handler: NetworkController['removeNetwork'];
};

export type NetworkControllerUpdateNetworkAction = {
type: 'NetworkController:updateNetwork';
handler: NetworkController['updateNetwork'];
};

export type NetworkControllerActions =
| NetworkControllerGetStateAction
| NetworkControllerGetEthQueryAction
Expand All @@ -487,7 +512,10 @@ export type NetworkControllerActions =
| NetworkControllerSetActiveNetworkAction
| NetworkControllerSetProviderTypeAction
| NetworkControllerGetNetworkConfigurationByChainId
| NetworkControllerGetNetworkConfigurationByNetworkClientId;
| NetworkControllerGetNetworkConfigurationByNetworkClientId
| NetworkControllerAddNetworkAction
| NetworkControllerRemoveNetworkAction
| NetworkControllerUpdateNetworkAction;

export type NetworkControllerMessenger = RestrictedControllerMessenger<
typeof controllerName,
Expand Down Expand Up @@ -958,6 +986,27 @@ export class NetworkController extends BaseController<
`${this.name}:getSelectedNetworkClient`,
this.getSelectedNetworkClient.bind(this),
);

this.messagingSystem.registerActionHandler(
// ESLint is mistaken here; `name` is a string.
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`${this.name}:addNetwork`,
this.addNetwork.bind(this),
);

this.messagingSystem.registerActionHandler(
// ESLint is mistaken here; `name` is a string.
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`${this.name}:removeNetwork`,
this.removeNetwork.bind(this),
);

this.messagingSystem.registerActionHandler(
// ESLint is mistaken here; `name` is a string.
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`${this.name}:updateNetwork`,
this.updateNetwork.bind(this),
);
}

/**
Expand Down Expand Up @@ -1938,6 +1987,11 @@ export class NetworkController extends BaseController<
buildNetworkConfigurationsByNetworkClientId(
this.state.networkConfigurationsByChainId,
);

this.messagingSystem.publish(
'NetworkController:networkRemoved',
existingNetworkConfiguration,
);
}

/**
Expand Down
5 changes: 5 additions & 0 deletions packages/network-controller/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export type {
NetworkControllerNetworkDidChangeEvent,
NetworkControllerInfuraIsBlockedEvent,
NetworkControllerInfuraIsUnblockedEvent,
NetworkControllerNetworkAddedEvent,
NetworkControllerNetworkRemovedEvent,
NetworkControllerEvents,
NetworkControllerGetStateAction,
NetworkControllerGetEthQueryAction,
Expand All @@ -26,6 +28,9 @@ export type {
NetworkControllerFindNetworkClientIdByChainIdAction,
NetworkControllerSetProviderTypeAction,
NetworkControllerSetActiveNetworkAction,
NetworkControllerAddNetworkAction,
NetworkControllerRemoveNetworkAction,
NetworkControllerUpdateNetworkAction,
NetworkControllerGetNetworkConfigurationByNetworkClientId,
NetworkControllerActions,
NetworkControllerMessenger,
Expand Down
153 changes: 153 additions & 0 deletions packages/network-controller/tests/NetworkController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3857,6 +3857,56 @@ describe('NetworkController', () => {
});
});
});

it('is callable from the controller messenger', async () => {
uuidV4Mock.mockReturnValueOnce('AAAA-AAAA-AAAA-AAAA');

await withController(({ messenger }) => {
const networkAddedEventListener = jest.fn();
messenger.subscribe(
'NetworkController:networkAdded',
networkAddedEventListener,
);

const newNetworkConfiguration = messenger.call(
'NetworkController:addNetwork',
{
blockExplorerUrls: ['https://block.explorer'],
chainId: '0x1337',
defaultBlockExplorerUrlIndex: 0,
defaultRpcEndpointIndex: 0,
name: 'Some Network',
nativeCurrency: 'TOKEN',
rpcEndpoints: [
{
name: 'Test Network',
type: RpcEndpointType.Custom,
url: 'https://test.endpoint',
},
],
lastUpdatedAt: FAKE_DATE_NOW_MS,
},
);

expect(newNetworkConfiguration).toStrictEqual({
blockExplorerUrls: ['https://block.explorer'],
chainId: '0x1337',
defaultBlockExplorerUrlIndex: 0,
defaultRpcEndpointIndex: 0,
name: 'Some Network',
nativeCurrency: 'TOKEN',
rpcEndpoints: [
{
name: 'Test Network',
networkClientId: 'AAAA-AAAA-AAAA-AAAA',
type: RpcEndpointType.Custom,
url: 'https://test.endpoint',
},
],
lastUpdatedAt: FAKE_DATE_NOW_MS,
});
});
});
});
});

Expand Down Expand Up @@ -4548,6 +4598,59 @@ describe('NetworkController', () => {
);
});

it('is callable from the controller messenger', async () => {
const originalNetwork = buildCustomNetworkConfiguration({
chainId: '0x1337',
rpcEndpoints: [
buildCustomRpcEndpoint({
networkClientId: 'AAAA-AAAA-AAAA-AAAA',
url: 'https://rpc.network',
}),
],
});

const networkToUpdate = buildCustomNetworkConfiguration({
chainId: '0x1337',
rpcEndpoints: [
buildCustomRpcEndpoint({
name: 'Custom Name',
networkClientId: 'AAAA-AAAA-AAAA-AAAA',
url: 'https://rpc.network',
}),
],
});

const controllerState =
buildNetworkControllerStateWithDefaultSelectedNetworkClientId({
networkConfigurationsByChainId: {
[originalNetwork.chainId]: originalNetwork,
},
networksMetadata: {
'AAAA-AAAA-AAAA-AAAA': {
EIPS: {
'1559': true,
},
status: NetworkStatus.Available,
},
},
});

await withController(
{ state: controllerState },
async ({ controller, messenger }) => {
await messenger.call(
'NetworkController:updateNetwork',
networkToUpdate.chainId,
networkToUpdate,
);
expect(
controller.state.networkConfigurationsByChainId['0x1337']
.rpcEndpoints[0].name,
).toBe('Custom Name');
},
);
});

for (const infuraNetworkType of Object.values(InfuraNetworkType)) {
const infuraChainId = ChainId[infuraNetworkType];
const infuraNativeTokenName = NetworksTicker[infuraNetworkType];
Expand Down Expand Up @@ -11446,6 +11549,56 @@ describe('NetworkController', () => {
},
);
});

it('is callable from the controller messenger', async () => {
await withController(
{
state: {
selectedNetworkClientId: InfuraNetworkType.goerli,
networkConfigurationsByChainId: {
'0x1337': buildCustomNetworkConfiguration(),
[ChainId.goerli]: buildInfuraNetworkConfiguration(
InfuraNetworkType.goerli,
),
},
},
},
({ controller, messenger }) => {
messenger.call('NetworkController:removeNetwork', '0x1337');
expect(
controller.state.networkConfigurationsByChainId,
).not.toHaveProperty('0x1337');
},
);
});

it('emits the NetworkController:networkRemoved event', async () => {
const networkConfig = buildCustomNetworkConfiguration();
await withController(
{
state: {
selectedNetworkClientId: InfuraNetworkType.goerli,
networkConfigurationsByChainId: {
'0x1337': networkConfig,
[ChainId.goerli]: buildInfuraNetworkConfiguration(
InfuraNetworkType.goerli,
),
},
},
},
({ controller, messenger }) => {
const networkRemovedListener = jest.fn();
messenger.subscribe(
'NetworkController:networkRemoved',
networkRemovedListener,
);

controller.removeNetwork('0x1337');

expect(networkRemovedListener).toHaveBeenCalledWith(networkConfig);
},
);
});
});
});

Expand Down

0 comments on commit 9857fad

Please sign in to comment.