Repository navigation
chore: Migrate Perps-involved legacy API method calls to messengers - #47254
Conversation
|
CLA Signature Action: All authors have signed the CLA. You may need to manually re-run the blocking PR check if it doesn't pass in a few minutes. |
✨ Files requiring CODEOWNER review ✨🫰 @MetaMask/core-platform (1 files, +3 -1)
👨🔧 @MetaMask/extension-platform (1 files, +3 -1)
👨🔧 @MetaMask/perps (22 files, +221 -168)
|
Builds ready [a114083]
⚡ Performance Benchmarks (Total: 🟢 9 pass · 🟡 2 warn · 🔴 2 fail)
Bundle Size Diffs [🚨 Warning! Bundle size has increased!]
|
Builds ready [cc1dfd7]
⚡ Performance Benchmarks (Total: 🟢 6 pass · 🟡 5 warn · 🔴 2 fail)
Bundle Size Diffs [🚨 Warning! Bundle size has increased!]
|
Builds ready [0de3799]
⚡ Performance Benchmarks (Total: 🟢 8 pass · 🟡 3 warn · 🔴 2 fail)
Bundle Size Diffs [🚨 Warning! Bundle size has increased!]
|
c538b69 to
dbd3d3d
Compare
dbd3d3d to
4cb0379
Compare
0de3799 to
ca9220d
Compare
MajorLift
left a comment
There was a problem hiding this comment.
One breaking change: the calls this PR migrates lose their Sentry span names. The diff below names their spans after the action they call.
| const value = await submitRequestToBackground( | ||
| 'PerpsController:getMaxSlippage', | ||
| [], | ||
| ); |
There was a problem hiding this comment.
Every call this PR migrates now reaches the background as messengerCall, and the rpc.handler span is named after that method (createMetaRPCHandler.ts L40-L43). The span names these calls have today stop appearing, such as Background RPC: PerpsController.perpsSetVisibleCandleCount and Background RPC: PerpsController.perpsGetMaxSlippage (project metamask, production, 2026-10-22 to 2026-10-29).
Actions that aren't read-only get a Messenger Call: PerpsController:<method> child span, but read-only actions like this one are skipped (messenger-tracing.ts L63-L71), so getMaxSlippage, getWithdrawalRoutes and getPerpsDiscountForAccount are not named in any span.
Could we name messengerCall spans after the action they dispatch? Here's a diff if it helps:
diff --git a/app/scripts/lib/createMetaRPCHandler.test.ts b/app/scripts/lib/createMetaRPCHandler.test.ts
index 31f798bd019..5eebcd1e8b1 100644
--- a/app/scripts/lib/createMetaRPCHandler.test.ts
+++ b/app/scripts/lib/createMetaRPCHandler.test.ts
@@ -214,6 +214,39 @@ describe('createMetaRPCHandler', () => {
);
});
+ it('names messengerCall spans after the action they dispatch', async () => {
+ const messengerCall = jest.fn().mockReturnValue('result');
+ const api = { messengerCall } as unknown as Api;
+ const streamTest = createStream();
+ const handler = createMetaRPCHandler(api, streamTest);
+
+ await handler({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'messengerCall',
+ params: [
+ 'PerpsController:getMaxSlippage',
+ [],
+ { _traceContext: { _traceId: 'trace123', _spanId: 'span456' } },
+ ],
+ });
+
+ expect(trace).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: 'Background RPC: PerpsController:getMaxSlippage',
+ data: {
+ method: 'messengerCall',
+ action: 'PerpsController:getMaxSlippage',
+ },
+ }),
+ expect.any(Function),
+ );
+ expect(messengerCall).toHaveBeenCalledWith(
+ 'PerpsController:getMaxSlippage',
+ [],
+ );
+ });
+
it('continues trace context but skips rpc.handler span when shouldSampleWrappers rejects', async () => {
jest.mocked(shouldSampleWrappers).mockReturnValue(false);
const foo = jest.fn().mockReturnValue('result');
diff --git a/app/scripts/lib/createMetaRPCHandler.ts b/app/scripts/lib/createMetaRPCHandler.ts
index cd2360dcce9..0ee0b9cf69d 100644
--- a/app/scripts/lib/createMetaRPCHandler.ts
+++ b/app/scripts/lib/createMetaRPCHandler.ts
@@ -38,9 +38,17 @@ const createMetaRPCHandler = (api: MetaRpcApi, outStream: RpcStream) => {
const { cleanParams, traceContext } = extractTraceContext(data.params);
const handler = api[data.method];
const controller = handler._controllerName;
+ // Root-messenger actions all arrive as `messengerCall(action, args)`, so
+ // the span is named after the action rather than the shared method.
+ const messengerAction =
+ data.method === 'messengerCall' &&
+ Array.isArray(cleanParams) &&
+ typeof cleanParams[0] === 'string'
+ ? cleanParams[0]
+ : undefined;
const spanName: `Background RPC: ${string}` = controller
? `Background RPC: ${controller}.${data.method}`
- : `Background RPC: ${data.method}`;
+ : `Background RPC: ${messengerAction ?? data.method}`;
let result: unknown;
let error: unknown;
@@ -59,7 +67,11 @@ const createMetaRPCHandler = (api: MetaRpcApi, outStream: RpcStream) => {
name: spanName,
parentContext: traceContext,
op: 'rpc.handler',
- data: { method: data.method, ...(controller && { controller }) },
+ data: {
+ method: data.method,
+ ...(controller && { controller }),
+ ...(messengerAction && { action: messengerAction }),
+ },
},
() => handler.call(api, ...cleanParams),
);There was a problem hiding this comment.
Thank you. This is a good callout. I have created a new PR that aims to solve this problem, can you take a look at it? #47517
geositta
left a comment
There was a problem hiding this comment.
Approve. The migration preserves the saved slippage preference in the verified startup flow. Across four normal cold restarts the preference requests reach the background after handler registration, return the saved 50 bps, and order entry displayed and computed 0.5%. The baseline behaved identically. Static review found no remaining callers of the removed legacy perps methods, and trading operations retained their existing initialization and disconnect guards, no confirmed regressions remain from this review.
Builds ready [c1941ff]
⚡ Performance Benchmarks (Total: 🟢 6 pass · 🟡 4 warn · 🔴 3 fail)
Bundle Size Diffs [🚀 Bundle size reduced!]
|
|
Moving back to draft as this is now blocked by #47517. |
Builds ready [d1b6c73]
⚡ Performance Benchmarks (Total: 🟢 7 pass · 🟡 3 warn · 🔴 3 fail)
Bundle Size Diffs [🚀 Bundle size reduced!]
|
|


Description
Currently, the background process aggregates methods from various controllers and services into an API object, and the UI calls a method on this object by passing its name and arguments to
submitRequestToBackground.The "root" messenger — the messenger for MetamaskController — is meant to replace this API, and we want to transition to it by replacing
submitRequestToBackgroundcalls so that they pass action type strings (e.g.NetworkController:addNetwork) instead of method names (e.g.addNetwork). Then, eventually, we want to remove the original methods from the legacy API object. This PR is one of a series of PRs which aims to unlock this refactor.The tactic used to create this PR was to look for
submitRequestToBackgroundcalls in controllers, services, and files owned by the Perps team (although the changes may have affected other files as well).Calls for the following API methods defined within the PerpsController init object were migrated to use messenger action type strings (and the methods were removed):
perpsClearDepositResultperpsClearPendingTradeConfigurationperpsClearPendingTransactionRequestsperpsClearWithdrawResultperpsGetBlockExplorerUrlperpsGetConnectionStateperpsGetCurrentNetworkperpsGetMarketFilterPreferencesperpsGetMaxSlippageperpsGetOrderBookGroupingperpsGetOrderBookPreferencesperpsGetPendingTradeConfigurationperpsGetProLayoutPreferencesperpsGetSelectedOrderTypeperpsGetTradeConfigurationperpsGetVisibleCandleCountperpsGetWatchlistMarketsperpsGetWithdrawalProgressperpsGetWithdrawalRoutesperpsIsFirstTimeUserOnCurrentNetworkperpsIsWatchlistMarketperpsMarkFirstOrderCompletedperpsMarkTutorialCompletedperpsReconnectperpsRefreshEligibilityperpsResetFirstTimeUserStateperpsResetSelectedPaymentTokenperpsSaveMarketFilterPreferencesperpsSaveOrderBookGroupingperpsSavePendingTradeConfigurationperpsSaveTradeConfigurationperpsSetAttributionContextperpsSetMaxSlippageperpsSetOrderBookPreferencesperpsSetProLayoutPreferencesperpsSetSelectedOrderTypeperpsSetSelectedPaymentTokenperpsSetVisibleCandleCountperpsToggleWatchlistMarketCalls for the following API methods defined within
MetamaskController.getApiwere migrated to use messenger action type strings:rewardsGetPerpsDiscountForAccount(->
RewardsController:getPerpsDiscountForAccount)setLastPerpsDepositEntryPoint(->
AppStateController:setLastPerpsDepositEntryPoint)Calls for the following API methods were not migrated because they include behavior that would have to be moved into the controller:
perpsCalculateFeesperpsCalculateFeesperpsCalculateLiquidationPriceperpsCancelOrderperpsCancelOrdersperpsClosePositionperpsClosePositionsperpsDepositWithConfirmationperpsDisconnectperpsFetchHistoricalCandlesperpsFlipPositionperpsGetAccountStateperpsGetFundingperpsGetLifecycleContextperpsGetMarketDataWithPricesperpsGetMarketsperpsGetOpenOrdersperpsGetOrderFillsperpsGetOrdersperpsGetPositionsperpsGetUserHistoryperpsInitperpsMarkForegroundSettledperpsStartEligibilityMonitoringperpsStopEligibilityMonitoringperpsToggleTestnetperpsUpdateMarginperpsUpdatePositionTPSLperpsViewActiveCalls for the following API methods were not migrated because they come from
PerpsStreamBridge, which needs special attention:perpsActivateCandleStreamperpsActivateOrderBookAggregatedStreamperpsActivateOrderBookStreamperpsActivatePriceStreamperpsCheckHealthperpsDeactivateCandleStreamperpsDeactivateOrderBookAggregatedStreamperpsDeactivateOrderBookStreamperpsDeactivatePriceStreamperpsInitForAccountperpsRegisterPreloadperpsStopPreloadChangelog
CHANGELOG entry: null
Related issues
https://consensyssoftware.atlassian.net/browse/WPC-1422
Manual testing steps
This PR should have no functional changes. All flows should work like they do today, and the changes here should be covered by tests.
Screenshots/Recordings
(N/A)
Before
After
Pre-merge author checklist
Pre-merge reviewer checklist
Note
Medium Risk
Wide Perps UI and background wiring changes (prefs, withdrawals, disconnect) with no intended behavior change, but a missed call site could break flows at runtime.
Overview
This PR continues the move off the aggregated background API by switching Perps-related
submitRequestToBackgroundcalls to messenger action strings (e.g.PerpsController:saveTradeConfiguration,RewardsController:getPerpsDiscountForAccount,PreferencesController:setPreference,AppStateController:setLastPerpsDepositEntryPoint).The Perps controller init layer drops a large set of thin
perps*wrappers fromgetApi(preferences, withdrawal routes/progress, connection/attribution helpers, watchlist, tutorials, etc.) so those capabilities are invoked via the root messenger instead of the legacy API object.MetaMaskControllernow reads WebSocket disconnect state withPerpsController:getWebSocketConnectionStaterather thanperpsGetConnectionState.getPerpsControllerMessengerwidens allowed actions to the package’sPerpsControllerActionsunion. Tests across init, UI, and hooks were updated to match the new action names and slimmer API surface.Reviewed by Cursor Bugbot for commit d1b6c73. Bugbot is set up for automated code reviews on this repo. Configure here.