Skip to content

Commit

Permalink
Added QR code (#23428)
Browse files Browse the repository at this point in the history
## **Description**

Develop and implement a QR code-based system to enable secure and
efficient connections between custodian accounts and the web extension,
leveraging advanced encryption methods and API communication.


https://www.loom.com/share/5968d1ab02894f88a1b4155cd1c55fe1?sid=58fc6793-4a82-4e79-b2ab-6bd81377d5df

## **Related issues**

Fixes:

## **Manual testing steps**

1. Go to this page...
2.
3.

## **Screenshots/Recordings**

<!-- If applicable, add screenshots and/or recordings to visualize the
before and after of your change. -->

### **Before**

<!-- [screenshots/recordings] -->

### **After**

<!-- [screenshots/recordings] -->

## **Pre-merge author checklist**

- [x] I’ve followed [MetaMask Coding
Standards](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've clearly explained what problem this PR is solving and how it
is solved.
- [x] I've linked related issues
- [x] I've included manual testing steps
- [x] I've included screenshots/recordings if applicable
- [x] I’ve included tests if applicable
- [x] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [x] I’ve applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.
- [x] I’ve properly set the pull request status:
  - [x] In case it's not yet "ready for review", I've set it to "draft".
- [x] In case it's "ready for review", I've changed it from "draft" to
"non-draft".

## **Pre-merge reviewer checklist**

- [x] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [x] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.

---------

Co-authored-by: MetaMask Bot <metamaskbot@users.noreply.github.com>
Co-authored-by: Antonio Regadas <antonio.regadas@consensys.net>
Co-authored-by: António Regadas <apregadas@gmail.com>
  • Loading branch information
4 people committed May 2, 2024
1 parent 249d85b commit 8d4e334
Show file tree
Hide file tree
Showing 20 changed files with 814 additions and 108 deletions.
6 changes: 6 additions & 0 deletions app/_locales/en/messages.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions app/scripts/controllers/mmi-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
IInteractiveRefreshTokenChangeEvent,
Label,
Signature,
ConnectionRequest,
} from '../../../shared/constants/mmi-controller';
import AccountTracker from '../lib/account-tracker';
import AppStateController from './app-state';
Expand Down Expand Up @@ -106,6 +107,10 @@ export default class MMIController extends EventEmitter {

private updateTransactionHash: (txId: string, txHash: string) => void;

private setChannelId: (channelId: string) => void;

private setConnectionRequest: (payload: ConnectionRequest | null) => void;

public trackTransactionEvents: (
args: { transactionMeta: TransactionMeta },
// TODO: Replace `any` with type
Expand Down Expand Up @@ -147,6 +152,8 @@ export default class MMIController extends EventEmitter {
this.extension = opts.extension;

this.updateTransactionHash = opts.updateTransactionHash;
this.setChannelId = opts.setChannelId;
this.setConnectionRequest = opts.setConnectionRequest;

this.trackTransactionEvents = opts.trackTransactionEvents;
this.txStateManager = {
Expand Down Expand Up @@ -185,6 +192,20 @@ export default class MMIController extends EventEmitter {
await this.handleSigningEvents(signature, messageId, 'v4');
},
);

this.transactionUpdateController.on(
'handshake',
async ({ channelId }: { channelId: string }) => {
this.setChannelId(channelId);
},
);

this.transactionUpdateController.on(
'connection.request',
async (payload: ConnectionRequest) => {
this.setConnectionRequest(payload);
},
);
} // End of constructor

async persistKeyringsAfterRefreshTokenChange() {
Expand Down
8 changes: 8 additions & 0 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -1812,6 +1812,10 @@ export default class MetamaskController extends EventEmitter {
this.txController.updateTransaction(txMeta, note),
updateTransactionHash: (id, hash) =>
this.txController.updateCustodialTransaction(id, { hash }),
setChannelId: (channelId) =>
this.institutionalFeaturesController.setChannelId(channelId),
setConnectionRequest: (payload) =>
this.institutionalFeaturesController.setConnectionRequest(payload),
});
///: END:ONLY_INCLUDE_IF

Expand Down Expand Up @@ -3356,6 +3360,10 @@ export default class MetamaskController extends EventEmitter {
this.institutionalFeaturesController.removeAddTokenConnectRequest.bind(
this.institutionalFeaturesController,
),
setConnectionRequest:
this.institutionalFeaturesController.setConnectionRequest.bind(
this.institutionalFeaturesController,
),
showInteractiveReplacementTokenBanner:
appStateController.showInteractiveReplacementTokenBanner.bind(
appStateController,
Expand Down
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -261,14 +261,14 @@
"@lavamoat/lavadome-react": "0.0.17",
"@lavamoat/snow": "^2.0.1",
"@material-ui/core": "^4.11.0",
"@metamask-institutional/custody-controller": "^0.2.24",
"@metamask-institutional/custody-keyring": "^1.0.12",
"@metamask-institutional/extension": "^0.3.20",
"@metamask-institutional/institutional-features": "^1.2.15",
"@metamask-institutional/custody-controller": "^0.2.25",
"@metamask-institutional/custody-keyring": "^1.1.0",
"@metamask-institutional/extension": "^0.3.21",
"@metamask-institutional/institutional-features": "^1.3.0",
"@metamask-institutional/portfolio-dashboard": "^1.4.0",
"@metamask-institutional/rpc-allowlist": "1.0.3",
"@metamask-institutional/sdk": "^0.1.25",
"@metamask-institutional/transaction-update": "^0.1.38",
"@metamask-institutional/rpc-allowlist": "^1.0.3",
"@metamask-institutional/sdk": "^0.1.26",
"@metamask-institutional/transaction-update": "^0.2.0",
"@metamask/abi-utils": "^2.0.2",
"@metamask/accounts-controller": "^11.0.0",
"@metamask/address-book-controller": "^3.1.7",
Expand Down
8 changes: 8 additions & 0 deletions shared/constants/mmi-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ export type MMIControllerOptions = {
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
updateTransaction: (txMeta: any) => void;
setChannelId: (channelId: string) => void;
setConnectionRequest: (payload: ConnectionRequest | null) => void;
};

export type ISignedEvent = {
Expand Down Expand Up @@ -89,3 +91,9 @@ export type NetworkConfiguration = {
chainId: string;
setActiveNetwork: (chainId: string) => void;
};

export type ConnectionRequest = {
payload: string;
traceId: string;
channelId: string;
};
19 changes: 18 additions & 1 deletion test/e2e/mmi/custodian-hooks/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ export class CustodianTestClient implements ICustodianTestClient {
const diffTime = transactions.map((tx: { createdAt: string }) =>
Math.abs(
new Date(tx.createdAt).getTime() -
parseInt(signedTransactionTime, 10),
parseInt(signedTransactionTime, 10),
),
);
const min = Math.min(...diffTime);
Expand Down Expand Up @@ -346,4 +346,21 @@ export class CustodianTestClient implements ICustodianTestClient {
async rejectPersonalSignatureId(txId: string): Promise<string | RegExp> {
return txId;
}

public async postConnectionRequest(data: any) {
return (await axios
.post("https://neptune-custody.dev.metamask-institutional.io/qrcode/connection-request", data, {
headers: {
'Content-Type': 'application/json',
},
})
.then(function (response) {
expect(response.status).toBe(200);
return response.data;
})
.catch(function (error) {
console.log(error.response.data);
throw error;
})) as string;
}
}
57 changes: 40 additions & 17 deletions test/e2e/mmi/pageObjects/mmi-accountMenu-page.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { type Locator, type Page, test, expect } from '@playwright/test';
import { getCustodianInfoByName } from '../helpers/custodian-helper';
import { MMISaturnUIPage } from './mmi-saturn-ui-page';
import { CustodianTestClient } from '../custodian-hooks/hooks';

export class MMIAccountMenuPage {
readonly page: Page;
Expand Down Expand Up @@ -46,7 +47,7 @@ export class MMIAccountMenuPage {
.filter({ hasText: 'Select an account' });
}

async connectCustodian(name: string, visual?: boolean) {
async connectCustodian(name: string, visual?: boolean, qrCode?: boolean) {
await this.page
.getByRole('button', { name: /Add account or hardware wallet/iu })
.click();
Expand All @@ -61,6 +62,7 @@ export class MMIAccountMenuPage {
}

const custodian = await getCustodianInfoByName(name);

await this.page
.getByRole('list')
.locator('div')
Expand All @@ -69,24 +71,45 @@ export class MMIAccountMenuPage {
.getByTestId('custody-connect-button')
.click();

await expect(
this.page.getByText(/connect saturn custody accounts/iu),
).toBeVisible();
if (visual) {
await test.expect
.soft(this.page)
.toHaveScreenshot('custodian_connection_info.png', { fullPage: true });
if (qrCode) {
const spanElement = await this.page.$('span.hidden');

if (spanElement) {
let data = await spanElement.getAttribute('data-value');

while (!data) {
await new Promise(resolve => setTimeout(resolve, 1000));
data = await spanElement.getAttribute('data-value');
}

const client = new CustodianTestClient();
await client.setup();
await client.postConnectionRequest(data);
await this.page.getByTestId('select-all-accounts-selected-false').click();
await this.page.getByRole('button', { name: /connect/iu }).click();
await this.page.getByRole('button', { name: /close/iu }).first().click();
}
} else {
await expect(
this.page.getByText(/connect saturn custody accounts/iu),
).toBeVisible();
if (visual) {
await test.expect
.soft(this.page)
.toHaveScreenshot('custodian_connection_info.png', { fullPage: true });
}

const pagePromise = this.page.context().waitForEvent('page');
await this.page.getByRole('button', { name: /continue/iu }).click();
const saturnUI = await pagePromise;
await saturnUI.waitForLoadState();

const saturnUIPage = new MMISaturnUIPage(saturnUI);
await saturnUIPage.connectMMI();
await this.page.getByRole('button', { name: /cancel/iu }).click();
await this.page.getByRole('button', { name: /back/iu }).click();
}

const pagePromise = this.page.context().waitForEvent('page');
await this.page.getByRole('button', { name: /continue/iu }).click();
const saturnUI = await pagePromise;
await saturnUI.waitForLoadState();

const saturnUIPage = new MMISaturnUIPage(saturnUI);
await saturnUIPage.connectMMI();
await this.page.getByRole('button', { name: /cancel/iu }).click();
await this.page.getByRole('button', { name: /back/iu }).click();
}

async selectCustodyAccount(account: string) {
Expand Down
3 changes: 2 additions & 1 deletion test/e2e/mmi/pageObjects/mmi-network-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export class MMINetworkPage {
}

async selectNetwork(network: string) {
await this.page.getByText(network).first().click();
await this.page.waitForSelector(`text=${network}`, { state: 'visible' });
await this.page.click(`text=${network}`, { force: true });
}
}
65 changes: 65 additions & 0 deletions test/e2e/mmi/specs/qrCode.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { type Page, type BrowserContext } from '@playwright/test';
import { test } from '../helpers/extension-loader';
import { ChromeExtensionPage } from '../pageObjects/mmi-extension-page';
import { MMIMainMenuPage } from '../pageObjects/mmi-mainMenu-page';
import { MMINetworkPage } from '../pageObjects/mmi-network-page';
import { MMISignUpPage } from '../pageObjects/mmi-signup-page';
import { MMIMainPage } from '../pageObjects/mmi-main-page';
import { MMIAccountMenuPage } from '../pageObjects/mmi-accountMenu-page';
import { CustodianTestClient } from '../custodian-hooks/hooks';
import { SEPOLIA_DISPLAY_NAME } from '../helpers/utils';

test.describe('QR Code Connection Request', () => {
test('run the extension and add custodian accounts using the QR Code feature', async ({
page,
context,
}) => {
const client = new CustodianTestClient();
await client.setup();

// Getting extension id of MMI
const extensions = new ChromeExtensionPage(await context.newPage());
await extensions.goto();
await extensions.setDevMode();
const extensionId = await extensions.getExtensionId();
await extensions.close();

const signUp = new MMISignUpPage(
await context.newPage(),
extensionId as string,
);
await signUp.goto();
await signUp.start();
await signUp.authentication();
await signUp.info();
await signUp.close();

// Setup testnetwork in settings
const mainMenuPage = new MMIMainMenuPage(page, extensionId as string);
await mainMenuPage.goto();
await mainMenuPage.fillPassword();
await mainMenuPage.finishOnboarding();
await mainMenuPage.selectMenuOption('settings');
await mainMenuPage.selectSettings('Advance');
await mainMenuPage.switchTestNetwork();
await mainMenuPage.closeSettings();

// Check network
const networkPage = new MMINetworkPage(page);
await networkPage.open();
await networkPage.selectNetwork(
process.env.MMI_E2E_TEST_NETWORK || SEPOLIA_DISPLAY_NAME,
);

// Get account from and to name
const accountFrom = await client.getAccountFrom();

const accountsPopup = new MMIAccountMenuPage(page);
await accountsPopup.accountsMenu();
await accountsPopup.connectCustodian('Neptune Custody', false, true);
await accountsPopup.selectCustodyAccount(accountFrom);

const mainPage = new MMIMainPage(page);
await mainPage.bringToFront();
});
});
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions ui/components/institutional/qr-code-modal/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './qr-code-modal';
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React from 'react';
import { Meta, StoryFn } from '@storybook/react';
import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';
import QRCodeModal from './qr-code-modal';

const mockStore = configureMockStore();
const testData = {
metamask: {
institutionalFeatures: {
channelId: 'channel123',
connectionRequest: {
payload: 'encryptedPayload',
},
},
},
};

const store = mockStore(testData);

const meta: Meta<typeof QRCodeModal> = {
title: 'Components/QRCodeModal',
decorators: [
(storyFn: any) => <Provider store={store}>{storyFn()}</Provider>,
],
component: QRCodeModal,
argTypes: {
onClose: { action: 'closed' },
custodianName: { control: 'text' },
custodianURL: { control: 'text' },
},
};

export default meta;

const Template: StoryFn<typeof QRCodeModal> = (args) => (
<QRCodeModal {...args} />
);

export const Default = Template.bind({});
Default.args = {
custodianName: 'Test Custodian',
custodianURL: 'http://testcustodian.com',
};

export const WithError = Template.bind({});
WithError.args = {
...Default.args,
error: 'Failed to load data',
};

0 comments on commit 8d4e334

Please sign in to comment.