Skip to content

feat: Add function getCallsStatus for middleware to handle wallet_getCallsStatus requests #15015

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

Open
wants to merge 30 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
a17f1b5
Adding wallet middleware in mobile
jpuri Apr 23, 2025
f257fb0
update
jpuri Apr 23, 2025
09852cd
update
jpuri Apr 23, 2025
68869a6
update
jpuri Apr 23, 2025
61e0e4d
Merge branch 'main' into adding_wallet_middleware
jpuri Apr 23, 2025
c2bcf42
Creating transaction for batch transaction request
jpuri Apr 24, 2025
b93a514
Merge branch 'main' of github.com:MetaMask/metamask-mobile into addin…
jpuri Apr 24, 2025
c1b50a1
Merge branch 'adding_wallet_middleware' of github.com:MetaMask/metama…
jpuri Apr 24, 2025
520b822
update
jpuri Apr 24, 2025
67011b9
Merge branch 'main' into adding_wallet_middleware
jpuri Apr 28, 2025
b5934cd
Adding validation for batch request
jpuri Apr 30, 2025
e9e0169
Adding test coverage
jpuri Apr 30, 2025
89f5227
update
jpuri Apr 30, 2025
00fd316
update
jpuri Apr 30, 2025
ab89539
update
jpuri Apr 30, 2025
0278c00
Merge branch 'main' into adding_wallet_middleware
jpuri Apr 30, 2025
d2823ea
Merge branch 'adding_wallet_middleware' into send_call_validations
jpuri Apr 30, 2025
333aec7
Add support for wallet_getCallsStatus in middleware
jpuri Apr 30, 2025
fa3b77a
merge
jpuri Apr 30, 2025
78c596d
update
jpuri Apr 30, 2025
4059f4d
Merge branch 'send_call_validations' into support_call_status
jpuri Apr 30, 2025
5b576d8
Merge branch 'send_call_validations' into support_call_status
jpuri May 1, 2025
e67d111
Merge branch 'support_call_status' of https://github.com/MetaMask/met…
jpuri May 1, 2025
46792cb
update
jpuri May 1, 2025
82b0c18
update
jpuri May 1, 2025
60675a2
update
jpuri May 2, 2025
05967e3
update
jpuri May 5, 2025
c6ec12a
Merge branch 'main' into send_call_validations
jpuri May 5, 2025
cceeaf8
merge
jpuri May 5, 2025
918ca3b
merge
jpuri May 6, 2025
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
1 change: 1 addition & 0 deletions app/core/Permissions/specifications.js
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,7 @@ export const unrestrictedMethods = Object.freeze([
'wallet_switchEthereumChain',
'wallet_addEthereumChain',
'wallet_sendCalls',
'wallet_getCallsStatus',
///: BEGIN:ONLY_INCLUDE_IF(preinstalled-snaps,external-snaps)
'wallet_getAllSnaps',
'wallet_getSnaps',
Expand Down
167 changes: 1 addition & 166 deletions app/core/RPCMethods/createAsyncWalletMiddleware.test.ts
Original file line number Diff line number Diff line change
@@ -1,173 +1,8 @@
import {
createAsyncWalletMiddleware,
getAccounts,
processSendCalls,
} from './createAsyncWalletMiddleware';
import Engine from '../Engine';
import { SendCalls } from '@metamask/eth-json-rpc-middleware';
import { JsonRpcRequest } from '@metamask/utils';

const MOCK_ACCOUNT = '0x1234';
jest.mock('../Engine', () => ({
context: {
AccountsController: {
getSelectedAccount: () => ({ address: MOCK_ACCOUNT }),
},
KeyringController: {
state: {
isUnlocked: true,
},
},
PermissionController: {
getCaveat: () => ({
type: 'authorizedScopes',
value: {
requiredScopes: {},
optionalScopes: {
'eip155:1': {
accounts: ['eip155:1:0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'],
},
},
isMultichainOrigin: false,
},
}),
},
TransactionController: {
addTransactionBatch: jest.fn().mockResolvedValue({ batchId: 123 }),
isAtomicBatchSupported: jest.fn().mockResolvedValue([true]),
},
},
controllerMessenger: {
call: jest.fn().mockReturnValue({ configuration: { chainId: '0xaa36a7' } }),
},
}));

const MockEngine = jest.mocked(Engine);
import { createAsyncWalletMiddleware } from './createAsyncWalletMiddleware';

describe('createAsyncWalletMiddleware', () => {
it('return instance of Wallet Middleware', async () => {
const middleware = createAsyncWalletMiddleware();
expect(middleware).toBeDefined();
});
});

describe('getAccounts', () => {
it('return selected account address', async () => {
const accounts = await getAccounts();
expect(accounts).toStrictEqual([MOCK_ACCOUNT]);
});

it('return empty array if origin is metamask and AccountsController returns no selected account', async () => {
MockEngine.context.AccountsController.getSelectedAccount = (() =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
undefined) as any;
const accounts = await getAccounts();
expect(accounts).toStrictEqual([]);
});
});

Comment on lines -54 to -67
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this removal necessary/related?

Copy link
Contributor

Choose a reason for hiding this comment

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

Or I guess its moved

describe('processSendCalls', () => {
const MOCK_PARAMS = {
version: '2.0.0',
from: '0x935e73edb9ff52e23bac7f7ty67u1ecd06d05477',
chainId: '0xaa36a7',
atomicRequired: true,
calls: [
{
to: '0x0c54FcCd2e384b4BB6f2E405Bf5Cbc15a017AaFb',
data: '0x654365436543',
value: '0x3B9ACA00',
},
],
} as SendCalls;
const MOCK_REQUEST = {
method: 'wallet_sendCalls',
params: MOCK_PARAMS,
jsonrpc: '2.0',
id: 1315126919,
toNative: true,
origin: 'metamask.github.io',
networkClientId: 'sepolia',
} as JsonRpcRequest;

it('creates transaction instance for batch request', async () => {
const result = await processSendCalls(MOCK_PARAMS, MOCK_REQUEST);
expect(
Engine.context.TransactionController.addTransactionBatch,
).toHaveBeenCalledTimes(1);
expect(result.id).toStrictEqual(123);
});

it('throw error if wrong version of request is used', async () => {
expect(async () => {
await processSendCalls(
{ ...MOCK_PARAMS, version: '3.0.0' },
MOCK_REQUEST,
);
}).rejects.toThrow('Version not supported: Got 3.0.0, expected 2.0.0');
});

it('throw error if TransactionController.isAtomicBatchSupported returns false', async () => {
Engine.context.TransactionController.isAtomicBatchSupported = jest
.fn()
.mockResolvedValue([]);
expect(async () => {
await processSendCalls(MOCK_PARAMS, MOCK_REQUEST);
}).rejects.toThrow('EIP-7702 not supported on chain: 0xaa36a7');
Engine.context.TransactionController.isAtomicBatchSupported = jest
.fn()
.mockResolvedValue([{}]);
});

it('throws if top-level capability is required', async () => {
await expect(
processSendCalls(
{
...MOCK_PARAMS,
capabilities: {
test: {},
test2: { optional: true },
test3: { optional: false },
},
},
MOCK_REQUEST,
),
).rejects.toThrow('Unsupported non-optional capabilities: test, test3');
});

it('throws if call capability is required', async () => {
await expect(
processSendCalls(
{
...MOCK_PARAMS,
calls: [
...MOCK_PARAMS.calls,
{
...MOCK_PARAMS.calls[0],
capabilities: {
test: {},
test2: { optional: true },
test3: { optional: false },
},
},
],
},
MOCK_REQUEST,
),
).rejects.toThrow('Unsupported non-optional capabilities: test, test3');
});

it('throw error if dappChainId is different from request chainId', async () => {
Engine.controllerMessenger.call = jest
.fn()
.mockReturnValue({ configuration: { chainId: '0x1' } });
expect(async () => {
await processSendCalls(MOCK_PARAMS, {
...MOCK_REQUEST,
networkClientId: 'linea',
} as JsonRpcRequest);
}).rejects.toThrow(
'Chain ID must match the dApp selected network: Got 0xaa36a7, expected 0x1',
);
});
});
146 changes: 4 additions & 142 deletions app/core/RPCMethods/createAsyncWalletMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,148 +1,9 @@
import {
createWalletMiddleware,
SendCalls,
SendCallsResult,
} from '@metamask/eth-json-rpc-middleware';
import { createWalletMiddleware } from '@metamask/eth-json-rpc-middleware';
import { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { JsonRpcParams } from '@metamask/eth-query';
import { Hex, Json, JsonRpcRequest } from '@metamask/utils';
import { JsonRpcError, rpcErrors } from '@metamask/rpc-errors';
import { v4 as uuidv4 } from 'uuid';
import { Json } from '@metamask/utils';

import ppomUtil from '../../lib/ppom/ppom-util';
import Engine from '../Engine';

const VERSION = '2.0.0';

enum EIP5792ErrorCode {
UnsupportedNonOptionalCapability = 5700,
UnsupportedChainId = 5710,
UnknownBundleId = 5730,
RejectedUpgrade = 5750,
}

type JSONRPCRequest = JsonRpcRequest & {
networkClientId: string;
origin?: string;
};

export const getAccounts = async () => {
const { AccountsController } = Engine.context;
const selectedAddress = AccountsController.getSelectedAccount()?.address;
return Promise.resolve(selectedAddress ? [selectedAddress] : []);
};

function validateSendCallsVersion(sendCalls: SendCalls) {
const { version } = sendCalls;

if (version !== VERSION) {
throw rpcErrors.invalidInput(
`Version not supported: Got ${version}, expected ${VERSION}`,
);
}
}

async function validateSendCallsChainId(
sendCalls: SendCalls,
req: JSONRPCRequest,
) {
const { TransactionController, AccountsController } = Engine.context;
const { chainId } = sendCalls;
const { networkClientId } = req;

const dappChainId = Engine.controllerMessenger.call(
'NetworkController:getNetworkClientById',
networkClientId,
).configuration.chainId;

if (chainId && chainId.toLowerCase() !== dappChainId.toLowerCase()) {
throw rpcErrors.invalidParams(
`Chain ID must match the dApp selected network: Got ${chainId}, expected ${dappChainId}`,
);
}

const from =
sendCalls.from ?? (AccountsController.getSelectedAccount()?.address as Hex);

const batchSupport = await TransactionController.isAtomicBatchSupported({
address: from,
chainIds: [dappChainId],
});

const chainBatchSupport = batchSupport?.[0];

if (!chainBatchSupport) {
throw new JsonRpcError(
EIP5792ErrorCode.UnsupportedChainId,
`EIP-7702 not supported on chain: ${dappChainId}`,
);
}
}

function validateCapabilities(sendCalls: SendCalls) {
const { calls, capabilities } = sendCalls;

const requiredTopLevelCapabilities = Object.keys(capabilities ?? {}).filter(
(name) => capabilities?.[name].optional !== true,
);

const requiredCallCapabilities = calls.flatMap((call) =>
Object.keys(call.capabilities ?? {}).filter(
(name) => call.capabilities?.[name].optional !== true,
),
);

const requiredCapabilities = [
...requiredTopLevelCapabilities,
...requiredCallCapabilities,
];

if (requiredCapabilities.length) {
throw new JsonRpcError(
EIP5792ErrorCode.UnsupportedNonOptionalCapability,
`Unsupported non-optional capabilities: ${requiredCapabilities.join(
', ',
)}`,
);
}
}

async function validateSendCalls(sendCalls: SendCalls, req: JSONRPCRequest) {
validateSendCallsVersion(sendCalls);
await validateSendCallsChainId(sendCalls, req);
validateCapabilities(sendCalls);
}

export async function processSendCalls(
params: SendCalls,
req: JsonRpcRequest,
): Promise<SendCallsResult> {
const { TransactionController, AccountsController } = Engine.context;
const { calls, from: paramFrom } = params;
const { networkClientId, origin } = req as JsonRpcRequest & {
networkClientId: string;
origin?: string;
};
const transactions = calls.map((call) => ({ params: call }));

await validateSendCalls(params, req as JSONRPCRequest);

const from =
paramFrom ?? (AccountsController.getSelectedAccount()?.address as Hex);
const securityAlertId = uuidv4();

const { batchId: id } = await TransactionController.addTransactionBatch({
from,
networkClientId,
origin,
securityAlertId,
transactions,
validateSecurity:
ppomUtil.createValidatorForSecurityAlertId(securityAlertId),
});

return { id };
}
import { getAccounts, processSendCalls, getCallsStatus } from './eip5792';

export const createAsyncWalletMiddleware = (): JsonRpcMiddleware<
JsonRpcParams,
Expand All @@ -151,4 +12,5 @@ export const createAsyncWalletMiddleware = (): JsonRpcMiddleware<
createWalletMiddleware({
getAccounts,
processSendCalls,
getCallsStatus,
}) as JsonRpcMiddleware<JsonRpcParams, Json>;
Loading
Loading