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

Implement EIP-6963 #263

Merged
merged 22 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 11 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
22 changes: 21 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,32 @@ module.exports = {
},

{
files: ['*.test.ts', '*.test.js'],
files: ['*.test.ts', '*.test.js', 'jest.setup*.js'],
extends: [
'@metamask/eslint-config-jest',
'@metamask/eslint-config-nodejs',
],
},

{
files: ['EIP6963.test.ts', 'jest.setup.browser.js'],
rules: {
// We're mixing Node and browser environments in these files.
'no-restricted-globals': 'off',
},
},

{
files: ['jest.setup.browser.js'],
env: { browser: true },
// This file contains copypasta and we're not going to bother fixing these.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😅

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/Users/jiexi/Projects/providers/jest.setup.browser.js
  25:1  error  All hooks must be wrapped in a describe block  jest/require-top-level-describe
  30:5  error  Missing JSDoc block description                jsdoc/require-description
  32:1  error  Missing JSDoc @param "type" description        jsdoc/require-param-description
  32:1  error  Missing JSDoc @param "type" type               jsdoc/require-param-type
  33:1  error  Missing JSDoc @param "listener" description    jsdoc/require-param-description
  33:1  error  Missing JSDoc @param "listener" type           jsdoc/require-param-type
  34:1  error  Missing JSDoc @param "options" description     jsdoc/require-param-description
  34:1  error  Missing JSDoc @param "options" type            jsdoc/require-param-type
  55:1  error  All hooks must be wrapped in a describe block  jest/require-top-level-describe

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely need to ignore jest/require-top-level-describe

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you feel it's worthwhile to add jsdoc to the rest? I can go either way

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lol, this was me btw. It seems strictly not worth it, as I have a hard time imagining a lot of work being done in that file, but not my call of course!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm good with this, just thought it was funny :)

rules: {
'jest/require-top-level-describe': 'off',
'jsdoc/require-description': 'off',
'jsdoc/require-param-description': 'off',
'jsdoc/require-param-type': 'off',
},
},
],

