Skip to content

Commit

Permalink
Update TypeScript to v4.4 (MetaMask#795)
Browse files Browse the repository at this point in the history
See the release announcement for more details about v4.4:
https://devblogs.microsoft.com/typescript/announcing-typescript-4-4-rc/

The main breaking change that affected us was the change in the default
type of the `catch` error parameter from `any` to `unknown`. This was
resolved in some places by changing the expected type to `unknown`. In
cases where we need it to be an `Error` or where we use an `Error`
property, the type is now checked at runtime.

A minor change was needed in `BaseControllerV2` as well, because
TypeScript wasn't happy with the fact that it was never initialized
for some reason, even though it wasn't supposed to be initialized
(it was set to `never`). But initializing it as `undefined` serves the
exact same purpose and resolved the error.
  • Loading branch information
Gudahtt authored Apr 22, 2022
1 parent a8d4a87 commit 6abbc5d
Show file tree
Hide file tree
Showing 14 changed files with 65 additions and 71 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@
"ts-jest": "^26.5.2",
"typedoc": "^0.22.15",
"typedoc-plugin-missing-exports": "^0.22.6",
"typescript": "~4.3.5"
"typescript": "~4.4.4"
},
"engines": {
"node": ">=12.0.0"
Expand Down
7 changes: 3 additions & 4 deletions src/BaseControllerV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,10 @@ export class BaseController<

/**
* The existence of the `subscribe` property is how the ComposableController detects whether a
* controller extends the old BaseController or the new one. We set it to `never` here to ensure
* this property is never used for new BaseController-based controllers, to ensure the
* ComposableController never mistakes them for an older style controller.
* controller extends the old BaseController or the new one. We set it to `undefined` here to
* ensure the ComposableController never mistakes them for an older style controller.
*/
public readonly subscribe: never;
public readonly subscribe: undefined;

/**
* Creates a BaseController instance.
Expand Down
4 changes: 2 additions & 2 deletions src/apis/token-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ async function queryApi(
fetchOptions.headers.set('Content-Type', 'application/json');
try {
return await timeoutFetch(apiURL, fetchOptions, timeout);
} catch (err) {
if (err.name === 'AbortError') {
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
console.log('Request is aborted');
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/approval/ApprovalController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { RestrictedControllerMessenger } from '../ControllerMessenger';
const controllerName = 'ApprovalController';

type ApprovalPromiseResolve = (value?: unknown) => void;
type ApprovalPromiseReject = (error?: Error) => void;
type ApprovalPromiseReject = (error?: unknown) => void;

type ApprovalRequestData = Record<string, Json> | null;

Expand Down Expand Up @@ -396,7 +396,7 @@ export class ApprovalController extends BaseController<
* @param id - The id of the approval request.
* @param error - The error to reject the approval promise with.
*/
reject(id: string, error: Error): void {
reject(id: string, error: unknown): void {
this._deleteApprovalAndGetCallbacks(id).reject(error);
}

Expand Down
7 changes: 6 additions & 1 deletion src/assets/CollectiblesController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1059,7 +1059,12 @@ export class CollectiblesController extends BaseController<
try {
isOwned = await this.isCollectibleOwner(userAddress, address, tokenId);
} catch (error) {
if (!error.message.includes('Unable to verify ownership')) {
if (
!(
error instanceof Error &&
error.message.includes('Unable to verify ownership')
)
) {
throw error;
}
}
Expand Down
7 changes: 6 additions & 1 deletion src/assets/CurrencyRateController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,12 @@ export class CurrencyRateController extends BaseController<
conversionDate = Date.now() / 1000;
}
} catch (error) {
if (!error.message.includes('market does not exist for this coin pair')) {
if (
!(
error instanceof Error &&
error.message.includes('market does not exist for this coin pair')
)
) {
throw error;
}
} finally {
Expand Down
2 changes: 1 addition & 1 deletion src/assets/TokenBalancesController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ describe('TokenBalancesController', () => {
await tokenBalances.updateBalances();
const mytoken = getToken(tokenBalances, address);
expect(mytoken?.balanceError).toBeInstanceOf(Error);
expect(mytoken?.balanceError?.message).toBe(errorMsg);
expect(mytoken?.balanceError).toHaveProperty('message', errorMsg);
expect(
tokenBalances.state.contractBalances[address].toNumber(),
).toStrictEqual(0);
Expand Down
3 changes: 2 additions & 1 deletion src/assets/TokenRatesController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export interface Token {
decimals: number;
symbol: string;
image?: string;
balanceError?: Error | null;
balanceError?: unknown;
isERC721?: boolean;
}

Expand Down Expand Up @@ -396,6 +396,7 @@ export class TokenRatesController extends BaseController<
]);
} catch (error) {
if (
error instanceof Error &&
error.message.includes('market does not exist for this coin pair')
) {
return {};
Expand Down
2 changes: 1 addition & 1 deletion src/assets/TokensController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export class TokensController extends BaseController<

private failSuggestedAsset(
suggestedAssetMeta: SuggestedAssetMeta,
error: Error,
error: unknown,
) {
const failedSuggestedAssetMeta = {
...suggestedAssetMeta,
Expand Down
9 changes: 6 additions & 3 deletions src/gas/determineGasFeeCalculations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,12 @@ export default async function determineGasFeeCalculations({
gasEstimateType: GAS_ESTIMATE_TYPES.ETH_GASPRICE,
};
} catch (error) {
throw new Error(
`Gas fee/price estimation failed. Message: ${error.message}`,
);
if (error instanceof Error) {
throw new Error(
`Gas fee/price estimation failed. Message: ${error.message}`,
);
}
throw error;
}
}
}
44 changes: 16 additions & 28 deletions src/keyring/KeyringController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,19 +221,13 @@ describe('KeyringController', () => {

it('should import account with strategy json wrong password', async () => {
const somePassword = 'holachao12';
let error;
try {
await keyringController.importAccountWithStrategy(
AccountImportStrategy.json,
[input, somePassword],
);
} catch (e) {
error = e;
}

expect(error.message).toBe(
'Key derivation failed - possibly wrong passphrase',
);
await expect(
keyringController.importAccountWithStrategy(AccountImportStrategy.json, [
input,
somePassword,
]),
).rejects.toThrow('Key derivation failed - possibly wrong passphrase');
});

it('should remove account', async () => {
Expand Down Expand Up @@ -435,26 +429,20 @@ describe('KeyringController', () => {
it('should fail when sign typed message format is wrong', async () => {
const msgParams = [{}];
const account = initialState.keyrings[0].accounts[0];
let error1;
try {
await keyringController.signTypedMessage(

await expect(
keyringController.signTypedMessage(
{ data: msgParams, from: account },
SignTypedDataVersion.V1,
);
} catch (e) {
error1 = e;
}
let error2;
try {
await keyringController.signTypedMessage(
),
).rejects.toThrow('Keyring Controller signTypedMessage:');

await expect(
keyringController.signTypedMessage(
{ data: msgParams, from: account },
SignTypedDataVersion.V3,
);
} catch (e) {
error2 = e;
}
expect(error1.message).toContain('Keyring Controller signTypedMessage:');
expect(error2.message).toContain('Keyring Controller signTypedMessage:');
),
).rejects.toThrow('Keyring Controller signTypedMessage:');
});

it('should sign transaction', async () => {
Expand Down
18 changes: 11 additions & 7 deletions src/permissions/PermissionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Mutable } from '@metamask/types';
import deepFreeze from 'deep-freeze-strict';
import { castDraft, Draft, Patch } from 'immer';
import { nanoid } from 'nanoid';
import { EthereumRpcError } from 'eth-rpc-errors';
import {
AcceptRequest as AcceptApprovalRequest,
AddApprovalRequest,
Expand Down Expand Up @@ -1996,12 +1997,15 @@ export class PermissionController<
try {
this.validateRequestedPermissions(origin, permissions);
} catch (error) {
// Re-throw as an internal error; we should never receive invalid approved
// permissions.
throw internalError(
`Invalid approved permissions request: ${error.message}`,
error.data,
);
if (error instanceof EthereumRpcError) {
// Re-throw as an internal error; we should never receive invalid approved
// permissions.
throw internalError(
`Invalid approved permissions request: ${error.message}`,
error.data,
);
}
throw internalError('Unrecognized error type', { error });
}
}

Expand Down Expand Up @@ -2087,7 +2091,7 @@ export class PermissionController<
* @param error - The error associated with the rejection.
* @returns Nothing
*/
private _rejectPermissionsRequest(id: string, error: Error): void {
private _rejectPermissionsRequest(id: string, error: unknown): void {
return this.messagingSystem.call(
'ApprovalController:rejectRequest',
id,
Expand Down
19 changes: 4 additions & 15 deletions src/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -809,14 +809,7 @@ describe('util', () => {
});

it('should throw error for an unsuccessful fetch', async () => {
let error;
try {
await util.successfulFetch(SOME_FAILING_API);
} catch (e) {
error = e;
}

expect(error.message).toBe(
await expect(util.successfulFetch(SOME_FAILING_API)).rejects.toThrow(
`Fetch failed with status '500' for request '${SOME_FAILING_API}'`,
);
});
Expand All @@ -834,13 +827,9 @@ describe('util', () => {
});

it('should fail fetch with timeout', async () => {
let error;
try {
await util.timeoutFetch(SOME_API, {}, 100);
} catch (e) {
error = e;
}
expect(error.message).toBe('timeout');
await expect(util.timeoutFetch(SOME_API, {}, 100)).rejects.toThrow(
'timeout',
);
});
});

Expand Down
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8091,10 +8091,10 @@ typedoc@^0.22.15:
minimatch "^5.0.1"
shiki "^0.10.1"

typescript@~4.3.5:
version "4.3.5"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.3.5.tgz#4d1c37cc16e893973c45a06886b7113234f119f4"
integrity sha512-DqQgihaQ9cUrskJo9kIyW/+g0Vxsk8cDtZ52a3NGh0YNTfpUSArXSohyUGnvbPazEPLu398C0UxmKSOrPumUzA==
typescript@~4.4.4:
version "4.4.4"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.4.4.tgz#2cd01a1a1f160704d3101fd5a58ff0f9fcb8030c"
integrity sha512-DqGhF5IKoBl8WNf8C1gu8q0xZSInh9j1kJJMqT3a94w1JzVaBU4EXOSMrz9yDqMT0xt3selp83fuFMQ0uzv6qA==

unbox-primitive@^1.0.1:
version "1.0.1"
Expand Down

0 comments on commit 6abbc5d

Please sign in to comment.