diff --git a/packages/network-controller/src/NetworkController.ts b/packages/network-controller/src/NetworkController.ts index 3a7bc32a7a..f63fda5efa 100644 --- a/packages/network-controller/src/NetworkController.ts +++ b/packages/network-controller/src/NetworkController.ts @@ -1237,13 +1237,6 @@ export class NetworkController extends BaseController< upsertedNetworkConfigurationId, ); - this.update((state) => { - state.networkConfigurations[upsertedNetworkConfigurationId] = { - id: upsertedNetworkConfigurationId, - ...sanitizedNetworkConfiguration, - }; - }); - const customNetworkClientRegistry = autoManagedNetworkClientRegistry[NetworkClientType.Custom]; const existingAutoManagedNetworkClient = @@ -1267,6 +1260,13 @@ export class NetworkController extends BaseController< }); } + this.update((state) => { + state.networkConfigurations[upsertedNetworkConfigurationId] = { + id: upsertedNetworkConfigurationId, + ...sanitizedNetworkConfiguration, + }; + }); + if (!existingNetworkConfiguration) { this.#trackMetaMetricsEvent({ event: 'Custom Network Added', diff --git a/packages/network-controller/tests/NetworkController.test.ts b/packages/network-controller/tests/NetworkController.test.ts index a7b5ae4ad0..3d6e7358db 100644 --- a/packages/network-controller/tests/NetworkController.test.ts +++ b/packages/network-controller/tests/NetworkController.test.ts @@ -3921,6 +3921,50 @@ describe('NetworkController', () => { ); }); + it('updates state only after creating the new network client', async () => { + await withController( + { infuraProjectId: 'some-infura-project-id' }, + async ({ controller, messenger }) => { + uuidV4Mock.mockReturnValue('AAAA-AAAA-AAAA-AAAA'); + const newCustomNetworkClient = buildFakeClient(); + mockCreateNetworkClientWithDefaultsForBuiltInNetworkClients({ + infuraProjectId: 'some-infura-project-id', + }) + .calledWith({ + chainId: toHex(111), + rpcUrl: 'https://test.network', + type: NetworkClientType.Custom, + ticker: 'TICKER', + }) + .mockReturnValue(newCustomNetworkClient); + + await waitForStateChanges({ + messenger, + count: 1, + operation: async () => { + await controller.upsertNetworkConfiguration( + { + rpcUrl: 'https://test.network', + chainId: toHex(111), + ticker: 'TICKER', + }, + { + referrer: 'https://test-dapp.com', + source: 'dapp', + }, + ); + }, + beforeResolving: () => { + const newNetworkClient = controller.getNetworkClientById( + 'AAAA-AAAA-AAAA-AAAA', + ); + expect(newNetworkClient).toBeDefined(); + }, + }); + }, + ); + }); + describe('if the setActive option is not given', () => { it('does not update the provider config to the new network configuration by default', async () => { const originalProvider = {