Skip to content
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

refactor: Typescript conversion of ethereum-chain-utils.js #26103

Open
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

NiranjanaBinoy
Copy link
Contributor

@NiranjanaBinoy NiranjanaBinoy commented Jul 24, 2024

Description

Converting the level 6 dependency file app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.js to typescript for contributing to metamask-controller.js.

Open in GitHub Codespaces

Related issues

Part of #23014
Fixes: #26102

Manual testing steps

  1. Go to this page...

Screenshots/Recordings

Before

After

Pre-merge author checklist

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.

Copy link
Contributor

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.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

Converted ethereum-chain-utils.js to TypeScript, enhancing type safety and maintainability.

  • File Added: app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.ts
    • Converted functions like validateChainId, validateSwitchEthereumChainParams, validateAddEthereumChainParams, and switchChain to TypeScript.
  • File Added: app/scripts/lib/rpc-method-middleware/handlers/types.ts
    • Defined TypeScript types for handler wrappers, approval flows, caveat retrieval, chain permissions, user approvals, and network settings.

Ensure thorough testing to validate type definitions against actual data structures and usage patterns.

2 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

Converted ethereum-chain-utils.js to TypeScript, enhancing type safety and maintainability.

  • File Removed: app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.js
    • Deleted JavaScript file as part of TypeScript migration.
  • File Added: app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.ts
    • Converted utility functions like validateChainId, validateSwitchEthereumChainParams, validateAddEthereumChainParams, and switchChain to TypeScript.
  • File Added: app/scripts/lib/rpc-method-middleware/handlers/types.ts
    • Defined TypeScript types for handler wrappers, approval flows, caveat retrieval, chain permissions, user approvals, and network settings.

Ensure thorough testing to validate type definitions against actual data structures and usage patterns.

1 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

Copy link
Contributor

@MajorLift MajorLift left a comment

Choose a reason for hiding this comment

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

Looks like most of the as assertions being added that could be removed:

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

Converted ethereum-chain-utils.js to TypeScript, enhancing type safety and maintainability.

  • File Removed: app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.js
    • Deleted JavaScript file as part of TypeScript migration.
  • File Added: app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.ts
    • Converted utility functions like validateChainId, validateSwitchEthereumChainParams, validateAddEthereumChainParams, and switchChain to TypeScript.
  • File Modified: app/scripts/lib/rpc-method-middleware/handlers/types.ts
    • Added new TypeScript type definitions for FindNetworkConfigurationBy, GetCaveat, GetChainPermissionsFeatureFlag, RequestPermittedChainsPermission, RequestUserApproval, and SetActiveNetwork.
    • Removed HandlerWrapper type, indicating a possible refactor or simplification.

2 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

Converted ethereum-chain-utils.js to TypeScript, enhancing type safety and maintainability.

  • File Removed: app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.js
    • Deleted JavaScript file as part of TypeScript migration.
  • File Added: app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.ts
    • Converted utility functions like validateChainId, validateSwitchEthereumChainParams, validateAddEthereumChainParams, and switchChain to TypeScript.
  • File Modified: app/scripts/lib/rpc-method-middleware/handlers/types.ts
    • Added new TypeScript type definitions for FindNetworkConfigurationBy, GetCaveat, GetChainPermissionsFeatureFlag, RequestPermittedChainsPermission, RequestUserApproval, and SetActiveNetwork.
    • Removed HandlerWrapper type, indicating a possible refactor or simplification.

1 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

