Skip to content

Commit

Permalink
Jl/caip multichain/provider authorize metrics (#26699)
Browse files Browse the repository at this point in the history
<!--
Please submit this PR as a draft initially.
Do not mark it as "Ready for review" until the template has been
completely filled out, and PR status checks have passed at least once.
-->

## **Description**

* Add metrics to `provider_authorize`
* Add jsdoc to `removeScope()`

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

## **Related issues**

See: MetaMask/MetaMask-planning#3049

## **Manual testing steps**

1. Go to this page...
2.
3.

## **Screenshots/Recordings**

<!-- If applicable, add screenshots and/or recordings to visualize the
before and after of your change. -->

### **Before**

<!-- [screenshots/recordings] -->

### **After**

<!-- [screenshots/recordings] -->

## **Pre-merge author checklist**

- [ ] I've followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask
Extension Coding
Standards](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/CODING_GUIDELINES.md).
- [ ] I've completed the PR template to the best of my ability
- [ ] I’ve included tests if applicable
- [ ] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [ ] 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.

## **Pre-merge reviewer checklist**

- [ ] 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
jiexi authored Aug 28, 2024
1 parent 9fb5fed commit a9e92c5
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 8 deletions.
14 changes: 7 additions & 7 deletions app/scripts/lib/multichain-api/caip25permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,28 +201,28 @@ function removeAccount(
* `endowment:caip25` caveats. No-ops if the target scopeString is not in
* the existing scopes,.
*
* @param targetScopeString - TODO
* @param existingScopes - TODO
* @param targetScopeString - The scope that is being removed.
* @param caip25CaveatValue - The CAIP-25 permission caveat value to remove the scope from.
*/
export function removeScope(
targetScopeString: Scope,
existingScopes: Caip25CaveatValue,
caip25CaveatValue: Caip25CaveatValue,
) {
const newRequiredScopes = Object.entries(
existingScopes.requiredScopes,
caip25CaveatValue.requiredScopes,
).filter(([scope]) => scope !== targetScopeString);
const newOptionalScopes = Object.entries(
existingScopes.optionalScopes,
caip25CaveatValue.optionalScopes,
).filter(([scope]) => {
return scope !== targetScopeString;
});

const requiredScopesRemoved =
newRequiredScopes.length !==
Object.keys(existingScopes.requiredScopes).length;
Object.keys(caip25CaveatValue.requiredScopes).length;
const optionalScopesRemoved =
newOptionalScopes.length !==
Object.keys(existingScopes.optionalScopes).length;
Object.keys(caip25CaveatValue.optionalScopes).length;

if (requiredScopesRemoved) {
return {
Expand Down
27 changes: 26 additions & 1 deletion app/scripts/lib/multichain-api/provider-authorize/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ import {
Caip25CaveatType,
Caip25EndowmentPermissionName,
} from '../caip25permissions';
import { shouldEmitDappViewedEvent } from '../../util';
import {
MetaMetricsEventCategory,
MetaMetricsEventName,
} from '../../../../../shared/constants/metametrics';
import { assignAccountsToScopes, validateAndUpsertEip3085 } from './helpers';

const getAccountsFromPermission = (permission) => {
Expand Down Expand Up @@ -197,7 +202,27 @@ export async function providerAuthorizeHandler(req, res, _next, end, hooks) {
},
});

// TODO: metrics/tracking after approval
// TODO: Contact analytics team for how they would prefer to track this
// first time connection to dapp will lead to no log in the permissionHistory
// and if user has connected to dapp before, the dapp origin will be included in the permissionHistory state
// we will leverage that to identify `is_first_visit` for metrics
const isFirstVisit = !Object.keys(
hooks.metamaskState.permissionHistory,
).includes(origin);
if (shouldEmitDappViewedEvent(hooks.metamaskState.metaMetricsId)) {
hooks.sendMetrics({
event: MetaMetricsEventName.DappViewed,
category: MetaMetricsEventCategory.InpageProvider,
referrer: {
url: origin,
},
properties: {
is_first_visit: isFirstVisit,
number_of_accounts: Object.keys(hooks.metamaskState.accounts).length,
number_of_accounts_connected: permittedAccounts.length,
},
});
}

res.result = {
sessionId,
Expand Down
50 changes: 50 additions & 0 deletions app/scripts/lib/multichain-api/provider-authorize/handler.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,15 @@ import {
Caip25CaveatType,
Caip25EndowmentPermissionName,
} from '../caip25permissions';
import { shouldEmitDappViewedEvent } from '../../util';
import { providerAuthorizeHandler } from './handler';
import { assignAccountsToScopes, validateAndUpsertEip3085 } from './helpers';

jest.mock('../../util', () => ({
...jest.requireActual('../../util'),
shouldEmitDappViewedEvent: jest.fn(),
}));

jest.mock('../scope', () => ({
...jest.requireActual('../scope'),
validateAndFlattenScopes: jest.fn(),
Expand Down Expand Up @@ -85,6 +91,16 @@ const createMockedHandler = () => {
unsubscribeDomain: jest.fn(),
unsubscribeScope: jest.fn(),
};
const sendMetrics = jest.fn();
const metamaskState = {
permissionHistory: {},
metaMetricsId: 'metaMetricsId',
accounts: {
'0x1': {},
'0x2': {},
'0x3': {},
},
};
const response = {};
const handler = (request) =>
providerAuthorizeHandler(request, response, next, end, {
Expand All @@ -95,6 +111,8 @@ const createMockedHandler = () => {
removeNetworkConfiguration,
multichainMiddlewareManager,
multichainSubscriptionManager,
metamaskState,
sendMetrics,
});

return {
Expand All @@ -108,6 +126,8 @@ const createMockedHandler = () => {
removeNetworkConfiguration,
multichainMiddlewareManager,
multichainSubscriptionManager,
metamaskState,
sendMetrics,
handler,
};
};
Expand Down Expand Up @@ -671,6 +691,36 @@ describe('provider_authorize', () => {
);
});

it('emits the dapp viewed metrics event', async () => {
shouldEmitDappViewedEvent.mockResolvedValue(true);
const { handler, sendMetrics } = createMockedHandler();
bucketScopes
.mockReturnValueOnce({
supportedScopes: {},
supportableScopes: {},
unsupportableScopes: {},
})
.mockReturnValueOnce({
supportedScopes: {},
supportableScopes: {},
unsupportableScopes: {},
});
await handler(baseRequest);

expect(sendMetrics).toHaveBeenCalledWith({
category: 'inpage_provider',
event: 'Dapp Viewed',
properties: {
is_first_visit: true,
number_of_accounts: 3,
number_of_accounts_connected: 4,
},
referrer: {
url: 'http://test.com',
},
});
});

it('returns the session ID, properties, and merged scopes', async () => {
const { handler, response } = createMockedHandler();
bucketScopes
Expand Down

0 comments on commit a9e92c5

Please sign in to comment.