ignorePatterns: [
Expand Down
16 changes: 10 additions & 6 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ const baseConfig = {
// An object that configures minimum threshold enforcement for coverage results
coverageThreshold: {
global: {
branches: 61.29,
functions: 60.24,
lines: 63.82,
statements: 63.97,
branches: 64.25,
functions: 64.89,
lines: 66.35,
statements: 66.43,
},
},

Expand Down Expand Up @@ -222,8 +222,12 @@ const browserConfig = {
...baseConfig,
displayName: 'Browser Providers',
testEnvironment: 'jsdom',
testMatch: ['**/*InpageProvider.test.ts', '**/*ExtensionProvider.test.ts'],
setupFilesAfterEnv: ['./jest.setup.js'],
testMatch: [
'**/*InpageProvider.test.ts',
'**/*ExtensionProvider.test.ts',
'**/EIP6963.test.ts',
],
setupFilesAfterEnv: ['./jest.setup.browser.js'],
};

module.exports = {
Expand Down
87 changes: 87 additions & 0 deletions jest.setup.browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
Object.assign(global, require('jest-chrome'));

// Clean up jsdom between tests.
// Courtesy @jhildenbiddle
// https://github.com/jestjs/jest/issues/1224#issuecomment-716075260
const sideEffects = {
document: {
addEventListener: {
fn: document.addEventListener,
refs: [],
},
keys: Object.keys(document),
},
window: {
addEventListener: {
fn: window.addEventListener,
refs: [],
},
keys: Object.keys(window),
},
};

// Lifecycle Hooks
// -----------------------------------------------------------------------------
beforeAll(async () => {
// Spy addEventListener
['document', 'window'].forEach((obj) => {
const { fn, refs } = sideEffects[obj].addEventListener;

/**
*
* @param type
* @param listener
* @param options
*/
function addEventListenerSpy(type, listener, options) {
// Store listener reference so it can be removed during reset
refs.push({ type, listener, options });
// Call original window.addEventListener
fn(type, listener, options);
}

// Add to default key array to prevent removal during reset
sideEffects[obj].keys.push('addEventListener');

// Replace addEventListener with mock
global[obj].addEventListener = addEventListenerSpy;
});
});

// Reset JSDOM. This attempts to remove side effects from tests, however it does
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran into JSDOM state issues when working on the phishing warning page too. In that case, I found it easiest to just use a real browser. See MetaMask/phishing-warning#62

Likewise for browser-passworder, that one is a plain library that we wanted to test in a real browser to ensure we were using browser APIs correctly. That uses playwright too: https://github.com/MetaMask/browser-passworder/blob/f870292ec5db729c8f69bbe4b2d3cff60053f333/test/index.spec.ts

Something to consider, if this needs further maintenance or continues to be a burden.

// not reset all changes made to globals like the window and document
// objects. Tests requiring a full JSDOM reset should be stored in separate
// files, which is only way to do a complete JSDOM reset with Jest.
beforeEach(async () => {
const rootElm = document.documentElement;

// Remove attributes on root element
[...rootElm.attributes].forEach((attr) => rootElm.removeAttribute(attr.name));

// Remove elements (faster than setting innerHTML)
while (rootElm.firstChild) {
rootElm.removeChild(rootElm.firstChild);
}

// Remove global listeners and keys
['document', 'window'].forEach((obj) => {
const { refs } = sideEffects[obj].addEventListener;

// Listeners
while (refs.length) {
const { type, listener, options } = refs.pop();
global[obj].removeEventListener(type, listener, options);
}

// This breaks coverage.
// // Keys
// Object.keys(global[obj])
// .filter((key) => !sideEffects[obj].keys.includes(key))
// .forEach((key) => {
// delete global[obj][key];
// });
});

// Restore base elements
rootElm.innerHTML = '<head></head><body></body>';
});
1 change: 0 additions & 1 deletion jest.setup.js

This file was deleted.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"dependencies": {
"@metamask/object-multiplex": "^1.1.0",
"@metamask/safe-event-emitter": "^3.0.0",
"@metamask/utils": "^5.0.2",
"detect-browser": "^5.2.0",
"eth-rpc-errors": "^4.0.2",
"extension-port-stream": "^2.0.1",
Expand All @@ -61,6 +62,7 @@
"@types/node": "^17.0.23",
"@types/pump": "^1.1.0",
"@types/readable-stream": "^2.3.15",
"@types/uuid": "^9.0.1",
"@types/webextension-polyfill": "^0.10.0",
"@typescript-eslint/eslint-plugin": "^5.43.0",
"@typescript-eslint/parser": "^5.43.0",
Expand Down
195 changes: 195 additions & 0 deletions src/EIP6963.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
import { announceProvider, requestProvider } from './EIP6963';

const getProviderInfo = () => ({
name: 'test',
icon: 'https://wallet.io/icon.svg',
uuid: '1449211e-5560-4235-9ab1-582cbe2b165f',
});

const providerInfoValidationError = () =>
new Error(
'Invalid EIP-6963 ProviderDetail object. See https://eips.ethereum.org/EIPS/eip-6963 for requirements.',
);

describe('EIP6963', () => {
describe('announceProvider', () => {
describe('provider info validation', () => {
it('throws if the provider info is not a plain object', () => {
[null, undefined, Symbol('bar'), []].forEach((invalidInfo) => {
expect(() => announceProvider(invalidInfo as any)).toThrow(
providerInfoValidationError(),
);
});
});

it('throws if the `icon` field is invalid', () => {
[null, undefined, '', 'not-a-url', Symbol('bar')].forEach(
(invalidIcon) => {
const provider: any = { name: 'test' };
const providerDetail = { info: getProviderInfo(), provider };
providerDetail.info.icon = invalidIcon as any;

expect(() => announceProvider(providerDetail)).toThrow(
providerInfoValidationError(),
);
},
);
});

it('throws if the `name` field is invalid', () => {
[null, undefined, '', {}, [], Symbol('bar')].forEach((invalidName) => {
const provider: any = { name: 'test' };
const providerDetail = { info: getProviderInfo(), provider };
providerDetail.info.name = invalidName as any;

expect(() => announceProvider(providerDetail)).toThrow(
providerInfoValidationError(),
);
});
});

it('throws if the `uuid` field is invalid', () => {
[null, undefined, '', 'foo', Symbol('bar')].forEach((invalidUuid) => {
const provider: any = { name: 'test' };
const providerDetail = { info: getProviderInfo(), provider };
providerDetail.info.uuid = invalidUuid as any;

expect(() => announceProvider(providerDetail)).toThrow(
providerInfoValidationError(),
);
});
});
});

describe('provider validation', () => {
it('throws if the provider is not a plain object', () => {
[null, undefined, Symbol('bar'), []].forEach((invalidProvider) => {
const provider: any = invalidProvider;
const providerDetail = { info: getProviderInfo(), provider };

expect(() => announceProvider(providerDetail)).toThrow(
providerInfoValidationError(),
);
});
});
});

it('should announce a provider', () => {
jiexi marked this conversation as resolved.
Show resolved Hide resolved
const provider: any = { name: 'test' };
const providerDetail = { info: getProviderInfo(), provider };
const dispatchEvent = jest.spyOn(window, 'dispatchEvent');
const addEventListener = jest.spyOn(window, 'addEventListener');

announceProvider(providerDetail);

expect(dispatchEvent).toHaveBeenCalledTimes(1);
expect(dispatchEvent).toHaveBeenCalledWith(
new CustomEvent('eip6963:announceProvider', {
detail: {
info: getProviderInfo(),
provider,
},
}),
);
expect(addEventListener).toHaveBeenCalledTimes(1);
expect(addEventListener).toHaveBeenCalledWith(
'eip6963:requestProvider',
expect.any(Function),
);
});
});

describe('requestProvider', () => {
it('should receive an announced provider (called before announceProvider)', async () => {
const provider: any = { name: 'test' };
const providerDetail = { info: getProviderInfo(), provider };
const handleProvider = jest.fn();
const dispatchEvent = jest.spyOn(window, 'dispatchEvent');
const addEventListener = jest.spyOn(window, 'addEventListener');
jiexi marked this conversation as resolved.
Show resolved Hide resolved

requestProvider(handleProvider);
announceProvider(providerDetail);
await delay();

expect(dispatchEvent).toHaveBeenCalledTimes(2);
expect(dispatchEvent).toHaveBeenNthCalledWith(
1,
new Event('eip6963:requestProvider'),
);
expect(dispatchEvent).toHaveBeenNthCalledWith(
2,
new CustomEvent('eip6963:announceProvider'),
);
jiexi marked this conversation as resolved.
Show resolved Hide resolved

expect(addEventListener).toHaveBeenCalledTimes(2);
expect(addEventListener).toHaveBeenCalledWith(
'eip6963:announceProvider',
expect.any(Function),
);
expect(addEventListener).toHaveBeenCalledWith(
'eip6963:requestProvider',
expect.any(Function),
);

expect(handleProvider).toHaveBeenCalledTimes(1);
expect(handleProvider).toHaveBeenCalledWith({
info: getProviderInfo(),
provider,
});
});

it('should receive an announced provider (called after announceProvider)', async () => {
const provider: any = { name: 'test' };
const providerDetail = { info: getProviderInfo(), provider };
const handleProvider = jest.fn();
const dispatchEvent = jest.spyOn(window, 'dispatchEvent');
const addEventListener = jest.spyOn(window, 'addEventListener');

announceProvider(providerDetail);
requestProvider(handleProvider);
await delay();

// Notice that 3 events are dispatched in total when requestProvider is
// called after announceProvider.
expect(dispatchEvent).toHaveBeenCalledTimes(3);
expect(dispatchEvent).toHaveBeenNthCalledWith(
1,
new CustomEvent('eip6963:announceProvider'),
);
expect(dispatchEvent).toHaveBeenNthCalledWith(
2,
new Event('eip6963:requestProvider'),
);
expect(dispatchEvent).toHaveBeenNthCalledWith(
3,
new CustomEvent('eip6963:announceProvider'),
);
jiexi marked this conversation as resolved.
Show resolved Hide resolved

expect(addEventListener).toHaveBeenCalledTimes(2);
expect(addEventListener).toHaveBeenCalledWith(
'eip6963:announceProvider',
expect.any(Function),
);
expect(addEventListener).toHaveBeenCalledWith(
'eip6963:requestProvider',
expect.any(Function),
);

expect(handleProvider).toHaveBeenCalledTimes(1);
expect(handleProvider).toHaveBeenCalledWith({
info: getProviderInfo(),
provider,
});
});
});
});

/**
* Delay for a number of milliseconds by awaiting a promise
* resolved after the specified number of milliseconds.
*
* @param ms - The number of milliseconds to delay for.
*/
async function delay(ms = 1) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
Loading