From afdfa91a7113f079f0b1a5c7aab96dc04faf1cbf Mon Sep 17 00:00:00 2001 From: woodenfurniture <125113430+woodenfurniture@users.noreply.github.com> Date: Thu, 18 Jan 2024 07:42:20 +1100 Subject: [PATCH 1/8] chore: remove unused selectors in swapper slice --- src/state/apis/swapper/selectors.ts | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/state/apis/swapper/selectors.ts b/src/state/apis/swapper/selectors.ts index a2e8cdc79af..0bf6e77a9f8 100644 --- a/src/state/apis/swapper/selectors.ts +++ b/src/state/apis/swapper/selectors.ts @@ -1,18 +1,7 @@ import { QueryStatus } from '@reduxjs/toolkit/query' import type { ReduxState } from 'state/reducer' -export const selectSwapperApiPending = (state: ReduxState) => - Object.values(state.swapperApi.queries).some(query => query?.status === QueryStatus.pending) - -export const selectSwapperApiTradeQuotePending = (state: ReduxState) => - Object.values(state.swapperApi.queries).some( - query => query?.endpointName === 'getTradeQuote' && query?.status === QueryStatus.pending, - ) - export const selectSwapperApiTradingActivePending = (state: ReduxState) => Object.values(state.swapperApi.queries).some( query => query?.endpointName === 'getIsTradingActive' && query?.status === QueryStatus.pending, ) - -export const selectSwapperQueriesInitiated = (state: ReduxState) => - Object.keys(state.swapperApi.queries).length From f2011710aa370445fb3128e360be629a4019d869 Mon Sep 17 00:00:00 2001 From: woodenfurniture <125113430+woodenfurniture@users.noreply.github.com> Date: Thu, 18 Jan 2024 07:54:01 +1100 Subject: [PATCH 2/8] chore: merge swapperApi into swappersApi --- .../hooks/useIsTradingActive.tsx | 4 +-- .../Deposit/components/Confirm.tsx | 4 +-- .../Overview/ThorchainSaversOverview.tsx | 6 ++-- .../Withdraw/components/Confirm.tsx | 4 +-- .../apis/swapper/getIsTradingActiveApi.ts | 29 ----------------- src/state/apis/swapper/selectors.ts | 7 ---- src/state/apis/swapper/swapperApi.ts | 8 ----- src/state/apis/swappers/selectors.ts | 5 +++ src/state/apis/swappers/swappersApi.ts | 32 ++++++++++++++++--- src/state/reducer.ts | 4 --- src/state/store.ts | 3 -- src/test/mocks/store.ts | 1 - 12 files changed, 42 insertions(+), 65 deletions(-) delete mode 100644 src/state/apis/swapper/getIsTradingActiveApi.ts delete mode 100644 src/state/apis/swapper/selectors.ts delete mode 100644 src/state/apis/swapper/swapperApi.ts diff --git a/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx b/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx index aa8d441f717..bf0ca67504e 100644 --- a/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx +++ b/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react' import type { ThorEvmTradeQuote } from 'lib/swapper/swappers/ThorchainSwapper/getThorTradeQuote/getTradeQuote' import { TradeType } from 'lib/swapper/swappers/ThorchainSwapper/utils/longTailHelpers' -import { getIsTradingActiveApi } from 'state/apis/swapper/getIsTradingActiveApi' +import { swappersApi } from 'state/apis/swappers/swappersApi' import { selectBuyAsset, selectSellAsset } from 'state/slices/swappersSlice/selectors' import { selectActiveQuote, selectActiveSwapperName } from 'state/slices/tradeQuoteSlice/selectors' import { useAppDispatch, useAppSelector } from 'state/store' @@ -18,7 +18,7 @@ export const useIsTradingActive = () => { const buyAssetId = useAppSelector(selectBuyAsset).assetId const sellAssetId = useAppSelector(selectSellAsset).assetId - const { getIsTradingActive } = getIsTradingActiveApi.endpoints + const { getIsTradingActive } = swappersApi.endpoints const swapperName = useAppSelector(selectActiveSwapperName) useEffect(() => { diff --git a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Deposit/components/Confirm.tsx b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Deposit/components/Confirm.tsx index 67b630e6cb8..615923f6000 100644 --- a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Deposit/components/Confirm.tsx +++ b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Deposit/components/Confirm.tsx @@ -58,7 +58,7 @@ import { import { fromThorBaseUnit, getThorchainFromAddress, toThorBaseUnit } from 'lib/utils/thorchain' import { BASE_BPS_POINTS } from 'lib/utils/thorchain/constants' import { getInboundAddressDataForChain } from 'lib/utils/thorchain/getInboundAddressDataForChain' -import { getIsTradingActiveApi } from 'state/apis/swapper/getIsTradingActiveApi' +import { swappersApi } from 'state/apis/swappers/swappersApi' import { getMaybeThorchainSaversDepositQuote, getThorchainSaversPosition, @@ -561,7 +561,7 @@ export const Confirm: React.FC = ({ accountId, onNext }) => { contextDispatch({ type: ThorchainSaversDepositActionType.SET_LOADING, payload: true }) - const { getIsTradingActive } = getIsTradingActiveApi.endpoints + const { getIsTradingActive } = swappersApi.endpoints const { data: isTradingActive } = await appDispatch( getIsTradingActive.initiate({ assetId, diff --git a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Overview/ThorchainSaversOverview.tsx b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Overview/ThorchainSaversOverview.tsx index fb127825cd9..4ee99a2b08e 100644 --- a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Overview/ThorchainSaversOverview.tsx +++ b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Overview/ThorchainSaversOverview.tsx @@ -36,8 +36,8 @@ import { Text } from 'components/Text' import { useBrowserRouter } from 'hooks/useBrowserRouter/useBrowserRouter' import { bnOrZero } from 'lib/bignumber/bignumber' import { fromBaseUnit, toBaseUnit } from 'lib/math' -import { getIsTradingActiveApi } from 'state/apis/swapper/getIsTradingActiveApi' -import { selectSwapperApiTradingActivePending } from 'state/apis/swapper/selectors' +import { selectSwapperApiTradingActivePending } from 'state/apis/swappers/selectors' +import { swappersApi } from 'state/apis/swappers/swappersApi' import type { ThorchainSaversStakingSpecificMetadata } from 'state/slices/opportunitiesSlice/resolvers/thorchainsavers/types' import { getMaybeThorchainSaversDepositQuote, @@ -134,7 +134,7 @@ export const ThorchainSaversOverview: React.FC = ({ useEffect(() => { ;(async () => { - const { getIsTradingActive } = getIsTradingActiveApi.endpoints + const { getIsTradingActive } = swappersApi.endpoints const { data: isTradingActive } = await appDispatch( getIsTradingActive.initiate({ assetId, diff --git a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Withdraw/components/Confirm.tsx b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Withdraw/components/Confirm.tsx index 4b985ec61ea..0f9e15d39bb 100644 --- a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Withdraw/components/Confirm.tsx +++ b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Withdraw/components/Confirm.tsx @@ -58,7 +58,7 @@ import { import { fromThorBaseUnit, toThorBaseUnit } from 'lib/utils/thorchain' import { BASE_BPS_POINTS } from 'lib/utils/thorchain/constants' import { getInboundAddressDataForChain } from 'lib/utils/thorchain/getInboundAddressDataForChain' -import { getIsTradingActiveApi } from 'state/apis/swapper/getIsTradingActiveApi' +import { swappersApi } from 'state/apis/swappers/swappersApi' import { getThorchainSaversPosition, getThorchainSaversWithdrawQuote, @@ -625,7 +625,7 @@ export const Confirm: React.FC = ({ accountId, onNext }) => { return } - const { getIsTradingActive } = getIsTradingActiveApi.endpoints + const { getIsTradingActive } = swappersApi.endpoints const { data: isTradingActive } = await appDispatch( getIsTradingActive.initiate({ assetId, diff --git a/src/state/apis/swapper/getIsTradingActiveApi.ts b/src/state/apis/swapper/getIsTradingActiveApi.ts deleted file mode 100644 index 67c879347c1..00000000000 --- a/src/state/apis/swapper/getIsTradingActiveApi.ts +++ /dev/null @@ -1,29 +0,0 @@ -import type { AssetId } from '@shapeshiftoss/caip' -import type { SwapperName } from '@shapeshiftoss/swapper' -import { isTradingActive } from 'components/MultiHopTrade/utils' -import { swapperApi } from 'state/apis/swapper/swapperApi' -import { apiErrorHandler } from 'state/apis/utils' - -type GetIsTradingActiveArgs = { assetId: AssetId | undefined; swapperName: SwapperName } - -type GetIsTradingActiveReturn = boolean - -const getIsTradingActiveErrorHandler = apiErrorHandler( - 'getIsTradingActiveApi: error getting trading status', -) - -export const getIsTradingActiveApi = swapperApi.injectEndpoints({ - endpoints: build => ({ - getIsTradingActive: build.query({ - queryFn: async ({ assetId, swapperName }) => { - const maybeIsTradingActive = await isTradingActive(assetId, swapperName) - if (maybeIsTradingActive.isErr()) { - return getIsTradingActiveErrorHandler(maybeIsTradingActive.unwrapErr()) - } - return { - data: maybeIsTradingActive.unwrap(), - } - }, - }), - }), -}) diff --git a/src/state/apis/swapper/selectors.ts b/src/state/apis/swapper/selectors.ts deleted file mode 100644 index 0bf6e77a9f8..00000000000 --- a/src/state/apis/swapper/selectors.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { QueryStatus } from '@reduxjs/toolkit/query' -import type { ReduxState } from 'state/reducer' - -export const selectSwapperApiTradingActivePending = (state: ReduxState) => - Object.values(state.swapperApi.queries).some( - query => query?.endpointName === 'getIsTradingActive' && query?.status === QueryStatus.pending, - ) diff --git a/src/state/apis/swapper/swapperApi.ts b/src/state/apis/swapper/swapperApi.ts deleted file mode 100644 index bb2154bb994..00000000000 --- a/src/state/apis/swapper/swapperApi.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { createApi } from '@reduxjs/toolkit/query/react' -import { BASE_RTK_CREATE_API_CONFIG } from 'state/apis/const' - -export const swapperApi = createApi({ - ...BASE_RTK_CREATE_API_CONFIG, - reducerPath: 'swapperApi', - endpoints: () => ({}), -}) diff --git a/src/state/apis/swappers/selectors.ts b/src/state/apis/swappers/selectors.ts index 4931939b0c7..61fbb011940 100644 --- a/src/state/apis/swappers/selectors.ts +++ b/src/state/apis/swappers/selectors.ts @@ -50,3 +50,8 @@ export const selectSwappersApiTradeQuotePending = createSelector( selectMostRecentTradeQuoteQuery, query => query?.status === QueryStatus.pending, ) + +export const selectSwapperApiTradingActivePending = (state: ReduxState) => + Object.values(state.swappersApi.queries).some( + query => query?.endpointName === 'getIsTradingActive' && query?.status === QueryStatus.pending, + ) diff --git a/src/state/apis/swappers/swappersApi.ts b/src/state/apis/swappers/swappersApi.ts index 2e925380b0a..566a857f6f6 100644 --- a/src/state/apis/swappers/swappersApi.ts +++ b/src/state/apis/swappers/swappersApi.ts @@ -1,8 +1,9 @@ import { createApi } from '@reduxjs/toolkit/dist/query/react' import type { ChainId } from '@shapeshiftoss/caip' import { type AssetId, fromAssetId } from '@shapeshiftoss/caip' -import type { GetTradeQuoteInput } from '@shapeshiftoss/swapper' +import type { GetTradeQuoteInput, SwapperName } from '@shapeshiftoss/swapper' import orderBy from 'lodash/orderBy' +import { isTradingActive } from 'components/MultiHopTrade/utils' import { bnOrZero } from 'lib/bignumber/bignumber' import { getSupportedBuyAssetIds, @@ -32,7 +33,7 @@ import { import { tradeQuoteSlice } from 'state/slices/tradeQuoteSlice/tradeQuoteSlice' import { BASE_RTK_CREATE_API_CONFIG } from '../const' -import { getIsTradingActiveApi } from '../swapper/getIsTradingActiveApi' +import { apiErrorHandler } from '../utils' import { validateQuoteRequest } from './helpers/validateQuoteRequest' import { validateTradeQuote } from './helpers/validateTradeQuote' @@ -42,12 +43,35 @@ const sortQuotes = (unorderedQuotes: Omit[], startingIndex: n ) } +const getIsTradingActiveErrorHandler = apiErrorHandler( + 'getIsTradingActiveApi: error getting trading status', +) + export const GET_TRADE_QUOTE_POLLING_INTERVAL = 20_000 -export const swappersApi = createApi({ +export const _swappersApi = createApi({ ...BASE_RTK_CREATE_API_CONFIG, reducerPath: 'swappersApi', keepUnusedDataFor: Number.MAX_SAFE_INTEGER, // never clear, we will manage this tagTypes: ['TradeQuote'], + endpoints: build => ({ + getIsTradingActive: build.query< + boolean, + { assetId: AssetId | undefined; swapperName: SwapperName } + >({ + queryFn: async ({ assetId, swapperName }) => { + const maybeIsTradingActive = await isTradingActive(assetId, swapperName) + if (maybeIsTradingActive.isErr()) { + return getIsTradingActiveErrorHandler(maybeIsTradingActive.unwrapErr()) + } + return { + data: maybeIsTradingActive.unwrap(), + } + }, + }), + }), +}) + +export const swappersApi = _swappersApi.injectEndpoints({ endpoints: build => ({ getTradeQuote: build.query({ queryFn: async (tradeQuoteInput: GetTradeQuoteInput, { dispatch, getState }) => { @@ -149,7 +173,7 @@ export const swappersApi = createApi({ await Promise.all( [sellAsset.assetId, buyAsset.assetId].map(assetId => { return dispatch( - getIsTradingActiveApi.endpoints.getIsTradingActive.initiate({ + _swappersApi.endpoints.getIsTradingActive.initiate({ assetId, swapperName, }), diff --git a/src/state/reducer.ts b/src/state/reducer.ts index d04032dd640..ad4899d4d75 100644 --- a/src/state/reducer.ts +++ b/src/state/reducer.ts @@ -1,7 +1,6 @@ import { combineReducers } from '@reduxjs/toolkit' import localforage from 'localforage' import { persistReducer } from 'redux-persist' -import { swapperApi } from 'state/apis/swapper/swapperApi' import { tradeQuoteSlice } from 'state/slices/tradeQuoteSlice/tradeQuoteSlice' import { abiApi } from './apis/abi/abiApi' @@ -49,7 +48,6 @@ export const sliceReducers = { txHistory: txHistory.reducer, portfolio: portfolio.reducer, preferences: persistReducer(preferencesPersistConfig, preferences.reducer), - swapperApi: swapperApi.reducer, swappers: swappers.reducer, opportunities: opportunities.reducer, nft: nft.reducer, @@ -63,7 +61,6 @@ export const apiSlices = { portfolioApi, marketApi, txHistoryApi, - swapperApi, swappersApi, foxyApi, fiatRampApi, @@ -82,7 +79,6 @@ export const apiReducers = { [portfolioApi.reducerPath]: portfolioApi.reducer, [marketApi.reducerPath]: marketApi.reducer, [txHistoryApi.reducerPath]: txHistoryApi.reducer, - [swapperApi.reducerPath]: swapperApi.reducer, [swappersApi.reducerPath]: swappersApi.reducer, [foxyApi.reducerPath]: foxyApi.reducer, [fiatRampApi.reducerPath]: fiatRampApi.reducer, diff --git a/src/state/store.ts b/src/state/store.ts index 399337b5ebb..b0a76043c16 100644 --- a/src/state/store.ts +++ b/src/state/store.ts @@ -5,7 +5,6 @@ import type { TypedUseSelectorHook } from 'react-redux' import { useDispatch, useSelector } from 'react-redux' import { createMigrate, PERSIST, persistReducer, persistStore, PURGE } from 'redux-persist' import { getStateWith, registerSelectors } from 'reselect-tools' -import { swapperApi } from 'state/apis/swapper/swapperApi' import { abiApi } from './apis/abi/abiApi' import { covalentApi } from './apis/covalent/covalentApi' @@ -43,7 +42,6 @@ const apiMiddleware = [ assetApi.middleware, txHistoryApi.middleware, foxyApi.middleware, - swapperApi.middleware, swappersApi.middleware, fiatRampApi.middleware, snapshotApi.middleware, @@ -78,7 +76,6 @@ export const clearState = () => { store.dispatch(apiSlices.nftApi.util.resetApiState()) store.dispatch(apiSlices.covalentApi.util.resetApiState()) store.dispatch(apiSlices.zapper.util.resetApiState()) - store.dispatch(apiSlices.swapperApi.util.resetApiState()) store.dispatch(apiSlices.swappersApi.util.resetApiState()) } diff --git a/src/test/mocks/store.ts b/src/test/mocks/store.ts index 3eecd9b91a1..116d081103c 100644 --- a/src/test/mocks/store.ts +++ b/src/test/mocks/store.ts @@ -36,7 +36,6 @@ export const mockStore: ReduxState = { nftApi: mockApiFactory('nftApi' as const), covalentApi: mockApiFactory('covalentApi' as const), zapper: mockApiFactory('zapper' as const), - swapperApi: mockApiFactory('swapperApi' as const), swappersApi: mockSwappersApi, foxyApi: mockApiFactory('foxyApi' as const), fiatRampApi: mockApiFactory('fiatRampApi' as const), From 4f7aa6f98b1ea6cc3f2b1dc9599568fd40280e8d Mon Sep 17 00:00:00 2001 From: woodenfurniture <125113430+woodenfurniture@users.noreply.github.com> Date: Thu, 18 Jan 2024 07:58:35 +1100 Subject: [PATCH 3/8] chore: rename swappersApi to swapeprApi --- .../components/TradeInput/TradeInput.tsx | 2 +- .../components/TradeQuotes/TradeQuote.tsx | 2 +- .../components/TradeQuotes/TradeQuotes.tsx | 2 +- .../TradeInput/getQuoteErrorTranslation.ts | 4 ++-- .../getQuoteRequestErrorTranslation.ts | 4 ++-- .../useGetTradeQuotes/useGetTradeQuotes.tsx | 10 +++++----- .../MultiHopTrade/hooks/useIsTradingActive.tsx | 4 ++-- .../MultiHopTrade/hooks/useSupportedAssets.tsx | 2 +- .../Deposit/components/Confirm.tsx | 4 ++-- .../Overview/ThorchainSaversOverview.tsx | 6 +++--- .../Withdraw/components/Confirm.tsx | 4 ++-- .../helpers/getInputOutputRatioFromQuote.test.ts | 4 ++-- .../helpers/getInputOutputRatioFromQuote.ts | 0 .../{swappers => swapper}/helpers/testData.ts | 0 .../helpers/validateQuoteRequest.ts | 0 .../helpers/validateTradeQuote.ts | 0 src/state/apis/{swappers => swapper}/index.ts | 0 .../apis/{swappers => swapper}/selectors.ts | 8 ++++---- .../swappersApi.ts => swapper/swapperApi.ts} | 16 ++++++++-------- src/state/apis/{swappers => swapper}/types.ts | 0 src/state/reducer.ts | 6 +++--- src/state/slices/tradeQuoteSlice/selectors.ts | 6 +++--- src/state/store.ts | 4 ++-- src/test/mocks/store.ts | 4 ++-- 24 files changed, 46 insertions(+), 46 deletions(-) rename src/state/apis/{swappers => swapper}/helpers/getInputOutputRatioFromQuote.test.ts (97%) rename src/state/apis/{swappers => swapper}/helpers/getInputOutputRatioFromQuote.ts (100%) rename src/state/apis/{swappers => swapper}/helpers/testData.ts (100%) rename src/state/apis/{swappers => swapper}/helpers/validateQuoteRequest.ts (100%) rename src/state/apis/{swappers => swapper}/helpers/validateTradeQuote.ts (100%) rename src/state/apis/{swappers => swapper}/index.ts (100%) rename src/state/apis/{swappers => swapper}/selectors.ts (89%) rename src/state/apis/{swappers/swappersApi.ts => swapper/swapperApi.ts} (97%) rename src/state/apis/{swappers => swapper}/types.ts (100%) diff --git a/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx b/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx index 6220a99b361..f51410d2fff 100644 --- a/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx @@ -57,7 +57,7 @@ import { selectSwappersApiTradeQuotes, selectTradeQuoteRequestErrors, selectTradeQuoteRequestFailed, -} from 'state/apis/swappers/selectors' +} from 'state/apis/swapper/selectors' import { selectBuyAsset, selectManualReceiveAddressIsValidating, diff --git a/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuote.tsx b/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuote.tsx index 4095b08d50e..0d3811aa6e0 100644 --- a/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuote.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuote.tsx @@ -28,7 +28,7 @@ import { useIsTradingActive } from 'components/MultiHopTrade/hooks/useIsTradingA import { RawText } from 'components/Text' import { useLocaleFormatter } from 'hooks/useLocaleFormatter/useLocaleFormatter' import { bn, bnOrZero } from 'lib/bignumber/bignumber' -import { type ApiQuote, TradeQuoteValidationError } from 'state/apis/swappers' +import { type ApiQuote, TradeQuoteValidationError } from 'state/apis/swapper' import { selectBuyAsset, selectFeeAssetByChainId, diff --git a/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuotes.tsx b/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuotes.tsx index 4ae2f5891b7..51f4fbcea86 100644 --- a/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuotes.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuotes.tsx @@ -9,7 +9,7 @@ import { SlideTransitionY } from 'components/SlideTransitionY' import { useIsSnapInstalled } from 'hooks/useIsSnapInstalled/useIsSnapInstalled' import { useWallet } from 'hooks/useWallet/useWallet' import { useWalletSupportsChain } from 'hooks/useWalletSupportsChain/useWalletSupportsChain' -import type { ApiQuote } from 'state/apis/swappers' +import type { ApiQuote } from 'state/apis/swapper' import { selectBuyAsset } from 'state/slices/selectors' import { selectActiveQuoteIndex } from 'state/slices/tradeQuoteSlice/selectors' import { useAppSelector } from 'state/store' diff --git a/src/components/MultiHopTrade/components/TradeInput/getQuoteErrorTranslation.ts b/src/components/MultiHopTrade/components/TradeInput/getQuoteErrorTranslation.ts index 66794be3ea3..6e546a7bb6e 100644 --- a/src/components/MultiHopTrade/components/TradeInput/getQuoteErrorTranslation.ts +++ b/src/components/MultiHopTrade/components/TradeInput/getQuoteErrorTranslation.ts @@ -1,8 +1,8 @@ import { TradeQuoteError as SwapperTradeQuoteError } from '@shapeshiftoss/swapper' import type { InterpolationOptions } from 'node-polyglot' import { assertUnreachable } from 'lib/utils' -import type { ErrorWithMeta } from 'state/apis/swappers' -import { type TradeQuoteError, TradeQuoteValidationError } from 'state/apis/swappers' +import type { ErrorWithMeta } from 'state/apis/swapper' +import { type TradeQuoteError, TradeQuoteValidationError } from 'state/apis/swapper' export const getQuoteErrorTranslation = ( tradeQuoteError: ErrorWithMeta, diff --git a/src/components/MultiHopTrade/components/TradeInput/getQuoteRequestErrorTranslation.ts b/src/components/MultiHopTrade/components/TradeInput/getQuoteRequestErrorTranslation.ts index 129c46a70ad..98e86011f23 100644 --- a/src/components/MultiHopTrade/components/TradeInput/getQuoteRequestErrorTranslation.ts +++ b/src/components/MultiHopTrade/components/TradeInput/getQuoteRequestErrorTranslation.ts @@ -1,7 +1,7 @@ import type { InterpolationOptions } from 'node-polyglot' import { assertUnreachable } from 'lib/utils' -import type { ErrorWithMeta } from 'state/apis/swappers' -import { TradeQuoteRequestError } from 'state/apis/swappers' +import type { ErrorWithMeta } from 'state/apis/swapper' +import { TradeQuoteRequestError } from 'state/apis/swapper' export const getQuoteRequestErrorTranslation = ( tradeQuoteRequestError: ErrorWithMeta, diff --git a/src/components/MultiHopTrade/hooks/useGetTradeQuotes/useGetTradeQuotes.tsx b/src/components/MultiHopTrade/hooks/useGetTradeQuotes/useGetTradeQuotes.tsx index a26e01648d3..9269df6335d 100644 --- a/src/components/MultiHopTrade/hooks/useGetTradeQuotes/useGetTradeQuotes.tsx +++ b/src/components/MultiHopTrade/hooks/useGetTradeQuotes/useGetTradeQuotes.tsx @@ -17,12 +17,12 @@ import { getMixPanel } from 'lib/mixpanel/mixPanelSingleton' import { MixPanelEvent } from 'lib/mixpanel/types' import { isSkipToken, isSome } from 'lib/utils' import { selectIsSnapshotApiQueriesPending, selectVotingPower } from 'state/apis/snapshot/selectors' -import type { ApiQuote, TradeQuoteError } from 'state/apis/swappers' +import type { ApiQuote, TradeQuoteError } from 'state/apis/swapper' import { GET_TRADE_QUOTE_POLLING_INTERVAL, - swappersApi, + swapperApi, useGetTradeQuoteQuery, -} from 'state/apis/swappers/swappersApi' +} from 'state/apis/swapper/swapperApi' import { selectBuyAsset, selectFirstHopSellAccountId, @@ -205,7 +205,7 @@ export const useGetTradeQuotes = () => { // Always invalidate tags when this effect runs - args have changed, and whether we want to fetch an actual quote // or a "skipToken" no-op, we always want to ensure that the tags are invalidated before a new query is ran // That effectively means we'll unsubscribe to queries, considering them stale - dispatch(swappersApi.util.invalidateTags(['TradeQuote'])) + dispatch(swapperApi.util.invalidateTags(['TradeQuote'])) if (wallet && sellAccountId && sellAccountMetadata && receiveAddress && !isVotingPowerLoading) { ;(async () => { @@ -304,7 +304,7 @@ export const useGetTradeQuotes = () => { // NOTE: we're using currentData here, not data, see https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching // This ensures we never return cached data, if skip has been set after the initial query load // currentData is always undefined when skip === true, so we have to access it like so: - const { currentData } = swappersApi.endpoints.getTradeQuote.useQueryState(tradeQuoteInput) + const { currentData } = swapperApi.endpoints.getTradeQuote.useQueryState(tradeQuoteInput) useEffect(() => { if (currentData && mixpanel) { diff --git a/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx b/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx index bf0ca67504e..7910c6d9a19 100644 --- a/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx +++ b/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react' import type { ThorEvmTradeQuote } from 'lib/swapper/swappers/ThorchainSwapper/getThorTradeQuote/getTradeQuote' import { TradeType } from 'lib/swapper/swappers/ThorchainSwapper/utils/longTailHelpers' -import { swappersApi } from 'state/apis/swappers/swappersApi' +import { swapperApi } from 'state/apis/swapper/swapperApi' import { selectBuyAsset, selectSellAsset } from 'state/slices/swappersSlice/selectors' import { selectActiveQuote, selectActiveSwapperName } from 'state/slices/tradeQuoteSlice/selectors' import { useAppDispatch, useAppSelector } from 'state/store' @@ -18,7 +18,7 @@ export const useIsTradingActive = () => { const buyAssetId = useAppSelector(selectBuyAsset).assetId const sellAssetId = useAppSelector(selectSellAsset).assetId - const { getIsTradingActive } = swappersApi.endpoints + const { getIsTradingActive } = swapperApi.endpoints const swapperName = useAppSelector(selectActiveSwapperName) useEffect(() => { diff --git a/src/components/MultiHopTrade/hooks/useSupportedAssets.tsx b/src/components/MultiHopTrade/hooks/useSupportedAssets.tsx index 0dc8cf32336..5404d5ded0f 100644 --- a/src/components/MultiHopTrade/hooks/useSupportedAssets.tsx +++ b/src/components/MultiHopTrade/hooks/useSupportedAssets.tsx @@ -4,7 +4,7 @@ import { useIsSnapInstalled } from 'hooks/useIsSnapInstalled/useIsSnapInstalled' import { useWallet } from 'hooks/useWallet/useWallet' import { walletSupportsChain } from 'hooks/useWalletSupportsChain/useWalletSupportsChain' import { isSome } from 'lib/utils' -import { useGetSupportedAssetsQuery } from 'state/apis/swappers/swappersApi' +import { useGetSupportedAssetsQuery } from 'state/apis/swapper/swapperApi' import { selectAssetsSortedByMarketCapUserCurrencyBalanceAndName } from 'state/slices/common-selectors' import { selectAssets } from 'state/slices/selectors' import { useAppSelector } from 'state/store' diff --git a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Deposit/components/Confirm.tsx b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Deposit/components/Confirm.tsx index 615923f6000..eb9678104b4 100644 --- a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Deposit/components/Confirm.tsx +++ b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Deposit/components/Confirm.tsx @@ -58,7 +58,7 @@ import { import { fromThorBaseUnit, getThorchainFromAddress, toThorBaseUnit } from 'lib/utils/thorchain' import { BASE_BPS_POINTS } from 'lib/utils/thorchain/constants' import { getInboundAddressDataForChain } from 'lib/utils/thorchain/getInboundAddressDataForChain' -import { swappersApi } from 'state/apis/swappers/swappersApi' +import { swapperApi } from 'state/apis/swapper/swapperApi' import { getMaybeThorchainSaversDepositQuote, getThorchainSaversPosition, @@ -561,7 +561,7 @@ export const Confirm: React.FC = ({ accountId, onNext }) => { contextDispatch({ type: ThorchainSaversDepositActionType.SET_LOADING, payload: true }) - const { getIsTradingActive } = swappersApi.endpoints + const { getIsTradingActive } = swapperApi.endpoints const { data: isTradingActive } = await appDispatch( getIsTradingActive.initiate({ assetId, diff --git a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Overview/ThorchainSaversOverview.tsx b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Overview/ThorchainSaversOverview.tsx index 4ee99a2b08e..6abcdaa998e 100644 --- a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Overview/ThorchainSaversOverview.tsx +++ b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Overview/ThorchainSaversOverview.tsx @@ -36,8 +36,8 @@ import { Text } from 'components/Text' import { useBrowserRouter } from 'hooks/useBrowserRouter/useBrowserRouter' import { bnOrZero } from 'lib/bignumber/bignumber' import { fromBaseUnit, toBaseUnit } from 'lib/math' -import { selectSwapperApiTradingActivePending } from 'state/apis/swappers/selectors' -import { swappersApi } from 'state/apis/swappers/swappersApi' +import { selectSwapperApiTradingActivePending } from 'state/apis/swapper/selectors' +import { swapperApi } from 'state/apis/swapper/swapperApi' import type { ThorchainSaversStakingSpecificMetadata } from 'state/slices/opportunitiesSlice/resolvers/thorchainsavers/types' import { getMaybeThorchainSaversDepositQuote, @@ -134,7 +134,7 @@ export const ThorchainSaversOverview: React.FC = ({ useEffect(() => { ;(async () => { - const { getIsTradingActive } = swappersApi.endpoints + const { getIsTradingActive } = swapperApi.endpoints const { data: isTradingActive } = await appDispatch( getIsTradingActive.initiate({ assetId, diff --git a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Withdraw/components/Confirm.tsx b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Withdraw/components/Confirm.tsx index 0f9e15d39bb..524ec484c59 100644 --- a/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Withdraw/components/Confirm.tsx +++ b/src/features/defi/providers/thorchain-savers/components/ThorchainSaversManager/Withdraw/components/Confirm.tsx @@ -58,7 +58,7 @@ import { import { fromThorBaseUnit, toThorBaseUnit } from 'lib/utils/thorchain' import { BASE_BPS_POINTS } from 'lib/utils/thorchain/constants' import { getInboundAddressDataForChain } from 'lib/utils/thorchain/getInboundAddressDataForChain' -import { swappersApi } from 'state/apis/swappers/swappersApi' +import { swapperApi } from 'state/apis/swapper/swapperApi' import { getThorchainSaversPosition, getThorchainSaversWithdrawQuote, @@ -625,7 +625,7 @@ export const Confirm: React.FC = ({ accountId, onNext }) => { return } - const { getIsTradingActive } = swappersApi.endpoints + const { getIsTradingActive } = swapperApi.endpoints const { data: isTradingActive } = await appDispatch( getIsTradingActive.initiate({ assetId, diff --git a/src/state/apis/swappers/helpers/getInputOutputRatioFromQuote.test.ts b/src/state/apis/swapper/helpers/getInputOutputRatioFromQuote.test.ts similarity index 97% rename from src/state/apis/swappers/helpers/getInputOutputRatioFromQuote.test.ts rename to src/state/apis/swapper/helpers/getInputOutputRatioFromQuote.test.ts index 6ba3aee43dd..1bf5697f6f5 100644 --- a/src/state/apis/swappers/helpers/getInputOutputRatioFromQuote.test.ts +++ b/src/state/apis/swapper/helpers/getInputOutputRatioFromQuote.test.ts @@ -6,14 +6,14 @@ import { mockStore } from 'test/mocks/store' import { describe, expect, it, vi } from 'vitest' import { ETH } from 'lib/swapper/swappers/utils/test-data/assets' import { assertUnreachable } from 'lib/utils' -import { getInputOutputRatioFromQuote } from 'state/apis/swappers/helpers/getInputOutputRatioFromQuote' +import { getInputOutputRatioFromQuote } from 'state/apis/swapper/helpers/getInputOutputRatioFromQuote' import { cowQuote, lifiQuote, oneInchQuote, thorQuote, zrxQuote, -} from 'state/apis/swappers/helpers/testData' +} from 'state/apis/swapper/helpers/testData' import type { ReduxState } from 'state/reducer' const usdcAssetId: AssetId = 'eip155:1/erc20:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' diff --git a/src/state/apis/swappers/helpers/getInputOutputRatioFromQuote.ts b/src/state/apis/swapper/helpers/getInputOutputRatioFromQuote.ts similarity index 100% rename from src/state/apis/swappers/helpers/getInputOutputRatioFromQuote.ts rename to src/state/apis/swapper/helpers/getInputOutputRatioFromQuote.ts diff --git a/src/state/apis/swappers/helpers/testData.ts b/src/state/apis/swapper/helpers/testData.ts similarity index 100% rename from src/state/apis/swappers/helpers/testData.ts rename to src/state/apis/swapper/helpers/testData.ts diff --git a/src/state/apis/swappers/helpers/validateQuoteRequest.ts b/src/state/apis/swapper/helpers/validateQuoteRequest.ts similarity index 100% rename from src/state/apis/swappers/helpers/validateQuoteRequest.ts rename to src/state/apis/swapper/helpers/validateQuoteRequest.ts diff --git a/src/state/apis/swappers/helpers/validateTradeQuote.ts b/src/state/apis/swapper/helpers/validateTradeQuote.ts similarity index 100% rename from src/state/apis/swappers/helpers/validateTradeQuote.ts rename to src/state/apis/swapper/helpers/validateTradeQuote.ts diff --git a/src/state/apis/swappers/index.ts b/src/state/apis/swapper/index.ts similarity index 100% rename from src/state/apis/swappers/index.ts rename to src/state/apis/swapper/index.ts diff --git a/src/state/apis/swappers/selectors.ts b/src/state/apis/swapper/selectors.ts similarity index 89% rename from src/state/apis/swappers/selectors.ts rename to src/state/apis/swapper/selectors.ts index 61fbb011940..67ed7d8983a 100644 --- a/src/state/apis/swappers/selectors.ts +++ b/src/state/apis/swapper/selectors.ts @@ -6,12 +6,12 @@ import { createDeepEqualOutputSelector } from 'state/selector-utils' import type { ApiQuote, ErrorWithMeta, TradeQuoteRequestError, TradeQuoteResponse } from './types' -const selectSwappersApi = (state: ReduxState) => state.swappersApi +const selectSwappersApi = (state: ReduxState) => state.swapperApi const selectMostRecentTradeQuoteQuery = createDeepEqualOutputSelector( selectSwappersApi, - swappersApi => { - const getTradeQuoteQueries = Object.values(swappersApi.queries).filter( + swapperApi => { + const getTradeQuoteQueries = Object.values(swapperApi.queries).filter( query => query?.endpointName === 'getTradeQuote', ) @@ -52,6 +52,6 @@ export const selectSwappersApiTradeQuotePending = createSelector( ) export const selectSwapperApiTradingActivePending = (state: ReduxState) => - Object.values(state.swappersApi.queries).some( + Object.values(state.swapperApi.queries).some( query => query?.endpointName === 'getIsTradingActive' && query?.status === QueryStatus.pending, ) diff --git a/src/state/apis/swappers/swappersApi.ts b/src/state/apis/swapper/swapperApi.ts similarity index 97% rename from src/state/apis/swappers/swappersApi.ts rename to src/state/apis/swapper/swapperApi.ts index 566a857f6f6..095eb5697be 100644 --- a/src/state/apis/swappers/swappersApi.ts +++ b/src/state/apis/swapper/swapperApi.ts @@ -11,9 +11,9 @@ import { getTradeQuotes, } from 'lib/swapper/swapper' import { getEnabledSwappers } from 'lib/swapper/utils' -import { getInputOutputRatioFromQuote } from 'state/apis/swappers/helpers/getInputOutputRatioFromQuote' -import type { ApiQuote, TradeQuoteResponse } from 'state/apis/swappers/types' -import { TradeQuoteRequestError, TradeQuoteValidationError } from 'state/apis/swappers/types' +import { getInputOutputRatioFromQuote } from 'state/apis/swapper/helpers/getInputOutputRatioFromQuote' +import type { ApiQuote, TradeQuoteResponse } from 'state/apis/swapper/types' +import { TradeQuoteRequestError, TradeQuoteValidationError } from 'state/apis/swapper/types' import type { ReduxState } from 'state/reducer' import { selectAssets } from 'state/slices/assetsSlice/selectors' import { @@ -48,9 +48,9 @@ const getIsTradingActiveErrorHandler = apiErrorHandler( ) export const GET_TRADE_QUOTE_POLLING_INTERVAL = 20_000 -export const _swappersApi = createApi({ +export const _swapperApi = createApi({ ...BASE_RTK_CREATE_API_CONFIG, - reducerPath: 'swappersApi', + reducerPath: 'swapperApi', keepUnusedDataFor: Number.MAX_SAFE_INTEGER, // never clear, we will manage this tagTypes: ['TradeQuote'], endpoints: build => ({ @@ -71,7 +71,7 @@ export const _swappersApi = createApi({ }), }) -export const swappersApi = _swappersApi.injectEndpoints({ +export const swapperApi = _swapperApi.injectEndpoints({ endpoints: build => ({ getTradeQuote: build.query({ queryFn: async (tradeQuoteInput: GetTradeQuoteInput, { dispatch, getState }) => { @@ -173,7 +173,7 @@ export const swappersApi = _swappersApi.injectEndpoints({ await Promise.all( [sellAsset.assetId, buyAsset.assetId].map(assetId => { return dispatch( - _swappersApi.endpoints.getIsTradingActive.initiate({ + _swapperApi.endpoints.getIsTradingActive.initiate({ assetId, swapperName, }), @@ -289,4 +289,4 @@ export const swappersApi = _swappersApi.injectEndpoints({ }), }) -export const { useGetTradeQuoteQuery, useGetSupportedAssetsQuery } = swappersApi +export const { useGetTradeQuoteQuery, useGetSupportedAssetsQuery } = swapperApi diff --git a/src/state/apis/swappers/types.ts b/src/state/apis/swapper/types.ts similarity index 100% rename from src/state/apis/swappers/types.ts rename to src/state/apis/swapper/types.ts diff --git a/src/state/reducer.ts b/src/state/reducer.ts index ad4899d4d75..a45729a2319 100644 --- a/src/state/reducer.ts +++ b/src/state/reducer.ts @@ -9,7 +9,7 @@ import { fiatRampApi } from './apis/fiatRamps/fiatRamps' import { foxyApi } from './apis/foxy/foxyApi' import { nft, nftApi } from './apis/nft/nftApi' import { snapshot, snapshotApi } from './apis/snapshot/snapshot' -import { swappersApi } from './apis/swappers/swappersApi' +import { swapperApi } from './apis/swapper/swapperApi' import { zapper, zapperApi } from './apis/zapper/zapperApi' import { zerionApi } from './apis/zerion/zerionApi' import { assetApi, assets } from './slices/assetsSlice/assetsSlice' @@ -61,7 +61,7 @@ export const apiSlices = { portfolioApi, marketApi, txHistoryApi, - swappersApi, + swappersApi: swapperApi, foxyApi, fiatRampApi, snapshotApi, @@ -79,7 +79,7 @@ export const apiReducers = { [portfolioApi.reducerPath]: portfolioApi.reducer, [marketApi.reducerPath]: marketApi.reducer, [txHistoryApi.reducerPath]: txHistoryApi.reducer, - [swappersApi.reducerPath]: swappersApi.reducer, + [swapperApi.reducerPath]: swapperApi.reducer, [foxyApi.reducerPath]: foxyApi.reducer, [fiatRampApi.reducerPath]: fiatRampApi.reducer, [snapshotApi.reducerPath]: snapshotApi.reducer, diff --git a/src/state/slices/tradeQuoteSlice/selectors.ts b/src/state/slices/tradeQuoteSlice/selectors.ts index e0eda38fdca..04efe8b42ee 100644 --- a/src/state/slices/tradeQuoteSlice/selectors.ts +++ b/src/state/slices/tradeQuoteSlice/selectors.ts @@ -7,9 +7,9 @@ import { getDefaultSlippageDecimalPercentageForSwapper } from 'constants/constan import type { Selector } from 'reselect' import { bn, bnOrZero } from 'lib/bignumber/bignumber' import { fromBaseUnit } from 'lib/math' -import type { ApiQuote, ErrorWithMeta, TradeQuoteError } from 'state/apis/swappers' -import { TradeQuoteWarning } from 'state/apis/swappers' -import { selectSwappersApiTradeQuotes } from 'state/apis/swappers/selectors' +import type { ApiQuote, ErrorWithMeta, TradeQuoteError } from 'state/apis/swapper' +import { TradeQuoteWarning } from 'state/apis/swapper' +import { selectSwappersApiTradeQuotes } from 'state/apis/swapper/selectors' import { isCrossAccountTradeSupported } from 'state/helpers' import type { ReduxState } from 'state/reducer' import { createDeepEqualOutputSelector } from 'state/selector-utils' diff --git a/src/state/store.ts b/src/state/store.ts index b0a76043c16..62aa44294b3 100644 --- a/src/state/store.ts +++ b/src/state/store.ts @@ -12,7 +12,7 @@ import { fiatRampApi } from './apis/fiatRamps/fiatRamps' import { foxyApi } from './apis/foxy/foxyApi' import { nftApi } from './apis/nft/nftApi' import { snapshotApi } from './apis/snapshot/snapshot' -import { swappersApi } from './apis/swappers/swappersApi' +import { swapperApi } from './apis/swapper/swapperApi' import { zapper, zapperApi } from './apis/zapper/zapperApi' import { zerionApi } from './apis/zerion/zerionApi' import { migrations } from './migrations' @@ -42,7 +42,7 @@ const apiMiddleware = [ assetApi.middleware, txHistoryApi.middleware, foxyApi.middleware, - swappersApi.middleware, + swapperApi.middleware, fiatRampApi.middleware, snapshotApi.middleware, zapper.middleware, diff --git a/src/test/mocks/store.ts b/src/test/mocks/store.ts index 116d081103c..4bd9a120164 100644 --- a/src/test/mocks/store.ts +++ b/src/test/mocks/store.ts @@ -21,7 +21,7 @@ const mockApiFactory = (reducerPath: T) => ({ }, }) -const mockSwappersApi = Object.assign(mockApiFactory('swappersApi' as const), { +const mockSwapperApi = Object.assign(mockApiFactory('swapperApi' as const), { provided: { TradeQuote: {}, }, @@ -36,7 +36,7 @@ export const mockStore: ReduxState = { nftApi: mockApiFactory('nftApi' as const), covalentApi: mockApiFactory('covalentApi' as const), zapper: mockApiFactory('zapper' as const), - swappersApi: mockSwappersApi, + swapperApi: mockSwapperApi, foxyApi: mockApiFactory('foxyApi' as const), fiatRampApi: mockApiFactory('fiatRampApi' as const), snapshotApi: mockApiFactory('snapshotApi' as const), From 07e1c56c6042733386f230bf14b5ccd1fbe18379 Mon Sep 17 00:00:00 2001 From: woodenfurniture <125113430+woodenfurniture@users.noreply.github.com> Date: Thu, 18 Jan 2024 08:17:44 +1100 Subject: [PATCH 4/8] chore: rename swappersSlice to tradeInputSlice --- .../MultiHopTrade/MultiHopTrade.tsx | 12 +++---- .../MultiHopTradeConfirm.tsx | 2 +- .../components/SlippagePopover.tsx | 8 ++--- .../components/TradeConfirm/TradeConfirm.tsx | 2 +- .../components/TradeInput/TradeInput.tsx | 10 +++--- .../components/ManualAddressEntry.tsx | 12 +++---- .../TradeInput/components/SellAssetInput.tsx | 4 +-- .../MultiHopTrade/hooks/useAccountIds.tsx | 6 ++-- .../hooks/useIsTradingActive.tsx | 2 +- .../MultiHopTrade/hooks/useReceiveAddress.tsx | 2 +- src/state/apis/swapper/swapperApi.ts | 2 +- src/state/reducer.ts | 6 ++-- src/state/slices/selectors.ts | 2 +- .../selectors.ts | 36 +++++++++---------- .../tradeInputSlice.ts} | 8 ++--- src/state/slices/tradeQuoteSlice/selectors.ts | 2 +- src/state/store.ts | 2 +- src/test/mocks/store.ts | 2 +- 18 files changed, 60 insertions(+), 60 deletions(-) rename src/state/slices/{swappersSlice => tradeInputSlice}/selectors.ts (80%) rename src/state/slices/{swappersSlice/swappersSlice.ts => tradeInputSlice/tradeInputSlice.ts} (95%) diff --git a/src/components/MultiHopTrade/MultiHopTrade.tsx b/src/components/MultiHopTrade/MultiHopTrade.tsx index 358d62c6769..07b4582ee8f 100644 --- a/src/components/MultiHopTrade/MultiHopTrade.tsx +++ b/src/components/MultiHopTrade/MultiHopTrade.tsx @@ -9,7 +9,7 @@ import { MemoryRouter, Route, Switch, useLocation, useParams } from 'react-route import { useFeatureFlag } from 'hooks/useFeatureFlag/useFeatureFlag' import { useIsSnapInstalled } from 'hooks/useIsSnapInstalled/useIsSnapInstalled' import { selectAssetById } from 'state/slices/assetsSlice/selectors' -import { swappers } from 'state/slices/swappersSlice/swappersSlice' +import { tradeInput } from 'state/slices/tradeInputSlice/tradeInputSlice' import { useAppDispatch, useAppSelector } from 'state/store' import { TradeRoutePaths } from './types' @@ -78,10 +78,10 @@ export const MultiHopTrade = memo( const defaultSellAsset = useAppSelector(state => selectAssetById(state, defaultSellAssetId)) useEffect(() => { - dispatch(swappers.actions.clear()) - if (defaultSellAsset) dispatch(swappers.actions.setSellAsset(defaultSellAsset)) - if (routeBuyAsset) dispatch(swappers.actions.setBuyAsset(routeBuyAsset)) - else if (defaultBuyAsset) dispatch(swappers.actions.setBuyAsset(defaultBuyAsset)) + dispatch(tradeInput.actions.clear()) + if (defaultSellAsset) dispatch(tradeInput.actions.setSellAsset(defaultSellAsset)) + if (routeBuyAsset) dispatch(tradeInput.actions.setBuyAsset(routeBuyAsset)) + else if (defaultBuyAsset) dispatch(tradeInput.actions.setBuyAsset(defaultBuyAsset)) }, [defaultBuyAsset, defaultSellAsset, dispatch, routeBuyAsset]) return ( @@ -108,7 +108,7 @@ const MultiHopRoutes = memo(() => { // Reset the swapper slice to initial state on mount // Don't move me to one of the trade route components, this needs to be at router-level // We only want to clear swapper state when trade components are fully unmounted, not when trade routes change - dispatch(swappers.actions.clear()) + dispatch(tradeInput.actions.clear()) } }, [dispatch]) diff --git a/src/components/MultiHopTrade/components/MultiHopTradeConfirm/MultiHopTradeConfirm.tsx b/src/components/MultiHopTrade/components/MultiHopTradeConfirm/MultiHopTradeConfirm.tsx index 106d30671f0..b225575406e 100644 --- a/src/components/MultiHopTrade/components/MultiHopTradeConfirm/MultiHopTradeConfirm.tsx +++ b/src/components/MultiHopTrade/components/MultiHopTradeConfirm/MultiHopTradeConfirm.tsx @@ -5,7 +5,7 @@ import { WithBackButton } from 'components/MultiHopTrade/components/WithBackButt import { TradeRoutePaths } from 'components/MultiHopTrade/types' import { SlideTransition } from 'components/SlideTransition' import { Text } from 'components/Text' -import { swappers as swappersSlice } from 'state/slices/swappersSlice/swappersSlice' +import { tradeInput as swappersSlice } from 'state/slices/tradeInputSlice/tradeInputSlice' import { selectTradeExecutionState } from 'state/slices/tradeQuoteSlice/selectors' import { tradeQuoteSlice } from 'state/slices/tradeQuoteSlice/tradeQuoteSlice' import { TradeExecutionState } from 'state/slices/tradeQuoteSlice/types' diff --git a/src/components/MultiHopTrade/components/SlippagePopover.tsx b/src/components/MultiHopTrade/components/SlippagePopover.tsx index 8772141ddb6..292843fcca2 100644 --- a/src/components/MultiHopTrade/components/SlippagePopover.tsx +++ b/src/components/MultiHopTrade/components/SlippagePopover.tsx @@ -23,8 +23,8 @@ import { HelperTooltip } from 'components/HelperTooltip/HelperTooltip' import { Row } from 'components/Row/Row' import { Text } from 'components/Text' import { useFeatureFlag } from 'hooks/useFeatureFlag/useFeatureFlag' -import { selectUserSlippagePercentage } from 'state/slices/swappersSlice/selectors' -import { swappers } from 'state/slices/swappersSlice/swappersSlice' +import { selectUserSlippagePercentage } from 'state/slices/tradeInputSlice/selectors' +import { tradeInput } from 'state/slices/tradeInputSlice/tradeInputSlice' import { selectDefaultSlippagePercentage } from 'state/slices/tradeQuoteSlice/selectors' import { useAppDispatch, useAppSelector } from 'state/store' @@ -79,9 +79,9 @@ export const SlippagePopover: FC = () => { const handleClose = useCallback(() => { if (slippageType === SlippageType.Custom && !isInvalid) - dispatch(swappers.actions.setSlippagePreferencePercentage(slippageAmount)) + dispatch(tradeInput.actions.setSlippagePreferencePercentage(slippageAmount)) else if (slippageType === SlippageType.Auto) - dispatch(swappers.actions.setSlippagePreferencePercentage(undefined)) + dispatch(tradeInput.actions.setSlippagePreferencePercentage(undefined)) }, [dispatch, isInvalid, slippageAmount, slippageType]) const handleSlippageTypeChange = useCallback( diff --git a/src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx b/src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx index f6b714ca3f0..cb8ce3f007a 100644 --- a/src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx +++ b/src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx @@ -51,7 +51,7 @@ import { getMixPanel } from 'lib/mixpanel/mixPanelSingleton' import { MixPanelEvent } from 'lib/mixpanel/types' import { THORCHAIN_STREAM_SWAP_SOURCE } from 'lib/swapper/swappers/ThorchainSwapper/constants' import { assertUnreachable } from 'lib/utils' -import { selectManualReceiveAddress } from 'state/slices/swappersSlice/selectors' +import { selectManualReceiveAddress } from 'state/slices/tradeInputSlice/selectors' import { selectActiveQuote, selectActiveStepOrDefault, diff --git a/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx b/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx index f51410d2fff..b6c4afd3574 100644 --- a/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx @@ -64,7 +64,7 @@ import { selectSellAmountCryptoPrecision, selectSellAsset, } from 'state/slices/selectors' -import { swappers } from 'state/slices/swappersSlice/swappersSlice' +import { tradeInput } from 'state/slices/tradeInputSlice/tradeInputSlice' import { selectActiveQuote, selectActiveQuoteErrors, @@ -162,15 +162,15 @@ export const TradeInput = memo(() => { }, [activeQuoteErrors, quoteRequestErrors]) const setBuyAsset = useCallback( - (asset: Asset) => dispatch(swappers.actions.setBuyAsset(asset)), + (asset: Asset) => dispatch(tradeInput.actions.setBuyAsset(asset)), [dispatch], ) const setSellAsset = useCallback( - (asset: Asset) => dispatch(swappers.actions.setSellAsset(asset)), + (asset: Asset) => dispatch(tradeInput.actions.setSellAsset(asset)), [dispatch], ) const handleSwitchAssets = useCallback( - () => dispatch(swappers.actions.switchAssets()), + () => dispatch(tradeInput.actions.switchAssets()), [dispatch], ) @@ -180,7 +180,7 @@ export const TradeInput = memo(() => { dispatch(tradeQuoteSlice.actions.resetConfirmedQuote()) // clear the active quote index on mount to prevent stale data affecting the selectors dispatch(tradeQuoteSlice.actions.resetActiveQuoteIndex()) - dispatch(swappers.actions.setSlippagePreferencePercentage(undefined)) + dispatch(tradeInput.actions.setSlippagePreferencePercentage(undefined)) }, [dispatch]) const { diff --git a/src/components/MultiHopTrade/components/TradeInput/components/ManualAddressEntry.tsx b/src/components/MultiHopTrade/components/TradeInput/components/ManualAddressEntry.tsx index fd22e8a9a24..c821bdaa902 100644 --- a/src/components/MultiHopTrade/components/TradeInput/components/ManualAddressEntry.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/components/ManualAddressEntry.tsx @@ -13,8 +13,8 @@ import { useModal } from 'hooks/useModal/useModal' import { useWallet } from 'hooks/useWallet/useWallet' import { useWalletSupportsChain } from 'hooks/useWalletSupportsChain/useWalletSupportsChain' import { parseAddressInputWithChainId } from 'lib/address/address' -import { selectBuyAsset, selectManualReceiveAddress } from 'state/slices/swappersSlice/selectors' -import { swappers } from 'state/slices/swappersSlice/swappersSlice' +import { selectBuyAsset, selectManualReceiveAddress } from 'state/slices/tradeInputSlice/selectors' +import { tradeInput } from 'state/slices/tradeInputSlice/tradeInputSlice' import { useAppDispatch, useAppSelector } from 'state/store' export const ManualAddressEntry: FC = memo((): JSX.Element | null => { @@ -54,7 +54,7 @@ export const ManualAddressEntry: FC = memo((): JSX.Element | null => { // Reset the manual address input state when the user changes the buy asset useEffect(() => { - dispatch(swappers.actions.setManualReceiveAddress(undefined)) + dispatch(tradeInput.actions.setManualReceiveAddress(undefined)) setFormValue(SendFormFields.Input, '') }, [buyAssetAssetId, dispatch, setFormValue]) @@ -64,7 +64,7 @@ export const ManualAddressEntry: FC = memo((): JSX.Element | null => { }, [dispatch, manualReceiveAddress, setFormValue]) useEffect(() => { - dispatch(swappers.actions.setManualReceiveAddressIsValidating(isValidating)) + dispatch(tradeInput.actions.setManualReceiveAddressIsValidating(isValidating)) }, [dispatch, isValidating]) const rules = useMemo( @@ -82,7 +82,7 @@ export const ManualAddressEntry: FC = memo((): JSX.Element | null => { disableUrlParsing: true, } const { address } = await parseAddressInputWithChainId(parseAddressInputWithChainIdArgs) - dispatch(swappers.actions.setManualReceiveAddress(address || undefined)) + dispatch(tradeInput.actions.setManualReceiveAddress(address || undefined)) const invalidMessage = isYatSupported ? 'common.invalidAddressOrYat' : 'common.invalidAddress' @@ -90,7 +90,7 @@ export const ManualAddressEntry: FC = memo((): JSX.Element | null => { } catch (e) { // This function should never throw, but in case it ever does, we never want to have a stale manual receive address stored console.error(e) - dispatch(swappers.actions.setManualReceiveAddress(undefined)) + dispatch(tradeInput.actions.setManualReceiveAddress(undefined)) } }, }, diff --git a/src/components/MultiHopTrade/components/TradeInput/components/SellAssetInput.tsx b/src/components/MultiHopTrade/components/TradeInput/components/SellAssetInput.tsx index 529b5d77824..5e43c788176 100644 --- a/src/components/MultiHopTrade/components/TradeInput/components/SellAssetInput.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/components/SellAssetInput.tsx @@ -6,7 +6,7 @@ import type { TradeAssetInputProps } from 'components/MultiHopTrade/components/T import { TradeAssetInput } from 'components/MultiHopTrade/components/TradeAssetInput' import { bnOrZero, positiveOrZero } from 'lib/bignumber/bignumber' import { selectMarketDataByFilter } from 'state/slices/selectors' -import { swappers } from 'state/slices/swappersSlice/swappersSlice' +import { tradeInput } from 'state/slices/tradeInputSlice/tradeInputSlice' import { useAppDispatch, useAppSelector } from 'state/store' const formControlProps = { borderRadius: 0, background: 'transparent', borderWidth: 0 } @@ -45,7 +45,7 @@ export const SellAssetInput = memo( setSellAmountCryptoPrecision(sellAmountCryptoPrecision) dispatch( - swappers.actions.setSellAmountCryptoPrecision( + tradeInput.actions.setSellAmountCryptoPrecision( positiveOrZero(sellAmountCryptoPrecision).toString(), ), ) diff --git a/src/components/MultiHopTrade/hooks/useAccountIds.tsx b/src/components/MultiHopTrade/hooks/useAccountIds.tsx index cc92bc28471..aa3948f2df1 100644 --- a/src/components/MultiHopTrade/hooks/useAccountIds.tsx +++ b/src/components/MultiHopTrade/hooks/useAccountIds.tsx @@ -1,7 +1,7 @@ import type { AccountId } from '@shapeshiftoss/caip' import { useCallback } from 'react' import { selectFirstHopSellAccountId, selectLastHopBuyAccountId } from 'state/slices/selectors' -import { swappers } from 'state/slices/swappersSlice/swappersSlice' +import { tradeInput } from 'state/slices/tradeInputSlice/tradeInputSlice' import { useAppDispatch, useAppSelector } from 'state/store' export const useAccountIds = (): { @@ -19,13 +19,13 @@ export const useAccountIds = (): { const setSellAssetAccountId = useCallback( (accountId: AccountId | undefined) => - dispatch(swappers.actions.setSellAssetAccountNumber(accountId)), + dispatch(tradeInput.actions.setSellAssetAccountNumber(accountId)), [dispatch], ) const setBuyAssetAccountId = useCallback( (accountId: AccountId | undefined) => - dispatch(swappers.actions.setBuyAssetAccountNumber(accountId)), + dispatch(tradeInput.actions.setBuyAssetAccountNumber(accountId)), [dispatch], ) diff --git a/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx b/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx index 7910c6d9a19..9c59592d708 100644 --- a/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx +++ b/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react' import type { ThorEvmTradeQuote } from 'lib/swapper/swappers/ThorchainSwapper/getThorTradeQuote/getTradeQuote' import { TradeType } from 'lib/swapper/swappers/ThorchainSwapper/utils/longTailHelpers' import { swapperApi } from 'state/apis/swapper/swapperApi' -import { selectBuyAsset, selectSellAsset } from 'state/slices/swappersSlice/selectors' +import { selectBuyAsset, selectSellAsset } from 'state/slices/tradeInputSlice/selectors' import { selectActiveQuote, selectActiveSwapperName } from 'state/slices/tradeQuoteSlice/selectors' import { useAppDispatch, useAppSelector } from 'state/store' diff --git a/src/components/MultiHopTrade/hooks/useReceiveAddress.tsx b/src/components/MultiHopTrade/hooks/useReceiveAddress.tsx index 3407125046b..4c2e46522bb 100644 --- a/src/components/MultiHopTrade/hooks/useReceiveAddress.tsx +++ b/src/components/MultiHopTrade/hooks/useReceiveAddress.tsx @@ -10,7 +10,7 @@ import { selectBuyAsset, selectLastHopBuyAccountId, selectManualReceiveAddress, -} from 'state/slices/swappersSlice/selectors' +} from 'state/slices/tradeInputSlice/selectors' import { useAppSelector } from 'state/store' export const getReceiveAddress = async ({ diff --git a/src/state/apis/swapper/swapperApi.ts b/src/state/apis/swapper/swapperApi.ts index 095eb5697be..5c2e0278f49 100644 --- a/src/state/apis/swapper/swapperApi.ts +++ b/src/state/apis/swapper/swapperApi.ts @@ -29,7 +29,7 @@ import { selectFirstHopSellAccountId, selectManualReceiveAddress, selectSellAsset, -} from 'state/slices/swappersSlice/selectors' +} from 'state/slices/tradeInputSlice/selectors' import { tradeQuoteSlice } from 'state/slices/tradeQuoteSlice/tradeQuoteSlice' import { BASE_RTK_CREATE_API_CONFIG } from '../const' diff --git a/src/state/reducer.ts b/src/state/reducer.ts index a45729a2319..27680cafee0 100644 --- a/src/state/reducer.ts +++ b/src/state/reducer.ts @@ -19,7 +19,7 @@ import { opportunitiesApi } from './slices/opportunitiesSlice/opportunitiesApiSl import { opportunities } from './slices/opportunitiesSlice/opportunitiesSlice' import { portfolio, portfolioApi } from './slices/portfolioSlice/portfolioSlice' import { preferences } from './slices/preferencesSlice/preferencesSlice' -import { swappers } from './slices/swappersSlice/swappersSlice' +import { tradeInput } from './slices/tradeInputSlice/tradeInputSlice' import { txHistory, txHistoryApi } from './slices/txHistorySlice/txHistorySlice' export const slices = { @@ -30,7 +30,7 @@ export const slices = { preferences, opportunities, nft, - swappers, + tradeInput, tradeQuoteSlice, snapshot, localWalletSlice, @@ -48,7 +48,7 @@ export const sliceReducers = { txHistory: txHistory.reducer, portfolio: portfolio.reducer, preferences: persistReducer(preferencesPersistConfig, preferences.reducer), - swappers: swappers.reducer, + tradeInput: tradeInput.reducer, opportunities: opportunities.reducer, nft: nft.reducer, tradeQuoteSlice: tradeQuoteSlice.reducer, diff --git a/src/state/slices/selectors.ts b/src/state/slices/selectors.ts index 2239be8a9de..aadebf24da4 100644 --- a/src/state/slices/selectors.ts +++ b/src/state/slices/selectors.ts @@ -13,7 +13,7 @@ export * from './portfolioSlice/selectors' export * from './preferencesSlice/selectors' export * from './txHistorySlice/selectors' export * from './opportunitiesSlice/selectors' -export * from './swappersSlice/selectors' +export * from './tradeInputSlice/selectors' /** * some selectors span multiple business logic domains, e.g. portfolio and opportunities diff --git a/src/state/slices/swappersSlice/selectors.ts b/src/state/slices/tradeInputSlice/selectors.ts similarity index 80% rename from src/state/slices/swappersSlice/selectors.ts rename to src/state/slices/tradeInputSlice/selectors.ts index 31de708c079..22c0ced09a0 100644 --- a/src/state/slices/swappersSlice/selectors.ts +++ b/src/state/slices/tradeInputSlice/selectors.ts @@ -12,20 +12,20 @@ import { getHighestUserCurrencyBalanceAccountByAssetId, } from '../portfolioSlice/utils' -const selectSwappers = (state: ReduxState) => state.swappers +const selectTradeInput = (state: ReduxState) => state.tradeInput export const selectBuyAsset = createDeepEqualOutputSelector( - selectSwappers, - swappers => swappers.buyAsset, + selectTradeInput, + tradeInput => tradeInput.buyAsset, ) export const selectSellAsset = createDeepEqualOutputSelector( - selectSwappers, - swappers => swappers.sellAsset, + selectTradeInput, + tradeInput => tradeInput.sellAsset, ) export const selectUserSlippagePercentage: Selector = - createSelector(selectSwappers, swappers => swappers.slippagePreferencePercentage) + createSelector(selectTradeInput, tradeInput => tradeInput.slippagePreferencePercentage) // User input comes in as an actual percentage e.g 1 for 1%, so we need to convert it to a decimal e.g 0.01 for 1% export const selectUserSlippagePercentageDecimal: Selector = @@ -36,13 +36,13 @@ export const selectUserSlippagePercentageDecimal: Selector { + (tradeInput, sellAsset, accountIdAssetValues, accountIds) => { // return the users selection if it exists - if (swappers.sellAssetAccountId) return swappers.sellAssetAccountId + if (tradeInput.sellAssetAccountId) return tradeInput.sellAssetAccountId const highestFiatBalanceSellAccountId = getHighestUserCurrencyBalanceAccountByAssetId( accountIdAssetValues, @@ -57,13 +57,13 @@ export const selectFirstHopSellAccountId = createSelector( // selects the account ID we're buying into for the first hop export const selectLastHopBuyAccountId = createSelector( - selectSwappers, + selectTradeInput, selectBuyAsset, selectPortfolioAssetAccountBalancesSortedUserCurrency, selectWalletAccountIds, - (swappers, buyAsset, accountIdAssetValues, accountIds) => { + (tradeInput, buyAsset, accountIdAssetValues, accountIds) => { // return the users selection if it exists - if (swappers.buyAssetAccountId) return swappers.buyAssetAccountId + if (tradeInput.buyAssetAccountId) return tradeInput.buyAssetAccountId const highestFiatBalanceBuyAccountId = getHighestUserCurrencyBalanceAccountByAssetId( accountIdAssetValues, @@ -77,8 +77,8 @@ export const selectLastHopBuyAccountId = createSelector( ) export const selectSellAmountCryptoPrecision = createSelector( - selectSwappers, - swappers => swappers.sellAmountCryptoPrecision, + selectTradeInput, + tradeInput => tradeInput.sellAmountCryptoPrecision, ) export const selectSellAssetUsdRate = createSelector( @@ -100,13 +100,13 @@ export const selectBuyAssetUsdRate = createSelector( ) export const selectManualReceiveAddress = createSelector( - selectSwappers, - swappers => swappers.manualReceiveAddress, + selectTradeInput, + tradeInput => tradeInput.manualReceiveAddress, ) export const selectManualReceiveAddressIsValidating = createSelector( - selectSwappers, - swappers => swappers.manualReceiveAddressIsValidating, + selectTradeInput, + tradeInput => tradeInput.manualReceiveAddressIsValidating, ) export const selectSellAmountUsd = createSelector( diff --git a/src/state/slices/swappersSlice/swappersSlice.ts b/src/state/slices/tradeInputSlice/tradeInputSlice.ts similarity index 95% rename from src/state/slices/swappersSlice/swappersSlice.ts rename to src/state/slices/tradeInputSlice/tradeInputSlice.ts index 98c15cd6c8e..258b9b6f11d 100644 --- a/src/state/slices/swappersSlice/swappersSlice.ts +++ b/src/state/slices/tradeInputSlice/tradeInputSlice.ts @@ -8,7 +8,7 @@ import { bnOrZero } from 'lib/bignumber/bignumber' import { defaultAsset } from '../assetsSlice/assetsSlice' -export type SwappersState = { +export type TradeInputState = { buyAsset: Asset sellAsset: Asset sellAssetAccountId: AccountId | undefined @@ -20,7 +20,7 @@ export type SwappersState = { } // Define the initial state: -const initialState: SwappersState = { +const initialState: TradeInputState = { buyAsset: localAssetData[foxAssetId] ?? defaultAsset, sellAsset: localAssetData[ethAssetId] ?? defaultAsset, sellAssetAccountId: undefined, @@ -32,8 +32,8 @@ const initialState: SwappersState = { } // Create the slice: -export const swappers = createSlice({ - name: 'swappers', +export const tradeInput = createSlice({ + name: 'tradeInput', initialState, reducers: { clear: () => initialState, diff --git a/src/state/slices/tradeQuoteSlice/selectors.ts b/src/state/slices/tradeQuoteSlice/selectors.ts index 04efe8b42ee..8cf281260a8 100644 --- a/src/state/slices/tradeQuoteSlice/selectors.ts +++ b/src/state/slices/tradeQuoteSlice/selectors.ts @@ -18,7 +18,7 @@ import { selectFirstHopSellAccountId, selectLastHopBuyAccountId, selectUserSlippagePercentageDecimal, -} from 'state/slices/swappersSlice/selectors' +} from 'state/slices/tradeInputSlice/selectors' import { getBuyAmountAfterFeesCryptoPrecision, getHopTotalNetworkFeeUserCurrencyPrecision, diff --git a/src/state/store.ts b/src/state/store.ts index 62aa44294b3..0a5309fbf7a 100644 --- a/src/state/store.ts +++ b/src/state/store.ts @@ -64,7 +64,7 @@ export const clearState = () => { store.dispatch(slices.txHistory.actions.clear()) store.dispatch(slices.portfolio.actions.clear()) store.dispatch(slices.opportunities.actions.clear()) - store.dispatch(slices.swappers.actions.clear()) + store.dispatch(slices.tradeInput.actions.clear()) store.dispatch(slices.localWalletSlice.actions.clear()) store.dispatch(apiSlices.assetApi.util.resetApiState()) diff --git a/src/test/mocks/store.ts b/src/test/mocks/store.ts index 4bd9a120164..45c99bea645 100644 --- a/src/test/mocks/store.ts +++ b/src/test/mocks/store.ts @@ -169,7 +169,7 @@ export const mockStore: ReduxState = { ids: [], }, }, - swappers: { + tradeInput: { buyAsset: defaultAsset, sellAsset: defaultAsset, sellAssetAccountId: undefined, From c2d5a8d8dfa94cf3e4155fcea3a1653c1525fc58 Mon Sep 17 00:00:00 2001 From: woodenfurniture <125113430+woodenfurniture@users.noreply.github.com> Date: Thu, 18 Jan 2024 08:40:23 +1100 Subject: [PATCH 5/8] chore: rename trade input selectors to include the word input for clarity --- src/components/FeeExplainer/FeeExplainer.tsx | 4 +-- .../components/FeeModal/FeeBreakdown.tsx | 4 +-- .../components/TradeInput/TradeInput.tsx | 12 +++---- .../components/ManualAddressEntry.tsx | 7 +++-- .../components/TradeQuotes/TradeQuote.tsx | 12 +++---- .../components/TradeQuotes/TradeQuotes.tsx | 4 +-- .../VerifyAddresses/VerifyAddresses.tsx | 8 ++--- .../useGetTradeQuotes/useGetTradeQuotes.tsx | 20 ++++++------ .../hooks/useIsTradingActive.tsx | 6 ++-- .../MultiHopTrade/hooks/useReceiveAddress.tsx | 4 +-- .../swapper/helpers/validateTradeQuote.ts | 4 +-- src/state/apis/swapper/swapperApi.ts | 4 +-- src/state/slices/tradeInputSlice/selectors.ts | 31 +++++++------------ 13 files changed, 57 insertions(+), 63 deletions(-) diff --git a/src/components/FeeExplainer/FeeExplainer.tsx b/src/components/FeeExplainer/FeeExplainer.tsx index ae136da223c..78d44341104 100644 --- a/src/components/FeeExplainer/FeeExplainer.tsx +++ b/src/components/FeeExplainer/FeeExplainer.tsx @@ -26,7 +26,7 @@ import { calculateFees } from 'lib/fees/model' import { FEE_CURVE_MAX_FEE_BPS, FEE_CURVE_NO_FEE_THRESHOLD_USD } from 'lib/fees/parameters' import { isSome } from 'lib/utils' import { selectVotingPower } from 'state/apis/snapshot/selectors' -import { selectSellAmountUsd, selectUserCurrencyToUsdRate } from 'state/slices/selectors' +import { selectInputSellAmountUsd, selectUserCurrencyToUsdRate } from 'state/slices/selectors' import { useAppSelector } from 'state/store' import { CHART_TRADE_SIZE_MAX_USD } from './common' @@ -336,7 +336,7 @@ type FeeExplainerProps = CardProps export const FeeExplainer: React.FC = props => { const votingPower = useAppSelector(selectVotingPower) - const sellAmountUsd = useAppSelector(selectSellAmountUsd) + const sellAmountUsd = useAppSelector(selectInputSellAmountUsd) const [tradeSize, setTradeSize] = useState( sellAmountUsd ? Number.parseFloat(sellAmountUsd) : FEE_CURVE_NO_FEE_THRESHOLD_USD, diff --git a/src/components/MultiHopTrade/components/FeeModal/FeeBreakdown.tsx b/src/components/MultiHopTrade/components/FeeModal/FeeBreakdown.tsx index bdc6d57cb71..f21a5dbcbbd 100644 --- a/src/components/MultiHopTrade/components/FeeModal/FeeBreakdown.tsx +++ b/src/components/MultiHopTrade/components/FeeModal/FeeBreakdown.tsx @@ -7,7 +7,7 @@ import { RawText, Text } from 'components/Text' import { bn, bnOrZero } from 'lib/bignumber/bignumber' import { calculateFees } from 'lib/fees/model' import { selectVotingPower } from 'state/apis/snapshot/selectors' -import { selectSellAmountUsd, selectUserCurrencyToUsdRate } from 'state/slices/selectors' +import { selectInputSellAmountUsd, selectUserCurrencyToUsdRate } from 'state/slices/selectors' import { selectQuoteAffiliateFeeUserCurrency } from 'state/slices/tradeQuoteSlice/selectors' import { useAppSelector } from 'state/store' @@ -16,7 +16,7 @@ const divider = export const FeeBreakdown = () => { const translate = useTranslate() const votingPower = useAppSelector(selectVotingPower) - const sellAmountUsd = useAppSelector(selectSellAmountUsd) + const sellAmountUsd = useAppSelector(selectInputSellAmountUsd) const { foxDiscountUsd, foxDiscountPercent, feeUsdBeforeDiscount, feeBpsBeforeDiscount } = calculateFees({ tradeAmountUsd: bnOrZero(sellAmountUsd), diff --git a/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx b/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx index b6c4afd3574..b103b2607fa 100644 --- a/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/TradeInput.tsx @@ -59,10 +59,10 @@ import { selectTradeQuoteRequestFailed, } from 'state/apis/swapper/selectors' import { - selectBuyAsset, + selectInputBuyAsset, + selectInputSellAmountCryptoPrecision, + selectInputSellAsset, selectManualReceiveAddressIsValidating, - selectSellAmountCryptoPrecision, - selectSellAsset, } from 'state/slices/selectors' import { tradeInput } from 'state/slices/tradeInputSlice/tradeInputSlice' import { @@ -118,8 +118,8 @@ export const TradeInput = memo(() => { const isKeplr = useMemo(() => !!wallet && isKeplrHDWallet(wallet), [wallet]) const buyAssetSearch = useModal('buyAssetSearch') const sellAssetSearch = useModal('sellAssetSearch') - const buyAsset = useAppSelector(selectBuyAsset) - const sellAsset = useAppSelector(selectSellAsset) + const buyAsset = useAppSelector(selectInputBuyAsset) + const sellAsset = useAppSelector(selectInputSellAsset) const percentOptions = useMemo(() => { if (!sellAsset?.assetId) return [] if (!isToken(fromAssetId(sellAsset.assetId).assetReference)) return [] @@ -136,7 +136,7 @@ export const TradeInput = memo(() => { const buyAmountAfterFeesUserCurrency = useAppSelector(selectBuyAmountAfterFeesUserCurrency) const totalNetworkFeeFiatPrecision = useAppSelector(selectTotalNetworkFeeUserCurrencyPrecision) const manualReceiveAddressIsValidating = useAppSelector(selectManualReceiveAddressIsValidating) - const sellAmountCryptoPrecision = useAppSelector(selectSellAmountCryptoPrecision) + const sellAmountCryptoPrecision = useAppSelector(selectInputSellAmountCryptoPrecision) const slippageDecimal = useAppSelector(selectTradeSlippagePercentageDecimal) const activeQuoteErrors = useAppSelector(selectActiveQuoteErrors) const quoteRequestErrors = useAppSelector(selectTradeQuoteRequestErrors) diff --git a/src/components/MultiHopTrade/components/TradeInput/components/ManualAddressEntry.tsx b/src/components/MultiHopTrade/components/TradeInput/components/ManualAddressEntry.tsx index c821bdaa902..97a27218059 100644 --- a/src/components/MultiHopTrade/components/TradeInput/components/ManualAddressEntry.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/components/ManualAddressEntry.tsx @@ -13,7 +13,10 @@ import { useModal } from 'hooks/useModal/useModal' import { useWallet } from 'hooks/useWallet/useWallet' import { useWalletSupportsChain } from 'hooks/useWalletSupportsChain/useWalletSupportsChain' import { parseAddressInputWithChainId } from 'lib/address/address' -import { selectBuyAsset, selectManualReceiveAddress } from 'state/slices/tradeInputSlice/selectors' +import { + selectInputBuyAsset, + selectManualReceiveAddress, +} from 'state/slices/tradeInputSlice/selectors' import { tradeInput } from 'state/slices/tradeInputSlice/tradeInputSlice' import { useAppDispatch, useAppSelector } from 'state/store' @@ -31,7 +34,7 @@ export const ManualAddressEntry: FC = memo((): JSX.Element | null => { const { open: openSnapsModal } = useModal('snaps') const wallet = useWallet().state.wallet - const { chainId: buyAssetChainId, assetId: buyAssetAssetId } = useAppSelector(selectBuyAsset) + const { chainId: buyAssetChainId, assetId: buyAssetAssetId } = useAppSelector(selectInputBuyAsset) const isYatSupportedByReceiveChain = buyAssetChainId === ethChainId // yat only supports eth mainnet const isYatSupported = isYatFeatureEnabled && isYatSupportedByReceiveChain diff --git a/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuote.tsx b/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuote.tsx index 0d3811aa6e0..f851c0840b9 100644 --- a/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuote.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuote.tsx @@ -30,13 +30,13 @@ import { useLocaleFormatter } from 'hooks/useLocaleFormatter/useLocaleFormatter' import { bn, bnOrZero } from 'lib/bignumber/bignumber' import { type ApiQuote, TradeQuoteValidationError } from 'state/apis/swapper' import { - selectBuyAsset, selectFeeAssetByChainId, selectFeeAssetById, + selectInputBuyAsset, + selectInputSellAmountCryptoPrecision, + selectInputSellAsset, selectMarketDataByFilter, selectMarketDataById, - selectSellAmountCryptoPrecision, - selectSellAsset, selectUserSlippagePercentageDecimal, } from 'state/slices/selectors' import { @@ -86,15 +86,15 @@ export const TradeQuoteLoaded: FC = ({ const { isTradingActive } = useIsTradingActive() - const buyAsset = useAppSelector(selectBuyAsset) - const sellAsset = useAppSelector(selectSellAsset) + const buyAsset = useAppSelector(selectInputBuyAsset) + const sellAsset = useAppSelector(selectInputSellAsset) const userSlippagePercentageDecimal = useAppSelector(selectUserSlippagePercentageDecimal) const buyAssetMarketData = useAppSelector(state => selectMarketDataById(state, buyAsset.assetId ?? ''), ) - const sellAmountCryptoPrecision = useAppSelector(selectSellAmountCryptoPrecision) + const sellAmountCryptoPrecision = useAppSelector(selectInputSellAmountCryptoPrecision) // NOTE: don't pull this from the slice - we're not displaying the active quote here const networkFeeUserCurrencyPrecision = useMemo(() => { diff --git a/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuotes.tsx b/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuotes.tsx index 51f4fbcea86..bcf1037f86d 100644 --- a/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuotes.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/components/TradeQuotes/TradeQuotes.tsx @@ -10,7 +10,7 @@ import { useIsSnapInstalled } from 'hooks/useIsSnapInstalled/useIsSnapInstalled' import { useWallet } from 'hooks/useWallet/useWallet' import { useWalletSupportsChain } from 'hooks/useWalletSupportsChain/useWalletSupportsChain' import type { ApiQuote } from 'state/apis/swapper' -import { selectBuyAsset } from 'state/slices/selectors' +import { selectInputBuyAsset } from 'state/slices/selectors' import { selectActiveQuoteIndex } from 'state/slices/tradeQuoteSlice/selectors' import { useAppSelector } from 'state/store' @@ -26,7 +26,7 @@ const arrowDownIcon = export const TradeQuotes: React.FC = memo( ({ sortedQuotes: _sortedQuotes, isLoading }) => { const wallet = useWallet().state.wallet - const { chainId: buyAssetChainId } = useAppSelector(selectBuyAsset) + const { chainId: buyAssetChainId } = useAppSelector(selectInputBuyAsset) const isSnapInstalled = useIsSnapInstalled() const walletSupportsBuyAssetChain = useWalletSupportsChain({ chainId: buyAssetChainId, diff --git a/src/components/MultiHopTrade/components/VerifyAddresses/VerifyAddresses.tsx b/src/components/MultiHopTrade/components/VerifyAddresses/VerifyAddresses.tsx index 1bd3b0a0312..46fcbaadd9f 100644 --- a/src/components/MultiHopTrade/components/VerifyAddresses/VerifyAddresses.tsx +++ b/src/components/MultiHopTrade/components/VerifyAddresses/VerifyAddresses.tsx @@ -30,10 +30,10 @@ import { getChainAdapterManager } from 'context/PluginProvider/chainAdapterSingl import { useWallet } from 'hooks/useWallet/useWallet' import { walletSupportsChain } from 'hooks/useWalletSupportsChain/useWalletSupportsChain' import { - selectBuyAsset, + selectInputBuyAsset, + selectInputSellAsset, selectManualReceiveAddress, selectPortfolioAccountMetadataByAccountId, - selectSellAsset, } from 'state/slices/selectors' import { selectFirstHop } from 'state/slices/tradeQuoteSlice/selectors' import { useAppSelector } from 'state/store' @@ -52,8 +52,8 @@ export const VerifyAddresses = () => { const [verifiedAddresses, setVerifiedAddresses] = useState(new Set()) - const buyAsset = useAppSelector(selectBuyAsset) - const sellAsset = useAppSelector(selectSellAsset) + const buyAsset = useAppSelector(selectInputBuyAsset) + const sellAsset = useAppSelector(selectInputSellAsset) const tradeQuoteStep = useAppSelector(selectFirstHop) const { sellAssetAccountId, buyAssetAccountId } = useAccountIds() diff --git a/src/components/MultiHopTrade/hooks/useGetTradeQuotes/useGetTradeQuotes.tsx b/src/components/MultiHopTrade/hooks/useGetTradeQuotes/useGetTradeQuotes.tsx index 9269df6335d..33a7222c3eb 100644 --- a/src/components/MultiHopTrade/hooks/useGetTradeQuotes/useGetTradeQuotes.tsx +++ b/src/components/MultiHopTrade/hooks/useGetTradeQuotes/useGetTradeQuotes.tsx @@ -24,13 +24,13 @@ import { useGetTradeQuoteQuery, } from 'state/apis/swapper/swapperApi' import { - selectBuyAsset, selectFirstHopSellAccountId, + selectInputBuyAsset, + selectInputSellAmountCryptoPrecision, + selectInputSellAmountUsd, + selectInputSellAsset, selectLastHopBuyAccountId, selectPortfolioAccountMetadataByAccountId, - selectSellAmountCryptoPrecision, - selectSellAmountUsd, - selectSellAsset, selectUsdRateByAssetId, selectUserSlippagePercentageDecimal, } from 'state/slices/selectors' @@ -61,9 +61,9 @@ type GetMixPanelDataFromApiQuotesReturn = { const getMixPanelDataFromApiQuotes = (quotes: ApiQuote[]): GetMixPanelDataFromApiQuotesReturn => { const bestInputOutputRatio = quotes[0]?.inputOutputRatio const state = store.getState() - const { assetId: sellAssetId, chainId: sellAssetChainId } = selectSellAsset(state) - const { assetId: buyAssetId, chainId: buyAssetChainId } = selectBuyAsset(state) - const sellAmountUsd = selectSellAmountUsd(state) + const { assetId: sellAssetId, chainId: sellAssetChainId } = selectInputSellAsset(state) + const { assetId: buyAssetId, chainId: buyAssetChainId } = selectInputBuyAsset(state) + const sellAmountUsd = selectInputSellAmountUsd(state) const quoteMeta: MixPanelQuoteMeta[] = quotes .map(({ quote, errors, swapperName, inputOutputRatio }) => { const differenceFromBestQuoteDecimalPercentage = @@ -127,8 +127,8 @@ export const useGetTradeQuotes = () => { const previousTradeQuoteInput = usePrevious(tradeQuoteInput) const isTradeQuoteUpdated = tradeQuoteInput !== previousTradeQuoteInput const [hasFocus, setHasFocus] = useState(document.hasFocus()) - const sellAsset = useAppSelector(selectSellAsset) - const buyAsset = useAppSelector(selectBuyAsset) + const sellAsset = useAppSelector(selectInputSellAsset) + const buyAsset = useAppSelector(selectInputBuyAsset) const useReceiveAddressArgs = useMemo( () => ({ fetchUnchainedAddress: Boolean(wallet && isLedger(wallet)), @@ -136,7 +136,7 @@ export const useGetTradeQuotes = () => { [wallet], ) const receiveAddress = useReceiveAddress(useReceiveAddressArgs) - const sellAmountCryptoPrecision = useAppSelector(selectSellAmountCryptoPrecision) + const sellAmountCryptoPrecision = useAppSelector(selectInputSellAmountCryptoPrecision) const debouncedSellAmountCryptoPrecision = useDebounce(sellAmountCryptoPrecision, 500) const isDebouncing = debouncedSellAmountCryptoPrecision !== sellAmountCryptoPrecision diff --git a/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx b/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx index 9c59592d708..123e08ca80d 100644 --- a/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx +++ b/src/components/MultiHopTrade/hooks/useIsTradingActive.tsx @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react' import type { ThorEvmTradeQuote } from 'lib/swapper/swappers/ThorchainSwapper/getThorTradeQuote/getTradeQuote' import { TradeType } from 'lib/swapper/swappers/ThorchainSwapper/utils/longTailHelpers' import { swapperApi } from 'state/apis/swapper/swapperApi' -import { selectBuyAsset, selectSellAsset } from 'state/slices/tradeInputSlice/selectors' +import { selectInputBuyAsset, selectInputSellAsset } from 'state/slices/tradeInputSlice/selectors' import { selectActiveQuote, selectActiveSwapperName } from 'state/slices/tradeQuoteSlice/selectors' import { useAppDispatch, useAppSelector } from 'state/store' @@ -15,8 +15,8 @@ export const useIsTradingActive = () => { const dispatch = useAppDispatch() - const buyAssetId = useAppSelector(selectBuyAsset).assetId - const sellAssetId = useAppSelector(selectSellAsset).assetId + const buyAssetId = useAppSelector(selectInputBuyAsset).assetId + const sellAssetId = useAppSelector(selectInputSellAsset).assetId const { getIsTradingActive } = swapperApi.endpoints const swapperName = useAppSelector(selectActiveSwapperName) diff --git a/src/components/MultiHopTrade/hooks/useReceiveAddress.tsx b/src/components/MultiHopTrade/hooks/useReceiveAddress.tsx index 4c2e46522bb..adb1bd579d8 100644 --- a/src/components/MultiHopTrade/hooks/useReceiveAddress.tsx +++ b/src/components/MultiHopTrade/hooks/useReceiveAddress.tsx @@ -7,7 +7,7 @@ import { useWallet } from 'hooks/useWallet/useWallet' import { selectPortfolioAccountMetadataByAccountId } from 'state/slices/portfolioSlice/selectors' import { isUtxoAccountId } from 'state/slices/portfolioSlice/utils' import { - selectBuyAsset, + selectInputBuyAsset, selectLastHopBuyAccountId, selectManualReceiveAddress, } from 'state/slices/tradeInputSlice/selectors' @@ -37,7 +37,7 @@ export const useReceiveAddress = ({ const [receiveAddress, setReceiveAddress] = useState(undefined) // Selectors - const buyAsset = useAppSelector(selectBuyAsset) + const buyAsset = useAppSelector(selectInputBuyAsset) const buyAccountId = useAppSelector(selectLastHopBuyAccountId) const buyAccountMetadata = useAppSelector(state => selectPortfolioAccountMetadataByAccountId(state, { accountId: buyAccountId }), diff --git a/src/state/apis/swapper/helpers/validateTradeQuote.ts b/src/state/apis/swapper/helpers/validateTradeQuote.ts index 53ebae60bb1..d0e52eba3ed 100644 --- a/src/state/apis/swapper/helpers/validateTradeQuote.ts +++ b/src/state/apis/swapper/helpers/validateTradeQuote.ts @@ -19,8 +19,8 @@ import { selectAssets, selectFeeAssetById, selectFirstHopSellAccountId, + selectInputSellAmountCryptoPrecision, selectPortfolioAccountIdByNumberByChainId, - selectSellAmountCryptoPrecision, } from 'state/slices/selectors' import { getTotalProtocolFeeByAssetForStep } from 'state/slices/tradeQuoteSlice/helpers' import { @@ -109,7 +109,7 @@ export const validateTradeQuote = async ( const secondHop = quote.steps[1] const lastHop = isMultiHopTrade ? secondHop : firstHop const walletSupportedChainIds = selectWalletSupportedChainIds(state) - const sellAmountCryptoPrecision = selectSellAmountCryptoPrecision(state) + const sellAmountCryptoPrecision = selectInputSellAmountCryptoPrecision(state) const sellAmountCryptoBaseUnit = selectSellAmountCryptoBaseUnit(state) const buyAmountCryptoBaseUnit = lastHop.buyAmountBeforeFeesCryptoBaseUnit diff --git a/src/state/apis/swapper/swapperApi.ts b/src/state/apis/swapper/swapperApi.ts index 5c2e0278f49..b1334e72fdd 100644 --- a/src/state/apis/swapper/swapperApi.ts +++ b/src/state/apis/swapper/swapperApi.ts @@ -27,8 +27,8 @@ import type { FeatureFlags } from 'state/slices/preferencesSlice/preferencesSlic import { selectFeatureFlags } from 'state/slices/preferencesSlice/selectors' import { selectFirstHopSellAccountId, + selectInputSellAsset, selectManualReceiveAddress, - selectSellAsset, } from 'state/slices/tradeInputSlice/selectors' import { tradeQuoteSlice } from 'state/slices/tradeQuoteSlice/tradeQuoteSlice' @@ -257,7 +257,7 @@ export const swapperApi = _swapperApi.injectEndpoints({ const featureFlags = selectFeatureFlags(state) const enabledSwappers = getEnabledSwappers(featureFlags, false) const assets = selectAssets(state) - const sellAsset = selectSellAsset(state) + const sellAsset = selectInputSellAsset(state) const supportedSellAssetsSet = await getSupportedSellAssetIds(enabledSwappers, assets) const supportedSellAssetIds = sortedAssetIds diff --git a/src/state/slices/tradeInputSlice/selectors.ts b/src/state/slices/tradeInputSlice/selectors.ts index 22c0ced09a0..9b11c7b060a 100644 --- a/src/state/slices/tradeInputSlice/selectors.ts +++ b/src/state/slices/tradeInputSlice/selectors.ts @@ -14,12 +14,12 @@ import { const selectTradeInput = (state: ReduxState) => state.tradeInput -export const selectBuyAsset = createDeepEqualOutputSelector( +export const selectInputBuyAsset = createDeepEqualOutputSelector( selectTradeInput, tradeInput => tradeInput.buyAsset, ) -export const selectSellAsset = createDeepEqualOutputSelector( +export const selectInputSellAsset = createDeepEqualOutputSelector( selectTradeInput, tradeInput => tradeInput.sellAsset, ) @@ -37,7 +37,7 @@ export const selectUserSlippagePercentageDecimal: Selector { @@ -55,10 +55,10 @@ export const selectFirstHopSellAccountId = createSelector( }, ) -// selects the account ID we're buying into for the first hop +// selects the account ID we're buying into for the last hop export const selectLastHopBuyAccountId = createSelector( selectTradeInput, - selectBuyAsset, + selectInputBuyAsset, selectPortfolioAssetAccountBalancesSortedUserCurrency, selectWalletAccountIds, (tradeInput, buyAsset, accountIdAssetValues, accountIds) => { @@ -76,13 +76,13 @@ export const selectLastHopBuyAccountId = createSelector( }, ) -export const selectSellAmountCryptoPrecision = createSelector( +export const selectInputSellAmountCryptoPrecision = createSelector( selectTradeInput, tradeInput => tradeInput.sellAmountCryptoPrecision, ) -export const selectSellAssetUsdRate = createSelector( - selectSellAsset, +export const selectInputSellAssetUsdRate = createSelector( + selectInputSellAsset, selectCryptoMarketData, (sellAsset, cryptoMarketData) => { const sellAssetMarketData = cryptoMarketData[sellAsset.assetId] @@ -90,15 +90,6 @@ export const selectSellAssetUsdRate = createSelector( }, ) -export const selectBuyAssetUsdRate = createSelector( - selectBuyAsset, - selectCryptoMarketData, - (buyAsset, cryptoMarketData) => { - const buyAssetMarketData = cryptoMarketData[buyAsset.assetId] - return buyAssetMarketData?.price - }, -) - export const selectManualReceiveAddress = createSelector( selectTradeInput, tradeInput => tradeInput.manualReceiveAddress, @@ -109,9 +100,9 @@ export const selectManualReceiveAddressIsValidating = createSelector( tradeInput => tradeInput.manualReceiveAddressIsValidating, ) -export const selectSellAmountUsd = createSelector( - selectSellAmountCryptoPrecision, - selectSellAssetUsdRate, +export const selectInputSellAmountUsd = createSelector( + selectInputSellAmountCryptoPrecision, + selectInputSellAssetUsdRate, (sellAmountCryptoPrecision, sellAssetUsdRate) => { if (!sellAssetUsdRate) return return bn(sellAmountCryptoPrecision).times(sellAssetUsdRate).toFixed() From 3d518b03491ada2455840a7444adfcf7022e7fde Mon Sep 17 00:00:00 2001 From: woodenfurniture <125113430+woodenfurniture@users.noreply.github.com> Date: Thu, 18 Jan 2024 09:07:17 +1100 Subject: [PATCH 6/8] chore: cleaned up and improved naming of trade selectors --- .../components/Footer.tsx | 4 +- .../hooks/useIsApprovalInitiallyNeeded.tsx | 3 +- .../components/TradeConfirm/TradeConfirm.tsx | 8 +- .../components/TradeSuccess/TradeSuccess.tsx | 4 +- src/components/MultiHopTrade/helpers.ts | 12 +- .../hooks/quoteValidation/usePriceImpact.tsx | 4 +- .../MultiHopTrade/hooks/useHopHelper.tsx | 60 ------ .../swapper/helpers/validateTradeQuote.ts | 7 +- src/state/slices/tradeInputSlice/selectors.ts | 52 ++++- src/state/slices/tradeQuoteSlice/selectors.ts | 185 ++---------------- 10 files changed, 82 insertions(+), 257 deletions(-) delete mode 100644 src/components/MultiHopTrade/hooks/useHopHelper.tsx diff --git a/src/components/MultiHopTrade/components/MultiHopTradeConfirm/components/Footer.tsx b/src/components/MultiHopTrade/components/MultiHopTradeConfirm/components/Footer.tsx index 612a6977336..3412f6e5cd2 100644 --- a/src/components/MultiHopTrade/components/MultiHopTradeConfirm/components/Footer.tsx +++ b/src/components/MultiHopTrade/components/MultiHopTradeConfirm/components/Footer.tsx @@ -19,7 +19,7 @@ import { bnOrZero } from 'lib/bignumber/bignumber' import { selectActiveSwapperName, selectLastHopBuyAsset, - selectSellAmountUserCurrency, + selectQuoteSellAmountUserCurrency, selectTotalNetworkFeeUserCurrencyPrecision, selectTradeExecutionState, } from 'state/slices/tradeQuoteSlice/selectors' @@ -34,7 +34,7 @@ export const Footer = () => { const lastHopBuyAsset = useAppSelector(selectLastHopBuyAsset) const tradeExecutionState = useAppSelector(selectTradeExecutionState) const networkFeeUserCurrency = useAppSelector(selectTotalNetworkFeeUserCurrencyPrecision) - const sellAmountBeforeFeesUserCurrency = useAppSelector(selectSellAmountUserCurrency) + const sellAmountBeforeFeesUserCurrency = useAppSelector(selectQuoteSellAmountUserCurrency) const { isModeratePriceImpact } = usePriceImpact() const handleConfirm = useCallback(() => { diff --git a/src/components/MultiHopTrade/components/MultiHopTradeConfirm/hooks/useIsApprovalInitiallyNeeded.tsx b/src/components/MultiHopTrade/components/MultiHopTradeConfirm/hooks/useIsApprovalInitiallyNeeded.tsx index 3c19c729156..159b7a916e0 100644 --- a/src/components/MultiHopTrade/components/MultiHopTradeConfirm/hooks/useIsApprovalInitiallyNeeded.tsx +++ b/src/components/MultiHopTrade/components/MultiHopTradeConfirm/hooks/useIsApprovalInitiallyNeeded.tsx @@ -2,12 +2,11 @@ import type { AccountId } from '@shapeshiftoss/caip' import { isEvmChainId } from '@shapeshiftoss/chain-adapters' import type { TradeQuoteStep } from '@shapeshiftoss/swapper' import { useEffect, useMemo, useState } from 'react' -import { selectFirstHopSellAccountId } from 'state/slices/selectors' +import { selectFirstHopSellAccountId, selectSecondHopSellAccountId } from 'state/slices/selectors' import { selectFirstHop, selectIsActiveQuoteMultiHop, selectSecondHop, - selectSecondHopSellAccountId, } from 'state/slices/tradeQuoteSlice/selectors' import { tradeQuoteSlice } from 'state/slices/tradeQuoteSlice/tradeQuoteSlice' import { useAppDispatch, useAppSelector } from 'state/store' diff --git a/src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx b/src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx index cb8ce3f007a..f0a84010f76 100644 --- a/src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx +++ b/src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx @@ -65,8 +65,8 @@ import { selectFirstHopSellFeeAsset, selectLastHop, selectLastHopBuyAsset, - selectSellAmountBeforeFeesCryptoPrecision, - selectSellAmountUserCurrency, + selectQuoteSellAmountBeforeFeesCryptoPrecision, + selectQuoteSellAmountUserCurrency, selectTotalNetworkFeeUserCurrencyPrecision, selectTradeSlippagePercentageDecimal, } from 'state/slices/tradeQuoteSlice/selectors' @@ -137,14 +137,14 @@ export const TradeConfirm = () => { const buyAmountAfterFeesCryptoPrecision = useAppSelector(selectBuyAmountAfterFeesCryptoPrecision) const slippageDecimal = useAppSelector(selectTradeSlippagePercentageDecimal) const netBuyAmountUserCurrency = useAppSelector(selectBuyAmountAfterFeesUserCurrency) - const sellAmountBeforeFeesUserCurrency = useAppSelector(selectSellAmountUserCurrency) + const sellAmountBeforeFeesUserCurrency = useAppSelector(selectQuoteSellAmountUserCurrency) const networkFeeCryptoHuman = useAppSelector(selectFirstHopNetworkFeeCryptoPrecision) const networkFeeUserCurrency = useAppSelector(selectTotalNetworkFeeUserCurrencyPrecision) const buyAmountBeforeFeesCryptoPrecision = useAppSelector( selectBuyAmountBeforeFeesCryptoPrecision, ) const sellAmountBeforeFeesCryptoPrecision = useAppSelector( - selectSellAmountBeforeFeesCryptoPrecision, + selectQuoteSellAmountBeforeFeesCryptoPrecision, ) const sellAsset = useAppSelector(selectFirstHopSellAsset) diff --git a/src/components/MultiHopTrade/components/TradeSuccess/TradeSuccess.tsx b/src/components/MultiHopTrade/components/TradeSuccess/TradeSuccess.tsx index cd822c60704..defac8fb2dc 100644 --- a/src/components/MultiHopTrade/components/TradeSuccess/TradeSuccess.tsx +++ b/src/components/MultiHopTrade/components/TradeSuccess/TradeSuccess.tsx @@ -15,8 +15,8 @@ import { SlideTransition } from 'components/SlideTransition' import { RawText } from 'components/Text' import { getChainAdapterManager } from 'context/PluginProvider/chainAdapterSingleton' import { useLocaleFormatter } from 'hooks/useLocaleFormatter/useLocaleFormatter' -import { selectEquityTotalBalance } from 'state/slices/selectors' -import { selectLastHop, selectLastHopSellAccountId } from 'state/slices/tradeQuoteSlice/selectors' +import { selectEquityTotalBalance, selectLastHopSellAccountId } from 'state/slices/selectors' +import { selectLastHop } from 'state/slices/tradeQuoteSlice/selectors' import { useAppSelector } from 'state/store' import { TwirlyToggle } from '../TwirlyToggle' diff --git a/src/components/MultiHopTrade/helpers.ts b/src/components/MultiHopTrade/helpers.ts index 735134b9646..dbc2480a542 100644 --- a/src/components/MultiHopTrade/helpers.ts +++ b/src/components/MultiHopTrade/helpers.ts @@ -9,9 +9,9 @@ import { selectLastHopBuyAsset, selectQuoteAffiliateFeeUserCurrency, selectQuoteFeeAmountUsd, - selectSellAmountBeforeFeesCryptoPrecision, - selectSellAmountUsd, - selectSellAmountUserCurrency, + selectQuoteSellAmountBeforeFeesCryptoPrecision, + selectQuoteSellAmountUsd, + selectQuoteSellAmountUserCurrency, } from 'state/slices/tradeQuoteSlice/selectors' import { store } from 'state/store' @@ -30,10 +30,10 @@ export const getMixpanelEventData = () => { const assets = selectAssets(state) const shapeShiftFeeUserCurrency = selectQuoteAffiliateFeeUserCurrency(state) const shapeshiftFeeUsd = selectQuoteFeeAmountUsd(state) - const sellAmountBeforeFeesUsd = selectSellAmountUsd(state) - const sellAmountBeforeFeesUserCurrency = selectSellAmountUserCurrency(state) + const sellAmountBeforeFeesUsd = selectQuoteSellAmountUsd(state) + const sellAmountBeforeFeesUserCurrency = selectQuoteSellAmountUserCurrency(state) const buyAmountBeforeFeesCryptoPrecision = selectBuyAmountBeforeFeesCryptoPrecision(state) - const sellAmountBeforeFeesCryptoPrecision = selectSellAmountBeforeFeesCryptoPrecision(state) + const sellAmountBeforeFeesCryptoPrecision = selectQuoteSellAmountBeforeFeesCryptoPrecision(state) const swapperName = selectActiveSwapperName(state) const activeQuote = selectActiveQuote(state) diff --git a/src/components/MultiHopTrade/hooks/quoteValidation/usePriceImpact.tsx b/src/components/MultiHopTrade/hooks/quoteValidation/usePriceImpact.tsx index bd8e23c6274..29d14a6e9d4 100644 --- a/src/components/MultiHopTrade/hooks/quoteValidation/usePriceImpact.tsx +++ b/src/components/MultiHopTrade/hooks/quoteValidation/usePriceImpact.tsx @@ -2,13 +2,13 @@ import { useMemo } from 'react' import { bn } from 'lib/bignumber/bignumber' import { selectBuyAmountBeforeFeesUserCurrency, - selectSellAmountUserCurrency, + selectQuoteSellAmountUserCurrency, } from 'state/slices/tradeQuoteSlice/selectors' import { useAppSelector } from 'state/store' export const usePriceImpact = () => { const buyAmountBeforeFeesUserCurrency = useAppSelector(selectBuyAmountBeforeFeesUserCurrency) - const sellAmountBeforeFeesUserCurrency = useAppSelector(selectSellAmountUserCurrency) + const sellAmountBeforeFeesUserCurrency = useAppSelector(selectQuoteSellAmountUserCurrency) const priceImpactPercentage = useMemo(() => { if (!sellAmountBeforeFeesUserCurrency || !buyAmountBeforeFeesUserCurrency) return bn('0') diff --git a/src/components/MultiHopTrade/hooks/useHopHelper.tsx b/src/components/MultiHopTrade/hooks/useHopHelper.tsx deleted file mode 100644 index 16ff901ef2e..00000000000 --- a/src/components/MultiHopTrade/hooks/useHopHelper.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { useMemo } from 'react' -import { - selectPortfolioCryptoBalanceBaseUnitByFilter, - selectPortfolioCryptoPrecisionBalanceByFilter, -} from 'state/slices/common-selectors' -import { selectFirstHopSellAccountId } from 'state/slices/selectors' -import { - selectFirstHopSellAsset, - selectFirstHopSellFeeAsset, - selectSecondHopSellAccountId, - selectSecondHopSellFeeAsset, -} from 'state/slices/tradeQuoteSlice/selectors' -import { useAppSelector } from 'state/store' - -export const useHopHelper = () => { - const firstHopSellAsset = useAppSelector(selectFirstHopSellAsset) - - // the network fee asset for the first hop in the trade - const firstHopSellFeeAsset = useAppSelector(selectFirstHopSellFeeAsset) - - // the network fee asset for the second hop in the trade - const secondHopSellFeeAsset = useAppSelector(selectSecondHopSellFeeAsset) - - // this is the account we're selling from - network fees are paid from the sell account for the current hop - const firstHopSellAccountId = useAppSelector(selectFirstHopSellAccountId) - const secondHopSellAccountId = useAppSelector(selectSecondHopSellAccountId) - - const firstHopFeeAssetBalanceFilter = useMemo( - () => ({ assetId: firstHopSellFeeAsset?.assetId, accountId: firstHopSellAccountId ?? '' }), - [firstHopSellAccountId, firstHopSellFeeAsset?.assetId], - ) - - const secondHopFeeAssetBalanceFilter = useMemo( - () => ({ assetId: secondHopSellFeeAsset?.assetId, accountId: secondHopSellAccountId ?? '' }), - [secondHopSellAccountId, secondHopSellFeeAsset?.assetId], - ) - - const firstHopFeeAssetBalancePrecision = useAppSelector(s => - selectPortfolioCryptoPrecisionBalanceByFilter(s, firstHopFeeAssetBalanceFilter), - ) - - const secondHopFeeAssetBalancePrecision = useAppSelector(s => - selectPortfolioCryptoPrecisionBalanceByFilter(s, secondHopFeeAssetBalanceFilter), - ) - - const sellAssetBalanceFilter = useMemo( - () => ({ accountId: firstHopSellAccountId, assetId: firstHopSellAsset?.assetId ?? '' }), - [firstHopSellAccountId, firstHopSellAsset?.assetId], - ) - - const sellAssetBalanceCryptoBaseUnit = useAppSelector(state => - selectPortfolioCryptoBalanceBaseUnitByFilter(state, sellAssetBalanceFilter), - ) - - return { - sellAssetBalanceCryptoBaseUnit, - firstHopFeeAssetBalancePrecision, - secondHopFeeAssetBalancePrecision, - } -} diff --git a/src/state/apis/swapper/helpers/validateTradeQuote.ts b/src/state/apis/swapper/helpers/validateTradeQuote.ts index d0e52eba3ed..aabb3f51c72 100644 --- a/src/state/apis/swapper/helpers/validateTradeQuote.ts +++ b/src/state/apis/swapper/helpers/validateTradeQuote.ts @@ -21,12 +21,9 @@ import { selectFirstHopSellAccountId, selectInputSellAmountCryptoPrecision, selectPortfolioAccountIdByNumberByChainId, + selectSecondHopSellAccountId, } from 'state/slices/selectors' import { getTotalProtocolFeeByAssetForStep } from 'state/slices/tradeQuoteSlice/helpers' -import { - selectSecondHopSellAccountId, - selectSellAmountCryptoBaseUnit, -} from 'state/slices/tradeQuoteSlice/selectors' import type { ErrorWithMeta } from '../types' import { type TradeQuoteError, TradeQuoteValidationError, TradeQuoteWarning } from '../types' @@ -110,7 +107,7 @@ export const validateTradeQuote = async ( const lastHop = isMultiHopTrade ? secondHop : firstHop const walletSupportedChainIds = selectWalletSupportedChainIds(state) const sellAmountCryptoPrecision = selectInputSellAmountCryptoPrecision(state) - const sellAmountCryptoBaseUnit = selectSellAmountCryptoBaseUnit(state) + const sellAmountCryptoBaseUnit = firstHop.sellAmountIncludingProtocolFeesCryptoBaseUnit const buyAmountCryptoBaseUnit = lastHop.buyAmountBeforeFeesCryptoBaseUnit // the network fee asset for the first hop in the trade diff --git a/src/state/slices/tradeInputSlice/selectors.ts b/src/state/slices/tradeInputSlice/selectors.ts index 9b11c7b060a..07dc69dba73 100644 --- a/src/state/slices/tradeInputSlice/selectors.ts +++ b/src/state/slices/tradeInputSlice/selectors.ts @@ -5,7 +5,7 @@ import type { ReduxState } from 'state/reducer' import { createDeepEqualOutputSelector } from 'state/selector-utils' import { selectWalletAccountIds } from '../common-selectors' -import { selectCryptoMarketData } from '../marketDataSlice/selectors' +import { selectCryptoMarketData, selectUserCurrencyToUsdRate } from '../marketDataSlice/selectors' import { selectPortfolioAssetAccountBalancesSortedUserCurrency } from '../portfolioSlice/selectors' import { getFirstAccountIdByChainId, @@ -24,6 +24,42 @@ export const selectInputSellAsset = createDeepEqualOutputSelector( tradeInput => tradeInput.sellAsset, ) +export const selectInputSellAssetUsdRate = createSelector( + selectInputSellAsset, + selectCryptoMarketData, + (sellAsset, cryptoMarketDataById) => { + if (sellAsset === undefined) return + return cryptoMarketDataById[sellAsset.assetId]?.price + }, +) + +export const selectInputBuyAssetUsdRate = createSelector( + selectInputBuyAsset, + selectCryptoMarketData, + (buyAsset, cryptoMarketDataById) => { + if (buyAsset === undefined) return + return cryptoMarketDataById[buyAsset.assetId]?.price + }, +) + +export const selectInputSellAssetUserCurrencyRate = createSelector( + selectInputSellAssetUsdRate, + selectUserCurrencyToUsdRate, + (sellAssetUsdRate, userCurrencyToUsdRate) => { + if (sellAssetUsdRate === undefined) return + return bn(sellAssetUsdRate).times(userCurrencyToUsdRate).toString() + }, +) + +export const selectInputBuyAssetUserCurrencyRate = createSelector( + selectInputBuyAssetUsdRate, + selectUserCurrencyToUsdRate, + (buyAssetUsdRate, userCurrencyToUsdRate) => { + if (buyAssetUsdRate === undefined) return + return bn(buyAssetUsdRate).times(userCurrencyToUsdRate).toString() + }, +) + export const selectUserSlippagePercentage: Selector = createSelector(selectTradeInput, tradeInput => tradeInput.slippagePreferencePercentage) @@ -55,6 +91,11 @@ export const selectFirstHopSellAccountId = createSelector( }, ) +// selects the account ID we're selling from for the other hops +// for posterity, every hop always sells from the same account as the first hop +export const selectSecondHopSellAccountId = selectFirstHopSellAccountId +export const selectLastHopSellAccountId = selectFirstHopSellAccountId + // selects the account ID we're buying into for the last hop export const selectLastHopBuyAccountId = createSelector( selectTradeInput, @@ -81,15 +122,6 @@ export const selectInputSellAmountCryptoPrecision = createSelector( tradeInput => tradeInput.sellAmountCryptoPrecision, ) -export const selectInputSellAssetUsdRate = createSelector( - selectInputSellAsset, - selectCryptoMarketData, - (sellAsset, cryptoMarketData) => { - const sellAssetMarketData = cryptoMarketData[sellAsset.assetId] - return sellAssetMarketData?.price - }, -) - export const selectManualReceiveAddress = createSelector( selectTradeInput, tradeInput => tradeInput.manualReceiveAddress, diff --git a/src/state/slices/tradeQuoteSlice/selectors.ts b/src/state/slices/tradeQuoteSlice/selectors.ts index 8cf281260a8..3df590551bf 100644 --- a/src/state/slices/tradeQuoteSlice/selectors.ts +++ b/src/state/slices/tradeQuoteSlice/selectors.ts @@ -16,7 +16,10 @@ import { createDeepEqualOutputSelector } from 'state/selector-utils' import { selectFeeAssetById } from 'state/slices/assetsSlice/selectors' import { selectFirstHopSellAccountId, - selectLastHopBuyAccountId, + selectInputBuyAssetUserCurrencyRate, + selectInputSellAssetUsdRate, + selectInputSellAssetUserCurrencyRate, + selectSecondHopSellAccountId, selectUserSlippagePercentageDecimal, } from 'state/slices/tradeInputSlice/selectors' import { @@ -25,17 +28,13 @@ import { getHopTotalProtocolFeesFiatPrecision, getTotalProtocolFeeByAsset, } from 'state/slices/tradeQuoteSlice/helpers' -import { - convertBasisPointsToDecimalPercentage, - sumProtocolFeesToDenom, -} from 'state/slices/tradeQuoteSlice/utils' +import { convertBasisPointsToDecimalPercentage } from 'state/slices/tradeQuoteSlice/utils' import { selectCryptoMarketData, selectSelectedCurrencyMarketDataSortedByMarketCap, selectUserCurrencyToUsdRate, } from '../marketDataSlice/selectors' -import { selectAccountIdByAccountNumberAndChainId } from '../portfolioSlice/selectors' const selectTradeQuoteSlice = (state: ReduxState) => state.tradeQuoteSlice @@ -191,7 +190,7 @@ export const selectLastHopSellAsset: Selector = export const selectLastHopBuyAsset: Selector = createDeepEqualOutputSelector(selectLastHop, lastHop => (lastHop ? lastHop.buyAsset : undefined)) -export const selectSellAmountCryptoBaseUnit: Selector = +export const selectQuoteSellAmountCryptoBaseUnit: Selector = createSelector(selectFirstHop, firstHop => firstHop ? firstHop.sellAmountIncludingProtocolFeesCryptoBaseUnit : undefined, ) @@ -203,10 +202,10 @@ export const selectIsUnsafeActiveQuote: Selector = createSe }, ) -export const selectSellAmountCryptoPrecision: Selector = +export const selectQuoteSellAmountCryptoPrecision: Selector = createSelector( selectFirstHopSellAsset, - selectSellAmountCryptoBaseUnit, + selectQuoteSellAmountCryptoBaseUnit, (firstHopSellAsset, sellAmountCryptoBaseUnit) => firstHopSellAsset ? fromBaseUnit(bnOrZero(sellAmountCryptoBaseUnit), firstHopSellAsset?.precision) @@ -237,7 +236,7 @@ export const selectFirstHopTradeDeductionCryptoPrecision: Selector firstHopSellFeeAsset?.assetId === firstHopSellAsset?.assetId ? bnOrZero(sellAmountCryptoPrecision).toFixed() @@ -380,59 +379,7 @@ export const selectTradeSlippagePercentageDecimal: Selector }, ) -const selectSellAssetUsdRate = createSelector( - selectFirstHopSellAsset, - selectCryptoMarketData, - (sellAsset, cryptoMarketDataById) => { - if (sellAsset === undefined) return - return cryptoMarketDataById[sellAsset.assetId]?.price - }, -) - -const selectBuyAssetUsdRate = createSelector( - selectLastHopBuyAsset, - selectCryptoMarketData, - (buyAsset, cryptoMarketDataById) => { - if (buyAsset === undefined) return - return cryptoMarketDataById[buyAsset.assetId]?.price - }, -) - -const selectSellAssetUserCurrencyRate = createSelector( - selectSellAssetUsdRate, - selectUserCurrencyToUsdRate, - (sellAssetUsdRate, userCurrencyToUsdRate) => { - if (sellAssetUsdRate === undefined) return - return bn(sellAssetUsdRate).times(userCurrencyToUsdRate).toString() - }, -) - -const selectBuyAssetUserCurrencyRate = createSelector( - selectBuyAssetUsdRate, - selectUserCurrencyToUsdRate, - (buyAssetUsdRate, userCurrencyToUsdRate) => { - if (buyAssetUsdRate === undefined) return - return bn(buyAssetUsdRate).times(userCurrencyToUsdRate).toString() - }, -) - -export const selectTotalTradeFeeBuyAssetBaseUnit = createSelector( - selectLastHop, - selectCryptoMarketData, - selectBuyAssetUsdRate, - (lastHop, cryptoMarketDataById, buyAssetUsdRate) => { - if (!lastHop || !buyAssetUsdRate) return '0' - - return sumProtocolFeesToDenom({ - cryptoMarketDataById, - protocolFees: lastHop.feeData.protocolFees, - outputAssetPriceUsd: buyAssetUsdRate, - outputExponent: lastHop.buyAsset.precision, - }) - }, -) - -export const selectSellAmountIncludingProtocolFeesCryptoBaseUnit = createSelector( +export const selectQuoteSellAmountIncludingProtocolFeesCryptoBaseUnit = createSelector( selectFirstHop, firstHop => firstHop?.sellAmountIncludingProtocolFeesCryptoBaseUnit, ) @@ -442,8 +389,8 @@ export const selectBuyAmountBeforeFeesCryptoBaseUnit = createSelector( lastHop => lastHop?.buyAmountBeforeFeesCryptoBaseUnit, ) -export const selectSellAmountBeforeFeesCryptoPrecision = createSelector( - selectSellAmountIncludingProtocolFeesCryptoBaseUnit, +export const selectQuoteSellAmountBeforeFeesCryptoPrecision = createSelector( + selectQuoteSellAmountIncludingProtocolFeesCryptoBaseUnit, selectFirstHopSellAsset, (sellAmountBeforeFeesCryptoBaseUnit, sellAsset) => { if (!sellAmountBeforeFeesCryptoBaseUnit || !sellAsset) return @@ -460,18 +407,9 @@ export const selectBuyAmountBeforeFeesCryptoPrecision = createSelector( }, ) -export const selectBuyAssetProtocolFeesCryptoPrecision = createSelector(selectLastHop, lastHop => { - if (!lastHop) return '0' - const protocolFees = lastHop.feeData.protocolFees - return fromBaseUnit( - protocolFees[lastHop.buyAsset.assetId]?.amountCryptoBaseUnit ?? '0', - lastHop.buyAsset.precision, - ) -}) - export const selectBuyAmountAfterFeesUserCurrency = createSelector( selectBuyAmountAfterFeesCryptoPrecision, - selectBuyAssetUserCurrencyRate, + selectInputBuyAssetUserCurrencyRate, (buyAmountCryptoPrecision, buyAssetUserCurrencyRate) => { if (!buyAmountCryptoPrecision || !buyAssetUserCurrencyRate) return return bn(buyAmountCryptoPrecision).times(buyAssetUserCurrencyRate).toFixed() @@ -480,25 +418,25 @@ export const selectBuyAmountAfterFeesUserCurrency = createSelector( export const selectBuyAmountBeforeFeesUserCurrency = createSelector( selectBuyAmountBeforeFeesCryptoPrecision, - selectBuyAssetUserCurrencyRate, + selectInputBuyAssetUserCurrencyRate, (buyAmountBeforeFeesCryptoPrecision, buyAssetUserCurrencyRate) => { if (!buyAmountBeforeFeesCryptoPrecision || !buyAssetUserCurrencyRate) return return bn(buyAmountBeforeFeesCryptoPrecision).times(buyAssetUserCurrencyRate).toFixed() }, ) -export const selectSellAmountUsd = createSelector( - selectSellAmountCryptoPrecision, - selectSellAssetUsdRate, +export const selectQuoteSellAmountUsd = createSelector( + selectQuoteSellAmountCryptoPrecision, + selectInputSellAssetUsdRate, (sellAmountCryptoPrecision, sellAssetUsdRate) => { if (!sellAmountCryptoPrecision || !sellAssetUsdRate) return return bn(sellAmountCryptoPrecision).times(sellAssetUsdRate).toFixed() }, ) -export const selectSellAmountUserCurrency = createSelector( - selectSellAmountCryptoPrecision, - selectSellAssetUserCurrencyRate, +export const selectQuoteSellAmountUserCurrency = createSelector( + selectQuoteSellAmountCryptoPrecision, + selectInputSellAssetUserCurrencyRate, (sellAmountCryptoPrecision, sellAssetUserCurrencyRate) => { if (!sellAmountCryptoPrecision || !sellAssetUserCurrencyRate) return return bn(sellAmountCryptoPrecision).times(sellAssetUserCurrencyRate).toFixed() @@ -511,44 +449,9 @@ export const selectActiveQuoteAffiliateBps: Selector = - createSelector(selectActiveQuote, activeQuote => { - if (!activeQuote) return - return activeQuote.potentialAffiliateBps - }) - -export const selectPotentialAffiliateFeeAmountUserCurrency: Selector< - ReduxState, - string | undefined -> = createSelector( - selectSellAmountUserCurrency, - selectActiveQuotePotentialAffiliateBps, - (sellAmountUserCurrency, potentialAffiliateBps) => { - if (potentialAffiliateBps === undefined) return undefined - else { - const affiliatePercentage = convertBasisPointsToDecimalPercentage( - potentialAffiliateBps ?? '0', - ) - // The affiliate fee amount is a percentage of the sell amount - return bnOrZero(sellAmountUserCurrency).times(affiliatePercentage).toFixed() - } - }, -) - -export const selectPotentialAffiliateFeeAmountUsd: Selector = - createSelector( - selectPotentialAffiliateFeeAmountUserCurrency, - selectUserCurrencyToUsdRate, - (affiliateFeeUserCurrency, userCurrencyToUsdRate) => { - if (affiliateFeeUserCurrency === undefined) return undefined - - return bnOrZero(affiliateFeeUserCurrency).div(userCurrencyToUsdRate).toFixed() - }, - ) - export const selectQuoteAffiliateFeeUserCurrency = createSelector( selectActiveQuote, - selectSellAmountUserCurrency, + selectQuoteSellAmountUserCurrency, selectActiveQuoteAffiliateBps, (activeQuote, sellAmountUserCurrency, affiliateBps) => { if (!activeQuote) return '0' @@ -572,52 +475,6 @@ export const selectTradeExecutionState = createSelector( swappers => swappers.tradeExecution.state, ) -// selects the account ID we're buying into for the first hop -export const selectFirstHopBuyAccountId = createSelector( - selectIsActiveQuoteMultiHop, - selectLastHopBuyAccountId, - selectFirstHop, - selectFirstHopBuyAsset, - selectAccountIdByAccountNumberAndChainId, - ( - isMultiHopTrade, - lastHopBuyAccountId, - firstHop, - buyAsset, - accountIdByAccountNumberAndChainId, - ) => { - // single hop trade - same as last hop - if (!isMultiHopTrade) return lastHopBuyAccountId - - return buyAsset !== undefined && firstHop !== undefined - ? accountIdByAccountNumberAndChainId[firstHop.accountNumber]?.[buyAsset.chainId] - : undefined - }, -) - -// selects the account ID we're selling from for the second hop if it exists. This is different to "last hop" -export const selectSecondHopSellAccountId = createSelector( - selectIsActiveQuoteMultiHop, - selectFirstHopBuyAccountId, - (isMultiHopTrade, firstHopBuyAccountId) => { - // single hop trade - no sell account id for this hop as it doesn't exist - if (!isMultiHopTrade) return undefined - - // multi hop trade - the second hop sell account id is the same as the first hop buy account id - return firstHopBuyAccountId - }, -) - -// selects the account ID we're selling from for the last hop -export const selectLastHopSellAccountId = createSelector( - selectIsActiveQuoteMultiHop, - selectFirstHopSellAccountId, - selectSecondHopSellAccountId, - (isMultiHopTrade, firstHopSellAccountId, secondHopSellAccountId) => { - return isMultiHopTrade ? firstHopSellAccountId : secondHopSellAccountId - }, -) - // selects the account ID we're selling from for the given hop export const selectHopSellAccountId = createSelector( selectFirstHopSellAccountId, From 326b81c7a75f8c02b2fd43e0a98466a0de8e17f1 Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Thu, 18 Jan 2024 17:39:25 +0100 Subject: [PATCH 7/8] feat: bring bakk paranoia --- src/state/apis/swapper/helpers/validateTradeQuote.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/state/apis/swapper/helpers/validateTradeQuote.ts b/src/state/apis/swapper/helpers/validateTradeQuote.ts index aabb3f51c72..308f7c180bf 100644 --- a/src/state/apis/swapper/helpers/validateTradeQuote.ts +++ b/src/state/apis/swapper/helpers/validateTradeQuote.ts @@ -203,10 +203,12 @@ export const validateTradeQuote = async ( const recommendedMinimumCryptoBaseUnit = (quote as ThorTradeQuote) .recommendedMinimumCryptoBaseUnit - const isUnsafeQuote = !( - !recommendedMinimumCryptoBaseUnit || - bnOrZero(sellAmountCryptoBaseUnit).gte(recommendedMinimumCryptoBaseUnit) - ) + const isUnsafeQuote = + sellAmountCryptoBaseUnit && + !( + !recommendedMinimumCryptoBaseUnit || + bnOrZero(sellAmountCryptoBaseUnit).gte(recommendedMinimumCryptoBaseUnit) + ) const disableSmartContractSwap = await (async () => { // Swappers other than THORChain shouldn't be affected by this limitation From 56aa50aa689e9cd02f39687c9c882b54cbf11d00 Mon Sep 17 00:00:00 2001 From: gomes <17035424+gomesalexandre@users.noreply.github.com> Date: Thu, 18 Jan 2024 18:03:22 +0100 Subject: [PATCH 8/8] fix: merge --- .../hooks/useSupportedAssets.tsx | 54 ++++++++----------- 1 file changed, 22 insertions(+), 32 deletions(-) diff --git a/src/components/MultiHopTrade/hooks/useSupportedAssets.tsx b/src/components/MultiHopTrade/hooks/useSupportedAssets.tsx index 7878c901cdd..5404d5ded0f 100644 --- a/src/components/MultiHopTrade/hooks/useSupportedAssets.tsx +++ b/src/components/MultiHopTrade/hooks/useSupportedAssets.tsx @@ -1,53 +1,43 @@ +import { KnownChainIds } from '@shapeshiftoss/types' import { useMemo } from 'react' +import { useIsSnapInstalled } from 'hooks/useIsSnapInstalled/useIsSnapInstalled' +import { useWallet } from 'hooks/useWallet/useWallet' +import { walletSupportsChain } from 'hooks/useWalletSupportsChain/useWalletSupportsChain' +import { isSome } from 'lib/utils' import { useGetSupportedAssetsQuery } from 'state/apis/swapper/swapperApi' -import { - selectAssetsSortedByMarketCapUserCurrencyBalanceAndName, - selectAssetsSortedByName, - selectWalletSupportedChainIds, -} from 'state/slices/common-selectors' -import { selectMarketDataDidLoad } from 'state/slices/selectors' +import { selectAssetsSortedByMarketCapUserCurrencyBalanceAndName } from 'state/slices/common-selectors' +import { selectAssets } from 'state/slices/selectors' import { useAppSelector } from 'state/store' export const useSupportedAssets = () => { - const marketDataDidLoad = useAppSelector(selectMarketDataDidLoad) - const assetsSortedByName = useAppSelector(selectAssetsSortedByName) - const assetsSortedByMarketCapUserCurrencyBalanceAndName = useAppSelector( - selectAssetsSortedByMarketCapUserCurrencyBalanceAndName, - ) - - const sortedAssets = useMemo(() => { - // if the market data has not yet loaded once, return a simplified sorting of assets - if (!marketDataDidLoad) { - return assetsSortedByName - } else { - return assetsSortedByMarketCapUserCurrencyBalanceAndName - } - }, [assetsSortedByMarketCapUserCurrencyBalanceAndName, assetsSortedByName, marketDataDidLoad]) - - const walletSupportedChainIds = useAppSelector(selectWalletSupportedChainIds) + const sortedAssets = useAppSelector(selectAssetsSortedByMarketCapUserCurrencyBalanceAndName) + const assets = useAppSelector(selectAssets) + const wallet = useWallet().state.wallet + const isSnapInstalled = useIsSnapInstalled() const queryParams = useMemo(() => { return { - walletSupportedChainIds, + walletSupportedChainIds: Object.values(KnownChainIds).filter(chainId => + walletSupportsChain({ chainId, wallet, isSnapInstalled }), + ), + sortedAssetIds: sortedAssets.map(asset => asset.assetId), } - }, [walletSupportedChainIds]) + }, [isSnapInstalled, sortedAssets, wallet]) - const { data, isFetching } = useGetSupportedAssetsQuery(queryParams) + const { data, isLoading } = useGetSupportedAssetsQuery(queryParams) const supportedSellAssets = useMemo(() => { if (!data) return [] - const assetIdsSet = new Set(data.supportedSellAssetIds) - return sortedAssets.filter(({ assetId }) => assetIdsSet.has(assetId)) - }, [data, sortedAssets]) + return data.supportedSellAssetIds.map(assetId => assets[assetId]).filter(isSome) + }, [assets, data]) const supportedBuyAssets = useMemo(() => { if (!data) return [] - const assetIdsSet = new Set(data.supportedBuyAssetIds) - return sortedAssets.filter(({ assetId }) => assetIdsSet.has(assetId)) - }, [data, sortedAssets]) + return data.supportedBuyAssetIds.map(assetId => assets[assetId]).filter(isSome) + }, [assets, data]) return { - isLoading: isFetching, + isLoading, supportedSellAssets, supportedBuyAssets, }