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

fix: replace legacy eth-json-rpc deps #11952

Merged
merged 60 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
a7afca6
chore: nodejs 20.18.0
legobeat Oct 22, 2024
0e387a1
deps: json-rpc-engine@^6.1.0 -> @metamask/json-rpc-engine@^10.0.0
legobeat Apr 17, 2024
3953116
Update JsonRpcRequest typings
legobeat Apr 17, 2024
c724393
chainId is now hex string, not number
legobeat Apr 18, 2024
924f7f0
chore(test): eth_sendTransaction test type workarounds
legobeat May 20, 2024
d2d0588
fixup: console.error in test
legobeat May 20, 2024
d3e618d
fix(test): test for error cause message in RPCMethodMIddleware
legobeat May 20, 2024
72a6f77
deps: @metamask/eth-json-rpc-filters@^8.0.0->^9.0.0
legobeat Oct 24, 2024
69f7521
fix(deps): @metamask/eth-json-rpc-middleware@^11.0.2->^15.0.0
MarioAslau Jun 10, 2024
3ece450
background bridge cleanup fix
tommasini Jun 24, 2024
5d6b7c6
fix depcheck issues
tommasini Jun 24, 2024
8e340c4
fix lint issues
tommasini Jun 24, 2024
82b1ccc
fix lint and fix ts error
tommasini Jun 24, 2024
d1ea8dd
fix on snap bridge
tommasini Jun 25, 2024
8216ff4
feat: update createLegacyMethodMiddleware tests
MarioAslau Jun 25, 2024
04573b2
feat: remove type
MarioAslau Jun 25, 2024
b660823
feat: removed unused imports
MarioAslau Jun 25, 2024
309439d
fix: revert `Internal JSON-RPC error` message change
legobeat Oct 22, 2024
0bf3b62
deps: @metamask/rpc-errors@^6.2.1->^7.0.0
legobeat Oct 22, 2024
977f2ad
chore: fixup test for @metamask/rpc-errors 7.0.0+
legobeat Oct 22, 2024
07290cf
chore: migrate patch for @metamask/rpc-errors
legobeat Oct 22, 2024
060db63
fix: revert changing chainId from number to Hex
legobeat Oct 23, 2024
208b079
deps: @metamask/providers@^13.1.0->^16.1.0
legobeat Oct 28, 2024
d35ab75
deps: json-rpc-middleware-stream@^4.2.3 -> @metamask/json-rpc-middlew…
legobeat Oct 28, 2024
69b8ddc
deps: @metamask/utils@^9.2.1->^10.0.0
legobeat Oct 30, 2024
9a598c4
fix(deps): remove unused legacy eth-block-tracker
legobeat Oct 30, 2024
3d0d3d7
fix: force @metamask/utils v8
legobeat Oct 30, 2024
0739962
fix: transpile class syntax in @metamask/rpc-errors
legobeat Oct 30, 2024
5185b4a
transpile all the errors
legobeat Oct 30, 2024
5e36b03
Merge branch 'main' into chore/provider-middleware-filters-2
smilingkylan Nov 6, 2024
7f3880b
addressed conflicts and downgraded node to 20.18.0
sethkfman Nov 22, 2024
fccb410
removed rpc-errors patch for 7.0.0 since latest version is 7.0.1
sethkfman Nov 23, 2024
90ceb2c
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Nov 29, 2024
2cf7dc1
deduplicate
NicolasMassart Nov 29, 2024
ffc39c3
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 2, 2024
9c134f4
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 3, 2024
c80d36e
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 5, 2024
7aada0c
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 9, 2024
494f5d3
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 9, 2024
ffd4fba
dedup
NicolasMassart Dec 9, 2024
26e5e86
Merge branch 'chore/provider-middleware-filters-2' of github.com:Meta…
NicolasMassart Dec 9, 2024
d778bb0
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 9, 2024
efafe20
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 10, 2024
1bba31d
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 10, 2024
4070db8
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 10, 2024
25a1d36
revert unwanted prettier formatting
NicolasMassart Dec 12, 2024
abce830
revert unwanted prettier formatting
NicolasMassart Dec 12, 2024
48c9815
revert unwanted prettier formatting
NicolasMassart Dec 12, 2024
b7cb44f
revert unwanted prettier formatting
NicolasMassart Dec 12, 2024
dd1742f
revert unwanted prettier formatting
NicolasMassart Dec 12, 2024
c0173ba
revert unwanted prettier formatting
NicolasMassart Dec 12, 2024
74506de
revert unwanted prettier formatting
NicolasMassart Dec 12, 2024
1da2996
revert unwanted prettier formatting
NicolasMassart Dec 12, 2024
270b787
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 12, 2024
6bc0e0b
revert unwanted prettier formatting
NicolasMassart Dec 12, 2024
da493d3
update yarn lock
NicolasMassart Dec 12, 2024
c027ead
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 12, 2024
0080a0f
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 12, 2024
86b9fd7
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 13, 2024
c3db051
Merge branch 'main' into chore/provider-middleware-filters-2
NicolasMassart Dec 13, 2024
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
12 changes: 4 additions & 8 deletions app/core/BackgroundBridge/BackgroundBridge.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
/* eslint-disable import/no-commonjs */
import URL from 'url-parse';
import { JsonRpcEngine } from 'json-rpc-engine';
import {
createSelectedNetworkMiddleware,
METAMASK_DOMAIN,
} from '@metamask/selected-network-controller';
import EthQuery from '@metamask/eth-query';
import { JsonRpcEngine } from '@metamask/json-rpc-engine';
import MobilePortStream from '../MobilePortStream';
import { setupMultiplex } from '../../util/streams';
import {
Expand All @@ -25,10 +25,10 @@ import snapMethodMiddlewareBuilder from '../Snaps/SnapsMethodMiddleware';
import { SubjectType } from '@metamask/permission-controller';
///: END:ONLY_INCLUDE_IF

import { createEngineStream } from '@metamask/json-rpc-middleware-stream';
const createFilterMiddleware = require('@metamask/eth-json-rpc-filters');
const createSubscriptionManager = require('@metamask/eth-json-rpc-filters/subscriptionManager');
const { providerAsMiddleware } = require('@metamask/eth-json-rpc-middleware');
import { createEngineStream } from '@metamask/json-rpc-middleware-stream';
import { providerAsMiddleware } from '@metamask/eth-json-rpc-middleware';
const pump = require('pump');
// eslint-disable-next-line import/no-nodejs-modules
const EventEmitter = require('events').EventEmitter;
Expand Down Expand Up @@ -388,11 +388,7 @@ export class BackgroundBridge extends EventEmitter {

pump(outStream, providerStream, outStream, (err) => {
// handle any middleware cleanup
this.engine._middleware.forEach((mid) => {
if (mid.destroy && typeof mid.destroy === 'function') {
mid.destroy();
}
});
this.engine.destroy();
if (err) Logger.log('Error with provider stream conn', err);
});
}
Expand Down
2 changes: 1 addition & 1 deletion app/core/Encryptor/pbkdf2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ describe('pbkdf2', () => {
afterEach(() => {
jest.restoreAllMocks();
});

it('uses the native implementation of pbkdf2 with main aes', async () => {
NativeModules.Aes.pbkdf2 = jest
.fn()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export { createRemoteFeatureFlagController } from './utils';

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { RemoteFeatureFlagControllerMessenger, RemoteFeatureFlagControllerState

export interface RemoteFeatureFlagInitParamTypes {
state?: RemoteFeatureFlagControllerState;
messenger: RemoteFeatureFlagControllerMessenger,
disabled: boolean
messenger: RemoteFeatureFlagControllerMessenger;
disabled: boolean;
}

Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ describe('RemoteFeatureFlagController utils', () => {

describe('createRemoteFeatureFlagController', () => {
it('creates controller with initial undefined state', () => {

const controller = createRemoteFeatureFlagController({
state: undefined,
messenger,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ export const createRemoteFeatureFlagController = ({
messenger,
disabled,
}: RemoteFeatureFlagInitParamTypes) => {

const remoteFeatureFlagController = new RemoteFeatureFlagController({
messenger,
state,
Expand All @@ -58,4 +57,3 @@ export const createRemoteFeatureFlagController = ({
}
return remoteFeatureFlagController;
};

1 change: 0 additions & 1 deletion app/core/Ledger/Ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,4 +251,3 @@ export const unlockLedgerWalletAccount = async (index: number) => {
}
};


32 changes: 19 additions & 13 deletions app/core/RPCMethods/RPCMethodMiddleware.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import {
JsonRpcEngine,
import { JsonRpcEngine, JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import type {
Json,
JsonRpcFailure,
JsonRpcMiddleware,
JsonRpcParams,
JsonRpcRequest,
JsonRpcResponse,
JsonRpcSuccess,
} from 'json-rpc-engine';
} from '@metamask/utils';
import { type JsonRpcError, providerErrors, rpcErrors } from '@metamask/rpc-errors';
import type { TransactionParams } from '@metamask/transaction-controller';
import { providerErrors, rpcErrors } from '@metamask/rpc-errors';
import Engine from '../Engine';
import { store } from '../../store';
import { getPermittedAccounts } from '../Permissions';
Expand Down Expand Up @@ -106,8 +107,8 @@ const jsonrpc = '2.0' as const;
* @throws If the given value is not a valid {@link JsonRpcSuccess} object.
*/
function assertIsJsonRpcSuccess(
response: JsonRpcResponse<unknown>,
): asserts response is JsonRpcSuccess<unknown> {
response: JsonRpcResponse<Json>,
): asserts response is JsonRpcSuccess<Json> {
if ('error' in response) {
throw new Error(`Response failed with error '${JSON.stringify('error')}'`);
} else if (!('result' in response)) {
Expand Down Expand Up @@ -208,8 +209,8 @@ async function callMiddleware({
middleware,
request,
}: {
middleware: JsonRpcMiddleware<unknown, unknown>;
request: JsonRpcRequest<unknown>;
middleware: JsonRpcMiddleware<JsonRpcParams, Json>;
request: JsonRpcRequest<JsonRpcParams>;
}) {
const engine = new JsonRpcEngine();
engine.push(middleware);
Expand Down Expand Up @@ -415,7 +416,6 @@ describe('getRpcMethodMiddleware', () => {
permissionController.createPermissionMiddleware({
origin: hostMock,
});
// @ts-expect-error JsonRpcId (number | string | void) doesn't match PS middleware's id, which is (string | number | null)
engine.push(permissionMiddleware);
const middleware = getRpcMethodMiddleware(getMinimalOptions());
engine.push(middleware);
Expand Down Expand Up @@ -1096,7 +1096,8 @@ describe('getRpcMethodMiddleware', () => {
it('returns a JSON-RPC error if an error is thrown when adding this transaction', async () => {
// Omit `from` and `chainId` here to skip validation for simplicity
// Downcast needed here because `from` is required by this type
const mockTransactionParameters = {} as TransactionParams;
const mockTransactionParameters = {} as (TransactionParams &
JsonRpcParams)[];
// Transaction fails before returning a result
mockAddTransaction.mockImplementation(async () => {
throw new Error('Failed to add transaction');
Expand All @@ -1119,12 +1120,17 @@ describe('getRpcMethodMiddleware', () => {
expect((response as JsonRpcFailure).error.message).toBe(
expectedError.message,
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(((response as JsonRpcFailure).error as JsonRpcError<any>).data.cause.message).toBe(
expectedError.message,
);
});

it('returns a JSON-RPC error if an error is thrown after approval', async () => {
// Omit `from` and `chainId` here to skip validation for simplicity
// Downcast needed here because `from` is required by this type
const mockTransactionParameters = {} as TransactionParams;
const mockTransactionParameters = {} as (TransactionParams &
JsonRpcParams)[];
setupGlobalState({
addTransactionResult: Promise.reject(
new Error('Failed to process transaction'),
Expand Down Expand Up @@ -1233,7 +1239,7 @@ describe('getRpcMethodMiddleware', () => {
jsonrpc,
id: 1,
method: 'personal_ecRecover',
params: [undefined, helloWorldSignature],
params: [undefined, helloWorldSignature] as JsonRpcParams,
};
const expectedError = rpcErrors.internal('Missing data parameter');

Expand Down
2 changes: 1 addition & 1 deletion app/core/RPCMethods/RPCMethodMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Alert } from 'react-native';
import { getVersion } from 'react-native-device-info';
import { createAsyncMiddleware } from 'json-rpc-engine';
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import { providerErrors, rpcErrors } from '@metamask/rpc-errors';
import {
EndFlowOptions,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
JsonRpcEngine,
JsonRpcEngineEndCallback,
JsonRpcEngineNextCallback,
} from 'json-rpc-engine';
} from '@metamask/json-rpc-engine';
import {
Json,
JsonRpcParams,
Expand Down Expand Up @@ -150,6 +150,10 @@ describe('createLegacyMethodMiddleware', () => {
});
assertIsJsonRpcFailure(response);

// Type assertion for the error not having cause object
const errorData = response.error.data as { cause?: Error };

expect(errorData.cause?.message).toBe('test error');
expect(response.error.message).toBe('test error');
});

Expand All @@ -166,6 +170,10 @@ describe('createLegacyMethodMiddleware', () => {
});
assertIsJsonRpcFailure(response);

// Type assertion for the error not having cause object
const errorData = response.error.data as { cause?: Error };

expect(errorData.cause?.message).toBe('test error');
expect(response.error.message).toBe('test error');
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { rpcErrors } from '@metamask/rpc-errors';
import type { JsonRpcMiddleware } from 'json-rpc-engine';
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';

import { UNSUPPORTED_RPC_METHODS } from '../utils';
import { Json, JsonRpcParams } from '@metamask/utils';

/**
* Creates a middleware that rejects explicitly unsupported RPC methods with the
* appropriate error.
*/
const createUnsupportedMethodMiddleware = (): JsonRpcMiddleware<
unknown,
void
JsonRpcParams,
Json
> =>
async function unsupportedMethodMiddleware(req, _res, next, end) {
if ((UNSUPPORTED_RPC_METHODS as Set<string>).has(req.method)) {
Expand Down
15 changes: 11 additions & 4 deletions app/core/RPCMethods/eth_sendTransaction.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
// eslint-disable-next-line import/no-nodejs-modules
import { inspect } from 'util';
import type { JsonRpcRequest, PendingJsonRpcResponse } from 'json-rpc-engine';
import type {
Json,
JsonRpcParams,
JsonRpcRequest,
PendingJsonRpcResponse,
} from '@metamask/utils';
import type {
TransactionParams,
TransactionController,
Expand Down Expand Up @@ -50,8 +55,8 @@ const NETWORK_CLIENT_ID_MOCK = 'testNetworkClientId';
* @returns The JSON-RPC request.
*/
function constructSendTransactionRequest(
params: unknown,
): JsonRpcRequest<unknown> & {
params: [TransactionParams & JsonRpcParams],
): JsonRpcRequest<[TransactionParams & JsonRpcParams]> & {
method: 'eth_sendTransaction';
networkClientId: string;
} {
Expand All @@ -69,7 +74,7 @@ function constructSendTransactionRequest(
*
* @returns A pending JSON-RPC response.
*/
function constructPendingJsonRpcResponse(): PendingJsonRpcResponse<unknown> {
function constructPendingJsonRpcResponse(): PendingJsonRpcResponse<Json> {
return {
jsonrpc: '2.0',
id: 1,
Expand Down Expand Up @@ -181,6 +186,7 @@ describe('eth_sendTransaction', () => {
async () =>
await eth_sendTransaction({
hostname: 'example.metamask.io',
//@ts-expect-error - invalid parameters forced
req: constructSendTransactionRequest(invalidParameter),
res: constructPendingJsonRpcResponse(),
sendTransaction: getMockAddTransaction({
Expand All @@ -203,6 +209,7 @@ describe('eth_sendTransaction', () => {
async () =>
await eth_sendTransaction({
hostname: 'example.metamask.io',
//@ts-expect-error - invalid parameters forced
req: constructSendTransactionRequest(invalidParameter),
res: constructPendingJsonRpcResponse(),
sendTransaction: getMockAddTransaction({
Expand Down
28 changes: 20 additions & 8 deletions app/core/RPCMethods/eth_sendTransaction.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import type { JsonRpcRequest, PendingJsonRpcResponse } from 'json-rpc-engine';
import type {
Json,
JsonRpcParams,
JsonRpcRequest,
PendingJsonRpcResponse,
} from '@metamask/utils';
import {
TransactionController,
TransactionParams,
WalletDevice,
} from '@metamask/transaction-controller';
import { rpcErrors } from '@metamask/rpc-errors';
Expand Down Expand Up @@ -46,6 +52,11 @@ const hasProperty = <
): objectToCheck is ObjectToCheck & Record<Property, unknown> =>
Object.hasOwnProperty.call(objectToCheck, name);

interface SendArgs {
from: string;
chainId?: number;
}

/**
* Handle a `eth_sendTransaction` request.
*
Expand All @@ -66,16 +77,13 @@ async function eth_sendTransaction({
validateAccountAndChainId,
}: {
hostname: string;
req: JsonRpcRequest<unknown> & {
req: JsonRpcRequest<[TransactionParams & JsonRpcParams]> & {
method: 'eth_sendTransaction';
networkClientId: string;
};
res: PendingJsonRpcResponse<unknown>;
res: PendingJsonRpcResponse<Json>;
sendTransaction: TransactionController['addTransaction'];
validateAccountAndChainId: (args: {
from: string;
chainId?: number;
}) => Promise<void>;
validateAccountAndChainId: (args: SendArgs) => Promise<void>;
}) {
if (
!Array.isArray(req.params) &&
Expand All @@ -91,9 +99,13 @@ async function eth_sendTransaction({
message: `Invalid parameters: expected the first parameter to be an object`,
});
}
// TODO: Normalize chainId to Hex string
const nChainId = typeof req.params[0].chainId === 'number'
? req.params[0].chainId
: parseInt(req.params[0].chainId || '0x0', 16);
await validateAccountAndChainId({
from: req.params[0].from,
chainId: req.params[0].chainId,
chainId: nChainId,
});

const { result, transactionMeta } = await sendTransaction(req.params[0], {
Expand Down
7 changes: 3 additions & 4 deletions app/core/RPCMethods/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { query } from '@metamask/controller-utils';
import Engine from '../Engine';
import { selectHooks } from '@metamask/snaps-rpc-methods';
import { OptionalDataWithOptionalCause, rpcErrors } from '@metamask/rpc-errors';
import { JsonRpcMiddleware } from 'json-rpc-engine';
import { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { PermittedHandlerExport } from '@metamask/permission-controller';
import { Json, JsonRpcParams, hasProperty } from '@metamask/utils';
import EthQuery from '@metamask/eth-query';
Expand Down Expand Up @@ -76,7 +76,7 @@ export function makeMethodMiddlewareMaker<U>(
const makeMethodMiddleware = (hooks: Record<string, unknown>) => {
assertExpectedHook(hooks, expectedHookNames);

const methodMiddleware: JsonRpcMiddleware<JsonRpcParams, unknown> = async (
const methodMiddleware: JsonRpcMiddleware<JsonRpcParams, Json> = async (
req,
res,
next,
Expand All @@ -88,12 +88,11 @@ export function makeMethodMiddlewareMaker<U>(
try {
// Implementations may or may not be async, so we must await them.
return await implementation(
// @ts-expect-error JsonRpcId (number | string | void) doesn't match the permission middleware's id, which is (string | number | null)
req,
res,
next,
end,
selectHooks(hooks, hookNames),
selectHooks(hooks, hookNames) as U,
smilingkylan marked this conversation as resolved.
Show resolved Hide resolved
);
} catch (error) {
if (process.env.METAMASK_DEBUG) {
Expand Down
2 changes: 1 addition & 1 deletion app/core/RPCMethods/wallet_watchAsset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import {
} from '../../constants/error';
import { selectChainId, selectNetworkClientId } from '../../selectors/networkController';
import { isValidAddress } from 'ethereumjs-util';
import { JsonRpcRequest, PendingJsonRpcResponse } from 'json-rpc-engine';
import { toChecksumHexAddress } from '@metamask/controller-utils';
import { JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils';

const wallet_watchAsset = async ({
req,
Expand Down
Loading
Loading