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

fix: Fix TS errors in core directory #7331

Merged
merged 17 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion app/constants/network.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { NetworkType } from '@metamask/controller-utils';

export const MAINNET = 'mainnet';
export const HOMESTEAD = 'homestead';
export const GOERLI = 'goerli';
export const SEPOLIA = 'sepolia';
export const LINEA_GOERLI = 'linea-goerli';
export const LINEA_MAINNET = 'linea-mainnet';
export const RPC = 'rpc';
export const RPC = NetworkType.rpc;
export const NO_RPC_BLOCK_EXPLORER = 'NO_BLOCK_EXPLORER';
export const PRIVATENETWORK = 'PRIVATENETWORK';
export const DEFAULT_MAINNET_CUSTOM_NAME = 'Ethereum Main Custom';
Expand Down
3 changes: 2 additions & 1 deletion app/core/AppConstants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { CoreTypes } from '@walletconnect/types';
import Device from '../util/device';

const DEVELOPMENT = 'development';
Expand Down Expand Up @@ -61,7 +62,7 @@ export default {
native: 'metamask://',
universal: 'https://metamask.app.link/',
},
},
} as CoreTypes.Metadata,
},
SWAPS: {
ACTIVE: true,
Expand Down
5 changes: 4 additions & 1 deletion app/core/BackupVault/backupVault.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { backupVault } from './backupVault';
import { VAULT_BACKUP_FAILED_UNDEFINED } from '../../constants/error';
import { KeyringControllerState } from '@metamask/keyring-controller';

//TODO Mock the react-native-keychain module test the other functions inside backupVault
/*
Expand All @@ -12,9 +13,11 @@ import { VAULT_BACKUP_FAILED_UNDEFINED } from '../../constants/error';
*/
describe('backupVault', () => {
it('should return an error response when the vault is undefined', async () => {
const keyringState = {
const keyringState: KeyringControllerState = {
vault: undefined,
keyrings: [],
isUnlocked: false,
keyringTypes: [],
};
const response = await backupVault(keyringState);
expect(response.success).toBe(false);
Expand Down
67 changes: 35 additions & 32 deletions app/core/GasPolling/GasPolling.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import {
startGasPolling,
getEIP1559TransactionData,
stopGasPolling,
// useDataStore,
} from './GasPolling';
import { parseTransactionEIP1559 } from '../../util/transactions';
import { GasFeeOptions, GetEIP1559TransactionDataProps } from './types';
import AppConstants from '../AppConstants';
jest.mock('../../util/transactions');
const mockedParseTransactionEIP1559 =
parseTransactionEIP1559 as jest.MockedFunction<
Expand All @@ -30,39 +31,43 @@ jest.mock('react-redux', () => ({
}));

const suggestedGasLimit = '0x123';
const selectedOption = 'medium';
const gas = {
maxWaitTimeEstimate: 45000,
minWaitTimeEstimate: 15000,
suggestedMaxFeePerGas: '1.500000018',
suggestedMaxPriorityFeePerGas: '1.5',
selectedOption,
};
const selectedOption = 'medium';
const gasFeeEstimates = {
baseFeeTrend: 'down',
estimatedBaseFee: '0.000000013',
high: {
maxWaitTimeEstimate: 60000,
minWaitTimeEstimate: 15000,
suggestedMaxFeePerGas: '2.450000023',
suggestedMaxPriorityFeePerGas: '2.45',
},
historicalBaseFeeRange: ['0.000000009', '0.000000014'],
historicalPriorityFeeRange: ['1', '96'],
latestPriorityFeeRange: ['1.5', '2.999999783'],
low: {
maxWaitTimeEstimate: 30000,
minWaitTimeEstimate: 15000,
suggestedMaxFeePerGas: '1.410000013',
suggestedMaxPriorityFeePerGas: '1.41',
},
medium: {
maxWaitTimeEstimate: 45000,
minWaitTimeEstimate: 15000,
suggestedMaxFeePerGas: '1.500000018',
suggestedMaxPriorityFeePerGas: '1.5',
const gasFeeEstimates: GasFeeOptions = {
estimatedBaseFee: null,
gasFeeEstimates: {
baseFeeTrend: 'down',
estimatedBaseFee: '0.000000013',
high: {
maxWaitTimeEstimate: 60000,
minWaitTimeEstimate: 15000,
suggestedMaxFeePerGas: '2.450000023',
suggestedMaxPriorityFeePerGas: '2.45',
},
historicalBaseFeeRange: ['0.000000009', '0.000000014'],
historicalPriorityFeeRange: ['1', '96'],
latestPriorityFeeRange: ['1.5', '2.999999783'],
low: {
maxWaitTimeEstimate: 30000,
minWaitTimeEstimate: 15000,
suggestedMaxFeePerGas: '1.410000013',
suggestedMaxPriorityFeePerGas: '1.41',
},
medium: {
maxWaitTimeEstimate: 45000,
minWaitTimeEstimate: 15000,
suggestedMaxFeePerGas: '1.500000018',
suggestedMaxPriorityFeePerGas: '1.5',
},
networkCongestion: 0.4713,
priorityFeeTrend: 'level',
},
networkCongestion: 0.4713,
priorityFeeTrend: 'level',
};
const contractExchangeRates = {};
const conversionRate = 1844.31;
Expand Down Expand Up @@ -104,10 +109,9 @@ describe('GasPolling', () => {
});

describe('GetEIP1559TransactionData', () => {
const transactionData = {
const transactionData: GetEIP1559TransactionDataProps = {
suggestedGasLimit,
gas,
selectedOption,
gasFeeEstimates,
transactionState,
contractExchangeRates,
Expand All @@ -117,10 +121,9 @@ describe('GetEIP1559TransactionData', () => {
};

it('should fail when incomplete props is passed for ', async () => {
const incompleteTransactionData = {
const incompleteTransactionData: Partial<GetEIP1559TransactionDataProps> = {
suggestedGasLimit,
gas,
selectedOption,
gasFeeEstimates,
transactionState,
contractExchangeRates,
Expand Down Expand Up @@ -169,7 +172,7 @@ describe('GetEIP1559TransactionData', () => {
suggestedMaxPriorityFeePerGasHex: '59682f00',
timeEstimate: 'Likely in < 30 seconds',
timeEstimateColor: 'green',
timeEstimateId: 'likely',
timeEstimateId: AppConstants.GAS_TIMES.LIKELY,
totalMaxConversion: '1844.4',
totalMaxHex: 'de0e3e3ba6645f6',
totalMaxNative: '1.00005',
Expand Down
8 changes: 7 additions & 1 deletion app/core/GasPolling/GasPolling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,13 @@ export const getEIP1559TransactionData = ({
conversionRate,
currentCurrency,
nativeCurrency,
transactionState,
transactionState: {
selectedAsset: transactionState.selectedAsset,
transaction: {
value: transactionState.transaction.value,
data: transactionState.transaction.data,
},
},
gasFeeEstimates,
swapsParams: undefined,
selectedGasFee: {
Expand Down
43 changes: 21 additions & 22 deletions app/core/GasPolling/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,31 +157,30 @@ export interface TransactionSharedProps {
* For UpdateEIP1559Transaction, the transactionState are undefined.
*/
transactionState: {
assetType: string | undefined;
ensRecipient: string | undefined;
id: string | undefined;
nonce: string | undefined;
paymentRequest: string | undefined;
proposedNonce: string | undefined;
readableValue: string | undefined;
assetType?: string;
ensRecipient?: string;
id?: string;
nonce?: string;
proposedNonce?: string;
readableValue?: string;
selectedAsset: Record<string, unknown>;
symbol: string | undefined;
symbol?: string;
transaction: {
data: string | undefined;
from: string | undefined;
gas: string | undefined;
gasPrice: string | undefined;
maxFeePerGas: string | undefined;
maxPriorityFeePerGas: string | undefined;
to: string | undefined;
value: string | undefined;
data?: string;
from?: string;
gas?: string;
gasPrice?: string;
maxFeePerGas?: string;
maxPriorityFeePerGas?: string;
to?: string;
value?: string;
};
transactionFromName: string | undefined;
transactionTo: string | undefined;
transactionToName: string | undefined;
transactionValue: string | undefined;
type: string | undefined;
warningGasPriceHigh: string | undefined;
transactionFromName?: string;
transactionTo?: string;
transactionToName?: string;
transactionValue?: string;
type?: string;
warningGasPriceHigh?: string;
};
contractExchangeRates: Record<string, unknown>;
}
Expand Down
37 changes: 21 additions & 16 deletions app/core/RPCMethods/RPCMethodMiddleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ import { getRpcMethodMiddleware } from './RPCMethodMiddleware';
import AppConstants from '../AppConstants';
import { PermissionConstraint } from '@metamask/permission-controller';
import PPOMUtil from '../../lib/ppom/ppom-util';
import initialBackgroundState from '../../util/test/initial-background-state.json';
import { Store } from 'redux';
import { RootState } from 'app/reducers';

jest.mock('../Engine', () => ({
context: {
Expand Down Expand Up @@ -55,8 +58,6 @@ jest.mock('../../store', () => ({
},
}));

const mockStore = store as { getState: jest.Mock };

jest.mock('../Permissions', () => ({
getPermittedAccounts: jest.fn(),
}));
Expand Down Expand Up @@ -212,21 +213,25 @@ function setupGlobalState({
providerConfig?: ProviderConfig;
selectedAddress?: string;
}) {
mockStore.getState.mockImplementation(() => ({
browser: activeTab
? {
activeTab,
}
: {},
engine: {
backgroundState: {
NetworkController: {
providerConfig: providerConfig || {},
// TODO: Remove any cast once PermissionController type is fixed. Currently, the state shows never.
jest
.spyOn(store as Store<Partial<RootState>, any>, 'getState')
.mockImplementation(() => ({
browser: activeTab
? {
activeTab,
}
: {},
engine: {
backgroundState: {
...initialBackgroundState,
NetworkController: {
providerConfig: providerConfig || {},
},
PreferencesController: selectedAddress ? { selectedAddress } : {},
},
PreferencesController: selectedAddress ? { selectedAddress } : {},
},
},
}));
} as any,
}));
if (addTransactionResult) {
MockEngine.context.TransactionController.addTransaction.mockImplementation(
async () => ({ result: addTransactionResult }),
Expand Down
10 changes: 5 additions & 5 deletions app/core/RPCMethods/eth_sendTransaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ function getMockAddTransaction({
) => {
expect(deviceConfirmedOn).toBe('metamask_mobile');
if (expectedOrigin) {
expect(origin).toBe(expectedOrigin);
expect(origin).toBe(expectedOrigin.origin);
}
if (expectedTransaction) {
expect(transaction).toBe(expectedTransaction);
Expand Down Expand Up @@ -120,7 +120,7 @@ describe('eth_sendTransaction', () => {
res: pendingResult,
sendTransaction: getMockAddTransaction({
expectedTransaction: mockTransactionParameters,
expectedOrigin: 'example.metamask.io',
expectedOrigin: { origin: 'example.metamask.io' },
returnValue: expectedResult,
}),
validateAccountAndChainId: jest.fn(),
Expand Down Expand Up @@ -205,7 +205,7 @@ describe('eth_sendTransaction', () => {
res: constructPendingJsonRpcResponse(),
sendTransaction: getMockAddTransaction({
expectedTransaction: mockTransactionParameters,
expectedOrigin: 'example.metamask.io',
expectedOrigin: { origin: 'example.metamask.io' },
addTransactionError: new Error('Failed to add transaction'),
}),
validateAccountAndChainId: jest.fn(),
Expand All @@ -225,7 +225,7 @@ describe('eth_sendTransaction', () => {
res: constructPendingJsonRpcResponse(),
sendTransaction: getMockAddTransaction({
expectedTransaction: mockTransactionParameters,
expectedOrigin: 'example.metamask.io',
expectedOrigin: { origin: 'example.metamask.io' },
processTransactionError: new Error('User rejected the transaction'),
}),
validateAccountAndChainId: jest.fn(),
Expand All @@ -246,7 +246,7 @@ describe('eth_sendTransaction', () => {
res: pendingResult,
sendTransaction: getMockAddTransaction({
expectedTransaction: mockTransactionParameters,
expectedOrigin: 'example.metamask.io',
expectedOrigin: { origin: 'example.metamask.io' },
returnValue: expectedResult,
}),
validateAccountAndChainId: jest.fn(),
Expand Down
4 changes: 2 additions & 2 deletions app/core/SDKConnect/SDKConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export interface ConnectionProps {
initialConnection?: boolean;
originatorInfo?: OriginatorInfo;
validUntil: number;
lastAuthorized: number; // timestamp of last received activity
lastAuthorized?: number; // timestamp of last received activity
}
export interface ConnectedSessions {
[id: string]: Connection;
Expand Down Expand Up @@ -133,7 +133,7 @@ export class Connection extends EventEmitter2 {
/*
* Timestamp of last activity, used to check if channel is still active and to prevent showing OTP approval modal too often.
*/
lastAuthorized: number;
lastAuthorized?: number;

/**
* Prevent double sending 'authorized' message.
Expand Down
10 changes: 6 additions & 4 deletions app/core/WalletConnect/WalletConnect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ describe('WalletConnect', () => {
});
const walletConnectorRejectSessionMock = jest.fn();

RNWalletConnect.mockImplementation(() => ({
on: walletConnectorSessionRequestCallbackMock,
rejectSession: walletConnectorRejectSessionMock,
}));
jest
.spyOn(RNWalletConnect.prototype, 'on')
.mockImplementation(walletConnectorSessionRequestCallbackMock);
jest
.spyOn(RNWalletConnect.prototype, 'rejectSession')
.mockImplementation(walletConnectorRejectSessionMock);

afterEach(() => {
// Reset WalletConnect
Expand Down
2 changes: 2 additions & 0 deletions app/declarations.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ declare module '*.png' {
export default content;
}

// TODO: eth-json-rpc-errors does not contain types. May want to create our own types.
declare module 'eth-json-rpc-errors';
declare module '@react-native-community/checkbox' {
import CheckBoxOriginal from '@react-native-community/checkbox';

Expand Down
2 changes: 1 addition & 1 deletion app/util/general/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export const getURLProtocol = (url) => {
* ipfs:// -> true
* ipfs://ipfs/ -> true
* https:// -> false
* @param {string | null} uri - string representing the source uri to the file
* @param {string | null | undefined} uri - string representing the source uri to the file
* @returns true if it's an ipfs url
*/
export const isIPFSUri = (uri) => {
Expand Down
Loading
Loading