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

[wip] suite: apply connect method info (attempt 2) #15038

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft
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
56 changes: 43 additions & 13 deletions packages/suite/src/actions/suite/__tests__/suiteActions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,27 +42,57 @@ const deviceReducer = prepareDeviceReducer(extraDependencies);
const TrezorConnect = testMocks.getTrezorConnectMock();

const setTrezorConnectFixtures = (fixture: any) => {
jest.spyOn(TrezorConnect, 'getFeatures').mockImplementation(
() =>
jest.spyOn(TrezorConnect, 'getFeatures').mockImplementation((params: any) => {
if (params.__info) {
return {
success: true,
payload: {
useDevice: true,
},
};
}

return (
fixture || {
success: true,
},
);
jest.spyOn(TrezorConnect, 'getDeviceState').mockImplementation(
({ device }: any) =>
}
);
});
jest.spyOn(TrezorConnect, 'getDeviceState').mockImplementation((params: any) => {
if (params.__info) {
return {
success: true,
payload: {
useDevice: true,
},
};
}

return (
fixture || {
success: true,
payload: {
state: `state@device-id:${device ? device.instance : undefined}`,
state: `state@device-id:${params.device ? params.device.instance : undefined}`,
},
},
);
jest.spyOn(TrezorConnect, 'applySettings').mockImplementation(
() =>
}
);
});
jest.spyOn(TrezorConnect, 'applySettings').mockImplementation(params => {
if (params.__info) {
return {
success: true,
payload: {
useDevice: true,
},
};
}

return (
fixture || {
success: true,
},
);
}
);
});
};

