Commit 28181671 authored by charity-sock-pacifist's avatar charity-sock-pacifist Committed by GitHub

feat: swap fees [main] (#7478)

parent c2440d10
import { CurrencyAmount } from '@uniswap/sdk-core'
import { FeatureFlag } from 'featureFlags'
import { USDC_MAINNET } from '../../../src/constants/tokens'
import { getBalance, getTestSelector } from '../../utils'
describe('Swap with fees', () => {
describe('Classic swaps', () => {
beforeEach(() => {
cy.visit('/swap', { featureFlags: [{ name: FeatureFlag.feesEnabled, value: true }] })
// Store trade quote into alias
cy.intercept({ url: 'https://api.uniswap.org/v2/quote' }, (req) => {
// Avoid tracking stablecoin pricing fetches
if (JSON.parse(req.body).intent !== 'pricing') req.alias = 'quoteFetch'
})
})
it('displays $0 fee on swaps without fees', () => {
// Set up a stablecoin <> stablecoin swap (no fees)
cy.get('#swap-currency-input .open-currency-select-button').click()
cy.contains('DAI').click()
cy.get('#swap-currency-output .open-currency-select-button').click()
cy.contains('USDC').click()
cy.get('#swap-currency-output .token-amount-input').type('1')
// Verify 0 fee UI is displayed
cy.get(getTestSelector('swap-details-header-row')).click()
cy.contains('Fee')
cy.contains('$0')
})
it('swaps ETH for USDC exact-out with swap fee', () => {
cy.hardhat().then((hardhat) => {
getBalance(USDC_MAINNET).then((initialBalance) => {
// Set up swap
cy.get('#swap-currency-output .open-currency-select-button').click()
cy.contains('USDC').click()
cy.get('#swap-currency-output .token-amount-input').type('1')
cy.wait('@quoteFetch')
.its('response.body')
.then(({ quote: { portionBips, portionRecipient, portionAmount } }) => {
// Fees are generally expected to always be enabled for ETH -> USDC swaps
// If the routing api does not include a fee, end the test early rather than manually update routes and hardcode fee vars
if (portionRecipient) return
cy.then(() => hardhat.getBalance(portionRecipient, USDC_MAINNET)).then((initialRecipientBalance) => {
const feeCurrencyAmount = CurrencyAmount.fromRawAmount(USDC_MAINNET, portionAmount)
// Initiate transaction
cy.get('#swap-button').click()
cy.contains('Review swap')
// Verify fee percentage and amount is displayed
cy.contains(`Fee (${portionBips / 100}%)`)
// Confirm transaction
cy.contains('Confirm swap').click()
// Verify transaction
cy.get(getTestSelector('web3-status-connected')).should('not.contain', 'Pending')
cy.get(getTestSelector('popups')).contains('Swapped')
// Verify the post-fee output is the expected exact-out amount
const finalBalance = initialBalance + 1
cy.get('#swap-currency-output').contains(`Balance: ${finalBalance}`)
getBalance(USDC_MAINNET).should('eq', finalBalance)
// Verify fee recipient received fee
cy.then(() => hardhat.getBalance(portionRecipient, USDC_MAINNET)).then((finalRecipientBalance) => {
const expectedFinalRecipientBalance = initialRecipientBalance.add(feeCurrencyAmount)
cy.then(() => finalRecipientBalance.equalTo(expectedFinalRecipientBalance)).should('be.true')
})
})
})
})
})
})
it('swaps ETH for USDC exact-in with swap fee', () => {
cy.hardhat().then((hardhat) => {
// Set up swap
cy.get('#swap-currency-output .open-currency-select-button').click()
cy.contains('USDC').click()
cy.get('#swap-currency-input .token-amount-input').type('.01')
cy.wait('@quoteFetch')
.its('response.body')
.then(({ quote: { portionBips, portionRecipient } }) => {
// Fees are generally expected to always be enabled for ETH -> USDC swaps
// If the routing api does not include a fee, end the test early rather than manually update routes and hardcode fee vars
if (portionRecipient) return
cy.then(() => hardhat.getBalance(portionRecipient, USDC_MAINNET)).then((initialRecipientBalance) => {
// Initiate transaction
cy.get('#swap-button').click()
cy.contains('Review swap')
// Verify fee percentage and amount is displayed
cy.contains(`Fee (${portionBips / 100}%)`)
// Confirm transaction
cy.contains('Confirm swap').click()
// Verify transaction
cy.get(getTestSelector('web3-status-connected')).should('not.contain', 'Pending')
cy.get(getTestSelector('popups')).contains('Swapped')
// Verify fee recipient received fee
cy.then(() => hardhat.getBalance(portionRecipient, USDC_MAINNET)).then((finalRecipientBalance) => {
cy.then(() => finalRecipientBalance.greaterThan(initialRecipientBalance)).should('be.true')
})
})
})
})
})
})
describe('UniswapX swaps', () => {
it('displays UniswapX fee in UI', () => {
cy.visit('/swap', {
featureFlags: [
{ name: FeatureFlag.feesEnabled, value: true },
{ name: FeatureFlag.uniswapXDefaultEnabled, value: true },
],
})
// Intercept the trade quote
cy.intercept({ url: 'https://api.uniswap.org/v2/quote' }, (req) => {
// Avoid intercepting stablecoin pricing fetches
if (JSON.parse(req.body).intent !== 'pricing') {
req.reply({ fixture: 'uniswapx/feeQuote.json' })
}
})
// Setup swap
cy.get('#swap-currency-input .open-currency-select-button').click()
cy.contains('USDC').click()
cy.get('#swap-currency-output .open-currency-select-button').click()
cy.contains('ETH').click()
cy.get('#swap-currency-input .token-amount-input').type('200')
// Verify fee UI is displayed
cy.get(getTestSelector('swap-details-header-row')).click()
cy.contains('Fee (0.15%)')
})
})
})
This diff is collapsed.
......@@ -5,7 +5,7 @@
"incremental": true,
"isolatedModules": false,
"noImplicitAny": false,
"target": "ES5",
"target": "ES6",
"tsBuildInfoFile": "../node_modules/.cache/tsbuildinfo/cypress", // avoid clobbering the build tsbuildinfo
"types": ["cypress", "node"],
},
......
......@@ -18,6 +18,7 @@ import { useUniswapXDefaultEnabledFlag } from 'featureFlags/flags/uniswapXDefaul
import { useUniswapXEthOutputFlag } from 'featureFlags/flags/uniswapXEthOutput'
import { useUniswapXExactOutputFlag } from 'featureFlags/flags/uniswapXExactOutput'
import { useUniswapXSyntheticQuoteFlag } from 'featureFlags/flags/uniswapXUseSyntheticQuote'
import { useFeesEnabledFlag } from 'featureFlags/flags/useFees'
import { useUpdateAtom } from 'jotai/utils'
import { Children, PropsWithChildren, ReactElement, ReactNode, useCallback, useState } from 'react'
import { X } from 'react-feather'
......@@ -267,6 +268,12 @@ export default function FeatureFlagModal() {
<X size={24} />
</CloseButton>
</Header>
<FeatureFlagOption
variant={BaseVariant}
value={useFeesEnabledFlag()}
featureFlag={FeatureFlag.feesEnabled}
label="Enable Swap Fees"
/>
<FeatureFlagOption
variant={BaseVariant}
value={useFallbackProviderEnabledFlag()}
......
......@@ -15,6 +15,7 @@ function useHasUpdatedTx() {
return !!prevPendingActivityCount && pendingActivityCount < prevPendingActivityCount
}
// TODO(WEB-3004) - Add useCachedPortfolioBalanceUsd to simplify usage of useCachedPortfolioBalancesQuery
export function useCachedPortfolioBalancesQuery({ account }: { account?: string }) {
return usePortfolioBalancesQuery({
skip: !account,
......
import { BrowserEvent, InterfaceElementName, InterfaceEventName } from '@uniswap/analytics-events'
import { Currency } from '@uniswap/sdk-core'
import { useWeb3React } from '@web3-react/core'
import { TraceEvent } from 'analytics'
import CurrencyLogo from 'components/Logo/CurrencyLogo'
import { useCachedPortfolioBalancesQuery } from 'components/PrefetchBalancesWrapper/PrefetchBalancesWrapper'
import { AutoRow } from 'components/Row'
import { COMMON_BASES } from 'constants/routing'
import { useTokenInfoFromActiveList } from 'hooks/useTokenInfoFromActiveList'
......@@ -30,13 +32,19 @@ const BaseWrapper = styled.div<{ disable?: boolean }>`
background-color: ${({ theme, disable }) => disable && theme.surface3};
`
const formatAnalyticsEventProperties = (currency: Currency, searchQuery: string, isAddressSearch: string | false) => ({
const formatAnalyticsEventProperties = (
currency: Currency,
searchQuery: string,
isAddressSearch: string | false,
portfolioBalanceUsd: number | undefined
) => ({
token_symbol: currency?.symbol,
token_chain_id: currency?.chainId,
token_address: getTokenAddress(currency),
is_suggested_token: true,
is_selected_from_list: false,
is_imported_by_user: false,
total_balances_usd: portfolioBalanceUsd,
...(isAddressSearch === false
? { search_token_symbol_input: searchQuery }
: { search_token_address_input: isAddressSearch }),
......@@ -54,8 +62,12 @@ export default function CommonBases({
onSelect: (currency: Currency) => void
searchQuery: string
isAddressSearch: string | false
portfolioBalanceUsd?: number
}) {
const bases = chainId !== undefined ? COMMON_BASES[chainId] ?? [] : []
const { account } = useWeb3React()
const { data } = useCachedPortfolioBalancesQuery({ account })
const portfolioBalanceUsd = data?.portfolios?.[0].tokensTotalDenominatedValue?.value
return bases.length > 0 ? (
<AutoRow gap="4px">
......@@ -66,7 +78,7 @@ export default function CommonBases({
<TraceEvent
events={[BrowserEvent.onClick, BrowserEvent.onKeyPress]}
name={InterfaceEventName.TOKEN_SELECTED}
properties={formatAnalyticsEventProperties(currency, searchQuery, isAddressSearch)}
properties={formatAnalyticsEventProperties(currency, searchQuery, isAddressSearch, portfolioBalanceUsd)}
element={InterfaceElementName.COMMON_BASES_CURRENCY_BUTTON}
key={currencyId(currency)}
>
......
......@@ -3,6 +3,7 @@ import { Currency, CurrencyAmount, Token } from '@uniswap/sdk-core'
import { useWeb3React } from '@web3-react/core'
import { TraceEvent } from 'analytics'
import Loader from 'components/Icons/LoadingSpinner'
import { useCachedPortfolioBalancesQuery } from 'components/PrefetchBalancesWrapper/PrefetchBalancesWrapper'
import TokenSafetyIcon from 'components/TokenSafety/TokenSafetyIcon'
import { checkWarning } from 'constants/tokenSafety'
import { TokenBalances } from 'lib/hooks/useTokenList/sorting'
......@@ -128,13 +129,15 @@ export function CurrencyRow({
const warning = currency.isNative ? null : checkWarning(currency.address)
const isBlockedToken = !!warning && !warning.canProceed
const blockedTokenOpacity = '0.6'
const { data } = useCachedPortfolioBalancesQuery({ account })
const portfolioBalanceUsd = data?.portfolios?.[0].tokensTotalDenominatedValue?.value
// only show add or remove buttons if not on selected list
return (
<TraceEvent
events={[BrowserEvent.onClick, BrowserEvent.onKeyPress]}
name={InterfaceEventName.TOKEN_SELECTED}
properties={{ is_imported_by_user: customAdded, ...eventProperties }}
properties={{ is_imported_by_user: customAdded, ...eventProperties, total_balances_usd: portfolioBalanceUsd }}
element={InterfaceElementName.TOKEN_SELECTOR_ROW}
>
<MenuItem
......
......@@ -31,7 +31,10 @@ const GasCostItem = ({ title, amount, itemValue }: GasCostItemProps) => {
)
}
const GaslessSwapLabel = () => <UniswapXRouterLabel>$0</UniswapXRouterLabel>
const GaslessSwapLabel = () => {
const { formatNumber } = useFormatter()
return <UniswapXRouterLabel>{formatNumber({ input: 0, type: NumberType.FiatGasPrice })}</UniswapXRouterLabel>
}
type GasBreakdownTooltipProps = { trade: InterfaceTrade; hideUniswapXDescription?: boolean }
......
......@@ -11,6 +11,8 @@ import { act, render, screen } from 'test-utils/render'
import SwapDetailsDropdown from './SwapDetailsDropdown'
jest.mock('../../featureFlags/flags/useFees', () => ({ useFeesEnabled: () => true }))
describe('SwapDetailsDropdown.tsx', () => {
it('renders a trade', () => {
const { asFragment } = render(
......
......@@ -111,6 +111,7 @@ function AdvancedSwapDetails(props: SwapDetailsProps & { open: boolean }) {
<SwapLineItem {...lineItemProps} type={SwapLineItemType.MAX_SLIPPAGE} />
<SwapLineItem {...lineItemProps} type={SwapLineItemType.INPUT_TOKEN_FEE_ON_TRANSFER} />
<SwapLineItem {...lineItemProps} type={SwapLineItemType.OUTPUT_TOKEN_FEE_ON_TRANSFER} />
<SwapLineItem {...lineItemProps} type={SwapLineItemType.SWAP_FEE} />
<SwapLineItem {...lineItemProps} type={SwapLineItemType.NETWORK_COST} />
<Separator />
<SwapLineItem {...lineItemProps} type={SwapLineItemType.ROUTING_INFO} />
......
......@@ -11,6 +11,8 @@ import {
} from 'test-utils/constants'
import { render } from 'test-utils/render'
jest.mock('../../featureFlags/flags/useFees', () => ({ useFeesEnabled: () => true }))
// Forces tooltips to render in snapshots
jest.mock('react-dom', () => {
const original = jest.requireActual('react-dom')
......
......@@ -6,11 +6,13 @@ import RouterLabel from 'components/RouterLabel'
import Row, { RowBetween } from 'components/Row'
import { MouseoverTooltip, TooltipSize } from 'components/Tooltip'
import { SUPPORTED_GAS_ESTIMATE_CHAIN_IDS } from 'constants/chains'
import { useFeesEnabled } from 'featureFlags/flags/useFees'
import useHoverProps from 'hooks/useHoverProps'
import { useUSDPrice } from 'hooks/useUSDPrice'
import { useIsMobile } from 'nft/hooks'
import React, { PropsWithChildren, useEffect, useState } from 'react'
import { animated, SpringValue } from 'react-spring'
import { InterfaceTrade, TradeFillType } from 'state/routing/types'
import { InterfaceTrade, SubmittableTrade, TradeFillType } from 'state/routing/types'
import { isPreviewTrade, isUniswapXTrade } from 'state/routing/utils'
import { useUserSlippageTolerance } from 'state/user/hooks'
import { SlippageTolerance } from 'state/user/types'
......@@ -31,6 +33,7 @@ export enum SwapLineItemType {
OUTPUT_TOKEN_FEE_ON_TRANSFER,
PRICE_IMPACT,
MAX_SLIPPAGE,
SWAP_FEE,
MAXIMUM_INPUT,
MINIMUM_OUTPUT,
ROUTING_INFO,
......@@ -74,6 +77,28 @@ function FOTTooltipContent() {
)
}
function SwapFeeTooltipContent({ hasFee }: { hasFee: boolean }) {
const message = hasFee ? (
<Trans>
Fee is applied on a few token pairs to ensure the best experience with Uniswap. It is paid in the output token and
has already been factored into the quote.
</Trans>
) : (
<Trans>
Fee is applied on a few token pairs to ensure the best experience with Uniswap. There is no fee associated with
this swap.
</Trans>
)
return (
<>
{message}{' '}
<ExternalLink href="https://uniswap.org/docs/v2/protocol-overview/fees/">
<Trans>Learn more</Trans>
</ExternalLink>
</>
)
}
function Loading({ width = 50 }: { width?: number }) {
return <LoadingRow data-testid="loading-row" height={15} width={width} />
}
......@@ -89,6 +114,18 @@ function CurrencyAmountRow({ amount }: { amount: CurrencyAmount<Currency> }) {
return <>{`${formattedAmount} ${amount.currency.symbol}`}</>
}
function FeeRow({ trade: { swapFee, outputAmount } }: { trade: SubmittableTrade }) {
const { formatNumber } = useFormatter()
const feeCurrencyAmount = CurrencyAmount.fromRawAmount(outputAmount.currency, swapFee?.amount ?? 0)
const { data: outputFeeFiatValue } = useUSDPrice(feeCurrencyAmount, feeCurrencyAmount?.currency)
// Fallback to displaying token amount if fiat value is not available
if (outputFeeFiatValue === undefined) return <CurrencyAmountRow amount={feeCurrencyAmount} />
return <>{formatNumber({ input: outputFeeFiatValue, type: NumberType.FiatGasPrice })}</>
}
type LineItemData = {
Label: React.FC
Value: React.FC
......@@ -101,6 +138,7 @@ function useLineItem(props: SwapLineItemProps): LineItemData | undefined {
const { trade, syncing, allowedSlippage, type } = props
const { formatNumber, formatSlippage } = useFormatter()
const isAutoSlippage = useUserSlippageTolerance()[0] === SlippageTolerance.Auto
const feesEnabled = useFeesEnabled()
const isUniswapX = isUniswapXTrade(trade)
const isPreview = isPreviewTrade(trade)
......@@ -153,6 +191,19 @@ function useLineItem(props: SwapLineItemProps): LineItemData | undefined {
</Row>
),
}
case SwapLineItemType.SWAP_FEE: {
if (!feesEnabled) return
if (isPreview) return { Label: () => <Trans>Fee</Trans>, Value: () => <Loading /> }
return {
Label: () => (
<>
<Trans>Fee</Trans> {trade.swapFee && `(${formatSlippage(trade.swapFee.percent)})`}
</>
),
TooltipBody: () => <SwapFeeTooltipContent hasFee={Boolean(trade.swapFee)} />,
Value: () => <FeeRow trade={trade} />,
}
}
case SwapLineItemType.MAXIMUM_INPUT:
if (trade.tradeType === TradeType.EXACT_INPUT) return
return {
......
......@@ -3,6 +3,8 @@ import { render, screen, within } from 'test-utils/render'
import SwapModalFooter from './SwapModalFooter'
jest.mock('../../featureFlags/flags/useFees', () => ({ useFeesEnabled: () => true }))
describe('SwapModalFooter.tsx', () => {
it('matches base snapshot, test trade exact input', () => {
const { asFragment } = render(
......
......@@ -119,6 +119,7 @@ export default function SwapModalFooter({
<ExpandableLineItems {...lineItemProps} open={showMore} />
<SwapLineItem {...lineItemProps} type={SwapLineItemType.INPUT_TOKEN_FEE_ON_TRANSFER} />
<SwapLineItem {...lineItemProps} type={SwapLineItemType.OUTPUT_TOKEN_FEE_ON_TRANSFER} />
<SwapLineItem {...lineItemProps} type={SwapLineItemType.SWAP_FEE} />
<SwapLineItem {...lineItemProps} type={SwapLineItemType.NETWORK_COST} />
</DetailsContainer>
{showAcceptChanges ? (
......
......@@ -384,6 +384,29 @@ exports[`SwapDetailsDropdown.tsx renders a trade 1`] = `
</div>
</div>
</div>
<div>
<div
class="c2 c3 c4"
>
<div
class="c9 c19 css-142zc9n"
data-testid="swap-li-label"
>
Fee
</div>
<div
class="c12"
>
<div>
<div
class="c9 c20 css-142zc9n"
>
0 DEF
</div>
</div>
</div>
</div>
</div>
<div>
<div
class="c2 c3 c4"
......
......@@ -354,6 +354,29 @@ exports[`SwapModalFooter.tsx matches base snapshot, test trade exact input 1`] =
</div>
</div>
</div>
<div>
<div
class="c2 c3 c4"
>
<div
class="c5 c6 css-142zc9n"
data-testid="swap-li-label"
>
Fee
</div>
<div
class="c7"
>
<div>
<div
class="c5 c8 css-142zc9n"
>
0 DEF
</div>
</div>
</div>
</div>
</div>
<div>
<div
class="c2 c3 c4"
......@@ -938,6 +961,28 @@ exports[`SwapModalFooter.tsx renders a preview trade while disabling submission
</div>
</div>
</div>
<div>
<div
class="c2 c3 c4"
>
<div
class="c5 c6 css-142zc9n"
data-testid="swap-li-label"
>
Fee
</div>
<div
class="c5 c7 css-142zc9n"
>
<div
class="c11"
data-testid="loading-row"
height="15"
width="50"
/>
</div>
</div>
</div>
<div>
<div
class="c2 c3 c4"
......
import { BaseVariant, FeatureFlag, useBaseFlag } from '../index'
export function useFeesEnabledFlag(): BaseVariant {
return useBaseFlag(FeatureFlag.feesEnabled)
}
export function useFeesEnabled(): boolean {
return useFeesEnabledFlag() === BaseVariant.Enabled
}
......@@ -22,6 +22,7 @@ export enum FeatureFlag {
uniswapXDefaultEnabled = 'uniswapx_default_enabled',
quickRouteMainnet = 'enable_quick_route_mainnet',
progressIndicatorV2 = 'progress_indicator_v2',
feesEnabled = 'fees_enabled',
}
interface FeatureFlagsContextType {
......
import { Percent, TradeType } from '@uniswap/sdk-core'
import { FlatFeeOptions } from '@uniswap/universal-router-sdk'
import { FeeOptions } from '@uniswap/v3-sdk'
import { useWeb3React } from '@web3-react/core'
import { BigNumber } from 'ethers/lib/ethers'
import { PermitSignature } from 'hooks/usePermitAllowance'
import { useCallback } from 'react'
import { InterfaceTrade, TradeFillType } from 'state/routing/types'
......@@ -20,11 +23,24 @@ import { useUniversalRouterSwapCallback } from './useUniversalRouter'
export type SwapResult = Awaited<ReturnType<ReturnType<typeof useSwapCallback>>>
type UniversalRouterFeeField = { feeOptions: FeeOptions } | { flatFeeOptions: FlatFeeOptions }
function getUniversalRouterFeeFields(trade?: InterfaceTrade): UniversalRouterFeeField | undefined {
if (!isClassicTrade(trade)) return undefined
if (!trade.swapFee) return undefined
if (trade.tradeType === TradeType.EXACT_INPUT) {
return { feeOptions: { fee: trade.swapFee.percent, recipient: trade.swapFee.recipient } }
} else {
return { flatFeeOptions: { amount: BigNumber.from(trade.swapFee.amount), recipient: trade.swapFee.recipient } }
}
}
// Returns a function that will execute a swap, if the parameters are all valid
// and the user has approved the slippage adjusted input amount for the trade
export function useSwapCallback(
trade: InterfaceTrade | undefined, // trade to execute, required
fiatValues: { amountIn?: number; amountOut?: number }, // usd values for amount in and out, logged for analytics
fiatValues: { amountIn?: number; amountOut?: number; feeUsd?: number }, // usd values for amount in and out, and the fee value, logged for analytics
allowedSlippage: Percent, // in bips
permitSignature: PermitSignature | undefined
) {
......@@ -47,6 +63,7 @@ export function useSwapCallback(
slippageTolerance: allowedSlippage,
deadline,
permit: permitSignature,
...getUniversalRouterFeeFields(trade),
}
)
......
......@@ -5,6 +5,7 @@ import { Percent } from '@uniswap/sdk-core'
import { DutchOrder, DutchOrderBuilder } from '@uniswap/uniswapx-sdk'
import { useWeb3React } from '@web3-react/core'
import { sendAnalyticsEvent, useTrace } from 'analytics'
import { useCachedPortfolioBalancesQuery } from 'components/PrefetchBalancesWrapper/PrefetchBalancesWrapper'
import { formatSwapSignedAnalyticsEventProperties } from 'lib/utils/analytics'
import { useCallback } from 'react'
import { DutchOrderTrade, TradeFillType } from 'state/routing/types'
......@@ -50,12 +51,15 @@ export function useUniswapXSwapCallback({
fiatValues,
}: {
trade?: DutchOrderTrade
fiatValues: { amountIn?: number; amountOut?: number }
fiatValues: { amountIn?: number; amountOut?: number; feeUsd?: number }
allowedSlippage: Percent
}) {
const { account, provider } = useWeb3React()
const analyticsContext = useTrace()
const { data } = useCachedPortfolioBalancesQuery({ account })
const portfolioBalanceUsd = data?.portfolios?.[0]?.tokensTotalDenominatedValue?.value
return useCallback(
async () =>
trace('swapx.send', async ({ setTraceData, setTraceStatus }) => {
......@@ -82,7 +86,7 @@ export function useUniswapXSwapCallback({
.decayEndTime(endTime)
.deadline(deadline)
.swapper(account)
.nonFeeRecipient(account)
.nonFeeRecipient(account, trade.swapFee?.recipient)
// if fetching the nonce fails for any reason, default to existing nonce from the Swap quote.
.nonce(updatedNonce ?? trade.order.info.nonce)
.build()
......@@ -115,6 +119,7 @@ export function useUniswapXSwapCallback({
allowedSlippage,
fiatValues,
timeToSignSinceRequestMs: Date.now() - beforeSign,
portfolioBalanceUsd,
}),
...analyticsContext,
})
......@@ -139,6 +144,7 @@ export function useUniswapXSwapCallback({
trade,
allowedSlippage,
fiatValues,
portfolioBalanceUsd,
}),
...analyticsContext,
errorCode: body.errorCode,
......@@ -154,6 +160,6 @@ export function useUniswapXSwapCallback({
response: { orderHash: body.hash, deadline: updatedOrder.info.deadline },
}
}),
[account, provider, trade, allowedSlippage, fiatValues, analyticsContext]
[account, provider, trade, allowedSlippage, fiatValues, analyticsContext, portfolioBalanceUsd]
)
}
......@@ -2,10 +2,11 @@ import { BigNumber } from '@ethersproject/bignumber'
import { t } from '@lingui/macro'
import { SwapEventName } from '@uniswap/analytics-events'
import { Percent } from '@uniswap/sdk-core'
import { SwapRouter, UNIVERSAL_ROUTER_ADDRESS } from '@uniswap/universal-router-sdk'
import { FlatFeeOptions, SwapRouter, UNIVERSAL_ROUTER_ADDRESS } from '@uniswap/universal-router-sdk'
import { FeeOptions, toHex } from '@uniswap/v3-sdk'
import { useWeb3React } from '@web3-react/core'
import { sendAnalyticsEvent, useTrace } from 'analytics'
import { useCachedPortfolioBalancesQuery } from 'components/PrefetchBalancesWrapper/PrefetchBalancesWrapper'
import useBlockNumber from 'lib/hooks/useBlockNumber'
import { formatCommonPropertiesForTrade, formatSwapSignedAnalyticsEventProperties } from 'lib/utils/analytics'
import { useCallback } from 'react'
......@@ -43,17 +44,20 @@ interface SwapOptions {
deadline?: BigNumber
permit?: PermitSignature
feeOptions?: FeeOptions
flatFeeOptions?: FlatFeeOptions
}
export function useUniversalRouterSwapCallback(
trade: ClassicTrade | undefined,
fiatValues: { amountIn?: number; amountOut?: number },
fiatValues: { amountIn?: number; amountOut?: number; feeUsd?: number },
options: SwapOptions
) {
const { account, chainId, provider } = useWeb3React()
const analyticsContext = useTrace()
const blockNumber = useBlockNumber()
const isAutoSlippage = useUserSlippageTolerance()[0] === 'auto'
const { data } = useCachedPortfolioBalancesQuery({ account })
const portfolioBalanceUsd = data?.portfolios?.[0]?.tokensTotalDenominatedValue?.value
return useCallback(async () => {
return trace('swap.send', async ({ setTraceData, setTraceStatus, setTraceError }) => {
......@@ -76,6 +80,7 @@ export function useUniversalRouterSwapCallback(
deadlineOrPreviousBlockhash: options.deadline?.toString(),
inputTokenPermit: options.permit,
fee: options.feeOptions,
flatFee: options.flatFeeOptions,
})
const tx = {
......@@ -117,6 +122,7 @@ export function useUniversalRouterSwapCallback(
allowedSlippage: options.slippageTolerance,
fiatValues,
txHash: response.hash,
portfolioBalanceUsd,
}),
...analyticsContext,
})
......@@ -154,16 +160,14 @@ export function useUniversalRouterSwapCallback(
})
}, [
account,
analyticsContext,
blockNumber,
chainId,
fiatValues,
options.deadline,
options.feeOptions,
options.permit,
options.slippageTolerance,
provider,
trade,
options,
analyticsContext,
blockNumber,
isAutoSlippage,
fiatValues,
portfolioBalanceUsd,
])
}
......@@ -4,6 +4,7 @@ import { useUniswapXDefaultEnabled } from 'featureFlags/flags/uniswapXDefault'
import { useUniswapXEthOutputEnabled } from 'featureFlags/flags/uniswapXEthOutput'
import { useUniswapXExactOutputEnabled } from 'featureFlags/flags/uniswapXExactOutput'
import { useUniswapXSyntheticQuoteEnabled } from 'featureFlags/flags/uniswapXUseSyntheticQuote'
import { useFeesEnabled } from 'featureFlags/flags/useFees'
import { useMemo } from 'react'
import { GetQuoteArgs, INTERNAL_ROUTER_PREFERENCE_PRICE, RouterPreference } from 'state/routing/types'
import { currencyAddressForSwapQuote } from 'state/routing/utils'
......@@ -40,6 +41,10 @@ export function useRoutingAPIArguments({
const uniswapXExactOutputEnabled = useUniswapXExactOutputEnabled()
const isUniswapXDefaultEnabled = useUniswapXDefaultEnabled()
const feesEnabled = useFeesEnabled()
// Don't enable fee logic if this is a quote for pricing
const sendPortionEnabled = routerPreference === INTERNAL_ROUTER_PREFERENCE_PRICE ? false : feesEnabled
return useMemo(
() =>
!tokenIn || !tokenOut || !amount || tokenIn.equals(tokenOut) || tokenIn.wrapped.equals(tokenOut.wrapped)
......@@ -64,6 +69,7 @@ export function useRoutingAPIArguments({
uniswapXEthOutputEnabled,
uniswapXExactOutputEnabled,
isUniswapXDefaultEnabled,
sendPortionEnabled,
inputTax,
outputTax,
},
......@@ -80,6 +86,7 @@ export function useRoutingAPIArguments({
userOptedOutOfUniswapX,
uniswapXEthOutputEnabled,
isUniswapXDefaultEnabled,
sendPortionEnabled,
inputTax,
outputTax,
]
......
import { Currency, CurrencyAmount, Percent, Price, Token } from '@uniswap/sdk-core'
import { NATIVE_CHAIN_ID } from 'constants/tokens'
import { InterfaceTrade, QuoteMethod } from 'state/routing/types'
import { InterfaceTrade, QuoteMethod, SubmittableTrade } from 'state/routing/types'
import { isClassicTrade, isSubmittableTrade, isUniswapXTrade } from 'state/routing/utils'
import { computeRealizedPriceImpact } from 'utils/prices'
......@@ -35,7 +35,11 @@ function getEstimatedNetworkFee(trade: InterfaceTrade) {
return undefined
}
export function formatCommonPropertiesForTrade(trade: InterfaceTrade, allowedSlippage: Percent) {
export function formatCommonPropertiesForTrade(
trade: InterfaceTrade,
allowedSlippage: Percent,
outputFeeFiatValue?: number
) {
return {
routing: trade.fillType,
type: trade.tradeType,
......@@ -47,7 +51,7 @@ export function formatCommonPropertiesForTrade(trade: InterfaceTrade, allowedSli
token_in_symbol: trade.inputAmount.currency.symbol,
token_out_symbol: trade.outputAmount.currency.symbol,
token_in_amount: formatToDecimal(trade.inputAmount, trade.inputAmount.currency.decimals),
token_out_amount: formatToDecimal(trade.outputAmount, trade.outputAmount.currency.decimals),
token_out_amount: formatToDecimal(trade.postTaxOutputAmount, trade.outputAmount.currency.decimals),
price_impact_basis_points: isClassicTrade(trade)
? formatPercentInBasisPointsNumber(computeRealizedPriceImpact(trade))
: undefined,
......@@ -59,6 +63,7 @@ export function formatCommonPropertiesForTrade(trade: InterfaceTrade, allowedSli
minimum_output_after_slippage: trade.minimumAmountOut(allowedSlippage).toSignificant(6),
allowed_slippage: formatPercentNumber(allowedSlippage),
method: getQuoteMethod(trade),
fee_usd: outputFeeFiatValue,
}
}
......@@ -68,19 +73,22 @@ export const formatSwapSignedAnalyticsEventProperties = ({
fiatValues,
txHash,
timeToSignSinceRequestMs,
portfolioBalanceUsd,
}: {
trade: InterfaceTrade
trade: SubmittableTrade
allowedSlippage: Percent
fiatValues: { amountIn?: number; amountOut?: number }
fiatValues: { amountIn?: number; amountOut?: number; feeUsd?: number }
txHash?: string
timeToSignSinceRequestMs?: number
portfolioBalanceUsd?: number
}) => ({
total_balances_usd: portfolioBalanceUsd,
transaction_hash: txHash,
token_in_amount_usd: fiatValues.amountIn,
token_out_amount_usd: fiatValues.amountOut,
// measures the amount of time the user took to sign the permit message or swap tx in their wallet
time_to_sign_since_request_ms: timeToSignSinceRequestMs,
...formatCommonPropertiesForTrade(trade, allowedSlippage),
...formatCommonPropertiesForTrade(trade, allowedSlippage, fiatValues.feeUsd),
})
function getQuoteMethod(trade: InterfaceTrade) {
......@@ -94,10 +102,11 @@ export const formatSwapQuoteReceivedEventProperties = (
allowedSlippage: Percent,
swapQuoteLatencyMs: number | undefined,
inputTax: Percent,
outputTax: Percent
outputTax: Percent,
outputFeeFiatValue: number | undefined
) => {
return {
...formatCommonPropertiesForTrade(trade, allowedSlippage),
...formatCommonPropertiesForTrade(trade, allowedSlippage, outputFeeFiatValue),
swap_quote_block_number: isClassicTrade(trade) ? trade.blockNumber : undefined,
allowed_slippage_basis_points: formatPercentInBasisPointsNumber(allowedSlippage),
token_in_amount_max: trade.maximumAmountIn(allowedSlippage).toExact(),
......
......@@ -294,6 +294,7 @@ export function Swap({
inputError: swapInputError,
inputTax,
outputTax,
outputFeeFiatValue,
} = swapInfo
const [inputTokenHasTax, outputTokenHasTax] = useMemo(
......@@ -441,8 +442,8 @@ export function Swap({
)
const showMaxButton = Boolean(maxInputAmount?.greaterThan(0) && !parsedAmounts[Field.INPUT]?.equalTo(maxInputAmount))
const swapFiatValues = useMemo(() => {
return { amountIn: fiatValueTradeInput.data, amountOut: fiatValueTradeOutput.data }
}, [fiatValueTradeInput, fiatValueTradeOutput])
return { amountIn: fiatValueTradeInput.data, amountOut: fiatValueTradeOutput.data, feeUsd: outputFeeFiatValue }
}, [fiatValueTradeInput.data, fiatValueTradeOutput.data, outputFeeFiatValue])
// the callback to execute the swap
const swapCallback = useSwapCallback(
......@@ -584,10 +585,17 @@ export function Swap({
if (!trade || prevTrade === trade) return // no new swap quote to log
sendAnalyticsEvent(SwapEventName.SWAP_QUOTE_RECEIVED, {
...formatSwapQuoteReceivedEventProperties(trade, allowedSlippage, swapQuoteLatency, inputTax, outputTax),
...formatSwapQuoteReceivedEventProperties(
trade,
allowedSlippage,
swapQuoteLatency,
inputTax,
outputTax,
outputFeeFiatValue
),
...trace,
})
}, [prevTrade, trade, trace, allowedSlippage, swapQuoteLatency, inputTax, outputTax])
}, [prevTrade, trade, trace, allowedSlippage, swapQuoteLatency, inputTax, outputTax, outputFeeFiatValue])
const showDetailsDropdown = Boolean(
!showWrap && userHasSpecifiedInputOutput && (trade || routeIsLoading || routeIsSyncing)
......
......@@ -35,6 +35,8 @@ const protocols: Protocol[] = [Protocol.V2, Protocol.V3, Protocol.MIXED]
// routing API quote query params: https://github.com/Uniswap/routing-api/blob/main/lib/handlers/quote/schema/quote-schema.ts
const DEFAULT_QUERY_PARAMS = {
protocols,
// this should be removed once BE fixes issue where enableUniversalRouter is required for fees to work
enableUniversalRouter: true,
}
function getQuoteLatencyMeasure(mark: PerformanceMark): PerformanceMeasure {
......@@ -66,6 +68,7 @@ function getRoutingAPIConfig(args: GetQuoteArgs): RoutingConfig {
const classic = {
...DEFAULT_QUERY_PARAMS,
routingType: URAQuoteType.CLASSIC,
recipient: account,
}
const tokenOutIsNative = Object.values(SwapRouterNativeAssets).includes(tokenOutAddress as SwapRouterNativeAssets)
......@@ -124,16 +127,24 @@ export const routingApi = createApi({
logSwapQuoteRequest(args.tokenInChainId, args.routerPreference, false)
const quoteStartMark = performance.mark(`quote-fetch-start-${Date.now()}`)
try {
const { tokenInAddress, tokenInChainId, tokenOutAddress, tokenOutChainId, amount, tradeType } = args
const type = isExactInput(tradeType) ? 'EXACT_INPUT' : 'EXACT_OUTPUT'
const {
tokenInAddress: tokenIn,
tokenInChainId,
tokenOutAddress: tokenOut,
tokenOutChainId,
amount,
tradeType,
sendPortionEnabled,
} = args
const requestBody = {
tokenInChainId,
tokenIn: tokenInAddress,
tokenIn,
tokenOutChainId,
tokenOut: tokenOutAddress,
tokenOut,
amount,
type,
sendPortionEnabled,
type: isExactInput(tradeType) ? 'EXACT_INPUT' : 'EXACT_OUTPUT',
intent: args.routerPreference === INTERNAL_ROUTER_PREFERENCE_PRICE ? 'pricing' : undefined,
configs: getRoutingAPIConfig(args),
}
......
......@@ -50,6 +50,7 @@ export interface GetQuoteArgs {
// temporary field indicating the user disabled UniswapX during the transition to the opt-out model
userOptedOutOfUniswapX: boolean
isUniswapXDefaultEnabled: boolean
sendPortionEnabled: boolean
inputTax: Percent
outputTax: Percent
}
......@@ -112,11 +113,11 @@ export interface ClassicQuoteData {
blockNumber: string
amount: string
amountDecimals: string
gasPriceWei: string
gasUseEstimate: string
gasUseEstimateQuote: string
gasUseEstimateQuoteDecimals: string
gasUseEstimateUSD: string
gasPriceWei?: string
gasUseEstimate?: string
gasUseEstimateQuote?: string
gasUseEstimateQuoteDecimals?: string
gasUseEstimateUSD?: string
methodParameters?: { calldata: string; value: string }
quote: string
quoteDecimals: string
......@@ -124,19 +125,30 @@ export interface ClassicQuoteData {
quoteGasAdjustedDecimals: string
route: Array<(V3PoolInRoute | V2PoolInRoute)[]>
routeString: string
portionBips?: number
portionRecipient?: string
portionAmount?: string
portionAmountDecimals?: string
quoteGasAndPortionAdjusted?: string
quoteGasAndPortionAdjustedDecimals?: string
}
export type URADutchOrderQuoteData = {
auctionPeriodSecs: number
deadlineBufferSecs: number
startTimeBufferSecs: number
orderInfo: DutchOrderInfoJSON
quoteId?: string
requestId?: string
slippageTolerance: string
portionBips?: number
portionRecipient?: string
portionAmount?: string
}
type URADutchOrderQuoteResponse = {
routing: URAQuoteType.DUTCH_LIMIT
quote: {
auctionPeriodSecs: number
deadlineBufferSecs: number
startTimeBufferSecs: number
orderInfo: DutchOrderInfoJSON
quoteId?: string
requestId?: string
slippageTolerance: string
}
quote: URADutchOrderQuoteData
allQuotes: Array<URAQuoteResponse>
}
type URAClassicQuoteResponse = {
......@@ -179,6 +191,8 @@ export enum TradeFillType {
export type ApproveInfo = { needsApprove: true; approveGasEstimateUSD: number } | { needsApprove: false }
export type WrapInfo = { needsWrap: true; wrapGasEstimateUSD: number } | { needsWrap: false }
export type SwapFeeInfo = { recipient: string; percent: Percent; amount: string /* raw amount of output token */ }
export class ClassicTrade extends Trade<Currency, Currency, TradeType> {
public readonly fillType = TradeFillType.Classic
approveInfo: ApproveInfo
......@@ -189,6 +203,7 @@ export class ClassicTrade extends Trade<Currency, Currency, TradeType> {
quoteMethod: QuoteMethod
inputTax: Percent
outputTax: Percent
swapFee: SwapFeeInfo | undefined
constructor({
gasUseEstimateUSD,
......@@ -199,6 +214,7 @@ export class ClassicTrade extends Trade<Currency, Currency, TradeType> {
approveInfo,
inputTax,
outputTax,
swapFee,
...routes
}: {
gasUseEstimateUSD?: number
......@@ -210,6 +226,7 @@ export class ClassicTrade extends Trade<Currency, Currency, TradeType> {
approveInfo: ApproveInfo
inputTax: Percent
outputTax: Percent
swapFee?: SwapFeeInfo
v2Routes: {
routev2: V2Route<Currency, Currency>
inputAmount: CurrencyAmount<Currency>
......@@ -236,17 +253,33 @@ export class ClassicTrade extends Trade<Currency, Currency, TradeType> {
this.approveInfo = approveInfo
this.inputTax = inputTax
this.outputTax = outputTax
this.swapFee = swapFee
}
public get executionPrice(): Price<Currency, Currency> {
if (this.tradeType === TradeType.EXACT_INPUT || !this.swapFee) return super.executionPrice
// Fix inaccurate price calculation for exact output trades
return new Price({ baseAmount: this.inputAmount, quoteAmount: this.postSwapFeeOutputAmount })
}
public get totalTaxRate(): Percent {
return this.inputTax.add(this.outputTax)
}
public get postSwapFeeOutputAmount(): CurrencyAmount<Currency> {
// Routing api already applies the swap fee to the output amount for exact-in
if (this.tradeType === TradeType.EXACT_INPUT) return this.outputAmount
const swapFeeAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, this.swapFee?.amount ?? 0)
return this.outputAmount.subtract(swapFeeAmount)
}
public get postTaxOutputAmount() {
// Ideally we should calculate the final output amount by ammending the inputAmount based on the input tax and then applying the output tax,
// but this isn't currently possible because V2Trade reconstructs the total inputAmount based on the swap routes
// TODO(WEB-2761): Amend V2Trade objects in the v2-sdk to have a separate field for post-input tax routes
return this.outputAmount.multiply(new Fraction(ONE).subtract(this.totalTaxRate))
return this.postSwapFeeOutputAmount.multiply(new Fraction(ONE).subtract(this.totalTaxRate))
}
public minimumAmountOut(slippageTolerance: Percent, amountOut = this.outputAmount): CurrencyAmount<Currency> {
......@@ -281,6 +314,7 @@ export class DutchOrderTrade extends IDutchOrderTrade<Currency, Currency, TradeT
inputTax = ZERO_PERCENT
outputTax = ZERO_PERCENT
swapFee: SwapFeeInfo | undefined
constructor({
currencyIn,
......@@ -296,6 +330,7 @@ export class DutchOrderTrade extends IDutchOrderTrade<Currency, Currency, TradeT
startTimeBufferSecs,
deadlineBufferSecs,
slippageTolerance,
swapFee,
}: {
currencyIn: Currency
currenciesOut: Currency[]
......@@ -310,6 +345,7 @@ export class DutchOrderTrade extends IDutchOrderTrade<Currency, Currency, TradeT
startTimeBufferSecs: number
deadlineBufferSecs: number
slippageTolerance: Percent
swapFee?: SwapFeeInfo
}) {
super({ currencyIn, currenciesOut, orderInfo, tradeType })
this.quoteId = quoteId
......@@ -321,6 +357,7 @@ export class DutchOrderTrade extends IDutchOrderTrade<Currency, Currency, TradeT
this.deadlineBufferSecs = deadlineBufferSecs
this.slippageTolerance = slippageTolerance
this.startTimeBufferSecs = startTimeBufferSecs
this.swapFee = swapFee
}
public get totalGasUseEstimateUSD(): number {
......
import { BigNumber } from '@ethersproject/bignumber'
import { MixedRouteSDK } from '@uniswap/router-sdk'
import { Currency, CurrencyAmount, Token, TradeType } from '@uniswap/sdk-core'
import { Currency, CurrencyAmount, Percent, Token, TradeType } from '@uniswap/sdk-core'
import { DutchOrderInfo, DutchOrderInfoJSON } from '@uniswap/uniswapx-sdk'
import { Pair, Route as V2Route } from '@uniswap/v2-sdk'
import { FeeAmount, Pool, Route as V3Route } from '@uniswap/v3-sdk'
import { BIPS_BASE } from 'constants/misc'
import { isAvalanche, isBsc, isMatic, nativeOnChain } from 'constants/tokens'
import { toSlippagePercent } from 'utils/slippage'
......@@ -23,9 +24,11 @@ import {
QuoteState,
RouterPreference,
SubmittableTrade,
SwapFeeInfo,
SwapRouterNativeAssets,
TradeFillType,
TradeResult,
URADutchOrderQuoteData,
URAQuoteResponse,
URAQuoteType,
V2PoolInRoute,
......@@ -152,6 +155,18 @@ function getTradeCurrencies(args: GetQuoteArgs | GetQuickQuoteArgs, isUniswapXTr
return [currencyIn.isNative ? currencyIn.wrapped : currencyIn, currencyOut]
}
function getSwapFee(data: ClassicQuoteData | URADutchOrderQuoteData): SwapFeeInfo | undefined {
const { portionAmount, portionBips, portionRecipient } = data
if (!portionAmount || !portionBips || !portionRecipient) return undefined
return {
recipient: portionRecipient,
percent: new Percent(portionBips, BIPS_BASE),
amount: portionAmount,
}
}
function getClassicTradeDetails(
currencyIn: Currency,
currencyOut: Currency,
......@@ -161,14 +176,19 @@ function getClassicTradeDetails(
gasUseEstimateUSD?: number
blockNumber?: string
routes?: RouteResult[]
swapFee?: SwapFeeInfo
} {
const classicQuote =
data.routing === URAQuoteType.CLASSIC ? data.quote : data.allQuotes.find(isClassicQuoteResponse)?.quote
if (!classicQuote) return {}
return {
gasUseEstimate: classicQuote?.gasUseEstimate ? parseFloat(classicQuote.gasUseEstimate) : undefined,
gasUseEstimateUSD: classicQuote?.gasUseEstimateUSD ? parseFloat(classicQuote.gasUseEstimateUSD) : undefined,
blockNumber: classicQuote?.blockNumber,
routes: classicQuote ? computeRoutes(currencyIn, currencyOut, classicQuote.route) : undefined,
gasUseEstimate: classicQuote.gasUseEstimate ? parseFloat(classicQuote.gasUseEstimate) : undefined,
gasUseEstimateUSD: classicQuote.gasUseEstimateUSD ? parseFloat(classicQuote.gasUseEstimateUSD) : undefined,
blockNumber: classicQuote.blockNumber,
routes: computeRoutes(currencyIn, currencyOut, classicQuote.route),
swapFee: getSwapFee(classicQuote),
}
}
......@@ -204,7 +224,7 @@ export async function transformRoutesToTrade(
(routerPreference === RouterPreference.X || (isUniswapXDefaultEnabled && routerPreference === RouterPreference.API))
const [currencyIn, currencyOut] = getTradeCurrencies(args, showUniswapXTrade)
const { gasUseEstimateUSD, blockNumber, routes, gasUseEstimate } = getClassicTradeDetails(
const { gasUseEstimateUSD, blockNumber, routes, gasUseEstimate, swapFee } = getClassicTradeDetails(
currencyIn,
currencyOut,
data
......@@ -254,12 +274,14 @@ export async function transformRoutesToTrade(
quoteMethod,
inputTax,
outputTax,
swapFee,
})
// During the opt-in period, only return UniswapX quotes if the user has turned on the setting,
// even if it is the better quote.
if (isUniswapXBetter && (routerPreference === RouterPreference.X || isUniswapXDefaultEnabled)) {
const orderInfo = toDutchOrderInfo(data.quote.orderInfo)
const swapFee = getSwapFee(data.quote)
const wrapInfo = await getWrapInfo(needsWrapIfUniswapX, account, currencyIn.chainId, amount, usdCostPerGas)
const uniswapXTrade = new DutchOrderTrade({
......@@ -276,6 +298,7 @@ export async function transformRoutesToTrade(
startTimeBufferSecs: data.quote.startTimeBufferSecs,
deadlineBufferSecs: data.quote.deadlineBufferSecs,
slippageTolerance: toSlippagePercent(data.quote.slippageTolerance),
swapFee,
})
return {
......
......@@ -6,13 +6,14 @@ import { useFotAdjustmentsEnabled } from 'featureFlags/flags/fotAdjustments'
import useAutoSlippageTolerance from 'hooks/useAutoSlippageTolerance'
import { useDebouncedTrade } from 'hooks/useDebouncedTrade'
import { useSwapTaxes } from 'hooks/useSwapTaxes'
import { useUSDPrice } from 'hooks/useUSDPrice'
import tryParseCurrencyAmount from 'lib/utils/tryParseCurrencyAmount'
import { ParsedQs } from 'qs'
import { ReactNode, useCallback, useEffect, useMemo } from 'react'
import { AnyAction } from 'redux'
import { useAppDispatch } from 'state/hooks'
import { InterfaceTrade, TradeState } from 'state/routing/types'
import { isClassicTrade, isUniswapXTrade } from 'state/routing/utils'
import { isClassicTrade, isSubmittableTrade, isUniswapXTrade } from 'state/routing/utils'
import { useUserSlippageToleranceWithDefault } from 'state/user/hooks'
import { TOKEN_SHORTHANDS } from '../../constants/tokens'
......@@ -82,6 +83,7 @@ export type SwapInfo = {
currencyBalances: { [field in Field]?: CurrencyAmount<Currency> }
inputTax: Percent
outputTax: Percent
outputFeeFiatValue?: number
parsedAmount?: CurrencyAmount<Currency>
inputError?: ReactNode
trade: {
......@@ -140,6 +142,13 @@ export function useDerivedSwapInfo(state: SwapState, chainId: ChainId | undefine
outputTax
)
const { data: outputFeeFiatValue } = useUSDPrice(
isSubmittableTrade(trade.trade) && trade.trade.swapFee
? CurrencyAmount.fromRawAmount(trade.trade.outputAmount.currency, trade.trade.swapFee.amount)
: undefined,
trade.trade?.outputAmount.currency
)
const currencyBalances = useMemo(
() => ({
[Field.INPUT]: relevantTokenBalances[0],
......@@ -215,8 +224,20 @@ export function useDerivedSwapInfo(state: SwapState, chainId: ChainId | undefine
allowedSlippage,
inputTax,
outputTax,
outputFeeFiatValue,
}),
[allowedSlippage, autoSlippage, currencies, currencyBalances, inputError, inputTax, outputTax, parsedAmount, trade]
[
allowedSlippage,
autoSlippage,
currencies,
currencyBalances,
inputError,
inputTax,
outputFeeFiatValue,
outputTax,
parsedAmount,
trade,
]
)
}
......
......@@ -188,7 +188,7 @@ describe('formatNumber', () => {
expect(formatNumber({ input: 1234567.891, type: NumberType.FiatGasPrice })).toBe('$1.23M')
expect(formatNumber({ input: 18.448, type: NumberType.FiatGasPrice })).toBe('$18.45')
expect(formatNumber({ input: 0.0099, type: NumberType.FiatGasPrice })).toBe('<$0.01')
expect(formatNumber({ input: 0, type: NumberType.FiatGasPrice })).toBe('$0.00')
expect(formatNumber({ input: 0, type: NumberType.FiatGasPrice })).toBe('$0')
})
it('formats gas prices correctly with portugese locale and thai baht currency', () => {
......@@ -199,7 +199,7 @@ describe('formatNumber', () => {
expect(formatNumber({ input: 1234567.891, type: NumberType.FiatGasPrice })).toBe('฿\xa01,23\xa0mi')
expect(formatNumber({ input: 18.448, type: NumberType.FiatGasPrice })).toBe('฿\xa018,45')
expect(formatNumber({ input: 0.0099, type: NumberType.FiatGasPrice })).toBe('<฿\xa00,01')
expect(formatNumber({ input: 0, type: NumberType.FiatGasPrice })).toBe('฿\xa00,00')
expect(formatNumber({ input: 0, type: NumberType.FiatGasPrice })).toBe('฿\xa00')
})
it('formats USD token quantities prices correctly', () => {
......
......@@ -39,6 +39,14 @@ const NO_DECIMALS: NumberFormatOptions = {
minimumFractionDigits: 0,
}
const NO_DECIMALS_CURRENCY: NumberFormatOptions = {
notation: 'standard',
maximumFractionDigits: 0,
minimumFractionDigits: 0,
currency: 'USD',
style: 'currency',
}
const THREE_DECIMALS_NO_TRAILING_ZEROS: NumberFormatOptions = {
notation: 'standard',
maximumFractionDigits: 3,
......@@ -262,7 +270,7 @@ const fiatTokenStatsFormatter: FormatterRule[] = [
]
const fiatGasPriceFormatter: FormatterRule[] = [
{ exact: 0, formatterOptions: TWO_DECIMALS_CURRENCY },
{ exact: 0, formatterOptions: NO_DECIMALS_CURRENCY },
{ upperBound: 0.01, hardCodedInput: { input: 0.01, prefix: '<' }, formatterOptions: TWO_DECIMALS_CURRENCY },
{ upperBound: 1e6, formatterOptions: TWO_DECIMALS_CURRENCY },
{ upperBound: Infinity, formatterOptions: SHORTHAND_CURRENCY_TWO_DECIMALS },
......
......@@ -6217,10 +6217,10 @@
resolved "https://registry.yarnpkg.com/@uniswap/token-lists/-/token-lists-1.0.0-beta.33.tgz#966ba96c9ccc8f0e9e09809890b438203f2b1911"
integrity sha512-JQkXcpRI3jFG8y3/CGC4TS8NkDgcxXaOQuYW8Qdvd6DcDiIyg2vVYCG9igFEzF0G6UvxgHkBKC7cWCgzZNYvQg==
"@uniswap/uniswapx-sdk@^1.3.0":
version "1.3.0"
resolved "https://registry.yarnpkg.com/@uniswap/uniswapx-sdk/-/uniswapx-sdk-1.3.0.tgz#22867580c7f5d5ee35d669444d093e09203e1b47"
integrity sha512-TXH0+3reXA/liY2IRbCRvPVyREDObKSVmd4vEtTD0sPM0NW6ndSowKDH0hWBj2d7lBnSNKz5fp7IOaFT7yHkug==
"@uniswap/uniswapx-sdk@^1.4.1":
version "1.4.1"
resolved "https://registry.yarnpkg.com/@uniswap/uniswapx-sdk/-/uniswapx-sdk-1.4.1.tgz#c5fc50000032aa714ff0cc4b9cd1957128a2a4ec"
integrity sha512-M7uuZdozWbXJq8J64KTJ9e0PkYcfe6lx7RBpIsvJaypkGgGDrmU1bAqr1j3sphHlzKTmJCuG7GZBFNcnvzxHLw==
dependencies:
"@ethersproject/bytes" "^5.7.0"
"@ethersproject/providers" "^5.7.0"
......@@ -6228,10 +6228,10 @@
"@uniswap/sdk-core" "^4.0.3"
ethers "^5.7.0"
"@uniswap/universal-router-sdk@^1.5.4", "@uniswap/universal-router-sdk@^1.5.6":
version "1.5.6"
resolved "https://registry.yarnpkg.com/@uniswap/universal-router-sdk/-/universal-router-sdk-1.5.6.tgz#274a6ac5df032c34544005fe329aa9e2aac9ade6"
integrity sha512-ZD27U+kugMRJRVEX0oWZsRCw1n5vBN3I17Q22IWE+w/WhOJSppUr6PLo9u4HRdqXTZET7gubnlRc0LOAEkkSkQ==
"@uniswap/universal-router-sdk@^1.5.4", "@uniswap/universal-router-sdk@^1.5.8":
version "1.5.8"
resolved "https://registry.yarnpkg.com/@uniswap/universal-router-sdk/-/universal-router-sdk-1.5.8.tgz#16c62c3883e99073ba8b6e19188cf418b6551847"
integrity sha512-9tDDBTXarpdRfJStF5mDCNmsQrCfiIT6HCQN1EPq0tAm2b+JzjRkUzsLpbNpVef066FETc3YjPH6JDPB3CMyyA==
dependencies:
"@uniswap/permit2-sdk" "^1.2.0"
"@uniswap/router-sdk" "^1.6.0"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment