From f3843eb8c6b03ce6f301e4a3b8846a79106258a3 Mon Sep 17 00:00:00 2001 From: Daniel Dimitrov Date: Tue, 4 Jun 2024 11:29:19 +0200 Subject: [PATCH] fix: switch between swap & limit loses token (#3791) We were re-rendering the widget when teh user switches between swap and a limit swap and this was causing the sellToken to reset. --- next-env.d.ts | 1 - src/features/swap/index.tsx | 26 +++++++++++++++++--------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/next-env.d.ts b/next-env.d.ts index fd36f9494e..4f11a03dc6 100644 --- a/next-env.d.ts +++ b/next-env.d.ts @@ -1,6 +1,5 @@ /// /// -/// // NOTE: This file should not be edited // see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/src/features/swap/index.tsx b/src/features/swap/index.tsx index 4bf4acc661..e420263099 100644 --- a/src/features/swap/index.tsx +++ b/src/features/swap/index.tsx @@ -55,6 +55,14 @@ const SwapWidget = ({ sell }: Params) => { const [blockedAddress, setBlockedAddress] = useState('') const wallet = useWallet() const { isConsentAccepted, onAccept } = useSwapConsent() + // useRefs as they don't trigger re-renders + const tradeTypeRef = useRef(tradeType) + const sellTokenRef = useRef( + sell || { + asset: '', + amount: '0', + }, + ) useEffect(() => { if (isBlockedAddress(safeAddress)) { @@ -136,9 +144,14 @@ const SwapWidget = ({ sell }: Params) => { { event: CowEvents.ON_CHANGE_TRADE_PARAMS, handler: (newTradeParams) => { - const { orderType: tradeType, recipient } = newTradeParams + const { orderType: tradeType, recipient, sellToken, sellTokenAmount } = newTradeParams dispatch(setSwapParams({ tradeType })) + tradeTypeRef.current = tradeType + sellTokenRef.current = { + asset: sellToken?.symbol || '', + amount: sellTokenAmount?.units || '0', + } if (recipient && isBlockedAddress(recipient)) { setBlockedAddress(recipient) } @@ -164,13 +177,8 @@ const SwapWidget = ({ sell }: Params) => { orderExecuted: null, postOrder: null, }, - tradeType, // TradeType.SWAP or TradeType.LIMIT - sell: sell - ? sell - : { - asset: '', - amount: '0', - }, + tradeType: tradeTypeRef.current, + sell: sellTokenRef.current, images: { emptyOrders: darkMode ? BASE_URL + '/images/common/swap-empty-dark.svg' @@ -195,7 +203,7 @@ const SwapWidget = ({ sell }: Params) => { 'Any future transaction fee incurred by Cow Protocol here will contribute to a license fee that supports the Safe Community. Neither Safe Ecosystem Foundation nor Core Contributors GmbH operate the CoW Swap Widget and/or Cow Swap.', }, }) - }, [sell, palette, darkMode, tradeType, chainId]) + }, [sell, palette, darkMode, chainId]) const chain = useCurrentChain()