Skip to content

Commit

Permalink
refactor(trading): tradingAccount replaced by only saved key of account
Browse files Browse the repository at this point in the history
  • Loading branch information
adderpositive authored and tomasklim committed Feb 3, 2025
1 parent 418bd0f commit a710615
Show file tree
Hide file tree
Showing 10 changed files with 86 additions and 82 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ export const CLEAR_QUOTES = '@trading-exchange/clear_exchange_quotes';
export const VERIFY_ADDRESS = '@trading-exchange/verify_address';
export const SAVE_TRANSACTION_ID = '@trading-exchange/save_transaction_id';
export const SET_IS_FROM_REDIRECT = '@trading-exchange/set_is_from_redirect';
export const SET_TRADING_ACCOUNT = '@trading-exchange/set_trading_account';
export const SET_TRADING_ACCOUNT_KEY = '@trading-exchange/set_trading_account_key';
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ export const SAVE_QUOTE = '@trading-sell/save_quote';
export const CLEAR_QUOTES = '@trading-sell/clear_quotes';
export const SAVE_TRANSACTION_ID = '@trading-sell/save_transaction_id';
export const SET_IS_FROM_REDIRECT = '@trading-sell/set_is_from_redirect';
export const SET_TRADING_ACCOUNT = '@trading-sell/set_trading_account';
export const SET_TRADING_ACCOUNT_KEY = '@trading-sell/set_trading_account_key';
11 changes: 7 additions & 4 deletions packages/suite/src/actions/wallet/tradingExchangeActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from 'invity-api';

import { invityAPI } from '@suite-common/trading';
import { AccountKey } from '@suite-common/wallet-types';

