Skip to content

Commit

Permalink
fix: use actual input output difference (#7817)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xApotheosis authored Sep 26, 2024
1 parent 1029292 commit 9c73047
Show file tree
Hide file tree
Showing 13 changed files with 79 additions and 19 deletions.
2 changes: 1 addition & 1 deletion src/assets/translations/de/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/es/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/fr/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/ja/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,7 @@
"manualReceiveAddress": "資金を受け取るアドレスです。手動で入力されていますので、正しいことを確認してください。",
"amountPercentageDifference": "これは、最良の見積もりと比較した、あなたが受け取る %{buyAssetSymbol} の合計額の差のパーセンテージです。",
"overallPercentageDifference": "これは、最良の見積もりと比較した、すべての手数料を差し引いた後の受け取り総額のパーセンテージの差です。",
"priceImpactDifference": "入力量と出力量のUSD値間の推定差",
"inputOutputDifference": "入力量と出力量のUSD値間の推定差",
"gasFee": "これは、この取引を完了するための推定ガス代です。",
"slippageWithAmount": "価格が変動し、受け取る金額が %{amount} 未満になる場合、トランザクションは取り消されます。これは受け取ることが保証される最低金額です。",
"slippage": "価格がこのパーセンテージを超えて不利に変化した場合、トランザクションは元に戻ります。",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/pt/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/ru/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -883,7 +883,7 @@
"manualReceiveAddress": "Это адрес, на который вы будете получать средства. Он был введен вручную, пожалуйста, проверьте его достоверность.",
"amountPercentageDifference": "Это процентная разница в общей сумме %{buyAssetSymbol}, которую вы получите, по сравнению с лучшим предложением",
"overallPercentageDifference": "Это процентная разница в общей сумме, полученной после вычета всех комиссий, по сравнению с лучшим предложением.",
"priceImpactDifference": "Расчетная разница между значениями входных и выходных сумм в долларах США.",
"inputOutputDifference": "Расчетная разница между значениями входных и выходных сумм в долларах США.",
"gasFee": "Это примерная стоимость газа для завершения этой сделки.",
"slippageWithAmount": "Если цена изменится таким образом, что вы получите меньше %{amount}, ваша сделка будет отменена. Это минимальная сумма, которую вы гарантированно получите.",
"slippage": "Ваша сделка будет отменена, если цена изменится в неблагоприятную сторону более чем на этот процент.",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/tr/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/uk/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -883,7 +883,7 @@
"manualReceiveAddress": "Це адреса, на яку ви отримаєте свої кошти. Вона була введена вручну, будь ласка, переконайтеся, що вона правильна.",
"amountPercentageDifference": "Це відсоткова різниця в загальній сумі %{buyAssetSymbol}, яку ви отримаєте, порівняно з найкращою пропозицією",
"overallPercentageDifference": "Це відсоткова різниця в загальній сумі, отриманій після вирахування всіх комісій, порівняно з найкращою пропозицією",
"priceImpactDifference": "Розрахункова різниця між значеннями вхідних і вихідних сум у доларах США.",
"inputOutputDifference": "Розрахункова різниця між значеннями вхідних і вихідних сум у доларах США.",
"gasFee": "Це приблизна вартість газу, необхідна для завершення цієї торгівлі.",
"slippageWithAmount": "Якщо ціна зміниться таким чином, що ви отримаєте менше %{amount}, ваша транзакція буде скасована. Це мінімальна сума, яку ви гарантовано отримаєте.",
"slippage": "Ваша транзакція буде скасована, якщо ціна зміниться несприятливо більш ніж на цей відсоток.",
Expand Down
2 changes: 1 addition & 1 deletion src/assets/translations/zh/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,7 @@
"manualReceiveAddress": "这是你接收资金的地址。已手动输入,请确保正确。",
"amountPercentageDifference": "这是你将收到的 %{buyAssetSymbol} 总数与最佳报价相比的百分比差异",
"overallPercentageDifference": "这是扣除所有费用后收到的总数与最佳报价相比的百分比差异",
"priceImpactDifference": "输入和输出金额的美元价值之间的估计差异。",
"inputOutputDifference": "输入和输出金额的美元价值之间的估计差异。",
"gasFee": "这是完成这笔交易的估计手续费。",
"slippageWithAmount": "如果价格变动导致你收到的金额少于 %{amount},你的交易将被还原。这是保证你收到的最低金额。",
"slippage": "如果价格不利变化超过此百分比,你的交易将恢复。",
Expand Down
14 changes: 8 additions & 6 deletions src/components/MultiHopTrade/components/TradeAmountInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ export type TradeAmountInputProps = {
cryptoAmount: string
fiatAmount: string
showFiatAmount?: boolean
priceImpactPercentage?: string
balance?: string
fiatBalance?: string
errors?: FieldError
Expand All @@ -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]
Expand Down Expand Up @@ -150,7 +150,6 @@ export const TradeAmountInput: React.FC<TradeAmountInputProps> = memo(
showFiatAmount = '0',
balance,
fiatBalance,
priceImpactPercentage,
errors,
percentOptions = defaultPercentOptions,
children,
Expand All @@ -164,6 +163,7 @@ export const TradeAmountInput: React.FC<TradeAmountInputProps> = memo(
layout = 'stacked',
isFiat,
onToggleIsFiat: handleIsInputtingFiatSellAmountChange,
inputOutputDifferenceDecimalPercentage: inputOutputDifferencePercentage,
}) => {
const {
number: { localeParts },
Expand Down Expand Up @@ -314,7 +314,9 @@ export const TradeAmountInput: React.FC<TradeAmountInputProps> = memo(

const handleOnMaxClick = useMemo(() => () => onMaxClick(Boolean(isFiat)), [isFiat, onMaxClick])

const priceImpactColor = usePriceImpactColor(priceImpactPercentage)
const priceImpactColor = usePriceImpactColor(
bnOrZero(inputOutputDifferencePercentage).times(100).toString(),
)

return (
<FormControl
Expand Down Expand Up @@ -399,16 +401,16 @@ export const TradeAmountInput: React.FC<TradeAmountInputProps> = memo(
>
<Skeleton isLoaded={!showFiatSkeleton}>{oppositeCurrency}</Skeleton>
</Button>
{priceImpactPercentage && (
<Tooltip label={translate('trade.tooltip.priceImpactDifference')}>
{inputOutputDifferencePercentage && (
<Tooltip label={translate('trade.tooltip.inputOutputDifference')}>
<Flex>
<Skeleton isLoaded={!showFiatSkeleton}>
<Amount.Percent
fontSize='sm'
prefix='('
suffix=')'
color={priceImpactColor ?? 'text.subtle'}
value={bnOrZero(priceImpactPercentage).div(100).times(-1).toString()}
value={bnOrZero(inputOutputDifferencePercentage).times(-1).toString()}
/>
</Skeleton>
</Flex>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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(() => {
Expand Down Expand Up @@ -218,7 +219,7 @@ export const TradeInputBody = ({
onAccountIdChange={setBuyAssetAccountId}
formControlProps={formControlProps}
labelPostFix={buyTradeAssetSelect}
priceImpactPercentage={priceImpactPercentage?.toString()}
inputOutputDifferenceDecimalPercentage={inputOutputDifferenceDecimalPercentage}
/>
</Stack>
)
Expand Down
57 changes: 57 additions & 0 deletions src/components/MultiHopTrade/hooks/useInputOutputDifference.ts
Original file line number Diff line number Diff line change
@@ -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()
}

0 comments on commit 9c73047

Please sign in to comment.