type SuiteState = ReturnType<typeof suiteReducer>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,15 @@ const TrezorConnect = testMocks.getTrezorConnectMock();
const setTrezorConnectFixtures = (fixture: any) => {
let buttonRequest: ((e?: any) => any) | undefined;

const getPublicKey = (_params: any) => {
const getPublicKey = (params: any) => {
if (params.__info) {
return {
success: true,
payload: {
useDevice: true,
},
};
}
if (fixture && fixture.getPublicKey) {
if (fixture.getPublicKey.success && buttonRequest) {
buttonRequest({ code: 'ButtonRequest_PublicKey' });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,15 @@ const TrezorConnect = testMocks.getTrezorConnectMock();
const setTrezorConnectFixtures = (fixture?: any) => {
let buttonRequest: ((e?: any) => any) | undefined;

const getAddress = (_params: any) => {
const getAddress = (params: any) => {
if (params.__info) {
return {
success: true,
payload: {
useDevice: true,
},
};
}
if (fixture && fixture.getAddress) {
if (fixture.getAddress.success && buttonRequest) {
buttonRequest({ code: 'ButtonRequest_Address' });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ describe('buttonRequest middleware', () => {
await store.dispatch(connectInitThunk());
const call = store.dispatch(deviceSettingsActions.changePin({ remove: false }));
const { emitTestEvent } = testMocks.getTrezorConnectMock();

// fake few ui events, just like when user is changing PIN
await Promise.resolve();
emitTestEvent(UI_EVENT, {
type: UI.REQUEST_BUTTON,
payload: { code: 'ButtonRequest_ProtectCall' },
Expand Down
6 changes: 6 additions & 0 deletions packages/suite/src/middlewares/wallet/discoveryMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export const prepareDiscoveryMiddleware = createMiddlewareWithExtraDeps(
!isDeviceLocked &&
(deviceActions.selectDevice.match(action) || action.type === SUITE.APP_CHANGED)
) {
console.log('true 1');
authorizationIntent = true;
}

Expand All @@ -113,12 +114,17 @@ export const prepareDiscoveryMiddleware = createMiddlewareWithExtraDeps(
device.connected
);
if (becomesAcquired) {
console.log('true 2');

authorizationIntent = true;
}
}

// 3. begin auth process
if (authorizationIntent) {
console.log('middleware handling action', action.type);

console.log('authorizeDeviceThunk()');
dispatch(authorizeDeviceThunk());
}

Expand Down
99 changes: 51 additions & 48 deletions suite-common/connect-init/src/connectInitThunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import { getSynchronize } from '@trezor/utils';
import { deviceConnectThunks } from '@suite-common/wallet-core';
import { isDesktop, isNative } from '@trezor/env-utils';

import { cardanoConnectPatch } from './cardanoConnectPatch';

const CONNECT_INIT_MODULE = '@common/connect-init';

// If you are looking where connectInitSettings is defined, it is defined in packages/suite/src/support/extraDependencies.ts
Expand Down Expand Up @@ -67,52 +65,57 @@ export const connectInitThunk = createThunk(

const synchronize = getSynchronize();

const wrappedMethods: Array<keyof typeof TrezorConnect> = [
'applySettings',
'authenticateDevice',
'authorizeCoinjoin',
'backupDevice',
'cancelCoinjoinAuthorization',
'cardanoGetAddress',
'cardanoGetPublicKey',
'cardanoSignTransaction',
'changePin',
'cipherKeyValue',
'ethereumGetAddress',
'ethereumSignTransaction',
'getAddress',
'getDeviceState',
'getFeatures',
'getOwnershipProof',
'getPublicKey',
'pushTransaction',
'recoveryDevice',
'resetDevice',
'rippleGetAddress',
'rippleSignTransaction',
'setBusy',
'showDeviceTutorial',
'signTransaction',
'solanaGetAddress',
'solanaSignTransaction',
'unlockPath',
'wipeDevice',
] as const;

wrappedMethods.forEach(key => {
// typescript complains about params and return type, need to be "any"
const original: any = TrezorConnect[key];
if (!original) return;
(TrezorConnect[key] as any) = async (params: any) => {
dispatch(lockDevice(true));
const result = await synchronize(() => original(params));
dispatch(lockDevice(false));

return result;
};
});

cardanoConnectPatch(getEnabledNetworks);
Object.keys(TrezorConnect)
.filter(
key =>
![
'on',
'off',
'init',
'manifest',
'cancel',
'uiResponse',
'dispose',
'requestWebUSBDevice',
'disableWebUSB',
'renderWebUSBButton',
'removeAllListeners',
].includes(key) &&
// blockchain methods don't need lockDevice anyway
!key.startsWith('blockchain'),
)
.forEach(key => {
// typescript complains about params and return type, need to be "any"
const original: any = TrezorConnect[key as keyof typeof TrezorConnect];
if (!original) return;

// @ts-expect-error
TrezorConnect[key] = async (params: any) => {
const infoResult = await original({ ...params, __info: true });
const useWrapped =
params.device && infoResult.success && infoResult.payload.useDevice;

// console.log('infoResult', infoResult);

if (!useWrapped) {
return original(params);
}

const enabledNetworks = getEnabledNetworks();
const cardanoEnabled =
infoResult.payload.useDeviceState &&
!!enabledNetworks.find(a => a === 'ada' || a === 'tada');

dispatch(lockDevice(true));
const result = await synchronize(() =>
original({ ...params, useCardanoDerivation: cardanoEnabled }),
);
dispatch(lockDevice(false));
// console.log('result', result);

return result;
};
});

// suite-web connect (explorer) webusb sync
// ====================================================== ==================== ====================
Expand Down
18 changes: 14 additions & 4 deletions suite-common/test-utils/__mocks__/@trezor/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,27 @@ const getNextFixture = (_methodName: string) => {
};

const result = (methodName: string, data: any) =>
jest.fn(params =>
Promise.resolve({
jest.fn(params => {
if (params.__info) {
// todo: calling actual produces neverending loop
return Promise.resolve({
success: true,
payload: {
useDevice: true,
},
});
}

return Promise.resolve({
success: true,
payload: { _comment: 'Default mock payload' },
...data,
...getNextFixture(methodName),
_method: methodName,
_fixtures: fixtures,
_params: params,
}),
);
});
});

const ERROR_RESULT = { success: false, payload: { error: 'Default mock error' } };

Expand Down
3 changes: 3 additions & 0 deletions suite-common/wallet-core/src/device/deviceThunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@
useEmptyPassphrase: device.useEmptyPassphrase,
};

console.log('getDeviceState 1');

Check failure on line 333 in suite-common/wallet-core/src/device/deviceThunks.ts

View workflow job for this annotation

GitHub Actions / Linting and formatting

Unexpected console statement
const response = await TrezorConnect.getDeviceState(deviceParams);

if (response.success) {
Expand Down Expand Up @@ -412,6 +413,8 @@
const device = selectDeviceSelector(getState());
if (!device) return false;

console.log('getDeviceState 2');

Check failure on line 416 in suite-common/wallet-core/src/device/deviceThunks.ts

View workflow job for this annotation

GitHub Actions / Linting and formatting

Unexpected console statement

const response = await TrezorConnect.getDeviceState({
device: {
path: device.path,
Expand Down
Loading