Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

swap orders hooks fixing #3557

Merged
merged 12 commits into from
Jun 24, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import TextField from '../common/TextField';
import type { RemoteTokenInfo } from '../../api/ada/lib/state-fetch/types';
import LoadingSpinner from '../widgets/LoadingSpinner';
import { useState } from 'react';
import type { FormattedTokenValue } from '../../containers/swap/orders/OrdersPage';
import { WrongPassphraseError } from '../../api/ada/lib/cardanoCrypto/cryptoErrors';
import { stringifyError } from '../../utils/logging';
import { InfoTooltip } from '../widgets/InfoTooltip';
Expand All @@ -16,6 +15,7 @@ import type { TokenLookupKey } from '../../api/common/lib/MultiToken';
import type { TokenRow } from '../../api/ada/lib/storage/database/primitives/tables';
import { SelectedExplorer } from '../../domain/SelectedExplorer';
import type LocalizableError from '../../i18n/LocalizableError';
import type { FormattedTokenValue } from '../../containers/swap/orders/util';

type Props = {|
order: any,
Expand Down Expand Up @@ -102,9 +102,9 @@ export default function CancelSwapOrderDialog({
>
{transactionParams ? (
transactionParams.returnValues.map((v, index) => (
<>
<Box key={v.ticker}>
{index > 0 && ' +'} {v.formattedValue} {v.ticker}
</>
</Box>
))
) : (
<LoadingSpinner small />
Expand Down
2 changes: 1 addition & 1 deletion packages/yoroi-extension/app/components/swap/SwapInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export default function SwapInput({
const { id, amount: quantity = undefined, ticker } = tokenInfo || {};

const handleChange = e => {
if (!disabled && value !== quantity) {
if (!disabled) {
handleAmountChange(e.target.value);
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,13 @@ function SwapPage(props: StoresAndActionsProps): Node {
},
frontendFeeTiersChanged,
} = useSwap();
const { sellTokenInfo, buyTokenInfo } = useSwapForm();
const {
sellTokenInfo,
buyTokenInfo,
resetSwapForm,
sellQuantity,
buyQuantity,
} = useSwapForm();

const isMarketOrder = orderType === 'market';
const impact = isMarketOrder ? Number(selectedPoolCalculation?.prices.priceImpact ?? 0) : 0;
Expand All @@ -71,17 +77,20 @@ function SwapPage(props: StoresAndActionsProps): Node {
);

const swapFormCanContinue =
selectedPoolCalculation != null &&
sell.quantity !== '0' &&
buy.quantity !== '0' &&
isValidTickers;
selectedPoolCalculation != null
&& sell.quantity !== '0'
&& buy.quantity !== '0'
&& sellQuantity.error == null
&& buyQuantity.error == null
&& isValidTickers;

const confirmationCanContinue = userPasswordState.value !== '' && signRequest != null;

const isButtonLoader = orderStep === 1 && signRequest == null;

const isSwapEnabled =
(orderStep === 0 && swapFormCanContinue) || (orderStep === 1 && confirmationCanContinue);
(orderStep === 0 && swapFormCanContinue)
|| (orderStep === 1 && confirmationCanContinue);

const wallet = props.stores.wallets.selectedOrFail;
const network = wallet.getParent().getNetworkInfo();
Expand Down Expand Up @@ -239,6 +248,7 @@ function SwapPage(props: StoresAndActionsProps): Node {
refreshWallet: () => props.stores.wallets.refreshWalletFromRemote(wallet),
});
setOrderStepValue(2);
resetSwapForm();
} catch (e) {
handleTransactionError(e);
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@ export default function SwapFormProvider({ swapStore, children }: Props): Node {
...defaultSwapFormState,
});

const {
sellTokenInfo: { ticker: sellTicker },
buyTokenInfo: { ticker: buyTicker },
} = swapFormState;

const actions = {
sellTouched: (token?: AssetAmount) =>
dispatch({ type: SwapFormActionTypeValues.SellTouched, token }),
Expand Down Expand Up @@ -136,33 +141,43 @@ export default function SwapFormProvider({ swapStore, children }: Props): Node {
dispatch({ type: SwapFormActionTypeValues.SellAmountErrorChanged, error }),
};

// on mount
/**
* On mount
*/
useEffect(() => actions.resetSwapForm(), []);
/**
* On unmount
*/
useEffect(() => () => actions.resetSwapForm(), []);

/**
* On sell asset changes - set default asset in case none is selected
*/
useEffect(() => {
// RESET
actions.resetSwapForm();
// SELECT DEFAULT SELL
const assets = swapStore.assets;
const defaultAsset = assets[0];
if (defaultAsset != null) {
actions.sellTouched({ ...defaultAsset });
sellTokenInfoChanged({
id: defaultAsset.id,
decimals: defaultAsset.decimals,
});
if (sellTokenId === '' && sellTicker == null) {
// SELECT DEFAULT SELL
const assets = swapStore.assets;
const defaultAsset = assets[0];
if (defaultAsset != null) {
actions.sellTouched({ ...defaultAsset });
sellTokenInfoChanged({
id: defaultAsset.id,
decimals: defaultAsset.decimals,
});
}
}
}, []);
}, [sellTokenId, sellTicker]);

// on unmount
useEffect(() => () => actions.resetSwapForm(), []);

// on token pair changes
/**
* On token pair changes - fetch pools for pair
*/
useEffect(() => {
if (sellTokenId != null && buyTokenId != null && sellTokenId !== buyTokenId) {
pools.list.byPair({ tokenA: sellTokenId, tokenB: buyTokenId })
.then(poolsArray => poolPairsChanged(poolsArray))
.catch(err => console.error(`Failed to fetch pools for pair: ${sellTokenId}/${buyTokenId}`, err));
}
}, [sellTokenId, buyTokenId]);
}, [sellTokenId, buyTokenId, sellTicker, buyTicker]);

const clearErrors = useCallback(() => {
if (swapFormState.sellQuantity.error != null) actions.sellAmountErrorChanged(null);
Expand Down
72 changes: 0 additions & 72 deletions packages/yoroi-extension/app/containers/swap/hooks.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
//@flow
import {
useSwap,
useSwapOrdersByStatusCompleted,
useSwapOrdersByStatusOpen,
useSwapTokensOnlyVerified,
} from '@yoroi/swap';
import { Quantities } from '../../utils/quantities';
import { useSwapForm } from './context/swap-form';
Expand Down Expand Up @@ -72,72 +69,3 @@ export function useSwapFeeDisplay(
formattedFee,
};
}

export function useRichOpenOrders(): any {
let openOrders = [];
try {
openOrders = useSwapOrdersByStatusOpen();
} catch (e) {
console.warn('useRichCompletedOrders.useSwapOrdersByStatusOpen', e);
}
let onlyVerifiedTokens = [];
try {
const res = useSwapTokensOnlyVerified();
onlyVerifiedTokens = res.onlyVerifiedTokens;
} catch (e) {
console.warn('useRichCompletedOrders.useSwapTokensOnlyVerified', e);
}
if ((openOrders?.length || 0) === 0 || (onlyVerifiedTokens?.length || 0) === 0) return [];
try {
const tokensMap = onlyVerifiedTokens.reduce((map, t) => ({ ...map, [t.id]: t }), {});
return openOrders.map(o => {
const fromToken = tokensMap[o.from.tokenId];
const toToken = tokensMap[o.to.tokenId];
return {
utxo: o.utxo,
from: { quantity: o.from.quantity, token: fromToken },
to: { quantity: o.to.quantity, token: toToken },
batcherFee: o.batcherFee,
valueAttached: o.valueAttached,
deposit: o.deposit,
provider: o.provider,
sender: o.sender,
};
});
} catch (e) {
console.warn('useRichOpenOrders', e);
return [];
}
}

export function useRichCompletedOrders(): any {
let completedOrders = [];
try {
completedOrders = useSwapOrdersByStatusCompleted();
} catch (e) {
console.warn('useRichCompletedOrders.useSwapOrdersByStatusCompleted', e);
}
let onlyVerifiedTokens = [];
try {
const res = useSwapTokensOnlyVerified();
onlyVerifiedTokens = res.onlyVerifiedTokens;
} catch (e) {
console.warn('useRichCompletedOrders.useSwapTokensOnlyVerified', e);
}
if ((completedOrders?.length || 0) === 0 || (onlyVerifiedTokens?.length || 0) === 0) return [];
try {
const tokensMap = onlyVerifiedTokens.reduce((map, t) => ({ ...map, [t.id]: t }), {});
return completedOrders.map(o => {
const fromToken = tokensMap[o.from.tokenId];
const toToken = tokensMap[o.to.tokenId];
return {
txHash: o.txHash,
from: { quantity: o.from.quantity, token: fromToken },
to: { quantity: o.to.quantity, token: toToken },
};
});
} catch (e) {
console.warn('useRichCompletedOrders', e);
return [];
}
}
Loading
Loading