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: Revert/8081 engine slice #8576

Merged
merged 1 commit into from
Feb 13, 2024
Merged
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
108 changes: 107 additions & 1 deletion app/components/UI/DrawerView/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
StyleSheet,
Text,
InteractionManager,
Platform,
} from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
Expand All @@ -27,6 +28,7 @@ import { strings } from '../../../../locales/i18n';
import Modal from 'react-native-modal';
import {
toggleInfoNetworkModal,
toggleNetworkModal,
toggleReceiveModal,
} from '../../../actions/modals';
import { showAlert } from '../../../actions/alert';
Expand All @@ -47,6 +49,7 @@ import { getEther } from '../../../util/transactions';
import { newAssetTransaction } from '../../../actions/transaction';
import { protectWalletModalVisible } from '../../../actions/user';
import DeeplinkManager from '../../../core/DeeplinkManager/SharedDeeplinkManager';
import SettingsNotification from '../SettingsNotification';
import { RPC } from '../../../constants/network';
import { findRouteNameFromNavigatorState } from '../../../util/general';
import AnalyticsV2 from '../../../util/analyticsV2';
Expand All @@ -56,6 +59,7 @@ import {
} from '../../../util/ENSUtils';
import ClipboardManager from '../../../core/ClipboardManager';
import { collectiblesSelector } from '../../../reducers/collectibles';
import { getCurrentRoute } from '../../../reducers/navigation';
import { ScrollView } from 'react-native-gesture-handler';
import { isZero } from '../../../util/lodash';
import { Authentication } from '../../../core/';
Expand All @@ -67,6 +71,7 @@ import {
} from '../../../actions/onboardNetwork';
import Routes from '../../../constants/navigation/Routes';
import { scale } from 'react-native-size-matters';
import generateTestId from '../../../../wdio/utils/generateTestId';
import { DRAWER_VIEW_LOCK_TEXT_ID } from '../../../../wdio/screen-objects/testIDs/Screens/DrawerView.testIds';
import {
selectNetworkConfigurations,
Expand Down Expand Up @@ -357,6 +362,10 @@ class DrawerView extends PureComponent {
* List of keyrings
*/
keyrings: PropTypes.array,
/**
* Action that toggles the network modal
*/
toggleNetworkModal: PropTypes.func,
/**
* Action that toggles the receive modal
*/
Expand All @@ -365,6 +374,10 @@ class DrawerView extends PureComponent {
* Action that shows the global alert
*/
showAlert: PropTypes.func.isRequired,
/**
* Boolean that determines the status of the networks modal
*/
networkModalVisible: PropTypes.bool.isRequired,
/**
* Boolean that determines the status of the receive modal
*/
Expand All @@ -377,6 +390,10 @@ class DrawerView extends PureComponent {
* Boolean that determines if the user has set a password before
*/
passwordSet: PropTypes.bool,
/**
* Wizard onboarding state
*/
wizard: PropTypes.object,
/**
* Current provider ticker
*/
Expand Down Expand Up @@ -410,11 +427,18 @@ class DrawerView extends PureComponent {
* Callback to close drawer
*/
onCloseDrawer: PropTypes.func,

/**
* Latest navigation route
*/
currentRoute: PropTypes.string,
/**
* handles action for onboarding to a network
*/
onboardNetworkAction: PropTypes.func,
/**
* returns switched network state
*/
switchedNetwork: PropTypes.object,
/**
* updates when network is switched
*/
Expand Down Expand Up @@ -976,6 +1000,8 @@ class DrawerView extends PureComponent {
identities,
selectedAddress,
currentCurrency,
seedphraseBackedUp,
currentRoute,
navigation,
infoNetworkModalVisible,
} = this.props;
Expand Down Expand Up @@ -1092,6 +1118,81 @@ class DrawerView extends PureComponent {
</View>
</StyledButton>
</View>
<View style={styles.menu}>
{this.getSections().map(
(section, i) =>
section?.length > 0 && (
<View
key={`section_${i}`}
style={[
styles.menuSection,
i === 0 ? styles.noTopBorder : null,
]}
>
{section
.filter((item) => {
if (!item) return undefined;
const { name = undefined } = item;
if (
name &&
name.toLowerCase().indexOf('etherscan') !== -1
) {
const type = providerConfig?.type;
return (
(type && this.hasBlockExplorer(type)) || undefined
);
}
return true;
})
.map((item, j) => (
<TouchableOpacity
key={`item_${i}_${j}`}
style={[
styles.menuItem,
item.routeNames &&
item.routeNames.includes(currentRoute)
? styles.selectedRoute
: null,
]}
ref={
item.name === strings('drawer.browser') &&
this.browserSectionRef
}
onPress={() => item.action()} // eslint-disable-line
>
{item.icon
? item.routeNames &&
item.routeNames.includes(currentRoute)
? item.selectedIcon
: item.icon
: null}
<Text
style={[
styles.menuItemName,
!item.icon ? styles.noIcon : null,
item.routeNames &&
item.routeNames.includes(currentRoute)
? styles.selectedName
: null,
]}
{...generateTestId(Platform, item.testID)}
numberOfLines={1}
>
{item.name}
</Text>
{!seedphraseBackedUp && item.warning ? (
<SettingsNotification isNotification isWarning>
<Text style={styles.menuItemWarningText}>
{item.warning}
</Text>
</SettingsNotification>
) : null}
</TouchableOpacity>
))}
</View>
),
)}
</View>
</ScrollView>

<Modal
Expand Down Expand Up @@ -1142,17 +1243,22 @@ const mapStateToProps = (state) => ({
networkConfigurations: selectNetworkConfigurations(state),
currentCurrency: selectCurrentCurrency(state),
keyrings: state.engine.backgroundState.KeyringController.keyrings,
networkModalVisible: state.modals.networkModalVisible,
receiveModalVisible: state.modals.receiveModalVisible,
infoNetworkModalVisible: state.modals.infoNetworkModalVisible,
passwordSet: state.user.passwordSet,
wizard: state.wizard,
ticker: selectTicker(state),
tokens: selectTokens(state),
tokenBalances: selectContractBalances(state),
collectibles: collectiblesSelector(state),
seedphraseBackedUp: state.user.seedphraseBackedUp,
currentRoute: getCurrentRoute(state),
switchedNetwork: state.networkOnboarded.switchedNetwork,
});

const mapDispatchToProps = (dispatch) => ({
toggleNetworkModal: () => dispatch(toggleNetworkModal()),
toggleReceiveModal: () => dispatch(toggleReceiveModal()),
showAlert: (config) => dispatch(showAlert(config)),
newAssetTransaction: (selectedAsset) =>
Expand Down
19 changes: 4 additions & 15 deletions app/core/EngineService/EngineService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@ interface InitializeEngineResult {
error?: string;
}

const UPDATE_BG_STATE_KEY = (controllerName: string) =>
`UPDATE_BG_STATE_${controllerName}`;
const INIT_BG_STATE_KEY = (controllerName: string) =>
`INIT_BG_STATE_${controllerName}`;
const UPDATE_BG_STATE_KEY = 'UPDATE_BG_STATE';
const INIT_BG_STATE_KEY = 'INIT_BG_STATE';
class EngineService {
private engineInitialized = false;

Expand Down Expand Up @@ -104,24 +102,15 @@ class EngineService {

engine?.datamodel?.subscribe?.(() => {
if (!this.engineInitialized) {
controllers.forEach((controller) => {
const { name } = controller;
store.dispatch({
type: INIT_BG_STATE_KEY(name),
payload: { key: name },
});
});
store.dispatch({ type: INIT_BG_STATE_KEY });
this.engineInitialized = true;
}
});

controllers.forEach((controller) => {
const { name, key = undefined } = controller;
const update_bg_state_cb = () => {
store.dispatch({
type: UPDATE_BG_STATE_KEY(name),
payload: { key: name },
});
store.dispatch({ type: UPDATE_BG_STATE_KEY, payload: { key: name } });
};
if (key) {
engine.controllerMessenger.subscribe(key, update_bg_state_cb);
Expand Down
51 changes: 51 additions & 0 deletions app/core/redux/slices/engine/engineReducer.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import engineReducer, { initBgState, updateBgState } from '.';

jest.mock('../../../Engine', () => ({
init: () => jest.requireActual('../../../Engine').default.init({}),
state: {},
}));
// importing Engine after mocking to avoid global mock from overwriting its values
import Engine from '../../../Engine';

describe('engineReducer', () => {
it('should return the initial state in default', () => {
jest.isolateModules(() => {
jest.mock('../../../Engine', () => ({
init: () => jest.requireActual('../../../Engine').default.init({}),
state: {},
}));
});

const initialStatDefault = { backgroundState: {} };
const nextState = engineReducer(undefined, {} as any);
expect(nextState).toEqual(initialStatDefault);
});

it('should initialize backgroundState when dispatching INIT_BG_STATE action', () => {
const initialState = { backgroundState: {} };
const nextState = engineReducer(initialState, initBgState());
expect(nextState).toEqual({ backgroundState: Engine.state });
});

it('should update backgroundState when dispatching UPDATE_BG_STATE action', () => {
const reduxInitialState = {
backgroundState: {
AccountTrackerController: {},
},
};

const key = 'AccountTrackerController';
// changing the mock version to suit this test manually due to our current global mock
(Engine as any).state = {
AccountTrackerController: { accounts: 'testValue' },
};
const { backgroundState } = engineReducer(
reduxInitialState,
updateBgState({ key }),
);
expect(backgroundState).toEqual({
...reduxInitialState.backgroundState,
AccountTrackerController: Engine.state[key],
});
});
});
39 changes: 39 additions & 0 deletions app/core/redux/slices/engine/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import Engine from '../../../Engine';
import { createAction, PayloadAction } from '@reduxjs/toolkit';

const initialState = {
backgroundState: {} as any,
};

// Create an action to initialize the background state
export const initBgState = createAction('INIT_BG_STATE');

// Create an action to update the background state
export const updateBgState = createAction('UPDATE_BG_STATE', (key) => ({
payload: key,
}));

export const counter: any = {};
const engineReducer = (
// eslint-disable-next-line @typescript-eslint/default-param-last
state = initialState,
action: PayloadAction<{ key: any } | undefined>,
) => {
switch (action.type) {
case initBgState.type: {
return { backgroundState: Engine.state };
}
case updateBgState.type: {
const newState = { ...state };
if (action.payload) {
newState.backgroundState[action.payload?.key] =
Engine.state[action.payload.key as keyof typeof Engine.state];
}
return newState;
}
default:
return state;
}
};

export default engineReducer;
6 changes: 3 additions & 3 deletions app/reducers/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import bookmarksReducer from './bookmarks';
import browserReducer from './browser';
import engineReducer from '../redux/slices/engine';
import engineReducer from '../core/redux/slices/engine';
import privacyReducer from './privacy';
import modalsReducer from './modals';
import settingsReducer from './settings';
Expand All @@ -11,11 +11,11 @@ import wizardReducer from './wizard';
import onboardingReducer from './onboarding';
import fiatOrders from './fiatOrders';
import swapsReducer from './swaps';
import navigationReducer from './navigation';
import signatureRequestReducer from './signatureRequest';
import notificationReducer from './notification';
import infuraAvailabilityReducer from './infuraAvailability';
import collectiblesReducer from './collectibles';
import navigationReducer from './navigation';
import networkOnboardReducer from './networkSelector';
import securityReducer from './security';
import { combineReducers, Reducer } from 'redux';
Expand Down Expand Up @@ -83,11 +83,11 @@ const rootReducer = combineReducers<RootState, any>({
wizard: wizardReducer,
onboarding: onboardingReducer,
notification: notificationReducer,
navigation: navigationReducer,
signatureRequest: signatureRequestReducer,
swaps: swapsReducer,
fiatOrders,
infuraAvailability: infuraAvailabilityReducer,
navigation: navigationReducer,
networkOnboarded: networkOnboardReducer,
security: securityReducer,
experimentalSettings: experimentalSettingsReducer,
Expand Down
3 changes: 3 additions & 0 deletions app/reducers/navigation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,8 @@ const navigationReducer = (state = initialState, action: any = {}) => {
/**
* Selectors
*/
export const getCurrentRoute = (state: any) => state.navigation.currentRoute;
export const getCurrentBottomNavRoute = (state: any) =>
state.navigation.currentBottomNavRoute;

export default navigationReducer;
Loading
Loading