export function validateChainId(chainId) {
const _chainId = typeof chainId === 'string' && chainId.toLowerCase();
export function validateChainId(chainId: Hex): Hex {
const _chainId = chainId.toLowerCase() as Hex;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@MajorLift When we do chainId.toLowerCase(), it seems to be returning type string. Is there any way for chainId to be Hex without the as assertion?

Copy link
Contributor

@MajorLift MajorLift Jul 30, 2024

Choose a reason for hiding this comment

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

We can also define a type guard here. The value is Hex predicate is safe to use since any string that's validated by isPrefixedFormattedHexString must be equivalent to or narrower than the Hex type.

diff --git a/app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.ts b/app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.ts
index 002d6554fc..8622b1047c 100644
--- a/app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.ts
+++ b/app/scripts/lib/rpc-method-middleware/handlers/ethereum-chain-utils.ts
@@ -58,9 +58,13 @@ export function findExistingNetwork(
 }
 
 export function validateChainId(chainId: Hex): Hex {
-  const _chainId = chainId.toLowerCase() as Hex;
+  const _chainId = chainId.toLowerCase();
 
-  if (!isPrefixedFormattedHexString(_chainId)) {
+  if (
+    !((value: string): value is Hex => isPrefixedFormattedHexString(value))(
+      _chainId,
+    )
+  ) {
     throw ethErrors.rpc.invalidParams({
       message: `Expected 0x-prefixed, unpadded, non-zero hexadecimal string 'chainId'. Received:\n${chainId}`,
     });

Copy link
Contributor

@MajorLift MajorLift Jul 31, 2024

Choose a reason for hiding this comment

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

toLowerCase does unnecessarily widen the type of chainId, and an as assertion is one way to resolve this.

However, there's a better way to reason about the type of _chainId. Because the code immediately invokes the validator function isPrefixedFormattedHexString, we are provided with a runtime guarantee that any _chainId value that doesn't throw an error in the first if-block will be of a type narrower than Hex.

So now all we have to do is make sure this guarantee is reflected at the type-level as well, which we achieve by using the type guard with the value is Hex predicate.

This successfully narrows _chainId back to Hex past the first if-block. Without relying on any assertions, or introducing any uncertainty about value-level vs. type-level discrepancies.

@NiranjanaBinoy NiranjanaBinoy force-pushed the ts-ethereum-chain-utils branch 2 times, most recently from e72e678 to 3b36759 Compare August 14, 2024 16:07
@NiranjanaBinoy NiranjanaBinoy force-pushed the ts-ethereum-chain-utils branch from 3b36759 to a60947e Compare August 14, 2024 18:37
Copy link

codecov bot commented Aug 14, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 70.12%. Comparing base (cdd543d) to head (4111fb1).
Report is 878 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop   #26103      +/-   ##
===========================================
+ Coverage    69.98%   70.12%   +0.14%     
===========================================
  Files         1422     1428       +6     
  Lines        49926    50107     +181     
  Branches     13861    13897      +36     
===========================================
+ Hits         34940    35136     +196     
+ Misses       14986    14971      -15     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@metamaskbot
Copy link
Collaborator

Builds ready [a60947e]
Page Load Metrics (82 ± 24 ms)
PlatformPageMetricMin (ms)Max (ms)Average (ms)StandardDeviation (ms)MarginOfError (ms)
ChromeHomefirstPaint682971124823
domContentLoaded9104272110
load42281825124
domInteractive9104272110
Bundle size diffs [🚨 Warning! Bundle size has increased!]
  • background: 180 Bytes (0.00%)
  • ui: 0 Bytes (0.00%)
  • common: 0 Bytes (0.00%)

Copy link

@metamaskbot
Copy link
Collaborator

Builds ready [4111fb1]
Page Load Metrics (67 ± 10 ms)
PlatformPageMetricMin (ms)Max (ms)Average (ms)StandardDeviation (ms)MarginOfError (ms)
ChromeHomefirstPaint6413496209
domContentLoaded96221157
load43116672010
domInteractive96121157
Bundle size diffs [🚨 Warning! Bundle size has increased!]
  • background: 183 Bytes (0.00%)
  • ui: 0 Bytes (0.00%)
  • common: 0 Bytes (0.00%)

Copy link
Contributor

This PR has been automatically marked as stale because it has not had recent activity in the last 60 days. It will be closed in 14 days. Thank you for your contributions.

@github-actions github-actions bot added stale issues and PRs marked as stale and removed stale issues and PRs marked as stale labels Oct 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

refactor: Typescript conversion of ethereum-chain-utils.js
3 participants