Skip to content

Commit

Permalink
fix(deps): update from eth-rpc-errors to @metamask/rpc-errors (cause …
Browse files Browse the repository at this point in the history
…edition) (#24496)

- Upgrade from obsolete `eth-rpc-errors` to `@metamask/rpc-errors`
  - This introduce handling of error causes

See [here](MetaMask/rpc-errors#140) for some
context.

[![Open in GitHub
Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/MetaMask/metamask-extension/pull/24496?quickstart=1)

- #22871

- [x] MetaMask/rpc-errors#158
- [x] MetaMask/rpc-errors#144
  - [x] MetaMask/rpc-errors#140

- #22875

- [x] I’ve followed [MetaMask Coding
Standards](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've completed the PR template to the best of my ability
- [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.

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] 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.
  • Loading branch information
legobeat authored and Gudahtt committed Oct 21, 2024
1 parent 22bf4ad commit b4c1f9c
Show file tree
Hide file tree
Showing 49 changed files with 1,378 additions and 290 deletions.
4 changes: 2 additions & 2 deletions app/scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { isObject } from '@metamask/utils';
import { ApprovalType } from '@metamask/controller-utils';
import PortStream from 'extension-port-stream';

import { ethErrors } from 'eth-rpc-errors';
import { providerErrors } from '@metamask/rpc-errors';
import { DIALOG_APPROVAL_TYPES } from '@metamask/snaps-rpc-methods';
import { NotificationServicesController } from '@metamask/notification-services-controller';

Expand Down Expand Up @@ -1156,7 +1156,7 @@ export function setupController(
default:
controller.approvalController.reject(
id,
ethErrors.provider.userRejectedRequest(),
providerErrors.userRejectedRequest(),
);
break;
}
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/lib/createMetaRPCHandler.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ethErrors, serializeError } from 'eth-rpc-errors';
import { rpcErrors, serializeError } from '@metamask/rpc-errors';
import { isStreamWritable } from './stream-utils';

const createMetaRPCHandler = (api, outStream) => {
Expand All @@ -9,7 +9,7 @@ const createMetaRPCHandler = (api, outStream) => {
if (!api[data.method]) {
outStream.write({
jsonrpc: '2.0',
error: ethErrors.rpc.methodNotFound({
error: rpcErrors.methodNotFound({
message: `${data.method} not found`,
}),
id: data.id,
Expand Down
1 change: 1 addition & 0 deletions app/scripts/lib/createMetaRPCHandler.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ describe('createMetaRPCHandler', () => {
});
streamTest.on('data', (data) => {
expect(data.error.message).toStrictEqual('foo-error');
expect(data.error.data.cause.message).toStrictEqual('foo-error');
streamTest.end();
});
});
Expand Down
2 changes: 1 addition & 1 deletion app/scripts/lib/createRPCMethodTrackingMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ApprovalType, detectSIWE } from '@metamask/controller-utils';
import { errorCodes } from 'eth-rpc-errors';
import { errorCodes } from '@metamask/rpc-errors';
import { isValidAddress } from 'ethereumjs-util';
import { MESSAGE_TYPE, ORIGIN_METAMASK } from '../../../shared/constants/app';
import {
Expand Down
2 changes: 1 addition & 1 deletion app/scripts/lib/createRPCMethodTrackingMiddleware.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { errorCodes } from 'eth-rpc-errors';
import { errorCodes } from '@metamask/rpc-errors';
import { detectSIWE } from '@metamask/controller-utils';

import MetaMetricsController from '../controllers/metametrics';
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/lib/metaRPCClientFactory.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { EthereumRpcError } from 'eth-rpc-errors';
import { JsonRpcError } from '@metamask/rpc-errors';
import SafeEventEmitter from '@metamask/safe-event-emitter';
import createRandomId from '../../../shared/modules/random-id';
import { TEN_SECONDS_IN_MILLISECONDS } from '../../../shared/lib/transactions-controller-utils';
Expand Down Expand Up @@ -77,7 +77,7 @@ class MetaRPCClient {
}

if (error) {
const e = new EthereumRpcError(error.code, error.message, error.data);
const e = new JsonRpcError(error.code, error.message, error.data);
// preserve the stack from serializeError
e.stack = error.stack;
if (cb) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { permissionRpcMethods } from '@metamask/permission-controller';
import { rpcErrors } from '@metamask/rpc-errors';
import { selectHooks } from '@metamask/snaps-rpc-methods';
import { hasProperty } from '@metamask/utils';
import { ethErrors } from 'eth-rpc-errors';
import { handlers as localHandlers, legacyHandlers } from './handlers';

const allHandlers = [...localHandlers, ...permissionRpcMethods.handlers];
Expand Down Expand Up @@ -67,7 +67,7 @@ function makeMethodMiddlewareMaker(handlers) {
return end(
error instanceof Error
? error
: ethErrors.rpc.internal({ data: error }),
: rpcErrors.internal({ data: error }),
);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ethErrors } from 'eth-rpc-errors';
import { rpcErrors } from '@metamask/rpc-errors';
import type { JsonRpcMiddleware } from 'json-rpc-engine';
import { UNSUPPORTED_RPC_METHODS } from '../../../../shared/constants/network';

Expand All @@ -12,7 +12,7 @@ export function createUnsupportedMethodMiddleware(): JsonRpcMiddleware<
> {
return async function unsupportedMethodMiddleware(req, _res, next, end) {
if ((UNSUPPORTED_RPC_METHODS as Set<string>).has(req.method)) {
return end(ethErrors.rpc.methodNotSupported());
return end(rpcErrors.methodNotSupported());
}
return next();
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ApprovalType } from '@metamask/controller-utils';
import * as URI from 'uri-js';
import { ApprovalType } from '@metamask/controller-utils';
import { RpcEndpointType } from '@metamask/network-controller';
import { ethErrors } from 'eth-rpc-errors';
import { rpcErrors } from '@metamask/rpc-errors';
import { cloneDeep } from 'lodash';
import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
import {
Expand Down Expand Up @@ -76,7 +76,7 @@ async function addEthereumChainHandler(
existingNetwork.nativeCurrency !== ticker
) {
return end(
ethErrors.rpc.invalidParams({
rpcErrors.invalidParams({
message: `nativeCurrency.symbol does not match currency symbol for a network the user already has added with the same chainId. Received:\n${ticker}`,
}),
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ethErrors } from 'eth-rpc-errors';
import { rpcErrors } from '@metamask/rpc-errors';
import { CHAIN_IDS } from '../../../../../shared/constants/network';
import addEthereumChain from './add-ethereum-chain';

Expand Down Expand Up @@ -365,7 +365,7 @@ describe('addEthereumChainHandler', () => {
);

expect(mockEnd).toHaveBeenCalledWith(
ethErrors.rpc.invalidParams({
rpcErrors.invalidParams({
message: `Expected 0x-prefixed, unpadded, non-zero hexadecimal string 'chainId'. Received:\ninvalid_chain_id`,
}),
);
Expand Down Expand Up @@ -592,7 +592,7 @@ describe('addEthereumChainHandler', () => {
);

expect(mockEnd).toHaveBeenCalledWith(
ethErrors.rpc.invalidParams({
rpcErrors.invalidParams({
message: `Received unexpected keys on object parameter. Unsupported keys:\n${unexpectedParam}`,
}),
);
Expand Down Expand Up @@ -676,7 +676,7 @@ describe('addEthereumChainHandler', () => {
);

expect(mockEnd).toHaveBeenCalledWith(
ethErrors.rpc.invalidParams({
rpcErrors.invalidParams({
message: `nativeCurrency.symbol does not match currency symbol for a network the user already has added with the same chainId. Received:\nWRONG`,
}),
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { errorCodes, ethErrors } from 'eth-rpc-errors';
import { errorCodes, rpcErrors } from '@metamask/rpc-errors';
import { ApprovalType } from '@metamask/controller-utils';
import {
isPrefixedFormattedHexString,
Expand All @@ -12,13 +12,13 @@ import { getValidUrl } from '../../util';
export function validateChainId(chainId) {
const _chainId = typeof chainId === 'string' && chainId.toLowerCase();
if (!isPrefixedFormattedHexString(_chainId)) {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Expected 0x-prefixed, unpadded, non-zero hexadecimal string 'chainId'. Received:\n${chainId}`,
});
}

if (!isSafeChainId(parseInt(_chainId, 16))) {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Invalid chain ID "${_chainId}": numerical value greater than max safe value. Received:\n${chainId}`,
});
}
Expand All @@ -28,7 +28,7 @@ export function validateChainId(chainId) {

export function validateSwitchEthereumChainParams(req, end) {
if (!req.params?.[0] || typeof req.params[0] !== 'object') {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Expected single, object parameter. Received:\n${JSON.stringify(
req.params,
)}`,
Expand All @@ -37,7 +37,7 @@ export function validateSwitchEthereumChainParams(req, end) {
const { chainId, ...otherParams } = req.params[0];

if (Object.keys(otherParams).length > 0) {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Received unexpected keys on object parameter. Unsupported keys:\n${Object.keys(
otherParams,
)}`,
Expand All @@ -49,7 +49,7 @@ export function validateSwitchEthereumChainParams(req, end) {

export function validateAddEthereumChainParams(params, end) {
if (!params || typeof params !== 'object') {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Expected single, object parameter. Received:\n${JSON.stringify(
params,
)}`,
Expand All @@ -71,14 +71,14 @@ export function validateAddEthereumChainParams(params, end) {
);

if (otherKeys.length > 0) {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Received unexpected keys on object parameter. Unsupported keys:\n${otherKeys}`,
});
}

const _chainId = validateChainId(chainId, end);
if (!rpcUrls || !Array.isArray(rpcUrls) || rpcUrls.length === 0) {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Expected an array with at least one valid string HTTPS url 'rpcUrls', Received:\n${rpcUrls}`,
});
}
Expand All @@ -101,13 +101,13 @@ export function validateAddEthereumChainParams(params, end) {
: null;

if (!firstValidRPCUrl) {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Expected an array with at least one valid string HTTPS url 'rpcUrls', Received:\n${rpcUrls}`,
});
}

if (typeof chainName !== 'string' || !chainName) {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Expected non-empty string 'chainName'. Received:\n${chainName}`,
});
}
Expand All @@ -117,18 +117,18 @@ export function validateAddEthereumChainParams(params, end) {

if (nativeCurrency !== null) {
if (typeof nativeCurrency !== 'object' || Array.isArray(nativeCurrency)) {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Expected null or object 'nativeCurrency'. Received:\n${nativeCurrency}`,
});
}
if (nativeCurrency.decimals !== 18) {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Expected the number 18 for 'nativeCurrency.decimals' when 'nativeCurrency' is provided. Received: ${nativeCurrency.decimals}`,
});
}

if (!nativeCurrency.symbol || typeof nativeCurrency.symbol !== 'string') {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Expected a string 'nativeCurrency.symbol'. Received: ${nativeCurrency.symbol}`,
});
}
Expand All @@ -139,7 +139,7 @@ export function validateAddEthereumChainParams(params, end) {
ticker !== UNKNOWN_TICKER_SYMBOL &&
(typeof ticker !== 'string' || ticker.length < 1 || ticker.length > 6)
) {
throw ethErrors.rpc.invalidParams({
throw rpcErrors.invalidParams({
message: `Expected 1-6 character string 'nativeCurrency.symbol'. Received:\n${ticker}`,
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ethErrors } from 'eth-rpc-errors';
import { isAllowedRPCOrigin } from '@metamask-institutional/rpc-allowlist';
import { rpcErrors } from '@metamask/rpc-errors';
import { MESSAGE_TYPE } from '../../../../../../shared/constants/app';

const mmiSetAccountAndNetwork = {
Expand Down Expand Up @@ -46,7 +46,7 @@ async function mmiSetAccountAndNetworkHandler(

if (!req.params?.[0] || typeof req.params[0] !== 'object') {
return end(
ethErrors.rpc.invalidParams({
rpcErrors.invalidParams({
message: `Expected single, object parameter. Received:\n${JSON.stringify(
req.params,
)}`,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ethErrors } from 'eth-rpc-errors';
import { rpcErrors } from '@metamask/rpc-errors';
import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
import {
MetaMetricsEventName,
Expand Down Expand Up @@ -71,7 +71,7 @@ async function requestEthereumAccountsHandler(
},
) {
if (locks.has(origin)) {
res.error = ethErrors.rpc.resourceUnavailable(
res.error = rpcErrors.resourceUnavailable(
`Already processing ${MESSAGE_TYPE.ETH_REQUEST_ACCOUNTS}. Please wait.`,
);
return end();
Expand Down Expand Up @@ -132,7 +132,7 @@ async function requestEthereumAccountsHandler(
} else {
// This should never happen, because it should be caught in the
// above catch clause
res.error = ethErrors.rpc.internal(
res.error = rpcErrors.internal(
'Accounts unexpectedly unavailable. Please report this bug.',
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ethErrors } from 'eth-rpc-errors';
import { rpcErrors } from '@metamask/rpc-errors';
import { MESSAGE_TYPE } from '../../../../../shared/constants/app';

/**
Expand Down Expand Up @@ -50,7 +50,7 @@ function sendMetadataHandler(
origin,
});
} else {
return end(ethErrors.rpc.invalidParams({ data: params }));
return end(rpcErrors.invalidParams({ data: params }));
}

res.result = true;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ethErrors } from 'eth-rpc-errors';
import { providerErrors } from '@metamask/rpc-errors';
import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
import {
validateSwitchEthereumChainParams,
Expand Down Expand Up @@ -59,7 +59,7 @@ async function switchEthereumChainHandler(

if (!networkClientIdToSwitchTo) {
return end(
ethErrors.provider.custom({
providerErrors.custom({
code: 4902,
message: `Unrecognized chain ID "${chainId}". Try adding the chain using ${MESSAGE_TYPE.ADD_ETHEREUM_CHAIN} first.`,
}),
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/lib/rpc-method-middleware/handlers/watch-asset.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ERC1155, ERC721 } from '@metamask/controller-utils';
import { ethErrors } from 'eth-rpc-errors';
import { rpcErrors } from '@metamask/rpc-errors';
import { MESSAGE_TYPE } from '../../../../../shared/constants/app';

const watchAsset = {
Expand Down Expand Up @@ -51,7 +51,7 @@ async function watchAssetHandler(
typeof tokenId !== 'string'
) {
return end(
ethErrors.rpc.invalidParams({
rpcErrors.invalidParams({
message: `Expected parameter 'tokenId' to be type 'string'. Received type '${typeof tokenId}'`,
}),
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ERC20, ERC721 } from '@metamask/controller-utils';
import { ethErrors } from 'eth-rpc-errors';
import { rpcErrors } from '@metamask/rpc-errors';
import watchAssetHandler from './watch-asset';

describe('watchAssetHandler', () => {
Expand Down Expand Up @@ -95,7 +95,7 @@ describe('watchAssetHandler', () => {
});

expect(mockEnd).toHaveBeenCalledWith(
ethErrors.rpc.invalidParams({
rpcErrors.invalidParams({
message: `Expected parameter 'tokenId' to be type 'string'. Received type 'number'`,
}),
);
Expand Down
10 changes: 5 additions & 5 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ import createFilterMiddleware from '@metamask/eth-json-rpc-filters';
import createSubscriptionManager from '@metamask/eth-json-rpc-filters/subscriptionManager';
import {
errorCodes as rpcErrorCodes,
EthereumRpcError,
ethErrors,
} from 'eth-rpc-errors';
JsonRpcError,
providerErrors,
} from '@metamask/rpc-errors';

import { Mutex } from 'await-semaphore';
import log from 'loglevel';
Expand Down Expand Up @@ -463,7 +463,7 @@ export default class MetamaskController extends EventEmitter {
this.encryptionPublicKeyController.clearUnapproved();
this.decryptMessageController.clearUnapproved();
this.signatureController.clearUnapproved();
this.approvalController.clear(ethErrors.provider.userRejectedRequest());
this.approvalController.clear(providerErrors.userRejectedRequest());
};

this.queuedRequestController = new QueuedRequestController({
Expand Down Expand Up @@ -6592,7 +6592,7 @@ export default class MetamaskController extends EventEmitter {
try {
this.approvalController.reject(
id,
new EthereumRpcError(error.code, error.message, error.data),
new JsonRpcError(error.code, error.message, error.data),
);
} catch (exp) {
if (!(exp instanceof ApprovalRequestNotFoundError)) {
Expand Down
Loading

0 comments on commit b4c1f9c

Please sign in to comment.