import * as modalActions from 'src/actions/suite/modalActions';
import { verifyAddress as verifyExchangeAddress } from 'src/actions/wallet/trading/tradingCommonActions';
Expand Down Expand Up @@ -39,7 +40,7 @@ export type TradingExchangeAction =
type: typeof TRADING_EXCHANGE.SAVE_QUOTE;
quote: ExchangeTrade | undefined;
}
| { type: typeof TRADING_EXCHANGE.SET_TRADING_ACCOUNT; account: Account | undefined }
| { type: typeof TRADING_EXCHANGE.SET_TRADING_ACCOUNT_KEY; accountKey: AccountKey | undefined }
| {
type: typeof TRADING_COMMON.SAVE_TRADE;
date: string;
Expand Down Expand Up @@ -152,7 +153,9 @@ export const setIsFromRedirect = (isFromRedirect: boolean): TradingExchangeActio
export const verifyAddress = (account: Account, address?: string, path?: string) =>
verifyExchangeAddress(account, address, path, TRADING_EXCHANGE.VERIFY_ADDRESS);

export const setTradingExchangeAccount = (account: Account | undefined): TradingExchangeAction => ({
type: TRADING_EXCHANGE.SET_TRADING_ACCOUNT,
account,
export const setTradingExchangeAccountKey = (
accountKey: AccountKey | undefined,
): TradingExchangeAction => ({
type: TRADING_EXCHANGE.SET_TRADING_ACCOUNT_KEY,
accountKey,
});
11 changes: 7 additions & 4 deletions packages/suite/src/actions/wallet/tradingSellActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from 'invity-api';

import { invityAPI } from '@suite-common/trading';
import { AccountKey } from '@suite-common/wallet-types';

import * as modalActions from 'src/actions/suite/modalActions';
import { Dispatch } from 'src/types/suite';
Expand All @@ -26,7 +27,7 @@ export type TradingSellAction =
| { type: typeof TRADING_SELL.SAVE_QUOTE_REQUEST; request: SellFiatTradeQuoteRequest }
| { type: typeof TRADING_SELL.SAVE_TRANSACTION_ID; transactionId?: string }
| { type: typeof TRADING_SELL.SET_IS_FROM_REDIRECT; isFromRedirect: boolean }
| { type: typeof TRADING_SELL.SET_TRADING_ACCOUNT; account: Account | undefined }
| { type: typeof TRADING_SELL.SET_TRADING_ACCOUNT_KEY; accountKey: AccountKey | undefined }
| {
type: typeof TRADING_SELL.SAVE_QUOTES;
quotes: SellFiatTrade[];
Expand Down Expand Up @@ -124,9 +125,11 @@ export const setIsFromRedirect = (isFromRedirect: boolean): TradingSellAction =>
isFromRedirect,
});

export const setTradingSellAccount = (account: Account | undefined): TradingSellAction => ({
type: TRADING_SELL.SET_TRADING_ACCOUNT,
account,
export const setTradingSellAccountKey = (
accountKey: AccountKey | undefined,
): TradingSellAction => ({
type: TRADING_SELL.SET_TRADING_ACCOUNT_KEY,
accountKey,
});

// this is only a wrapper for `openDeferredModal` since it doesn't work with `bindActionCreators`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,34 @@ import { useState } from 'react';

import { mapTestnetSymbol } from '@suite-common/trading';
import { selectAccounts, selectSelectedDevice } from '@suite-common/wallet-core';
import { Account, SelectedAccountLoaded } from '@suite-common/wallet-types';
import { AccountKey, SelectedAccountLoaded } from '@suite-common/wallet-types';
import { isTestnet } from '@suite-common/wallet-utils';

import { useSelector } from 'src/hooks/suite';
import { tradingGetSortedAccounts } from 'src/utils/wallet/trading/tradingUtils';

interface TradingUseAccountProps {
tradingAccount: Account | undefined;
interface TradingUseAccountKeyProps {
tradingAccountKey: AccountKey | undefined;
selectedAccount: SelectedAccountLoaded;
shouldUseTradingAccount?: boolean;
shouldUseTradingAccountKey?: boolean;
}

/**
* Hook used to get account for trade form (used in Sell/Swap)
* Hook used to get account key of selected account for trade form (used in Sell/Swap)
* - coinmarketAccount is used whether user is in the trading flow (persistent)
* - selectedAccount is used as initial state if user entries from different page than trade
*/
export const useTradingAccount = ({
tradingAccount,
export const useTradingAccountKey = ({
tradingAccountKey,
selectedAccount,
shouldUseTradingAccount,
}: TradingUseAccountProps): [Account, (state: Account) => void] => {
shouldUseTradingAccountKey,
}: TradingUseAccountKeyProps): [AccountKey, (state: AccountKey) => void] => {
const accounts = useSelector(selectAccounts);
const device = useSelector(selectSelectedDevice);

const [account, setAccount] = useState<Account>(() => {
if (tradingAccount && shouldUseTradingAccount) {
return tradingAccount;
const [accountKey, setAccountKey] = useState<AccountKey>(() => {
if (tradingAccountKey && shouldUseTradingAccountKey) {
return tradingAccountKey;
}

if (isTestnet(selectedAccount.account.symbol) && !selectedAccount.network.tradeCryptoId) {
Expand All @@ -42,13 +42,13 @@ export const useTradingAccount = ({
const accountNotInTestnet = accountsSorted.find(a => a.symbol === defaultSymbol);

// return account which is on production network, if account is discovered
if (accountNotInTestnet) return accountNotInTestnet;
if (accountNotInTestnet) return accountNotInTestnet.key;
// return first account if default symbol is not found
if (accountsSorted[0]) return accountsSorted[0];
if (accountsSorted[0]) return accountsSorted[0].key;
}

return selectedAccount.account;
return selectedAccount.account.key;
});

return [account, setAccount];
return [accountKey, setAccountKey];
};
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
tradingGetSuccessQuotes,
} from '@suite-common/trading';
import { networks } from '@suite-common/wallet-config';
import { selectAccountByKey } from '@suite-common/wallet-core';
import { Account } from '@suite-common/wallet-types';
import { amountToSmallestUnit, formatAmount, toFiatCurrency } from '@suite-common/wallet-utils';
import { EventType, analytics } from '@trezor/suite-analytics';
Expand All @@ -29,7 +30,7 @@ import * as tradingExchangeActions from 'src/actions/wallet/tradingExchangeActio
import { FORM_OUTPUT_AMOUNT, FORM_OUTPUT_FIAT } from 'src/constants/wallet/trading/form';
import { useDispatch, useSelector } from 'src/hooks/suite';
import { useSolanaSubscribeBlocks } from 'src/hooks/wallet/form/useSolanaSubscribeBlocks';
import { useTradingAccount } from 'src/hooks/wallet/trading/form/common/useTradingAccount';
import { useTradingAccountKey } from 'src/hooks/wallet/trading/form/common/useTradingAccountKey';
import { useTradingComposeTransaction } from 'src/hooks/wallet/trading/form/common/useTradingComposeTransaction';
import { useTradingCurrencySwitcher } from 'src/hooks/wallet/trading/form/common/useTradingCurrencySwitcher';
import { useTradingExchangeQuotesFilter } from 'src/hooks/wallet/trading/form/common/useTradingExchangeQuotesFilter';
Expand Down Expand Up @@ -74,17 +75,20 @@ export const useTradingExchangeForm = ({
isFromRedirect,
quotes,
transactionId,
tradingAccount,
tradingAccountKey,
selectedQuote,
addressVerified,
} = useSelector(state => state.wallet.trading.exchange);
const { cryptoIdToCoinSymbol } = useTradingInfo();
const isPreviousRouteFromTradeSection = useTradingPreviousRoute(type);
const [account, setAccount] = useTradingAccount({
tradingAccount,
const [accountKey, setAccountKey] = useTradingAccountKey({
tradingAccountKey,
selectedAccount,
shouldUseTradingAccount: isPreviousRouteFromTradeSection,
shouldUseTradingAccountKey: isPreviousRouteFromTradeSection,
});
const accountByKey = useSelector(state => selectAccountByKey(state, accountKey));
const account = accountByKey ?? selectedAccount.account;

const { callInProgress, timer, device, setCallInProgress, checkQuotesTimer } =
useTradingInitializer({ selectedAccount, pageType });
const { buildDefaultCryptoOption } = useTradingInfo();
Expand Down Expand Up @@ -318,8 +322,8 @@ export const useTradingExchangeForm = ({
composeRequest,
setComposedLevels,
setAccountOnChange: newAccount => {
dispatch(tradingExchangeActions.setTradingExchangeAccount(newAccount));
setAccount(newAccount);
dispatch(tradingExchangeActions.setTradingExchangeAccountKey(newAccount.key));
setAccountKey(newAccount.key);
},
});

Expand Down Expand Up @@ -622,12 +626,6 @@ export const useTradingExchangeForm = ({
}
}, [defaultValues, values, removeDraft]);

useEffect(() => {
if (account.key === tradingAccount?.key) {
setAccount(tradingAccount);
}
}, [account, setAccount, tradingAccount]);

// react-hook-form auto register custom form fields (without HTMLElement)
useEffect(() => {
register('options');
Expand Down
20 changes: 12 additions & 8 deletions packages/suite/src/hooks/wallet/trading/form/useTradingSellForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
tradingGetSuccessQuotes,
} from '@suite-common/trading';
import { networks } from '@suite-common/wallet-config';
import { selectAccountByKey } from '@suite-common/wallet-core';
import { amountToSmallestUnit, formatAmount } from '@suite-common/wallet-utils';
import { EventType, analytics } from '@trezor/suite-analytics';

Expand All @@ -30,7 +31,7 @@ import {
} from 'src/constants/wallet/trading/form';
import { useDispatch, useSelector } from 'src/hooks/suite';
import { useSolanaSubscribeBlocks } from 'src/hooks/wallet/form/useSolanaSubscribeBlocks';
import { useTradingAccount } from 'src/hooks/wallet/trading/form/common/useTradingAccount';
import { useTradingAccountKey } from 'src/hooks/wallet/trading/form/common/useTradingAccountKey';
import { useTradingComposeTransaction } from 'src/hooks/wallet/trading/form/common/useTradingComposeTransaction';
import { useTradingCurrencySwitcher } from 'src/hooks/wallet/trading/form/common/useTradingCurrencySwitcher';
import { useTradingFormActions } from 'src/hooks/wallet/trading/form/common/useTradingFormActions';
Expand Down Expand Up @@ -73,16 +74,19 @@ export const useTradingSellForm = ({
isFromRedirect,
quotes,
transactionId,
tradingAccount,
tradingAccountKey,
selectedQuote,
} = useSelector(state => state.wallet.trading.sell);
const { cryptoIdToCoinSymbol } = useTradingInfo();
const isPreviousRouteFromTradeSection = useTradingPreviousRoute(type);
const [account, setAccount] = useTradingAccount({
tradingAccount,
const [accountKey, setAccountKey] = useTradingAccountKey({
tradingAccountKey,
selectedAccount,
shouldUseTradingAccount: isPreviousRouteFromTradeSection,
shouldUseTradingAccountKey: isPreviousRouteFromTradeSection,
});
const accountByKey = useSelector(state => selectAccountByKey(state, accountKey));
const account = accountByKey ?? selectedAccount.account;

const { callInProgress, timer, device, setCallInProgress, checkQuotesTimer } =
useTradingInitializer({ selectedAccount, pageType });
const { paymentMethods, getPaymentMethods, getQuotesByPaymentMethod } =
Expand Down Expand Up @@ -332,8 +336,8 @@ export const useTradingSellForm = ({
composeRequest,
setComposedLevels,
setAccountOnChange: newAccount => {
dispatch(tradingSellActions.setTradingSellAccount(newAccount));
setAccount(newAccount);
dispatch(tradingSellActions.setTradingSellAccountKey(newAccount.key));
setAccountKey(newAccount.key);
},
});

Expand Down Expand Up @@ -426,7 +430,7 @@ export const useTradingSellForm = ({
const goToOffers = async () => {
await handleChange(true);

dispatch(tradingSellActions.setTradingSellAccount(account)); // save account for offers page
dispatch(tradingSellActions.setTradingSellAccountKey(account.key)); // save account for offers page
navigateToSellOffers();
};

Expand Down
34 changes: 14 additions & 20 deletions packages/suite/src/middlewares/wallet/tradingMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { MiddlewareAPI } from 'redux';

import { invityAPI } from '@suite-common/trading';
import { accountsActions } from '@suite-common/wallet-core';
import { UI } from '@trezor/connect';

import { MODAL, ROUTER } from 'src/actions/suite/constants';
Expand All @@ -21,12 +20,19 @@ import { getTradeTypeByRoute } from 'src/utils/wallet/trading/tradingUtils';
export const getAccountAccordingToRoute = (state: AppState) => {
const tradeType = getTradeTypeByRoute(state.router.route?.name);

const { account } = state.wallet.selectedAccount;
const sellSelectedAccount = state.wallet.trading.sell.tradingAccount;
const exchangeSelectedAccount = state.wallet.trading.exchange.tradingAccount;
const {
selectedAccount: { account },
accounts,
trading: {
sell: { tradingAccountKey: sellSelectedAccountKey },
exchange: { tradingAccountKey: exchangeSelectedAccountKey },
},
} = state.wallet;

if (tradeType === 'sell' && sellSelectedAccount) return sellSelectedAccount;
if (tradeType === 'exchange' && exchangeSelectedAccount) return exchangeSelectedAccount;
if (tradeType === 'sell' && sellSelectedAccountKey)
return accounts.find(account => account.key === sellSelectedAccountKey);
if (tradeType === 'exchange' && exchangeSelectedAccountKey)
return accounts.find(account => account.key === exchangeSelectedAccountKey);

return account;
};
Expand Down Expand Up @@ -174,8 +180,8 @@ export const tradingMiddleware =

// after an account change in the Sell or Swap update the invityAPIKey based on the account
if (
action.type === TRADING_EXCHANGE.SET_TRADING_ACCOUNT ||
action.type === TRADING_SELL.SET_TRADING_ACCOUNT
action.type === TRADING_EXCHANGE.SET_TRADING_ACCOUNT_KEY ||
action.type === TRADING_SELL.SET_TRADING_ACCOUNT_KEY
) {
const account = getAccountAccordingToRoute(newState);

Expand All @@ -184,17 +190,5 @@ export const tradingMiddleware =
}
}

if (isTradingRoute && action.type === accountsActions.updateAccount.type) {
const account = action.payload;

if (state.wallet.trading.sell.tradingAccount?.key === account.key) {
api.dispatch(tradingSellActions.setTradingSellAccount(account));
}

if (state.wallet.trading.exchange.tradingAccount?.key === account.key) {
api.dispatch(tradingExchangeActions.setTradingExchangeAccount(account));
}
}

return action;
};
Original file line number Diff line number Diff line change
Expand Up @@ -480,29 +480,29 @@ describe('settings reducer', () => {
it('TRADING_SELL.SET_TRADING_ACCOUNT', () => {
expect(
tradingReducer(undefined, {
type: TRADING_SELL.SET_TRADING_ACCOUNT,
account: accounts[0],
type: TRADING_SELL.SET_TRADING_ACCOUNT_KEY,
accountKey: accounts[0].key,
}),
).toEqual({
...initialState,
sell: {
...initialState.sell,
tradingAccount: accounts[0],
tradingAccountKey: accounts[0].key,
},
});
});

it('TRADING_EXCHANGE.SET_TRADING_ACCOUNT', () => {
expect(
tradingReducer(undefined, {
type: TRADING_EXCHANGE.SET_TRADING_ACCOUNT,
account: accounts[0],
type: TRADING_EXCHANGE.SET_TRADING_ACCOUNT_KEY,
accountKey: accounts[0].key,
}),
).toEqual({
...initialState,
exchange: {
...initialState.exchange,
tradingAccount: accounts[0],
tradingAccountKey: accounts[0].key,
},
});
});
Expand Down
Loading

0 comments on commit a710615

Please sign in to comment.