Skip to content

Commit

Permalink
refactor: Typescript conversion of get-provider-state.js (#23635)
Browse files Browse the repository at this point in the history
Part of #23014 
Fixes #23469 

Converting the level 6 dependency file
`app/scripts/lib/rpc-method-middleware/handlers/get-provider-state.js`
to typescript for contributing to `metamask-controller.js`.

## **Description**

<!--
Write a short description of the changes included in this pull request,
also include relevant motivation and context. Have in mind the following
questions:
1. What is the reason for the change?
2. What is the improvement/solution?
-->

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

## **Related issues**

Fixes:

## **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 Coding
Standards](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/CODING_GUIDELINES.md).
- [ ] I've clearly explained what problem this PR is solving and how it
is solved.
- [ ] I've linked related issues
- [ ] I've included manual testing steps
- [ ] I've included screenshots/recordings if applicable
- [ ] 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.
- [ ] I’ve properly set the pull request status:
  - [ ] In case it's not yet "ready for review", I've set it to "draft".
- [ ] In case it's "ready for review", I've changed it from "draft" to
"non-draft".

## **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.

---------

Co-authored-by: Jongsun Suh <[email protected]>
  • Loading branch information
NiranjanaBinoy and MajorLift authored Oct 2, 2024
1 parent b50b508 commit a7aacf8
Show file tree
Hide file tree
Showing 4 changed files with 144 additions and 49 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { PendingJsonRpcResponse } from '@metamask/utils';
import { JsonRpcEngineEndCallback } from 'json-rpc-engine';
import getProviderState, {
GetProviderState,
ProviderStateHandlerResult,
} from './get-provider-state';
import { HandlerRequestType } from './types';

describe('getProviderState', () => {
let mockEnd: JsonRpcEngineEndCallback;
let mockGetProviderState: GetProviderState;

beforeEach(() => {
mockEnd = jest.fn();
mockGetProviderState = jest.fn().mockResolvedValue({
chainId: '0x539',
isUnlocked: true,
networkVersion: '',
accounts: [],
});
});

it('should call getProviderState when the handler is invoked', async () => {
const req: HandlerRequestType = {
origin: 'testOrigin',
params: [],
id: '22',
jsonrpc: '2.0',
method: 'metamask_getProviderState',
};

const res: PendingJsonRpcResponse<ProviderStateHandlerResult> = {
id: '22',
jsonrpc: '2.0',
result: {
chainId: '0x539',
isUnlocked: true,
networkVersion: '',
accounts: [],
},
};

await getProviderState.implementation(req, res, jest.fn(), mockEnd, {
getProviderState: mockGetProviderState,
});

expect(mockGetProviderState).toHaveBeenCalledWith(req.origin);
expect(res.result).toStrictEqual({
chainId: '0x539',
isUnlocked: true,
networkVersion: '',
accounts: [],
});
expect(mockEnd).toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import type {
JsonRpcEngineNextCallback,
JsonRpcEngineEndCallback,
} from 'json-rpc-engine';
import type {
PendingJsonRpcResponse,
JsonRpcParams,
Hex,
} from '@metamask/utils';
import { OriginString } from '@metamask/permission-controller';
import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
import {
HandlerWrapper,
HandlerRequestType as ProviderStateHandlerRequest,
} from './types';

/**
* @property chainId - The current chain ID.
* @property isUnlocked - Whether the extension is unlocked or not.
* @property networkVersion - The current network ID.
* @property accounts - List of permitted accounts for the specified origin.
*/
export type ProviderStateHandlerResult = {
chainId: Hex;
isUnlocked: boolean;
networkVersion: string;
accounts: string[];
};

export type GetProviderState = (
origin: OriginString,
) => Promise<ProviderStateHandlerResult>;

type GetProviderStateConstraint<Params extends JsonRpcParams = JsonRpcParams> =
{
implementation: (
_req: ProviderStateHandlerRequest<Params>,
res: PendingJsonRpcResponse<ProviderStateHandlerResult>,
_next: JsonRpcEngineNextCallback,
end: JsonRpcEngineEndCallback,
{ _getProviderState }: Record<string, GetProviderState>,
) => Promise<void>;
} & HandlerWrapper;

/**
* This RPC method gets background state relevant to the provider.
* The background sends RPC notifications on state changes, but the provider
* first requests state on initialization.
*/
const getProviderState = {
methodNames: [MESSAGE_TYPE.GET_PROVIDER_STATE],
implementation: getProviderStateHandler,
hookNames: {
getProviderState: true,
},
} satisfies GetProviderStateConstraint;

export default getProviderState;

/**
* @param req - The JSON-RPC request object.
* @param res - The JSON-RPC response object.
* @param _next - The json-rpc-engine 'next' callback.
* @param end - The json-rpc-engine 'end' callback.
* @param options
* @param options.getProviderState - An async function that gets the current provider state.
*/
async function getProviderStateHandler<
Params extends JsonRpcParams = JsonRpcParams,
>(
req: ProviderStateHandlerRequest<Params>,
res: PendingJsonRpcResponse<ProviderStateHandlerResult>,
_next: JsonRpcEngineNextCallback,
end: JsonRpcEngineEndCallback,
{ getProviderState: _getProviderState }: Record<string, GetProviderState>,
): Promise<void> {
res.result = {
...(await _getProviderState(req.origin)),
};
return end();
}
7 changes: 7 additions & 0 deletions app/scripts/lib/rpc-method-middleware/handlers/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { OriginString } from '@metamask/permission-controller';
import { JsonRpcParams, JsonRpcRequest } from '@metamask/utils';
import { MessageType } from '../../../../../shared/constants/app';

export type HandlerWrapper = {
methodNames: [MessageType] | MessageType[];
hookNames: Record<string, boolean>;
};

export type HandlerRequestType<Params extends JsonRpcParams = JsonRpcParams> =
Required<JsonRpcRequest<Params>> & {
origin: OriginString;
};

0 comments on commit a7aacf8

Please sign in to comment.