1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-23 03:36:18 +02:00
metamask-extension/app/scripts/lib/rpc-method-middleware/handlers/log-web3-shim-usage.js
Erik Marks 05fae3fa1e
Add RPC method handler hook selection (#12664)
Adds a property, `hookNames`, to each RPC method handler export in `app/scripts/lib/rpc-method-middleware` and a function, `selectHooks`, to select from them.

`createMethodMiddleware` receives a giant `opts` object that includes a bunch of different methods from `MetaMaskController` and its subcontrollers. Each method implementation only requires a subset of these methods to do its work. Because they need some kind of name, we call these methods "hooks". With this change, whenever an RPC method is called, `selectHooks` will be called to ensure that each method only receives the hooks that it needs in order to do its job.

This implementation is based on [work in `snaps-skunkworks`](https://github.com/MetaMask/snaps-skunkworks/blob/a3e1248/packages/rpc-methods/src/utils.ts#L17-L34) that will be merged in the near future.
2021-11-15 15:11:51 -08:00

65 lines
1.8 KiB
JavaScript

import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
/**
* This RPC method is called by the inpage provider whenever it detects the
* accessing of a non-existent property on our window.web3 shim.
* We collect this data to understand which sites are breaking due to the
* removal of our window.web3.
*/
const logWeb3ShimUsage = {
methodNames: [MESSAGE_TYPE.LOG_WEB3_SHIM_USAGE],
implementation: logWeb3ShimUsageHandler,
hookNames: {
sendMetrics: true,
getWeb3ShimUsageState: true,
setWeb3ShimUsageRecorded: true,
},
};
export default logWeb3ShimUsage;
/**
* @typedef {Object} LogWeb3ShimUsageOptions
* @property {Function} sendMetrics - A function that registers a metrics event.
* @property {Function} getWeb3ShimUsageState - A function that gets web3 shim
* usage state for the given origin.
* @property {Function} setWeb3ShimUsageRecorded - A function that records web3 shim
* usage for a particular origin.
*/
/**
* @param {import('json-rpc-engine').JsonRpcRequest<unknown>} req - The JSON-RPC request object.
* @param {import('json-rpc-engine').JsonRpcResponse<true>} res - The JSON-RPC response object.
* @param {Function} _next - The json-rpc-engine 'next' callback.
* @param {Function} end - The json-rpc-engine 'end' callback.
* @param {LogWeb3ShimUsageOptions} options
*/
function logWeb3ShimUsageHandler(
req,
res,
_next,
end,
{ sendMetrics, getWeb3ShimUsageState, setWeb3ShimUsageRecorded },
) {
const { origin } = req;
if (getWeb3ShimUsageState(origin) === undefined) {
setWeb3ShimUsageRecorded(origin);
sendMetrics(
{
event: `Website Accessed window.web3 Shim`,
category: 'inpage_provider',
referrer: {
url: origin,
},
},
{
excludeMetaMetricsId: true,
},
);
}
res.result = true;
return end();
}