Skip to content

Commit

Permalink
stash
Browse files Browse the repository at this point in the history
  • Loading branch information
MajorLift committed Dec 10, 2024
1 parent 63d8618 commit f8ca26b
Show file tree
Hide file tree
Showing 15 changed files with 141 additions and 106 deletions.
23 changes: 13 additions & 10 deletions shared/modules/selectors/feature-flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@ import { ProviderConfigState, getCurrentChainId } from './networks';

type FeatureFlagsMetaMaskState = {
metamask: {
swapsState: {
swapsFeatureFlags: {
[key: string]: {
extensionActive: boolean;
mobileActive: boolean;
smartTransactions: {
expectedDeadline?: number;
maxDeadline?: number;
extensionReturnTxHashAsap?: boolean;
SwapsController: {
swapsState: {
swapsFeatureFlags: {
[key: string]: {
extensionActive: boolean;
mobileActive: boolean;
smartTransactions: {
expectedDeadline?: number;
maxDeadline?: number;
extensionReturnTxHashAsap?: boolean;
};
};
};
};
Expand All @@ -24,7 +26,8 @@ export function getFeatureFlagsByChainId(
) {
const chainId = getCurrentChainId(state);
const networkName = getNetworkNameByChainId(chainId);
const featureFlags = state.metamask.swapsState?.swapsFeatureFlags;
const featureFlags =
state.metamask.SwapsController.swapsState?.swapsFeatureFlags;
if (!featureFlags?.[networkName]) {
return null;
}
Expand Down
17 changes: 0 additions & 17 deletions shared/modules/selectors/util.js

This file was deleted.

25 changes: 25 additions & 0 deletions shared/modules/selectors/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import {
TransactionMeta,
TransactionStatus,
} from '@metamask/transaction-controller';
import { isEqual } from 'lodash';
import { createSelectorCreator, defaultMemoize } from 'reselect';

export const createDeepEqualSelector = createSelectorCreator(
defaultMemoize,
isEqual,
);

export const filterAndShapeUnapprovedTransactions = (
transactions: TransactionMeta[],
) => {
return transactions
.filter(({ status }) => status === TransactionStatus.unapproved)
.reduce<{ [transactionId: string]: TransactionMeta }>(
(result, transaction) => {
result[transaction.id] = transaction;
return result;
},
{},
);
};
22 changes: 9 additions & 13 deletions ui/ducks/bridge-status/selectors.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import { createSelector } from 'reselect';
import { Hex } from '@metamask/utils';
import {
BridgeStatusState,
BridgeHistoryItem,
} from '../../../shared/types/bridge-status';
import { BridgeHistoryItem } from '../../../shared/types/bridge-status';
import { getSelectedAddress } from '../../selectors';
import { Numeric } from '../../../shared/modules/Numeric';
import {
getCurrentChainId,
ProviderConfigState,
} from '../../../shared/modules/selectors/networks';
import { BackgroundStateProxy } from '../../../shared/types/metamask';
import { getCurrentChainId } from '../../../shared/modules/selectors/networks';

export type BridgeStatusAppState = ProviderConfigState & {
metamask: {
bridgeStatusState: BridgeStatusState;
};
export type BridgeStatusAppState = {
metamask: Pick<
BackgroundStateProxy,
'BridgeStatusController' | 'AccountsController' | 'NetworkController'
>;
};

export const selectBridgeStatusState = (state: BridgeStatusAppState) =>
state.metamask.bridgeStatusState;
state.metamask.BridgeStatusController.bridgeStatusState;

/**
* Returns a mapping of srcTxMetaId to txHistoryItem for the selected address
Expand Down
54 changes: 29 additions & 25 deletions ui/ducks/bridge/selectors.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
NetworkConfiguration,
NetworkState,
} from '@metamask/network-controller';
import { NetworkConfiguration } from '@metamask/network-controller';
import { orderBy, uniqBy } from 'lodash';
import { createSelector } from 'reselect';
import { GasFeeEstimates } from '@metamask/gas-fee-controller';
Expand All @@ -18,7 +15,6 @@ import {
BRIDGE_QUOTE_MAX_RETURN_DIFFERENCE_PERCENTAGE,
} from '../../../shared/constants/bridge';
import {
BridgeState,
BridgeFeatureFlagsKey,
// TODO: Remove restricted import
// eslint-disable-next-line import/no-restricted-paths
Expand Down Expand Up @@ -50,15 +46,14 @@ import {
isNativeAddress,
} from '../../pages/bridge/utils/quote';
import { decGWEIToHexWEI } from '../../../shared/modules/conversion.utils';
import { MultichainState } from '../../selectors/multichain';
import { BackgroundStateProxy } from '../../../shared/types/metamask';
import { BridgeSlice } from './bridge';

type BridgeAppState = {
metamask: { bridgeState: BridgeState } & NetworkState & {
useExternalServices: boolean;
currencyRates: { [currency: string]: { conversionRate: number } };
};
export type BridgeAppState = {
metamask: Pick<BackgroundStateProxy, 'BridgeController' | 'GasFeeController'>;
bridge: BridgeSlice;
};
} & MultichainState;

// only includes networks user has added
export const getAllBridgeableNetworks = createDeepEqualSelector(
Expand All @@ -77,7 +72,8 @@ export const getAllBridgeableNetworks = createDeepEqualSelector(

export const getFromChains = createDeepEqualSelector(
getAllBridgeableNetworks,
(state: BridgeAppState) => state.metamask.bridgeState?.bridgeFeatureFlags,
(state: BridgeAppState) =>
state.metamask.BridgeController.bridgeState?.bridgeFeatureFlags,
(allBridgeableNetworks, bridgeFeatureFlags) =>
allBridgeableNetworks.filter(({ chainId }) =>
bridgeFeatureFlags[BridgeFeatureFlagsKey.NETWORK_SRC_ALLOWLIST].includes(
Expand All @@ -101,7 +97,8 @@ export const getFromChain = createDeepEqualSelector(
export const getToChains = createDeepEqualSelector(
getFromChain,
getAllBridgeableNetworks,
(state: BridgeAppState) => state.metamask.bridgeState?.bridgeFeatureFlags,
(state: BridgeAppState) =>
state.metamask.BridgeController.bridgeState?.bridgeFeatureFlags,
(
fromChain,
allBridgeableNetworks,
Expand All @@ -125,19 +122,23 @@ export const getToChain = createDeepEqualSelector(
);

export const getFromTokens = (state: BridgeAppState) => {
return state.metamask.bridgeState.srcTokens ?? {};
return state.metamask.BridgeController.bridgeState.srcTokens ?? {};
};

export const getFromTopAssets = (state: BridgeAppState) => {
return state.metamask.bridgeState.srcTopAssets ?? [];
return state.metamask.BridgeController.bridgeState.srcTopAssets ?? [];
};

export const getToTopAssets = (state: BridgeAppState) => {
return state.bridge.toChainId ? state.metamask.bridgeState.destTopAssets : [];
return state.bridge.toChainId
? state.metamask.BridgeController.bridgeState.destTopAssets
: [];
};

export const getToTokens = (state: BridgeAppState) => {
return state.bridge.toChainId ? state.metamask.bridgeState.destTokens : {};
return state.bridge.toChainId
? state.metamask.BridgeController.bridgeState.destTokens
: {};
};

export const getFromToken = (
Expand All @@ -158,12 +159,12 @@ export const getFromAmount = (state: BridgeAppState): string | null =>
state.bridge.fromTokenInputValue;

export const getQuoteRequest = (state: BridgeAppState) => {
const { quoteRequest } = state.metamask.bridgeState;
const { quoteRequest } = state.metamask.BridgeController.bridgeState;
return quoteRequest;
};

export const getBridgeQuotesConfig = (state: BridgeAppState) =>
state.metamask.bridgeState?.bridgeFeatureFlags[
state.metamask.BridgeController.bridgeState?.bridgeFeatureFlags[
BridgeFeatureFlagsKey.EXTENSION_CONFIG
] ?? {};

Expand All @@ -190,7 +191,7 @@ export const getBridgeSortOrder = (state: BridgeAppState) =>
// A dest network can be selected before it's imported
// The cached exchange rate won't be available so the rate from the bridge state is used
const _getToTokenExchangeRate = createSelector(
(state) => state.metamask.currencyRates,
(state) => state.metamask.CurrencyController.currencyRates,
(state: BridgeAppState) => state.bridge.toTokenExchangeRate,
getToChain,
getToToken,
Expand All @@ -205,7 +206,7 @@ const _getToTokenExchangeRate = createSelector(
);

const _getQuotesWithMetadata = createDeepEqualSelector(
(state) => state.metamask.bridgeState.quotes,
(state) => state.metamask.BridgeController.bridgeState.quotes,
_getToTokenExchangeRate,
(state: BridgeAppState) => state.bridge.fromTokenExchangeRate,
getConversionRate,
Expand Down Expand Up @@ -320,7 +321,8 @@ const _getQuoteIdentifier = ({ quote }: QuoteResponse & L1GasFees) =>
`${quote.bridgeId}-${quote.bridges[0]}-${quote.steps.length}`;

const _getSelectedQuote = createSelector(
(state: BridgeAppState) => state.metamask.bridgeState.quotesRefreshCount,
(state: BridgeAppState) =>
state.metamask.BridgeController.bridgeState.quotesRefreshCount,
(state: BridgeAppState) => state.bridge.selectedQuote,
_getSortedQuotesWithMetadata,
(quotesRefreshCount, selectedQuote, sortedQuotesWithMetadata) =>
Expand All @@ -338,10 +340,12 @@ export const getBridgeQuotes = createSelector(
_getSortedQuotesWithMetadata,
_getRecommendedQuote,
_getSelectedQuote,
(state) => state.metamask.bridgeState.quotesLastFetched,
(state) => state.metamask.BridgeController.bridgeState.quotesLastFetched,
(state) =>
state.metamask.bridgeState.quotesLoadingStatus === RequestStatus.LOADING,
(state: BridgeAppState) => state.metamask.bridgeState.quotesRefreshCount,
state.metamask.BridgeController.bridgeState.quotesLoadingStatus ===
RequestStatus.LOADING,
(state: BridgeAppState) =>
state.metamask.BridgeController.bridgeState.quotesRefreshCount,
getBridgeQuotesConfig,
getQuoteRequest,
(
Expand Down
2 changes: 1 addition & 1 deletion ui/helpers/utils/token-util.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ export function getTokenApprovedParam(tokenData = {}) {
/**
* Get the token balance converted to fiat and optionally formatted for display
*
* @param {number} [contractExchangeRate] - The exchange rate between the current token and the native currency
* @param {number | string} [contractExchangeRate] - The exchange rate between the current token and the native currency
* @param {number} conversionRate - The exchange rate between the current fiat currency and the native currency
* @param {string} currentCurrency - The currency code for the user's chosen fiat currency
* @param {string} [tokenAmount] - The current token balance
Expand Down
4 changes: 2 additions & 2 deletions ui/hooks/snaps/useDisplayName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import {
getMemoizedAccountName,
getAddressBookEntryByNetwork,
AddressBookMetaMaskState,
AccountsMetaMaskState,
} from '../../selectors/snaps';
import { toChecksumHexAddress } from '../../../shared/modules/hexstring-utils';
import { decimalToHex } from '../../../shared/modules/conversion.utils';
import { MultichainState } from '../../selectors/multichain';

export type UseDisplayNameParams = {
chain: {
Expand Down Expand Up @@ -38,7 +38,7 @@ export const useDisplayName = (

const parsedAddress = isEip155 ? toChecksumHexAddress(address) : address;

const accountName = useSelector((state: AccountsMetaMaskState) =>
const accountName = useSelector((state: MultichainState) =>
getMemoizedAccountName(state, parsedAddress),
);

Expand Down
6 changes: 3 additions & 3 deletions ui/hooks/useAccountTotalCrossChainFiatBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { TokenWithBalance } from '../components/app/assets/asset-list/asset-list
import { getNetworkConfigurationsByChainId } from '../../shared/modules/selectors/networks';

type AddressBalances = {
[address: string]: number;
[address: string]: string | number;
};

export type Balances = {
Expand Down Expand Up @@ -61,7 +61,7 @@ export const useAccountTotalCrossChainFiatBalance = (
];
const totalFiatValue = getTokenFiatAmount(
tokenExchangeRate,
conversionRate,
conversionRate ?? 0,
currentCurrency,
token.string,
token.symbol,
Expand All @@ -79,7 +79,7 @@ export const useAccountTotalCrossChainFiatBalance = (
const nativeFiatValue = getValueFromWeiHex({
value: balanceCached,
toCurrency: currentCurrency,
conversionRate,
conversionRate: conversionRate ?? 0,
numberOfDecimals: 2,
});
return {
Expand Down
2 changes: 1 addition & 1 deletion ui/hooks/useDisplayName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export type UseDisplayNameRequest = {
preferContractSymbol?: boolean;
type: NameType;
value: string;
variation: string;
variation: Hex;
};

export type UseDisplayNameResponse = {
Expand Down
2 changes: 1 addition & 1 deletion ui/hooks/useGetFormattedTokensPerChain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ describe('useGetFormattedTokensPerChain', () => {
it('should tokensWithBalances for an array of chainIds', async () => {
(stringifyBalance as jest.Mock).mockReturnValueOnce(10.5);
(stringifyBalance as jest.Mock).mockReturnValueOnce(13);
const allChainIDs = ['0x1'];
const allChainIDs = ['0x1' as const];
const isTokenNetworkFilterEqualCurrentNetwork = true;
const shouldHideZeroBalanceTokens = true;
const testAccount = {
Expand Down
5 changes: 3 additions & 2 deletions ui/hooks/useGetFormattedTokensPerChain.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Hex } from '@metamask/utils';
import { useSelector } from 'react-redux';
import { BN } from 'bn.js';
import { Token } from '@metamask/assets-controllers';
Expand All @@ -22,14 +23,14 @@ export const useGetFormattedTokensPerChain = (
account: { address: string },
shouldHideZeroBalanceTokens: boolean,
shouldGetTokensPerCurrentChain: boolean,
allChainIDs: string[],
allChainIDs: Hex[],
) => {
const currentChainId = useSelector(getCurrentChainId);

const importedTokens = useSelector(getAllTokens); // returns the tokens only when they are imported
const currentTokenBalances: { tokenBalances: TokenBalancesMapping } =
useTokenBalances({
chainIds: allChainIDs as `0x${string}`[],
chainIds: allChainIDs,
});

// We will calculate aggregated balance only after the user imports the tokens to the wallet
Expand Down
7 changes: 4 additions & 3 deletions ui/hooks/useMultichainAccountTotalFiatBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from '../selectors/multichain';
import { formatCurrency } from '../helpers/utils/confirm-tx.util';
import { MULTICHAIN_NATIVE_CURRENCY_TO_CAIP19 } from '../../shared/constants/multichain/assets';
import { Numeric } from '../../shared/modules/Numeric';
import { getTokenFiatAmount } from '../helpers/utils/token-util';
import { useMultichainSelector } from './useMultichainSelector';
import { useAccountTotalFiatBalance } from './useAccountTotalFiatBalance';
Expand All @@ -26,7 +27,7 @@ export const useMultichainAccountTotalFiatBalance = (
account: InternalAccount,
shouldHideZeroBalanceTokens: boolean = false,
): {
formattedFiat: string;
formattedFiat: string | Numeric;
totalFiatBalance: string;
tokensWithBalances: {
address: string;
Expand Down Expand Up @@ -54,7 +55,7 @@ export const useMultichainAccountTotalFiatBalance = (
getMultichainConversionRate,
account,
);
const nativeCurrencyImage: string = useMultichainSelector(
const nativeCurrencyImage: string | undefined = useMultichainSelector(
getMultichainCurrencyImage,
account,
);
Expand Down Expand Up @@ -86,7 +87,7 @@ export const useMultichainAccountTotalFiatBalance = (

// Create an object with native token info. NOTE: Native token info is fetched from a separate controller
const nativeTokenValues = {
iconUrl: nativeCurrencyImage,
iconUrl: nativeCurrencyImage ?? '',
symbol: ticker,
fiatBalance: totalFiatBalance,
};
Expand Down
Loading

0 comments on commit f8ca26b

Please sign in to comment.