Skip to content

Commit

Permalink
chore: Typescript type coverage util lib folders (#10471)
Browse files Browse the repository at this point in the history
## **Description**

Increased the Typescript coverage across the utils files.

## **Related issues**

Fixes:
https://github.com/orgs/MetaMask/projects/60/views/16?pane=issue&itemId=69417476

## **Manual testing steps**

1. Go to `tsconfig.lint.json`
2. Uncomment the `// "app/util/**/*",` line
3. `yarn lint:tsc`
4. See if any errors show up from the `app/component` files

## **Screenshots/Recordings**

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

### **Before**

Typescript error present in test files listed in the ticket summary.

### **After**

No errors from those files

## **Pre-merge author checklist**

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

---------

Co-authored-by: tommasini <[email protected]>
  • Loading branch information
Daniel-Cross and tommasini authored Aug 1, 2024
1 parent 72ce8e1 commit 144fd92
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 38 deletions.
7 changes: 7 additions & 0 deletions app/lib/ppom/ppom-storage-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import { StorageBackend, StorageKey } from '@metamask/ppom-validator';

import { getArrayBufferForBlob } from 'react-native-blob-jsi-helper';

declare global {
interface FileReader {
_setReadyState(state: number): void;
_result: Uint8Array | null;
_error: string | null;
}
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (window.FileReader?.prototype.readAsArrayBuffer) {
Expand Down
28 changes: 22 additions & 6 deletions app/util/blockaid/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ import {
isBlockaidSupportedOnCurrentChain,
getBlockaidTransactionMetricsParams,
isBlockaidFeatureEnabled,
TransactionType,
} from '.';
import { TransactionStatus } from '@metamask/transaction-controller';

jest.mock('../../core/Engine', () => ({
resetState: jest.fn(),
Expand All @@ -40,10 +42,17 @@ describe('Blockaid util', () => {
});

it('returns empty object when transaction id does not match security response id', () => {
const transaction = {
id: 1,
const transaction: TransactionType = {
status: TransactionStatus.failed,
error: new Error('Simulated transaction error'),
id: '1',
chainId: '0x1',
time: Date.now(),
txParams: {
from: '0x1',
},
currentTransactionSecurityAlertResponse: {
id: 2,
id: '2',
response: {
result_type: ResultType.Malicious,
reason: Reason.notApplicable,
Expand All @@ -60,10 +69,17 @@ describe('Blockaid util', () => {
});

it('returns metrics params object when transaction id matches security response id', () => {
const transaction = {
id: 1,
const transaction: TransactionType = {
status: TransactionStatus.failed,
error: new Error('Simulated transaction error'),
id: '1',
chainId: '0x1',
time: Date.now(),
txParams: {
from: '0x1',
},
currentTransactionSecurityAlertResponse: {
id: 1,
id: '1',
response: {
result_type: ResultType.Malicious,
reason: Reason.notApplicable,
Expand Down
6 changes: 4 additions & 2 deletions app/util/dappTransactions/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
validateEtherAmount,
validateTokenAmount,
} from '.';
import { AssetsContractController } from '@metamask/assets-controllers';

const TEST_VALUE = new BN('0');
const TEST_INVALID_VALUE = '0';
Expand Down Expand Up @@ -92,8 +93,9 @@ describe('Dapp Transactions utils :: validateTokenAmount', () => {
it('should check value from contractBalances if selectedAddress is from address', async () => {
const mockGetERC20BalanceOf = jest.fn().mockReturnValue('0x0');
Engine.context.AssetsContractController = {
name: '',
getERC20BalanceOf: mockGetERC20BalanceOf,
};
} as Partial<AssetsContractController> as AssetsContractController;
expect(
await validateTokenAmount(
new BN(5),
Expand All @@ -112,7 +114,7 @@ describe('Dapp Transactions utils :: validateTokenAmount', () => {
const mockGetERC20BalanceOf = jest.fn().mockReturnValue('0x0');
Engine.context.AssetsContractController = {
getERC20BalanceOf: mockGetERC20BalanceOf,
};
} as Partial<AssetsContractController> as AssetsContractController;

const result = await validateTokenAmount(
new BN(5),
Expand Down
26 changes: 13 additions & 13 deletions app/util/dappTransactions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ import { estimateGas as controllerEstimateGas } from '../transaction-controller'

interface opts {
amount?: string;
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data?: any;
data?: string;
to?: string;
}

Expand Down Expand Up @@ -78,13 +76,16 @@ export const estimateGas = async (
let estimation;
try {
estimation = await controllerEstimateGas({
amount,
value: amount,
from,
data,
to: selectedAsset?.address ? selectedAsset.address : to,
});
} catch (e) {
estimation = { gas: TransactionTypes.CUSTOM_GAS.DEFAULT_GAS_LIMIT };
estimation = {
gas: TransactionTypes.CUSTOM_GAS.DEFAULT_GAS_LIMIT,
gasPrice: undefined,
};
}
return estimation;
};
Expand Down Expand Up @@ -145,16 +146,14 @@ export const validateTokenAmount = async (
}
// If user trying to send a token that doesn't own, validate balance querying contract
// If it fails, skip validation
let contractBalanceForAddress;
let contractBalanceForAddress: BN | undefined | number;
if (selectedAddress === from && contractBalances[selectedAsset.address]) {
contractBalanceForAddress = hexToBN(
contractBalances[selectedAsset.address].toString(),
);
} else {
try {
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { AssetsContractController }: any = Engine.context;
const { AssetsContractController } = Engine.context;
contractBalanceForAddress =
await AssetsContractController.getERC20BalanceOf(
selectedAsset.address,
Expand All @@ -167,7 +166,10 @@ export const validateTokenAmount = async (
if (value && !isBN(value)) return strings('transaction.invalid_amount');
const validateAssetAmount =
contractBalanceForAddress &&
lt(contractBalanceForAddress, value as unknown as number);
lt(
contractBalanceForAddress as unknown as number,
value as unknown as number,
);
if (validateAssetAmount) return strings('transaction.insufficient');
}
};
Expand All @@ -177,9 +179,7 @@ export const validateCollectibleOwnership = async (
tokenId: string,
selectedAddress: string,
): Promise<string | undefined> => {
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { AssetsContractController }: any = Engine.context;
const { AssetsContractController } = Engine.context;

try {
const owner = await AssetsContractController.getERC721OwnerOf(
Expand Down
10 changes: 6 additions & 4 deletions app/util/networks/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ describe('network-utils', () => {
const fromMock = '0x123';

it('returns value from TransactionController', async () => {
getNonceLock.mockReturnValueOnce({
(getNonceLock as jest.Mock).mockReturnValueOnce({
nextNonce: nonceMock,
releaseLock: jest.fn(),
});
Expand All @@ -335,7 +335,7 @@ describe('network-utils', () => {
it('releases nonce lock', async () => {
const releaseLockMock = jest.fn();

getNonceLock.mockReturnValueOnce({
(getNonceLock as jest.Mock).mockReturnValueOnce({
releaseLock: releaseLockMock,
});

Expand Down Expand Up @@ -378,7 +378,7 @@ describe('network-utils', () => {
// Reset mocks before each test
jest.clearAllMocks();
// Setup default behavior for mocked functions
Engine.controllerMessenger.call.mockReturnValue({
(Engine.controllerMessenger.call as jest.Mock).mockReturnValue({
sendAsync: mockSendAsync,
});
});
Expand All @@ -405,7 +405,9 @@ describe('network-utils', () => {

it('throws when provider is not initialized', async () => {
// Mock the call method to return undefined, simulating an uninitialized provider
Engine.controllerMessenger.call.mockReturnValueOnce(undefined);
(Engine.controllerMessenger.call as jest.Mock).mockReturnValueOnce(
undefined,
);

await expect(deprecatedGetNetworkId()).rejects.toThrow(
'Provider has not been initialized',
Expand Down
22 changes: 15 additions & 7 deletions app/util/smart-transactions/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { TransactionMeta } from '@metamask/transaction-controller';
import {
getShouldStartApprovalRequest,
getShouldUpdateApprovalRequest,
Expand Down Expand Up @@ -30,7 +31,8 @@ describe('Smart Transactions utils', () => {
value: '0x2386f26fc10000',
},
verifiedOnBlockchain: false,
};
} as TransactionMeta;

const chainId = '0x1';
const res = getTransactionType(txMeta, chainId);
expect(res).toEqual({
Expand Down Expand Up @@ -67,7 +69,8 @@ describe('Smart Transactions utils', () => {
value: '0x0',
},
verifiedOnBlockchain: false,
};
} as TransactionMeta;

const chainId = '0x1';
const res = getTransactionType(txMeta, chainId);
expect(res).toEqual({
Expand Down Expand Up @@ -103,7 +106,8 @@ describe('Smart Transactions utils', () => {
value: '0x2386f26fc10000',
},
verifiedOnBlockchain: false,
};
} as TransactionMeta;

const chainId = '0x1';
const res = getTransactionType(txMeta, chainId);
expect(res).toEqual({
Expand Down Expand Up @@ -139,7 +143,8 @@ describe('Smart Transactions utils', () => {
value: '0x0',
},
verifiedOnBlockchain: false,
};
} as TransactionMeta;

const chainId = '0x1';
const res = getTransactionType(txMeta, chainId);
expect(res).toEqual({
Expand Down Expand Up @@ -176,7 +181,8 @@ describe('Smart Transactions utils', () => {
value: '0x2386f26fc10000',
},
verifiedOnBlockchain: false,
};
} as TransactionMeta;

const chainId = '0x1';
const res = getTransactionType(txMeta, chainId);
expect(res).toEqual({
Expand Down Expand Up @@ -213,7 +219,8 @@ describe('Smart Transactions utils', () => {
value: '0x0',
},
verifiedOnBlockchain: false,
};
} as TransactionMeta;

const chainId = '0x1';
const res = getTransactionType(txMeta, chainId);
expect(res).toEqual({
Expand Down Expand Up @@ -250,7 +257,8 @@ describe('Smart Transactions utils', () => {
value: '0x0',
},
verifiedOnBlockchain: false,
};
} as TransactionMeta;

const chainId = '0x1';
const res = getTransactionType(txMeta, chainId);
expect(res).toEqual({
Expand Down
22 changes: 16 additions & 6 deletions app/util/smart-transactions/smart-publish-hook.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@ import {
import { ChainId } from '@metamask/controller-utils';
import { ApprovalController } from '@metamask/approval-controller';

interface PendingApprovalsData {
id: string;
origin: string;
type: string;
requestState: {
isInSwapFlow: boolean;
isSwapApproveTx: boolean;
};
}

jest.mock('uuid', () => ({
...jest.requireActual('uuid'),
v1: jest.fn(() => 'approvalId'),
Expand Down Expand Up @@ -52,9 +62,7 @@ const createApprovalControllerMock = ({
pendingApprovals,
}: {
addAndShowApprovalRequest: () => void;
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
pendingApprovals?: any[];
pendingApprovals?: PendingApprovalsData[];
}) =>
({
state: {
Expand Down Expand Up @@ -112,9 +120,7 @@ const defaultTransactionMeta: TransactionMeta = {

const createRequest = ({
addAndShowApprovalRequest = getDefaultAddAndShowApprovalRequest(),
// TODO: Replace "any" with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
pendingApprovals = [] as any[],
pendingApprovals = [] as PendingApprovalsData[],
transactionMeta = defaultTransactionMeta,
} = {}) => ({
transactionMeta: {
Expand All @@ -137,6 +143,10 @@ const createRequest = ({
maxDeadline: 150,
returnTxHashAsap: false,
},
mobile_active: true,
extension_active: true,
fallback_to_v1: false,
fallbackToV1: false,
},
});

Expand Down

0 comments on commit 144fd92

Please sign in to comment.