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

feat: allow to use same tokens for hooks #5075

Draft
wants to merge 3 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions apps/cowswap-frontend/src/api/cowProtocol/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ import { ApiErrorCodes } from './errors/OperatorError'
import QuoteApiError, { mapOperatorErrorToQuoteError, QuoteApiErrorDetails } from './errors/QuoteError'
import { getIsOrderBookTypedError } from './getIsOrderBookTypedError'


function getProfileUrl(): Partial<Record<ChainId, string>> {
if (isLocal || isDev || isPr || isBarn) {
return {
Expand Down Expand Up @@ -157,16 +156,16 @@ function _getAppDataQuoteParams(params: FeeQuoteParams) {
export async function getQuote(params: FeeQuoteParams): Promise<OrderQuoteResponse> {
const { chainId } = params
const quoteParams = _mapNewToLegacyParams(params)
const { sellToken, buyToken } = quoteParams

if (sellToken === buyToken) {
return Promise.reject(
mapOperatorErrorToQuoteError({
errorType: ApiErrorCodes.SameBuyAndSellToken,
description: QuoteApiErrorDetails.SameBuyAndSellToken,
}),
)
}
// const { sellToken, buyToken } = quoteParams

// if (sellToken === buyToken) {
// return Promise.reject(
// mapOperatorErrorToQuoteError({
// errorType: ApiErrorCodes.SameBuyAndSellToken,
// description: QuoteApiErrorDetails.SameBuyAndSellToken,
// }),
// )
// }

return orderBookApi.getQuote(quoteParams, { chainId }).catch((error) => {
if (getIsOrderBookTypedError(error)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ function handleQuoteError({ quoteData, error, addUnsupportedToken }: HandleQuote

// Some other error getting the quote ocurred
console.error('Error quoting price/fee: ' + error)
console.error(error)
return 'fetch-quote-error'
}
}
Expand Down
2 changes: 1 addition & 1 deletion apps/cowswap-frontend/src/legacy/utils/price.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export async function getBestQuote({
console.warn(
'[GP PRICE::API] getBestQuote - error using COWSWAP price strategy, reason: [',
err,
'] - trying back up price sources...'
'] - trying back up price sources...',
)
// ATTEMPT LEGACY CALL
return getBestQuote({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export function AdvancedOrdersWidget({
orderKind,
isUnlocked,
} = useAdvancedOrdersDerivedState()
const actions = useAdvancedOrdersActions()
const actions = useAdvancedOrdersActions({ allowSameToken: false })
const { isLoading: isTradePriceUpdating } = useTradeQuote()
const { showRecipient } = useAtomValue(advancedOrdersSettingsAtom)
const priceImpact = useTradePriceImpact()
Expand Down Expand Up @@ -124,6 +124,7 @@ export function AdvancedOrdersWidget({
isTradePriceUpdating,
priceImpact,
disablePriceImpact,
allowSameToken: false,
}

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import { useAdvancedOrdersDerivedState } from './useAdvancedOrdersDerivedState'
import { useUpdateAdvancedOrdersRawState } from './useAdvancedOrdersRawState'

// TODO: this should be also unified for each trade widget (swap, limit, advanced)
export function useAdvancedOrdersActions() {
export function useAdvancedOrdersActions({ allowSameToken }: { allowSameToken: boolean }) {
const { inputCurrency } = useAdvancedOrdersDerivedState()

const naviageOnCurrencySelection = useNavigateOnCurrencySelection()
const naviageOnCurrencySelection = useNavigateOnCurrencySelection({ allowSameToken })
const updateCurrencyAmount = useUpdateCurrencyAmount()
const resetTradeQuote = useResetTradeQuote()

Expand All @@ -33,7 +33,7 @@ export function useAdvancedOrdersActions() {
naviageOnCurrencySelection(field, currency)
resetTradeQuote()
},
[naviageOnCurrencySelection, updateCurrencyAmount, resetTradeQuote]
[naviageOnCurrencySelection, updateCurrencyAmount, resetTradeQuote],
)

const onUserInput = useCallback(
Expand All @@ -45,14 +45,14 @@ export function useAdvancedOrdersActions() {
field,
})
},
[inputCurrency, updateCurrencyAmount]
[inputCurrency, updateCurrencyAmount],
)

const onChangeRecipient = useCallback(
(recipient: string | null) => {
updateAdvancedOrdersState({ recipient })
},
[updateAdvancedOrdersState]
[updateAdvancedOrdersState],
)

const onSwitchTokensDefault = useSwitchTokensPlaces({
Expand All @@ -71,6 +71,6 @@ export function useAdvancedOrdersActions() {
onChangeRecipient,
onSwitchTokens,
}),
[onCurrencySelection, onUserInput, onChangeRecipient, onSwitchTokens]
[onCurrencySelection, onUserInput, onChangeRecipient, onSwitchTokens],
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function HooksStoreWidget() {
}, [chainId, isChainIdUnsupported, onDismiss])

useSetupHooksStoreOrderParams()
useSetRecipientOverride()
useSetRecipientOverride({ allowSameToken: true })

const isHookSelectionOpen = !!(selectedHookPosition || hookToEdit)
const hideSwapWidget = isHookSelectionOpen || isRescueWidgetOpen
Expand Down Expand Up @@ -114,7 +114,7 @@ export function HooksStoreWidget() {
return (
<>
<TradeWidgetWrapper visible$={!hideSwapWidget}>
<SwapWidget topContent={TopContent} bottomContent={BottomContent} />
<SwapWidget topContent={TopContent} bottomContent={BottomContent} allowSameToken />
</TradeWidgetWrapper>
<IframeDappsManifestUpdater />
{isHookSelectionOpen && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { useIsHooksTradeType, useIsNativeIn } from 'modules/trade'

import { usePostHooksRecipientOverride } from './usePostHooksRecipientOverride'

export function useSetRecipientOverride() {
const { onChangeRecipient } = useSwapActionHandlers()
export function useSetRecipientOverride({ allowSameToken }: { allowSameToken: boolean }): void {
const { onChangeRecipient } = useSwapActionHandlers({ allowSameToken })
const hookRecipientOverride = usePostHooksRecipientOverride()
const isHooksTradeType = useIsHooksTradeType()
const isNativeIn = useIsNativeIn()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export function LimitOrdersWarnings(props: LimitOrdersWarningsProps) {

{/*// TODO: must be replaced by <NotificationBanner>*/}
{showHighFeeWarning && <SmallVolumeWarningBanner feeAmount={feeAmount} feePercentage={feePercentage} />}
{showNativeSellWarning && <SellNativeWarningBanner />}
{showNativeSellWarning && <SellNativeWarningBanner allowSameToken={false} />}
</Wrapper>
) : null
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ import { useIsWrapOrUnwrap } from 'modules/trade/hooks/useIsWrapOrUnwrap'
import { useOnCurrencySelection } from 'modules/trade/hooks/useOnCurrencySelection'
import { useSwitchTokensPlaces } from 'modules/trade/hooks/useSwitchTokensPlaces'

export function useLimitOrdersWidgetActions(): TradeWidgetActions {
export function useLimitOrdersWidgetActions({ allowSameToken }: { allowSameToken: boolean }): TradeWidgetActions {
const { inputCurrency, outputCurrency, orderKind } = useLimitOrdersDerivedState()
const { activeRate } = useAtomValue(limitRateAtom)
const isWrapOrUnwrap = useIsWrapOrUnwrap()
const updateCurrencyAmount = useUpdateCurrencyAmount()

const updateLimitOrdersState = useUpdateLimitOrdersRawState()

const onCurrencySelection = useOnCurrencySelection()
const onCurrencySelection = useOnCurrencySelection({ allowSameToken })

const onUserInput = useCallback(
(field: Field, typedValue: string) => {
Expand All @@ -42,7 +42,7 @@ export function useLimitOrdersWidgetActions(): TradeWidgetActions {
orderKind: isWrapOrUnwrap || field === Field.INPUT ? OrderKind.SELL : OrderKind.BUY,
})
},
[updateCurrencyAmount, isWrapOrUnwrap, inputCurrency, outputCurrency, activeRate]
[updateCurrencyAmount, isWrapOrUnwrap, inputCurrency, outputCurrency, activeRate],
)

const onSwitchTokens = useSwitchTokensPlaces({
Expand All @@ -51,11 +51,11 @@ export function useLimitOrdersWidgetActions(): TradeWidgetActions {

const onChangeRecipient = useCallback(
(recipient: string | null) => updateLimitOrdersState({ recipient }),
[updateLimitOrdersState]
[updateLimitOrdersState],
)

return useMemo(
() => ({ onUserInput, onSwitchTokens, onChangeRecipient, onCurrencySelection }),
[onUserInput, onSwitchTokens, onChangeRecipient, onCurrencySelection]
[onUserInput, onSwitchTokens, onChangeRecipient, onCurrencySelection],
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export function LimitOrdersWidget() {
const { feeAmount } = useAtomValue(limitRateAtom)
const { isLoading: isRateLoading } = useTradeQuote()
const rateInfoParams = useRateInfoParams(inputCurrencyAmount, outputCurrencyAmount)
const widgetActions = useLimitOrdersWidgetActions()
const widgetActions = useLimitOrdersWidgetActions({ allowSameToken: false })
const isWrapOrUnwrap = useIsWrapOrUnwrap()

const { showRecipient: showRecipientSetting } = settingsState
Expand Down Expand Up @@ -228,6 +228,7 @@ const LimitOrders = React.memo((props: LimitOrdersProps) => {
disablePriceImpact: localFormValidation === LimitOrdersFormState.FeeExceedsFrom,
disableQuotePolling: isConfirmOpen,
hideTradeWarnings: !!localFormValidation,
allowSameToken: false,
}

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ export interface EthFlowActions {
directSwap(): void
}

export function useEthFlowActions(callbacks: EthFlowActionCallbacks): EthFlowActions {
export function useEthFlowActions(callbacks: EthFlowActionCallbacks, allowSameToken: boolean): EthFlowActions {
const { chainId } = useWalletInfo()
const { trade } = useDerivedSwapInfo()

const updateEthFlowContext = useSetAtom(updateEthFlowContextAtom)

const { onCurrencySelection } = useSwapActionHandlers()
const { onCurrencySelection } = useSwapActionHandlers({ allowSameToken })
const { onOpen: openSwapConfirmModal } = useTradeConfirmActions()

return useMemo(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ import { useEthFlowActions } from './hooks/useEthFlowActions'
import useRemainingNativeTxsAndCosts from './hooks/useRemainingNativeTxsAndCosts'
import { useSetupEthFlow } from './hooks/useSetupEthFlow'


export interface EthFlowProps {
nativeInput?: CurrencyAmount<Currency>
hasEnoughWrappedBalanceForSwap: boolean
wrapCallback: WrapUnwrapCallback | null
directSwapCallback: HandleSwapCallback
onDismiss: Command
allowSameToken: boolean
}

export function EthFlowModal({
Expand All @@ -40,6 +40,7 @@ export function EthFlowModal({
wrapCallback,
directSwapCallback,
hasEnoughWrappedBalanceForSwap,
allowSameToken,
}: EthFlowProps) {
const { chainId } = useWalletInfo()
const native = useNativeCurrency()
Expand All @@ -48,14 +49,17 @@ export function EthFlowModal({

const ethFlowContext = useAtomValue(ethFlowContextAtom)
const approveCallback = useTradeApproveCallback(
(nativeInput && currencyAmountToTokenAmount(nativeInput)) || undefined
(nativeInput && currencyAmountToTokenAmount(nativeInput)) || undefined,
)
const ethFlowActions = useEthFlowActions(
{
wrap: wrapCallback,
approve: approveCallback,
dismiss: onDismiss,
directSwap: directSwapCallback,
},
allowSameToken,
)
const ethFlowActions = useEthFlowActions({
wrap: wrapCallback,
approve: approveCallback,
dismiss: onDismiss,
directSwap: directSwapCallback,
})

const approveActivity = useSingleActivityDescriptor({ chainId, id: ethFlowContext.approve.txHash || undefined })
const wrapActivity = useSingleActivityDescriptor({ chainId, id: ethFlowContext.wrap.txHash || undefined })
Expand Down Expand Up @@ -86,7 +90,7 @@ export function EthFlowModal({
approvalState,
approveActivity,
wrapActivity,
onDismiss
onDismiss,
})

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useTradeSlippage, useIsSmartSlippageApplied } from 'modules/tradeSlippa
import { SwapAmountsFromUrlUpdater } from '../../updaters/SwapAmountsFromUrlUpdater'
import { SwapDerivedStateUpdater } from '../../updaters/SwapDerivedStateUpdater'

export function SwapUpdaters() {
export function SwapUpdaters({ allowSameToken }: { allowSameToken: boolean }) {
const slippage = useTradeSlippage()
const isSmartSlippageApplied = useIsSmartSlippageApplied()

Expand All @@ -18,7 +18,7 @@ export function SwapUpdaters() {
isSmartSlippage={isSmartSlippageApplied}
/>
<SwapDerivedStateUpdater />
<SwapAmountsFromUrlUpdater />
<SwapAmountsFromUrlUpdater allowSameToken={allowSameToken} />
</>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,17 @@ import { ConfirmSwapModalSetup } from '../ConfirmSwapModalSetup'
export interface SwapWidgetProps {
topContent?: ReactNode
bottomContent?: ReactNode
allowSameToken?: boolean
}

export function SwapWidget({ topContent, bottomContent }: SwapWidgetProps) {
export function SwapWidget({ topContent, bottomContent, allowSameToken = false }: SwapWidgetProps) {
const { chainId } = useWalletInfo()
const { currencies, trade } = useDerivedSwapInfo()
const slippage = useTradeSlippage()
const parsedAmounts = useSwapCurrenciesAmounts()
const { isSupportedWallet } = useWalletDetails()
const isSwapUnsupported = useIsTradeUnsupported(currencies.INPUT, currencies.OUTPUT)
const swapActions = useSwapActionHandlers()
const swapActions = useSwapActionHandlers({ allowSameToken })
const swapState = useSwapState()
const { independentField, recipient } = swapState
const showRecipientControls = useShowRecipientControls(recipient)
Expand Down Expand Up @@ -169,6 +170,7 @@ export function SwapWidget({ topContent, bottomContent }: SwapWidgetProps) {
openNativeWrapModal,
},
swapActions,
allowSameToken,
)

const tradeUrlParams = useTradeRouteContext()
Expand All @@ -181,6 +183,7 @@ export function SwapWidget({ topContent, bottomContent }: SwapWidgetProps) {
wrapCallback: swapButtonContext.onWrapOrUnwrap,
directSwapCallback: swapButtonContext.handleSwap,
hasEnoughWrappedBalanceForSwap: swapButtonContext.hasEnoughWrappedBalanceForSwap,
allowSameToken,
}

const swapModalsProps: SwapModalsProps = {
Expand Down Expand Up @@ -255,6 +258,7 @@ export function SwapWidget({ topContent, bottomContent }: SwapWidgetProps) {
priceImpact: priceImpactParams,
disableQuotePolling: true,
tradeQuoteStateOverride,
allowSameToken,
}

useSetLocalTimeOffset(getQuoteTimeOffset(swapButtonContext.quoteDeadlineParams))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ import { useSwapActionHandlers } from './useSwapState'
*
* In case when both sellAmount and buyAmount specified, buyAmount will be ignored
*/
export function useSetupSwapAmountsFromUrl() {
export function useSetupSwapAmountsFromUrl({ allowSameToken }: { allowSameToken: boolean }): void {
const { search, pathname } = useLocation()
const navigate = useNavigate()
const params = useMemo(() => new URLSearchParams(search), [search])
const { onUserInput } = useSwapActionHandlers()
const { onUserInput } = useSwapActionHandlers({ allowSameToken })

const cleanParams = useCallback(() => {
const queryParams = new URLSearchParams(search)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ export interface SwapButtonInput {
openNativeWrapModal(): void
}

export function useSwapButtonContext(input: SwapButtonInput, actions: TradeWidgetActions): SwapButtonsContext {
export function useSwapButtonContext(
input: SwapButtonInput,
actions: TradeWidgetActions,
allowSameToken: boolean,
): SwapButtonsContext {
const { feeWarningAccepted, impactWarningAccepted, openNativeWrapModal } = input

const { account, chainId } = useWalletInfo()
Expand All @@ -52,7 +56,7 @@ export function useSwapButtonContext(input: SwapButtonInput, actions: TradeWidge
inputError: swapInputError,
} = useDerivedSwapInfo()
const toggleWalletModal = useToggleWalletModal()
const { onCurrencySelection } = useSwapActionHandlers()
const { onCurrencySelection } = useSwapActionHandlers({ allowSameToken })
const isBestQuoteLoading = useIsBestQuoteLoading()
const tradeConfirmActions = useTradeConfirmActions()
const { standaloneMode } = useInjectedWidgetParams()
Expand Down
4 changes: 2 additions & 2 deletions apps/cowswap-frontend/src/modules/swap/hooks/useSwapState.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,10 @@ interface DerivedSwapInfo {
trade: TradeGp | undefined
}

export function useSwapActionHandlers(): TradeWidgetActions {
export function useSwapActionHandlers({ allowSameToken }: { allowSameToken: boolean }): TradeWidgetActions {
const { chainId } = useWalletInfo()
const dispatch = useAppDispatch()
const onCurrencySelection = useNavigateOnCurrencySelection()
const onCurrencySelection = useNavigateOnCurrencySelection({ allowSameToken })
const navigate = useTradeNavigate()
const swapState = useSwapState()

Expand Down
Loading
Loading