From 56a9ebfdaaf7831f42c3f3b3783901a2e8509eaf Mon Sep 17 00:00:00 2001 From: Apotheosis <97164662+0xApotheosis@users.noreply.github.com> Date: Thu, 26 Sep 2024 11:12:07 +1000 Subject: [PATCH 1/2] chore: improve translation key name --- src/assets/translations/de/main.json | 2 +- src/assets/translations/en/main.json | 2 +- src/assets/translations/es/main.json | 2 +- src/assets/translations/fr/main.json | 2 +- src/assets/translations/ja/main.json | 2 +- src/assets/translations/pt/main.json | 2 +- src/assets/translations/ru/main.json | 2 +- src/assets/translations/tr/main.json | 2 +- src/assets/translations/uk/main.json | 2 +- src/assets/translations/zh/main.json | 2 +- src/components/MultiHopTrade/components/TradeAmountInput.tsx | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/assets/translations/de/main.json b/src/assets/translations/de/main.json index b1cc975fe0e..0ffaabbe9f3 100644 --- a/src/assets/translations/de/main.json +++ b/src/assets/translations/de/main.json @@ -883,7 +883,7 @@ "manualReceiveAddress": "Dies ist die Adresse, an die Sie Ihr Geld erhalten. Sie wurde manuell eingegeben, bitte stellen Sie sicher, dass sie korrekt ist.", "amountPercentageDifference": "Dies ist die prozentuale Differenz des Gesamtbetrags von %{buyAssetSymbol}, den Sie erhalten, im Vergleich zum besten Angebot", "overallPercentageDifference": "Dies ist die prozentuale Differenz des Gesamtbetrags, den Sie nach Abzug aller Gebühren erhalten, im Vergleich zum besten Angebot", - "priceImpactDifference": "Die geschätzte Differenz zwischen dem USD-Wert der Eingabe- und Ausgabebeträge.", + "inputOutputDifference": "Die geschätzte Differenz zwischen dem USD-Wert der Eingabe- und Ausgabebeträge.", "gasFee": "Dies ist die geschätzte Gasgebühr für den Abschluss dieses Handels.", "slippageWithAmount": "Wenn sich der Preis so verändert, dass Sie weniger als %{amount} erhalten, wird Ihre Transaktion rückgängig gemacht. Dies ist der Mindestbetrag, den Sie garantiert erhalten.", "slippage": "Ihre Transaktion wird rückgängig gemacht, wenn sich der Preis um mehr als diesen Prozentsatz ungünstig ändert.", diff --git a/src/assets/translations/en/main.json b/src/assets/translations/en/main.json index bb1977df905..738cee4b47b 100644 --- a/src/assets/translations/en/main.json +++ b/src/assets/translations/en/main.json @@ -890,7 +890,7 @@ "manualReceiveAddress": "This is the address you will receive your funds to. It has been manually entered, please ensure it is correct.", "amountPercentageDifference": "This is the percentage difference in the total amount of %{buyAssetSymbol} you will receive, compared to the best quote", "overallPercentageDifference": "This is the percentage difference in the overall amount received after all fees are deducted, compared to the best quote", - "priceImpactDifference": "The estimated difference between the USD values of input and output amounts.", + "inputOutputDifference": "The estimated difference between the USD values of input and output amounts.", "gasFee": "This is the estimated gas fee to complete this trade.", "slippageWithAmount": "If the price moves so that you will receive less than %{amount}, your transaction will be reverted. This is the minimum amount you are guaranteed to receive.", "slippage": "Your transaction will revert if the price changes unfavorably by more than this percentage.", diff --git a/src/assets/translations/es/main.json b/src/assets/translations/es/main.json index ed1750f77a8..8a8b274567e 100644 --- a/src/assets/translations/es/main.json +++ b/src/assets/translations/es/main.json @@ -883,7 +883,7 @@ "manualReceiveAddress": "Esta es la dirección que recibirá los fondos. Se introdujo manualmente, asegúrese que sea correcta.", "amountPercentageDifference": "Esta es la diferencia porcentual en la cantidad total de %{buyAssetSymbol} que recibirá, en comparación con la mejor cotización.", "overallPercentageDifference": "Esta es la diferencia porcentual en el monto total recibido después de deducir todas las tarifas, en comparación con la mejor cotización.", - "priceImpactDifference": "La diferencia estimada entre los valores USD de las cantidades de insumos y productos.", + "inputOutputDifference": "La diferencia estimada entre los valores USD de las cantidades de insumos y productos.", "gasFee": "Esta es la tarifa de gas estimada para el intercambio.", "slippageWithAmount": "Si el precio se mueve de modo que usted reciba menos de %{amount}, su transacción se revertirá. Esta es la cantidad mínima que tiene garantizado recibir.", "slippage": "Su transacción revertirá si el precio cambia desfavorablemente más de este porcentaje.", diff --git a/src/assets/translations/fr/main.json b/src/assets/translations/fr/main.json index a77435003a8..2f6ffc94890 100644 --- a/src/assets/translations/fr/main.json +++ b/src/assets/translations/fr/main.json @@ -883,7 +883,7 @@ "manualReceiveAddress": "C'est l'adresse à laquelle vous recevrez vos fonds. Elle a été saisie manuellement, veuillez vous assurer qu'elle est correcte.", "amountPercentageDifference": "Il s'agit de la différence en pourcentage du montant total en %{buyAssetSymbol} que vous recevrez, par rapport au meilleur devis.", "overallPercentageDifference": "Il s'agit de la différence en pourcentage du montant global reçu après déduction de tous les frais, par rapport au meilleur devis.", - "priceImpactDifference": "La différence estimée entre les valeurs en USD des montants d’entrée et de sortie.", + "inputOutputDifference": "La différence estimée entre les valeurs en USD des montants d’entrée et de sortie.", "gasFee": "Il s'agit des frais de carburant estimés pour finaliser cette transaction.", "slippageWithAmount": "Si le prix change de telle manière que vous recevrez moins de %{amount}, votre transaction sera annulée. Il s’agit du montant minimum garanti que vous recevrez.", "slippage": "Votre transaction sera annulée si le prix change défavorablement de plus de ce pourcentage.", diff --git a/src/assets/translations/ja/main.json b/src/assets/translations/ja/main.json index d61bbf61d2c..b85ea97f530 100644 --- a/src/assets/translations/ja/main.json +++ b/src/assets/translations/ja/main.json @@ -882,7 +882,7 @@ "manualReceiveAddress": "資金を受け取るアドレスです。手動で入力されていますので、正しいことを確認してください。", "amountPercentageDifference": "これは、最良の見積もりと比較した、あなたが受け取る %{buyAssetSymbol} の合計額の差のパーセンテージです。", "overallPercentageDifference": "これは、最良の見積もりと比較した、すべての手数料を差し引いた後の受け取り総額のパーセンテージの差です。", - "priceImpactDifference": "入力量と出力量のUSD値間の推定差", + "inputOutputDifference": "入力量と出力量のUSD値間の推定差", "gasFee": "これは、この取引を完了するための推定ガス代です。", "slippageWithAmount": "価格が変動し、受け取る金額が %{amount} 未満になる場合、トランザクションは取り消されます。これは受け取ることが保証される最低金額です。", "slippage": "価格がこのパーセンテージを超えて不利に変化した場合、トランザクションは元に戻ります。", diff --git a/src/assets/translations/pt/main.json b/src/assets/translations/pt/main.json index be83b420348..dcc62672634 100644 --- a/src/assets/translations/pt/main.json +++ b/src/assets/translations/pt/main.json @@ -883,7 +883,7 @@ "manualReceiveAddress": "Este é o endereço para o qual você receberá seus fundos. Foi inserido manualmente, verifique se está correto.", "amountPercentageDifference": "Esta é a diferença percentual no valor total de %{buyAssetSymbol} que você receberá, em comparação com a melhor cotação", "overallPercentageDifference": "Esta é a diferença percentual no valor total recebido após a dedução de todas as taxas, em comparação com a melhor cotação", - "priceImpactDifference": "A diferença estimada entre os valores em USD dos valores de entrada e saída.", + "inputOutputDifference": "A diferença estimada entre os valores em USD dos valores de entrada e saída.", "gasFee": "Esta é a taxa de gás estimada para concluir esta negociação.", "slippageWithAmount": "Se o preço mudar de forma que você receba menos de %{amount}, sua transação será revertida. Este é o valor mínimo que você tem garantia de receber.", "slippage": "A sua transação será revertida se o preço mudar desfavoravelmente em mais do que esta percentagem.", diff --git a/src/assets/translations/ru/main.json b/src/assets/translations/ru/main.json index 6ac3e96cec7..771fb819148 100644 --- a/src/assets/translations/ru/main.json +++ b/src/assets/translations/ru/main.json @@ -883,7 +883,7 @@ "manualReceiveAddress": "Это адрес, на который вы будете получать средства. Он был введен вручную, пожалуйста, проверьте его достоверность.", "amountPercentageDifference": "Это процентная разница в общей сумме %{buyAssetSymbol}, которую вы получите, по сравнению с лучшим предложением", "overallPercentageDifference": "Это процентная разница в общей сумме, полученной после вычета всех комиссий, по сравнению с лучшим предложением.", - "priceImpactDifference": "Расчетная разница между значениями входных и выходных сумм в долларах США.", + "inputOutputDifference": "Расчетная разница между значениями входных и выходных сумм в долларах США.", "gasFee": "Это примерная стоимость газа для завершения этой сделки.", "slippageWithAmount": "Если цена изменится таким образом, что вы получите меньше %{amount}, ваша сделка будет отменена. Это минимальная сумма, которую вы гарантированно получите.", "slippage": "Ваша сделка будет отменена, если цена изменится в неблагоприятную сторону более чем на этот процент.", diff --git a/src/assets/translations/tr/main.json b/src/assets/translations/tr/main.json index 15873a5da75..04e782123f0 100644 --- a/src/assets/translations/tr/main.json +++ b/src/assets/translations/tr/main.json @@ -883,7 +883,7 @@ "manualReceiveAddress": "Bu, fonunuzu çekeceğiniz adrestir. Manuel olarak girilmiştir, lütfen doğru olduğundan emin olun.", "amountPercentageDifference": "En iyi fiyat teklifiyle karşılaştırıldığında alacağınız toplam %{buyAssetSymbol} tutarındaki yüzde farkıdır", "overallPercentageDifference": "En iyi teklifle karşılaştırıldığında, tüm ücretler düşüldükten sonra alınan toplam tutardaki yüzdelik farktır.", - "priceImpactDifference": "Girdi ve çıktı tutarlarının USD değerleri arasındaki tahmini fark.", + "inputOutputDifference": "Girdi ve çıktı tutarlarının USD değerleri arasındaki tahmini fark.", "gasFee": "Bu ticareti tamamlamak için gereken tahmini gaz ücretidir.", "slippageWithAmount": "Fiyat, %{amount} tutarından daha azını alacak şekilde hareket ederse işleminiz geri alınacaktır. Bu, alacağınız garanti edilen minimum tutardır.", "slippage": "Fiyatın bu yüzdeden daha fazla olumsuz yönde değişmesi durumunda işleminiz geri alınacaktır.", diff --git a/src/assets/translations/uk/main.json b/src/assets/translations/uk/main.json index 174117757f1..d46c89193ad 100644 --- a/src/assets/translations/uk/main.json +++ b/src/assets/translations/uk/main.json @@ -883,7 +883,7 @@ "manualReceiveAddress": "Це адреса, на яку ви отримаєте свої кошти. Вона була введена вручну, будь ласка, переконайтеся, що вона правильна.", "amountPercentageDifference": "Це відсоткова різниця в загальній сумі %{buyAssetSymbol}, яку ви отримаєте, порівняно з найкращою пропозицією", "overallPercentageDifference": "Це відсоткова різниця в загальній сумі, отриманій після вирахування всіх комісій, порівняно з найкращою пропозицією", - "priceImpactDifference": "Розрахункова різниця між значеннями вхідних і вихідних сум у доларах США.", + "inputOutputDifference": "Розрахункова різниця між значеннями вхідних і вихідних сум у доларах США.", "gasFee": "Це приблизна вартість газу, необхідна для завершення цієї торгівлі.", "slippageWithAmount": "Якщо ціна зміниться таким чином, що ви отримаєте менше %{amount}, ваша транзакція буде скасована. Це мінімальна сума, яку ви гарантовано отримаєте.", "slippage": "Ваша транзакція буде скасована, якщо ціна зміниться несприятливо більш ніж на цей відсоток.", diff --git a/src/assets/translations/zh/main.json b/src/assets/translations/zh/main.json index d8e1557933d..a5a4e93e8dc 100644 --- a/src/assets/translations/zh/main.json +++ b/src/assets/translations/zh/main.json @@ -882,7 +882,7 @@ "manualReceiveAddress": "这是你接收资金的地址。已手动输入,请确保正确。", "amountPercentageDifference": "这是你将收到的 %{buyAssetSymbol} 总数与最佳报价相比的百分比差异", "overallPercentageDifference": "这是扣除所有费用后收到的总数与最佳报价相比的百分比差异", - "priceImpactDifference": "输入和输出金额的美元价值之间的估计差异。", + "inputOutputDifference": "输入和输出金额的美元价值之间的估计差异。", "gasFee": "这是完成这笔交易的估计手续费。", "slippageWithAmount": "如果价格变动导致你收到的金额少于 %{amount},你的交易将被还原。这是保证你收到的最低金额。", "slippage": "如果价格不利变化超过此百分比,你的交易将恢复。", diff --git a/src/components/MultiHopTrade/components/TradeAmountInput.tsx b/src/components/MultiHopTrade/components/TradeAmountInput.tsx index a5dd407ec83..028ff0b52da 100644 --- a/src/components/MultiHopTrade/components/TradeAmountInput.tsx +++ b/src/components/MultiHopTrade/components/TradeAmountInput.tsx @@ -400,7 +400,7 @@ export const TradeAmountInput: React.FC = memo( {oppositeCurrency} {priceImpactPercentage && ( - + Date: Thu, 26 Sep 2024 12:32:09 +1000 Subject: [PATCH 2/2] fix: use actual input output difference --- .../components/TradeAmountInput.tsx | 12 ++-- .../TradeInput/components/TradeInputBody.tsx | 7 ++- .../hooks/useInputOutputDifference.ts | 57 +++++++++++++++++++ 3 files changed, 68 insertions(+), 8 deletions(-) create mode 100644 src/components/MultiHopTrade/hooks/useInputOutputDifference.ts diff --git a/src/components/MultiHopTrade/components/TradeAmountInput.tsx b/src/components/MultiHopTrade/components/TradeAmountInput.tsx index 028ff0b52da..34f896b0964 100644 --- a/src/components/MultiHopTrade/components/TradeAmountInput.tsx +++ b/src/components/MultiHopTrade/components/TradeAmountInput.tsx @@ -101,7 +101,6 @@ export type TradeAmountInputProps = { cryptoAmount: string fiatAmount: string showFiatAmount?: boolean - priceImpactPercentage?: string balance?: string fiatBalance?: string errors?: FieldError @@ -119,6 +118,7 @@ export type TradeAmountInputProps = { isAccountSelectionHidden?: boolean isFiat?: boolean onToggleIsFiat?: (isInputtingFiatSellAmount: boolean) => void + inputOutputDifferenceDecimalPercentage?: string } & PropsWithChildren const defaultPercentOptions = [0.25, 0.5, 0.75, 1] @@ -150,7 +150,6 @@ export const TradeAmountInput: React.FC = memo( showFiatAmount = '0', balance, fiatBalance, - priceImpactPercentage, errors, percentOptions = defaultPercentOptions, children, @@ -164,6 +163,7 @@ export const TradeAmountInput: React.FC = memo( layout = 'stacked', isFiat, onToggleIsFiat: handleIsInputtingFiatSellAmountChange, + inputOutputDifferenceDecimalPercentage: inputOutputDifferencePercentage, }) => { const { number: { localeParts }, @@ -314,7 +314,9 @@ export const TradeAmountInput: React.FC = memo( const handleOnMaxClick = useMemo(() => () => onMaxClick(Boolean(isFiat)), [isFiat, onMaxClick]) - const priceImpactColor = usePriceImpactColor(priceImpactPercentage) + const priceImpactColor = usePriceImpactColor( + bnOrZero(inputOutputDifferencePercentage).times(100).toString(), + ) return ( = memo( > {oppositeCurrency} - {priceImpactPercentage && ( + {inputOutputDifferencePercentage && ( @@ -408,7 +410,7 @@ export const TradeAmountInput: React.FC = memo( prefix='(' suffix=')' color={priceImpactColor ?? 'text.subtle'} - value={bnOrZero(priceImpactPercentage).div(100).times(-1).toString()} + value={bnOrZero(inputOutputDifferencePercentage).times(-1).toString()} /> diff --git a/src/components/MultiHopTrade/components/TradeInput/components/TradeInputBody.tsx b/src/components/MultiHopTrade/components/TradeInput/components/TradeInputBody.tsx index f06acd4c97f..b8c2e8f2acf 100644 --- a/src/components/MultiHopTrade/components/TradeInput/components/TradeInputBody.tsx +++ b/src/components/MultiHopTrade/components/TradeInput/components/TradeInputBody.tsx @@ -13,7 +13,7 @@ import { positiveOrZero } from '@shapeshiftoss/utils' import { useCallback, useEffect, useMemo } from 'react' import { useTranslate } from 'react-polyglot' import { TradeAssetSelect } from 'components/AssetSelection/AssetSelection' -import { usePriceImpact } from 'components/MultiHopTrade/hooks/quoteValidation/usePriceImpact' +import { useInputOutputDifferenceDecimalPercentage } from 'components/MultiHopTrade/hooks/useInputOutputDifference' import { useModal } from 'hooks/useModal/useModal' import { useWallet } from 'hooks/useWallet/useWallet' import { useWalletSupportsChain } from 'hooks/useWalletSupportsChain/useWalletSupportsChain' @@ -99,7 +99,8 @@ export const TradeInputBody = ({ return [1] }, [sellAsset.assetId]) const activeQuote = useAppSelector(selectActiveQuote) - const { priceImpactPercentage } = usePriceImpact(activeQuote) + const inputOutputDifferenceDecimalPercentage = + useInputOutputDifferenceDecimalPercentage(activeQuote) // If the user disconnects the chain for the currently selected sell asset, switch to the default asset useEffect(() => { @@ -218,7 +219,7 @@ export const TradeInputBody = ({ onAccountIdChange={setBuyAssetAccountId} formControlProps={formControlProps} labelPostFix={buyTradeAssetSelect} - priceImpactPercentage={priceImpactPercentage?.toString()} + inputOutputDifferenceDecimalPercentage={inputOutputDifferenceDecimalPercentage} /> ) diff --git a/src/components/MultiHopTrade/hooks/useInputOutputDifference.ts b/src/components/MultiHopTrade/hooks/useInputOutputDifference.ts new file mode 100644 index 00000000000..be31da7286b --- /dev/null +++ b/src/components/MultiHopTrade/hooks/useInputOutputDifference.ts @@ -0,0 +1,57 @@ +import type { SupportedTradeQuoteStepIndex } from '@shapeshiftoss/swapper' +import { getHopByIndex, type TradeQuote } from '@shapeshiftoss/swapper' +import { bn, bnOrZero, fromBaseUnit } from '@shapeshiftoss/utils' +import { useMemo } from 'react' +import { selectUsdRateByAssetId } from 'state/slices/selectors' +import { useAppSelector } from 'state/store' + +export const useInputOutputDifferenceDecimalPercentage = (tradeQuote: TradeQuote | undefined) => { + const numSteps = tradeQuote?.steps.length ?? 0 + const sellAsset = tradeQuote?.steps[0].sellAsset + const buyAsset = tradeQuote?.steps[numSteps - 1].buyAsset + + const sellAssetUsdRate = useAppSelector(state => + selectUsdRateByAssetId(state, sellAsset?.assetId ?? ''), + ) + + const buyAssetUsdRate = useAppSelector(state => + selectUsdRateByAssetId(state, buyAsset?.assetId ?? ''), + ) + + const sellAmountIncludingFeesUsd = useMemo(() => { + if (!tradeQuote || !sellAsset || !sellAssetUsdRate) return + + // A quote always has a first hop + const firstHop = getHopByIndex(tradeQuote, 0)! + const sellAmountIncludingProtocolFeesCryptoBaseUnit = + firstHop.sellAmountIncludingProtocolFeesCryptoBaseUnit + + const sellAmountIncludingProtocolFeesCryptoPrecision = fromBaseUnit( + sellAmountIncludingProtocolFeesCryptoBaseUnit, + sellAsset.precision, + ) + + return bn(sellAmountIncludingProtocolFeesCryptoPrecision).times(sellAssetUsdRate).toFixed() + }, [sellAsset, sellAssetUsdRate, tradeQuote]) + + const buyAmountAfterFeesUsd = useMemo(() => { + if (!tradeQuote || !buyAsset || !buyAssetUsdRate) return + + const lastHopIndex = (numSteps - 1) as SupportedTradeQuoteStepIndex + // A quote always has a last hop since it always has a first hop + const lastHop = getHopByIndex(tradeQuote, lastHopIndex)! + const buyAmountAfterProtocolFeesCryptoBaseUnit = lastHop.buyAmountAfterFeesCryptoBaseUnit + + const buyAmountAfterProtocolFeesCryptoPrecision = fromBaseUnit( + buyAmountAfterProtocolFeesCryptoBaseUnit, + buyAsset.precision, + ) + + return bn(buyAmountAfterProtocolFeesCryptoPrecision).times(buyAssetUsdRate).toFixed() + }, [buyAsset, buyAssetUsdRate, numSteps, tradeQuote]) + + if (buyAmountAfterFeesUsd === undefined || sellAmountIncludingFeesUsd === undefined) + return undefined + + return bn(1).minus(bnOrZero(buyAmountAfterFeesUsd).div(sellAmountIncludingFeesUsd)).toString() +}