1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-25 11:28:51 +01:00
metamask-extension/ui/store/store.ts

148 lines
4.8 KiB
TypeScript
Raw Normal View History

import { StoreEnhancer } from 'redux';
import { configureStore as baseConfigureStore } from '@reduxjs/toolkit';
import devtoolsEnhancer from 'remote-redux-devtools';
import { ApprovalControllerState } from '@metamask/approval-controller';
import { GasEstimateType, GasFeeEstimates } from '@metamask/gas-fee-controller';
import rootReducer from '../ducks';
import { LedgerTransportTypes } from '../../shared/constants/hardware-wallets';
import { TransactionMeta } from '../../shared/constants/transaction';
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556) The `network` store of the network controller crams two types of data into one place. It roughly tracks whether we have enough information to make requests to the network and whether the network is capable of receiving requests, but it also stores the ID of the network (as obtained via `net_version`). Generally we shouldn't be using the network ID for anything, as it has been completely replaced by chain ID, which all custom RPC endpoints have been required to support for over a year now. However, as the network ID is used in various places within the extension codebase, removing it entirely would be a non-trivial effort. So, minimally, this commit splits `network` into two stores: `networkId` and `networkStatus`. But it also expands the concept of network status. Previously, the network was in one of two states: "loading" and "not-loading". But now it can be in one of four states: - `available`: The network is able to receive and respond to requests. - `unavailable`: The network is not able to receive and respond to requests for unknown reasons. - `blocked`: The network is actively blocking requests based on the user's geolocation. (This is specific to Infura.) - `unknown`: We don't know whether the network can receive and respond to requests, either because we haven't checked or we tried to check and were unsuccessful. This commit also changes how the network status is determined — specifically, how many requests are used to determine that status, when they occur, and whether they are awaited. Previously, the network controller would make 2 to 3 requests during the course of running `lookupNetwork`. * First, if it was an Infura network, it would make a request for `eth_blockNumber` to determine whether Infura was blocking requests or not, then emit an appropriate event. This operation was not awaited. * Then, regardless of the network, it would fetch the network ID via `net_version`. This operation was awaited. * Finally, regardless of the network, it would fetch the latest block via `eth_getBlockByNumber`, then use the result to determine whether the network supported EIP-1559. This operation was awaited. Now: * One fewer request is made, specifically `eth_blockNumber`, as we don't need to make an extra request to determine whether Infura is blocking requests; we can reuse `eth_getBlockByNumber`; * All requests are awaited, which makes `lookupNetwork` run fully in-band instead of partially out-of-band; and * Both requests for `net_version` and `eth_getBlockByNumber` are performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
import type { NetworkStatus } from '../../shared/constants/network';
/**
* This interface is temporary and is copied from the message-manager.js file
* and is the 'msgParams' key of the interface declared there. We should get a
* universal Message type to use for this, the Message manager and all
* the other types of messages.
*
* TODO: Replace this
*/
export interface TemporaryMessageDataType {
id: number;
type: string;
msgParams: {
metamaskId: number;
data: string;
};
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
metadata?: {
custodyId?: string;
};
status?: string;
///: END:ONLY_INCLUDE_IN
}
export interface MessagesIndexedById {
[id: string]: TemporaryMessageDataType;
}
/**
* This interface is a temporary interface to describe the state tree that is
* sent from the background. Ideally we can build this using Types in the
* backend when we compose the stores, then we can import it here and use it.
*
* Some of this is duplicated in the metamask redux duck. In *most* cases the
* state received from the background takes precedence over anything in the
* metamask reducer.
*/
interface TemporaryBackgroundState {
addressBook: {
[chainId: string]: {
name: string;
}[];
};
providerConfig: {
chainId: string;
};
transactions: TransactionMeta[];
selectedAddress: string;
identities: {
[address: string]: {
balance: string;
};
};
ledgerTransportType: LedgerTransportTypes;
unapprovedDecryptMsgs: MessagesIndexedById;
unapprovedMsgs: MessagesIndexedById;
unapprovedPersonalMsgs: MessagesIndexedById;
unapprovedTypedMessages: MessagesIndexedById;
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556) The `network` store of the network controller crams two types of data into one place. It roughly tracks whether we have enough information to make requests to the network and whether the network is capable of receiving requests, but it also stores the ID of the network (as obtained via `net_version`). Generally we shouldn't be using the network ID for anything, as it has been completely replaced by chain ID, which all custom RPC endpoints have been required to support for over a year now. However, as the network ID is used in various places within the extension codebase, removing it entirely would be a non-trivial effort. So, minimally, this commit splits `network` into two stores: `networkId` and `networkStatus`. But it also expands the concept of network status. Previously, the network was in one of two states: "loading" and "not-loading". But now it can be in one of four states: - `available`: The network is able to receive and respond to requests. - `unavailable`: The network is not able to receive and respond to requests for unknown reasons. - `blocked`: The network is actively blocking requests based on the user's geolocation. (This is specific to Infura.) - `unknown`: We don't know whether the network can receive and respond to requests, either because we haven't checked or we tried to check and were unsuccessful. This commit also changes how the network status is determined — specifically, how many requests are used to determine that status, when they occur, and whether they are awaited. Previously, the network controller would make 2 to 3 requests during the course of running `lookupNetwork`. * First, if it was an Infura network, it would make a request for `eth_blockNumber` to determine whether Infura was blocking requests or not, then emit an appropriate event. This operation was not awaited. * Then, regardless of the network, it would fetch the network ID via `net_version`. This operation was awaited. * Finally, regardless of the network, it would fetch the latest block via `eth_getBlockByNumber`, then use the result to determine whether the network supported EIP-1559. This operation was awaited. Now: * One fewer request is made, specifically `eth_blockNumber`, as we don't need to make an extra request to determine whether Infura is blocking requests; we can reuse `eth_getBlockByNumber`; * All requests are awaited, which makes `lookupNetwork` run fully in-band instead of partially out-of-band; and * Both requests for `net_version` and `eth_getBlockByNumber` are performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
networkId: string | null;
networksMetadata: {
[NetworkClientId: string]: {
EIPS: { [eip: string]: boolean };
status: NetworkStatus;
};
};
selectedNetworkClientId: string;
pendingApprovals: ApprovalControllerState['pendingApprovals'];
approvalFlows: ApprovalControllerState['approvalFlows'];
knownMethodData?: {
[fourBytePrefix: string]: Record<string, unknown>;
};
gasFeeEstimates: GasFeeEstimates;
gasEstimateType: GasEstimateType;
///: BEGIN:ONLY_INCLUDE_IN(build-mmi)
custodyAccountDetails?: { [key: string]: any };
///: END:ONLY_INCLUDE_IN
}
type RootReducerReturnType = ReturnType<typeof rootReducer>;
export type CombinedBackgroundAndReduxState = RootReducerReturnType & {
activeTab: {
origin: string;
};
metamask: RootReducerReturnType['metamask'] & TemporaryBackgroundState;
};
export default function configureStore(preloadedState: any) {
const debugModeEnabled = Boolean(process.env.METAMASK_DEBUG);
const isDev = debugModeEnabled && !process.env.IN_TEST;
const enhancers: StoreEnhancer[] = [];
if (isDev) {
enhancers.push(
devtoolsEnhancer({
name: 'MetaMask',
hostname: 'localhost',
port: 8000,
realtime: true,
}) as StoreEnhancer,
);
}
return baseConfigureStore({
reducer: rootReducer as () => CombinedBackgroundAndReduxState,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
/**
* We do not persist the redux tree for rehydration, so checking for
* serializable state keys is not relevant for now. Any state that persists
* is managed in the background. We may at some point want this, but we can
* gradually implement by using the ignore options to ignore those actions
* and state keys that are not serializable, preventing us from adding new
* actions and state that would violate our ability to persist state keys.
* NOTE: redux-thunk is included by default in the middleware below.
*/
serializableCheck: false,
/**
* immutableCheck controls whether we get warnings about mutation of
* state, which will be true in dev. However in test lavamoat complains
* about something the middleware is doing. It would be good to figure
* that out and enable this in test environments so that mutation
* causes E2E failures.
*/
immutableCheck: isDev
? {
warnAfter: 100,
}
: false,
}),
devTools: false,
enhancers,
preloadedState,
});
}
type Store = ReturnType<typeof configureStore>;
export type MetaMaskReduxState = ReturnType<Store['getState']>;
export type MetaMaskReduxDispatch = Store['dispatch'];