Skip to content

Commit

Permalink
pass metaMetricsId into Engine contructor
Browse files Browse the repository at this point in the history
  • Loading branch information
joaoloureirop committed Jan 17, 2025
1 parent 3d4cdbd commit ae8dacc
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 38 deletions.
20 changes: 11 additions & 9 deletions app/core/Engine/Engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ export class Engine {
constructor(
initialState: Partial<EngineState> = {},
initialKeyringState?: KeyringControllerState | null,
metaMetricsId?: string,
) {
logEngineCreation(initialState, initialKeyringState);

Expand Down Expand Up @@ -514,7 +515,7 @@ export class Engine {
allowedEvents: [],
}),
disabled: !isBasicFunctionalityToggleEnabled(),
getMetaMetricsId: () => store.getState().user.metaMetricsId,
getMetaMetricsId: () => metaMetricsId ?? '',
});

const phishingController = new PhishingController({
Expand Down Expand Up @@ -1178,7 +1179,7 @@ export class Engine {

return Boolean(
hasProperty(showIncomingTransactions, currentChainId) &&
showIncomingTransactions?.[currentHexChainId],
showIncomingTransactions?.[currentHexChainId],
);
},
updateTransactions: true,
Expand Down Expand Up @@ -1523,7 +1524,7 @@ export class Engine {
(state: NetworkState) => {
if (
state.networksMetadata[state.selectedNetworkClientId].status ===
NetworkStatus.Available &&
NetworkStatus.Available &&
getGlobalChainId(networkController) !== currentChainId
) {
// We should add a state or event emitter saying the provider changed
Expand Down Expand Up @@ -1744,7 +1745,7 @@ export class Engine {
const decimalsToShow = (currentCurrency === 'usd' && 2) || undefined;
if (
accountsByChainId?.[toHexadecimal(chainId)]?.[
selectSelectedInternalAccountFormattedAddress
selectSelectedInternalAccountFormattedAddress
]
) {
// TODO - Non EVM accounts like BTC do not use hex formatted balances. We will need to modify this to use CAIP-2 identifiers in the future.
Expand Down Expand Up @@ -1783,7 +1784,7 @@ export class Engine {

const tokenBalances =
allTokenBalances?.[selectedInternalAccount.address as Hex]?.[
chainId
chainId
] ?? {};
tokens.forEach(
(item: { address: string; balance?: string; decimals: number }) => {
Expand All @@ -1794,9 +1795,9 @@ export class Engine {
item.balance ||
(item.address in tokenBalances
? renderFromTokenMinimalUnit(
tokenBalances[item.address as Hex],
item.decimals,
)
tokenBalances[item.address as Hex],
item.decimals,
)
: undefined);
const tokenBalanceFiat = balanceToFiatNumber(
// TODO: Fix this by handling or eliminating the undefined case
Expand Down Expand Up @@ -2166,8 +2167,9 @@ export default {
init(
state: Partial<EngineState> | undefined,
keyringState: KeyringControllerState | null = null,
metaMetricsId?: string,
) {
instance = Engine.instance || new Engine(state, keyringState);
instance = Engine.instance || new Engine(state, keyringState, metaMetricsId);
Object.freeze(instance);
return instance;
},
Expand Down
62 changes: 36 additions & 26 deletions app/core/EngineService/EngineService.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { waitFor } from '@testing-library/react-native';
import { EngineService } from './EngineService';
import ReduxService, { type ReduxStore } from '../redux';
import Engine from '../Engine';
Expand Down Expand Up @@ -119,37 +120,44 @@ describe('EngineService', () => {
engineService = new EngineService();
});

it('should have Engine initialized', () => {
it('should have Engine initialized', async () => {
engineService.start();
expect(Engine.context).toBeDefined();
await waitFor(() => {
expect(Engine.context).toBeDefined();
});
});

it('should log Engine initialization with state info', () => {
it('should log Engine initialization with state info', async () => {
engineService.start();
expect(Logger.log).toHaveBeenCalledWith(
'EngineService: Initializing Engine:',
{
hasState: true,
},
);
await waitFor(() => {
expect(Logger.log).toHaveBeenCalledWith(
'EngineService: Initializing Engine:',
{
hasState: true,
},
);
});

});

it('should log Engine initialization with empty state', () => {
it('should log Engine initialization with empty state', async () => {
jest.spyOn(ReduxService, 'store', 'get').mockReturnValue({
getState: () => ({ engine: { backgroundState: {} } }),
} as unknown as ReduxStore);

engineService.start();
expect(Logger.log).toHaveBeenCalledWith(
'EngineService: Initializing Engine:',
{
hasState: false,
},
);
await waitFor(() => {
expect(Logger.log).toHaveBeenCalledWith(
'EngineService: Initializing Engine:',
{
hasState: false,
},
);
});
});

it('should have recovered vault on redux store and log initialization', async () => {
engineService.start();
await engineService.start();
const { success } = await engineService.initializeVaultFromBackup();
expect(success).toBeTruthy();
expect(Engine.context.KeyringController.state.vault).toBeDefined();
Expand All @@ -161,19 +169,21 @@ describe('EngineService', () => {
);
});

it('should navigate to vault recovery if Engine fails to initialize', () => {
it('should navigate to vault recovery if Engine fails to initialize', async () => {
jest.spyOn(Engine, 'init').mockImplementation(() => {
throw new Error('Failed to initialize Engine');
});
engineService.start();
// Logs error to Sentry
expect(Logger.error).toHaveBeenCalledWith(
new Error('Failed to initialize Engine'),
'Failed to initialize Engine! Falling back to vault recovery.',
);
// Navigates to vault recovery
expect(NavigationService.navigation?.reset).toHaveBeenCalledWith({
routes: [{ name: Routes.VAULT_RECOVERY.RESTORE_WALLET }],
await waitFor(() => {
// Logs error to Sentry
expect(Logger.error).toHaveBeenCalledWith(
new Error('Failed to initialize Engine'),
'Failed to initialize Engine! Falling back to vault recovery.',
);
// Navigates to vault recovery
expect(NavigationService.navigation?.reset).toHaveBeenCalledWith({
routes: [{ name: Routes.VAULT_RECOVERY.RESTORE_WALLET }],
});
});
});
});
9 changes: 6 additions & 3 deletions app/core/EngineService/EngineService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import ReduxService from '../redux';
import NavigationService from '../NavigationService';
import Routes from '../../constants/navigation/Routes';
import { KeyringControllerState } from '@metamask/keyring-controller';
import { MetaMetrics } from '../Analytics';

const LOG_TAG = 'EngineService';

Expand Down Expand Up @@ -43,7 +44,7 @@ export class EngineService {
* - TypeError: undefined is not an object (evaluating 'TokenListController.tokenList')
* - V8: SES_UNHANDLED_REJECTION
*/
start = () => {
start = async () => {
const reduxState = ReduxService.store.getState();
trace({
name: TraceName.EngineInitialization,
Expand All @@ -57,7 +58,8 @@ export class EngineService {
hasState: Object.keys(state).length > 0,
});

Engine.init(state);
const metaMetricsId = await MetaMetrics.getInstance().getMetaMetricsId();
Engine.init(state, null, metaMetricsId);
this.updateControllers(Engine);
} catch (error) {
Logger.error(
Expand Down Expand Up @@ -257,7 +259,8 @@ export class EngineService {
hasState: Object.keys(state).length > 0,
});

const instance = Engine.init(state, newKeyringState);
const metaMetricsId = await MetaMetrics.getInstance().getMetaMetricsId();
const instance = Engine.init(state, newKeyringState, metaMetricsId);
if (instance) {
this.updateControllers(instance);
// this is a hack to give the engine time to reinitialize
Expand Down

0 comments on commit ae8dacc

Please sign in to comment.