Skip to content

Commit

Permalink
Simplify protocol name detection (#317)
Browse files Browse the repository at this point in the history
Simplify protocol name detection by using the `snaps-utils`
implementation. This makes the names chosen match the clients.

To bring in `snaps-utils` I had to make changes the Webpack
configuration and Jest because of the additional dependencies
introduced. All polyfills are intentionally turned off to not bloat the
bundle.

Closes #304
  • Loading branch information
FrederikBolding authored Feb 26, 2024
1 parent 2269694 commit 7d8f943
Show file tree
Hide file tree
Showing 14 changed files with 208 additions and 137 deletions.
18 changes: 18 additions & 0 deletions gatsby-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type { RequestInfo, RequestInit } from 'node-fetch';
import fetch from 'node-fetch';
import { fetchBuilder, FileSystemCache } from 'node-fetch-cache';
import path from 'path';
import { NormalModuleReplacementPlugin } from 'webpack';

import type { Fields } from './src/utils';
import { getLatestSnapVersion } from './src/utils';
Expand Down Expand Up @@ -520,6 +521,23 @@ export const onCreateWebpackConfig: GatsbyNode['onCreateWebpackConfig'] = ({

replaceWebpackConfig({
...config,
plugins: [
...config.plugins,
new NormalModuleReplacementPlugin(/node:/u, (resource) => {
resource.request = resource.request.replace(/^node:/u, '');
}),
],
resolve: {
...config.resolve,
fallback: {
...config.resolve.fallback,
assert: false,
crypto: false,
stream: false,
path: false,
url: false,
},
},
module: {
...config.module,
rules: [
Expand Down
4 changes: 3 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ module.exports = {
moduleNameMapper: {
'^.+\\.svg(\\?raw)?$': '<rootDir>/src/__mocks__/svg.tsx',
'^.+\\.(png|css)': '<rootDir>/src/__mocks__/file.ts',
// Force resolve nanoid to CJS to fix Jest tests
nanoid: require.resolve('nanoid'),
},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
Expand Down Expand Up @@ -154,7 +156,7 @@ module.exports = {
// snapshotSerializers: [],

// The test environment that will be used for testing
testEnvironment: 'jest-environment-jsdom',
testEnvironment: './jest.environment.js',

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
Expand Down
18 changes: 18 additions & 0 deletions jest.environment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/* eslint-disable */
const { TestEnvironment } = require('jest-environment-jsdom');

// Custom test environment copied from https://github.com/jsdom/jsdom/issues/2524
// in order to add TextEncoder to jsdom. TextEncoder is expected by jose.

module.exports = class CustomTestEnvironment extends TestEnvironment {
async setup() {
await super.setup();
if (typeof this.global.TextEncoder === 'undefined') {
const { TextEncoder, TextDecoder } = require('util');
this.global.TextEncoder = TextEncoder;
this.global.TextDecoder = TextDecoder;
this.global.ArrayBuffer = ArrayBuffer;
this.global.Uint8Array = Uint8Array;
}
}
};
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@
"@lingui/react": "^4.4.2",
"@metamask/logo": "^3.1.1",
"@metamask/providers": "^14.0.0",
"@metamask/slip44": "^3.1.0",
"@metamask/snaps-controllers": "^5.0.0",
"@metamask/snaps-sdk": "^2.0.0",
"@metamask/snaps-controllers": "^6.0.0",
"@metamask/snaps-sdk": "^3.0.0",
"@metamask/snaps-utils": "^7.0.0",
"@metamask/utils": "^8.1.0",
"@reduxjs/toolkit": "^1.9.6",
"framer-motion": "^10.16.2",
Expand Down Expand Up @@ -94,7 +94,6 @@
"@metamask/eslint-config-nodejs": "^12.0.0",
"@metamask/eslint-config-typescript": "^12.0.0",
"@metamask/snaps-registry": "^3.0.0",
"@metamask/snaps-utils": "^6.0.0",
"@svgr/webpack": "^8.1.0",
"@testing-library/jest-dom": "^6.1.3",
"@testing-library/react": "^14.0.0",
Expand Down Expand Up @@ -136,12 +135,14 @@
"jest-when": "^3.6.0",
"jimp": "^0.22.10",
"lint-staged": "^14.0.1",
"nanoid": "^3.3.7",
"node-fetch-cache": "^3.1.3",
"prettier": "^2.7.1",
"prettier-plugin-packagejson": "^2.3.0",
"sharp": "^0.32.5",
"simple-git-hooks": "^2.9.0",
"typescript": "~4.8.4"
"typescript": "~4.8.4",
"webpack": "^5.90.3"
},
"packageManager": "[email protected]",
"engines": {
Expand Down
8 changes: 4 additions & 4 deletions src/features/snap/permissions.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ describe('SNAP_PERMISSIONS', () => {
"id": "TuvFzN",
"message": "Manage {name} accounts",
"values": Object {
"name": "Testnet (all coins)",
"name": "Testnet",
},
},
"weight": 1,
Expand Down Expand Up @@ -575,7 +575,7 @@ describe('SNAP_PERMISSIONS', () => {
"id": "TuvFzN",
"message": "Manage {name} accounts",
"values": Object {
"name": "Testnet (all coins)",
"name": "Test Networks",
},
},
"weight": 1,
Expand Down Expand Up @@ -641,7 +641,7 @@ describe('SNAP_PERMISSIONS', () => {
"id": "P4MCkP",
"message": "View your public key for {name}",
"values": Object {
"name": "Testnet (all coins)",
"name": "Testnet",
},
},
"weight": 2,
Expand Down Expand Up @@ -894,7 +894,7 @@ describe('getPermissions', () => {
"id": "P4MCkP",
"message": "View your public key for {name}",
"values": Object {
"name": "Testnet (all coins)",
"name": "Testnet",
},
},
"weight": 2,
Expand Down
71 changes: 50 additions & 21 deletions src/features/snap/permissions.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import type { MessageDescriptor } from '@lingui/core';
import { defineMessage } from '@lingui/macro';
import slip44 from '@metamask/slip44';
import type { EmptyObject, InitialPermissions } from '@metamask/snaps-sdk';
import type { SnapsDerivationPath } from '@metamask/snaps-utils';
import {
getSnapDerivationPathName,
getSlip44ProtocolName,
} from '@metamask/snaps-utils';
import type { FunctionComponent } from 'react';

import type { IconProps } from '../../components';
Expand Down Expand Up @@ -71,16 +75,40 @@ type PermissionsMap = {
};

/**
* Get the label to use for a network.
* Get the label to use for a network using the coin type.
*
* @param networkId - The ID of the network to get the name for.
* @param coinType - The coin_type of the network to get the name for.
* @param fallback - The fallback name to use if the network is unknown.
* @returns The label for the network, or the fallback if the network is
* unknown.
*/
function getNetworkLabel(networkId: string, fallback: MessageDescriptor) {
// TODO: Use functions from `@metamask/snaps-utils` instead of `slip44`.
const name = slip44[networkId as keyof typeof slip44]?.name;
function getNetworkLabelByCoinType(
coinType: string,
fallback: MessageDescriptor,
) {
const name = getSlip44ProtocolName(coinType);
if (name) {
return defineMessage`Manage ${name} accounts`;
}

return fallback;
}

/**
* Get the label to use for a network using path and curve.
*
* @param path - The derivation path of the network to get the name for.
* @param curve - The curve of the network to get the name for.
* @param fallback - The fallback name to use if the network is unknown.
* @returns The label for the network, or the fallback if the network is
* unknown.
*/
function getNetworkLabelByPath(
path: SnapsDerivationPath['path'],
curve: SnapsDerivationPath['curve'],
fallback: MessageDescriptor,
) {
const name = getSnapDerivationPathName(path, curve);
if (name) {
return defineMessage`Manage ${name} accounts`;
}
Expand All @@ -91,17 +119,18 @@ function getNetworkLabel(networkId: string, fallback: MessageDescriptor) {
/**
* Get the label to use for a network.
*
* @param networkId - The ID of the network to get the name for.
* @param path - The derivation path of the network to get the name for.
* @param curve - The curve of the network to get the name for.
* @param fallback - The fallback name to use if the network is unknown.
* @returns The label for the network, or the fallback if the network is
* unknown.
*/
function getPublicKeyNetworkLabel(
networkId: string,
path: SnapsDerivationPath['path'],
curve: SnapsDerivationPath['curve'],
fallback: MessageDescriptor,
) {
// TODO: Use functions from `@metamask/snaps-utils` instead of `slip44`.
const name = slip44[networkId as keyof typeof slip44]?.name;
const name = getSnapDerivationPathName(path, curve);
if (name) {
return defineMessage`View your public key for ${name}`;
}
Expand Down Expand Up @@ -238,13 +267,13 @@ export const SNAP_PERMISSIONS: PermissionsMap = {
return permission.map(({ path, curve }) => {
const purpose = path[1];
const coinType = path[2] as string;
const isBip44 =
curve === 'secp256k1' && purpose === `44'` && coinType?.endsWith(`'`);

const fallback = defineMessage`Manage accounts (Unknown network "m/${purpose}/${coinType}")`;
const label = isBip44
? getNetworkLabel(coinType.slice(0, -1), fallback)
: fallback;
const label = getNetworkLabelByPath(
path as SnapsDerivationPath['path'],
curve,
fallback,
);

return {
label,
Expand All @@ -257,7 +286,7 @@ export const SNAP_PERMISSIONS: PermissionsMap = {
snap_getBip44Entropy: ({ name }, permission) => {
return permission.map(({ coinType }) => {
const fallback = defineMessage`Manage accounts (Unknown network "m/44'/${coinType}'")`;
const label = getNetworkLabel(String(coinType), fallback);
const label = getNetworkLabelByCoinType(String(coinType), fallback);

return {
label,
Expand All @@ -271,13 +300,13 @@ export const SNAP_PERMISSIONS: PermissionsMap = {
return permission.map(({ path, curve }) => {
const purpose = path[1];
const coinType = path[2] as string;
const isBip44 =
curve === 'secp256k1' && purpose === `44'` && coinType?.endsWith(`'`);

const fallback = defineMessage`View your public key (Unknown network "m/${purpose}/${coinType}")`;
const label = isBip44
? getPublicKeyNetworkLabel(coinType.slice(0, -1), fallback)
: fallback;
const label = getPublicKeyNetworkLabel(
path as SnapsDerivationPath['path'],
curve,
fallback,
);

return {
label,
Expand Down
1 change: 1 addition & 0 deletions src/locales/de-DE/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ msgstr "Link"
msgid "Live"
msgstr "Live"

#: src/features/snap/permissions.tsx
#: src/features/snap/permissions.tsx
msgid "Manage {name} accounts"
msgstr "{name}-Konten verwalten"
Expand Down
1 change: 1 addition & 0 deletions src/locales/en-US/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,7 @@ msgstr ""
msgid "Live"
msgstr ""

#: src/features/snap/permissions.tsx
#: src/features/snap/permissions.tsx
msgid "Manage {name} accounts"
msgstr ""
Expand Down
1 change: 1 addition & 0 deletions src/locales/ja-JP/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ msgstr "リンク"
msgid "Live"
msgstr "ライブ"

#: src/features/snap/permissions.tsx
#: src/features/snap/permissions.tsx
msgid "Manage {name} accounts"
msgstr "{name}アカウントの管理"
Expand Down
1 change: 1 addition & 0 deletions src/locales/pt-BR/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ msgstr "Link"
msgid "Live"
msgstr "No ar"

#: src/features/snap/permissions.tsx
#: src/features/snap/permissions.tsx
msgid "Manage {name} accounts"
msgstr "Gerenciar contas de {name}"
Expand Down
1 change: 1 addition & 0 deletions src/locales/ru-RU/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ msgstr "Ссылка"
msgid "Live"
msgstr "Выпущенная версия"

#: src/features/snap/permissions.tsx
#: src/features/snap/permissions.tsx
msgid "Manage {name} accounts"
msgstr "Управление счетами {name}"
Expand Down
1 change: 1 addition & 0 deletions src/locales/tr-TR/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ msgstr "Bağlantı"
msgid "Live"
msgstr "Canlı"

#: src/features/snap/permissions.tsx
#: src/features/snap/permissions.tsx
msgid "Manage {name} accounts"
msgstr "{name} hesaplarını yönet"
Expand Down
1 change: 1 addition & 0 deletions src/locales/zh-CN/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ msgstr "链接"
msgid "Live"
msgstr "在线"

#: src/features/snap/permissions.tsx
#: src/features/snap/permissions.tsx
msgid "Manage {name} accounts"
msgstr "管理 {name} 账户"
Expand Down
Loading

0 comments on commit 7d8f943

Please sign in to comment.