Skip to content

Commit

Permalink
refactor(controller-utils): replace any with types for type safety (#…
Browse files Browse the repository at this point in the history
…3975)

## Explanation

The current implementation uses any type for parameters in certain
utility functions within controller-utils, which lacks type safety and
can lead to runtime errors if incorrect values are passed. This approach
needs to change to ensure the reliability and maintainability of the
codebase.

## References

- Fixes #3717

## Changelog

<!--
If you're making any consumer-facing changes, list those changes here as
if you were updating a changelog, using the template below as a guide.

(CATEGORY is one of BREAKING, ADDED, CHANGED, DEPRECATED, REMOVED, or
FIXED. For security-related issues, follow the Security Advisory
process.)

Please take care to name the exact pieces of the API you've added or
changed (e.g. types, interfaces, functions, or methods).

If there are any breaking changes, make sure to offer a solution for
consumers to follow once they upgrade to the changes.

Finally, if you're only making changes to development scripts or tests,
you may replace the template below with "None".
-->

### `@metamask/controller-utils`

#### Fixed

- **BREAKING**: Replaced any type with BN for BNToHex and fractionBN
functions to enhance type safety.
- **BREAKING**: Replaced any type with unknown in logOrRethrowError.
- **BREAKING**: Replaced any type with string in isNetworkType.


## Checklist

- [x] I've updated the test suite for new or updated code as appropriate
- [x] I've updated documentation (JSDoc, Markdown, etc.) for new or
updated code as appropriate
- [x] I've highlighted breaking changes using the "BREAKING" category
above as appropriate
  • Loading branch information
cryptodev-2s authored Mar 5, 2024
1 parent a24869b commit e387b17
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 31 deletions.
15 changes: 7 additions & 8 deletions packages/assets-controllers/src/AccountTrackerController.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import type { BaseConfig, BaseState } from '@metamask/base-controller';
import {
BNToHex,
query,
safelyExecuteWithTimeout,
} from '@metamask/controller-utils';
import { query, safelyExecuteWithTimeout } from '@metamask/controller-utils';
import EthQuery from '@metamask/eth-query';
import type { Provider } from '@metamask/eth-query';
import type {
Expand Down Expand Up @@ -272,9 +268,12 @@ export class AccountTrackerController extends StaticIntervalPollingControllerV1<

const accountsForChain = { ...accountsByChainId[chainId] };
for (const address of accountsToUpdate) {
accountsForChain[address] = {
balance: BNToHex(await this.getBalanceFromChain(address, ethQuery)),
};
const balance = await this.getBalanceFromChain(address, ethQuery);
if (balance) {
accountsForChain[address] = {
balance,
};
}
}

this.update({
Expand Down
2 changes: 2 additions & 0 deletions packages/controller-utils/src/types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { isNetworkType, NetworkType } from './types';

describe('types', () => {
it('isNetworkType', () => {
// @ts-expect-error We are intentionally passing bad input.
expect(isNetworkType({})).toBe(false);
// @ts-expect-error We are intentionally passing bad input.
expect(isNetworkType(1)).toBe(false);
expect(isNetworkType('test')).toBe(false);
expect(isNetworkType('mainnet')).toBe(true);
Expand Down
6 changes: 2 additions & 4 deletions packages/controller-utils/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,8 @@ export type NetworkType = (typeof NetworkType)[keyof typeof NetworkType];
* @param val - the value to check whether it is NetworkType or not.
* @returns boolean indicating whether or not the argument is NetworkType.
*/
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isNetworkType(val: any): val is NetworkType {
return Object.values(NetworkType).includes(val);
export function isNetworkType(val: string): val is NetworkType {
return Object.values(NetworkType).includes(val as NetworkType);
}

/**
Expand Down
36 changes: 17 additions & 19 deletions packages/controller-utils/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ export function isSafeChainId(chainId: Hex): boolean {
* @param inputBn - BN instance to convert to a hex string.
* @returns A '0x'-prefixed hex string.
*/
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function BNToHex(inputBn: any) {
export function BNToHex(inputBn: BN) {
return add0x(inputBn.toString(16));
}

Expand All @@ -59,9 +57,7 @@ export function BNToHex(inputBn: any) {
* @returns Product of the multiplication.
*/
export function fractionBN(
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
targetBN: any,
targetBN: BN,
numerator: number | string,
denominator: number | string,
) {
Expand Down Expand Up @@ -539,25 +535,27 @@ export function isValidJson(value: unknown): value is Json {
* @param error - Caught error that we should either rethrow or log to console
* @param codesToCatch - array of error codes for errors we want to catch and log in a particular context
*/
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function logOrRethrowError(error: any, codesToCatch: number[] = []) {
function logOrRethrowError(error: unknown, codesToCatch: number[] = []) {
if (!error) {
return;
}

const includesErrorCodeToCatch = codesToCatch.some((code) =>
error.message?.includes(`Fetch failed with status '${code}'`),
);
if (error instanceof Error) {
const includesErrorCodeToCatch = codesToCatch.some((code) =>
error.message.includes(`Fetch failed with status '${code}'`),
);

if (
error instanceof Error &&
(includesErrorCodeToCatch ||
error.message?.includes('Failed to fetch') ||
error === TIMEOUT_ERROR)
) {
console.error(error);
if (
includesErrorCodeToCatch ||
error.message.includes('Failed to fetch') ||
error === TIMEOUT_ERROR
) {
console.error(error);
} else {
throw error;
}
} else {
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw error;
}
}

0 comments on commit e387b17

Please sign in to comment.