Skip to content
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

fix: Type fixes and optimizations for EngineService, Redux store #12509

Open
wants to merge 6 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
7 changes: 5 additions & 2 deletions app/core/Engine/Engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@
// eslint-disable-next-line @typescript-eslint/default-param-last
constructor(
initialState: Partial<EngineState> = {},
initialKeyringState?: KeyringControllerState | null,
initialKeyringState?: Partial<KeyringControllerState> | null,
) {
this.controllerMessenger = new ExtendedControllerMessenger();

Expand Down Expand Up @@ -1869,12 +1869,12 @@
const { tokenBalances } = backgroundState.TokenBalancesController;

let tokenFound = false;
tokenLoop: for (const chains of Object.values(tokenBalances)) {

Check warning on line 1872 in app/core/Engine/Engine.ts

View workflow job for this annotation

GitHub Actions / scripts (lint)

Unexpected labeled statement
for (const tokens of Object.values(chains)) {
for (const balance of Object.values(tokens)) {
if (!isZero(balance)) {
tokenFound = true;
break tokenLoop;

Check warning on line 1877 in app/core/Engine/Engine.ts

View workflow job for this annotation

GitHub Actions / scripts (lint)

Unexpected label in break statement
}
}
}
Expand Down Expand Up @@ -2151,7 +2151,10 @@
instance = null;
},

init(state: Partial<EngineState> | undefined, keyringState = null) {
init(
state: Partial<EngineState> | undefined,
keyringState: Partial<KeyringControllerState> | null = null,
) {
instance = Engine.instance || new Engine(state, keyringState);
Object.freeze(instance);
return instance;
Expand Down
169 changes: 28 additions & 141 deletions app/core/EngineService/EngineService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import UntypedEngine from '../Engine';
import AppConstants from '../AppConstants';
import { Engine as TypedEngine } from '../Engine/Engine';
import { getVaultFromBackup } from '../BackupVault';
import Logger from '../../util/Logger';
import {
Expand All @@ -9,6 +9,7 @@ import {
import { getTraceTags } from '../../util/sentry/tags';
import { trace, endTrace, TraceName, TraceOperation } from '../../util/trace';
import getUIStartupSpan from '../Performance/UIStartup';
import { BACKGROUND_STATE_CHANGE_EVENT_NAMES } from '../Engine/constants';
import ReduxService from '../redux';
import NavigationService from '../NavigationService';
import Routes from '../../constants/navigation/Routes';
Expand Down Expand Up @@ -48,13 +49,12 @@ export class EngineService {
parentContext: getUIStartupSpan(),
tags: getTraceTags(reduxState),
});
const state = reduxState?.engine?.backgroundState || {};
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const Engine = UntypedEngine as any;
const state = reduxState?.engine?.backgroundState ?? {};
const Engine = UntypedEngine;
try {
Engine.init(state);
this.updateControllers(Engine);
// `Engine.init()` call mutates `typeof UntypedEngine` to `TypedEngine`
this.updateControllers(Engine as unknown as TypedEngine);
} catch (error) {
Logger.error(
error as Error,
Expand All @@ -68,9 +68,7 @@ export class EngineService {
endTrace({ name: TraceName.EngineInitialization });
};

// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private updateControllers = (engine: any) => {
private updateControllers = (engine: TypedEngine) => {
if (!engine.context) {
Logger.error(
new Error(
Expand All @@ -80,121 +78,6 @@ export class EngineService {
return;
}

const controllers = [
{
name: 'AddressBookController',
key: `${engine.context.AddressBookController.name}:stateChange`,
},
{ name: 'NftController', key: 'NftController:stateChange' },
{
name: 'TokensController',
key: `${engine.context.TokensController.name}:stateChange`,
},
{
name: 'KeyringController',
key: `${engine.context.KeyringController.name}:stateChange`,
},
{
name: 'AccountTrackerController',
key: 'AccountTrackerController:stateChange',
},
{
name: 'NetworkController',
key: AppConstants.NETWORK_STATE_CHANGE_EVENT,
},
{
name: 'PhishingController',
key: `${engine.context.PhishingController.name}:stateChange`,
},
{
name: 'PreferencesController',
key: `${engine.context.PreferencesController.name}:stateChange`,
},
{
name: 'RemoteFeatureFlagController',
key: `${engine.context.RemoteFeatureFlagController.name}:stateChange`,
},
{
name: 'SelectedNetworkController',
key: `${engine.context.SelectedNetworkController.name}:stateChange`,
},
{
name: 'TokenBalancesController',
key: `${engine.context.TokenBalancesController.name}:stateChange`,
},
{ name: 'TokenRatesController', key: 'TokenRatesController:stateChange' },
{
name: 'TransactionController',
key: `${engine.context.TransactionController.name}:stateChange`,
},
{
name: 'SmartTransactionsController',
key: `${engine.context.SmartTransactionsController.name}:stateChange`,
},
{
name: 'SwapsController',
key: `${engine.context.SwapsController.name}:stateChange`,
},
{
name: 'TokenListController',
key: `${engine.context.TokenListController.name}:stateChange`,
},
{
name: 'CurrencyRateController',
key: `${engine.context.CurrencyRateController.name}:stateChange`,
},
{
name: 'GasFeeController',
key: `${engine.context.GasFeeController.name}:stateChange`,
},
{
name: 'ApprovalController',
key: `${engine.context.ApprovalController.name}:stateChange`,
},
///: BEGIN:ONLY_INCLUDE_IF(preinstalled-snaps,external-snaps)
{
name: 'SnapController',
key: `${engine.context.SnapController.name}:stateChange`,
},
{
name: 'SubjectMetadataController',
key: `${engine.context.SubjectMetadataController.name}:stateChange`,
},
{
name: 'AuthenticationController',
key: 'AuthenticationController:stateChange',
},
{
name: 'UserStorageController',
key: 'UserStorageController:stateChange',
},
{
name: 'NotificationServicesController',
key: 'NotificationServicesController:stateChange',
},
{
name: 'NotificationServicesPushController',
key: 'NotificationServicesPushController:stateChange',
},
///: END:ONLY_INCLUDE_IF
{
name: 'PermissionController',
key: `${engine.context.PermissionController.name}:stateChange`,
},
{
name: 'LoggingController',
key: `${engine.context.LoggingController.name}:stateChange`,
},
{
name: 'AccountsController',
key: `${engine.context.AccountsController.name}:stateChange`,
},
{
name: 'PPOMController',
key: `${engine.context.PPOMController.name}:stateChange`,
},
];

engine.controllerMessenger.subscribeOnceIf(
'ComposableController:stateChange',
() => {
Expand All @@ -207,18 +90,20 @@ export class EngineService {
() => !this.engineInitialized,
);

controllers.forEach((controller) => {
const { name, key } = controller;
const update_bg_state_cb = () => {
if (!engine.context.KeyringController.metadata.vault) {
Logger.log('keyringController vault missing for UPDATE_BG_STATE_KEY');
}
ReduxService.store.dispatch({
type: UPDATE_BG_STATE_KEY,
payload: { key: name },
});
};
engine.controllerMessenger.subscribe(key, update_bg_state_cb);
const update_bg_state_cb = (controllerName: string) => {
if (!engine.context.KeyringController.metadata.vault) {
Logger.log('keyringController vault missing for UPDATE_BG_STATE_KEY');
}
ReduxService.store.dispatch({
type: UPDATE_BG_STATE_KEY,
payload: { key: controllerName },
});
};

BACKGROUND_STATE_CHANGE_EVENT_NAMES.forEach((eventName) => {
engine.controllerMessenger.subscribe(eventName, () =>
update_bg_state_cb(eventName.split(':')[0]),
);
});
};

Expand All @@ -234,10 +119,8 @@ export class EngineService {
async initializeVaultFromBackup(): Promise<InitializeEngineResult> {
const keyringState = await getVaultFromBackup();
const reduxState = ReduxService.store.getState();
const state = reduxState?.engine?.backgroundState || {};
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const Engine = UntypedEngine as any;
const state = reduxState?.engine?.backgroundState ?? {};
const Engine = UntypedEngine;
// This ensures we create an entirely new engine
await Engine.destroyEngine();
this.engineInitialized = false;
Expand All @@ -246,7 +129,11 @@ export class EngineService {
keyrings: [],
vault: keyringState.vault,
};
const instance = Engine.init(state, newKeyringState);
// `Engine.init()` call mutates `typeof UntypedEngine` to `TypedEngine`
const instance = Engine.init(
state,
newKeyringState,
) as unknown as TypedEngine;
if (instance) {
this.updateControllers(instance);
// this is a hack to give the engine time to reinitialize
Expand Down
20 changes: 9 additions & 11 deletions app/store/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Store } from 'redux';
import { AnyAction } from 'redux';
import { configureStore } from '@reduxjs/toolkit';
import { persistStore, persistReducer } from 'redux-persist';
import createSagaMiddleware from 'redux-saga';
Expand All @@ -12,19 +12,17 @@ import thunk from 'redux-thunk';

import persistConfig from './persistConfig';
import getUIStartupSpan from '../core/Performance/UIStartup';
import ReduxService from '../core/redux';
import ReduxService, { ReduxStore } from '../core/redux';
import { onPersistedDataLoaded } from '../actions/user';

// TODO: Improve type safety by using real Action types instead of `any`
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const pReducer = persistReducer<RootState, any>(persistConfig, rootReducer);
// TODO: Improve type safety by using real Action types instead of `AnyAction`
const pReducer = persistReducer<RootState, AnyAction>(
persistConfig,
rootReducer,
);

// TODO: Fix the Action type. It's set to `any` now because some of the
// TypeScript reducers have invalid actions
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any, import/no-mutable-exports
let store: Store<RootState, any>, persistor;
// eslint-disable-next-line import/no-mutable-exports
let store: ReduxStore, persistor;
const createStoreAndPersistor = async () => {
trace({
name: TraceName.StoreInit,
Expand Down
Loading