Skip to content

Commit f6db4ef

Browse files
authored
Merge pull request #48 from dhruvi-16-me/fix/swap-preserve-amounts
fix(swap): preserve and recalculate amounts when swapping tokens
2 parents 972e8a3 + d1b268c commit f6db4ef

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

components/swap/swap-interface.tsx

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"use client";
22

3-
import { useState, useEffect, useMemo } from "react";
3+
import { useState, useEffect, useMemo, useRef } from "react";
44
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
55
import { TokenSelector } from "@/components/swap/token-selector";
66
import { SwapPreviewModal } from "@/components/swap/swap-preview-modal";
@@ -67,6 +67,9 @@ export function SwapInterface() {
6767
const [slippageTolerance, setSlippageTolerance] = useState<number>(0); // Start at 0 for zero slippage mode
6868
const [validationError, setValidationError] = useState<string>("");
6969
const [zeroSlippageMode, setZeroSlippageMode] = useState<boolean>(true); // Default to zero slippage mode
70+
const swapJustHappenedRef = useRef(false);
71+
const tokenInSellPriceForRef = useRef<Token | null>(null);
72+
const tokenOutBuyPriceForRef = useRef<Token | null>(null);
7073

7174
const calculateOutput = (amount: string, isInput: boolean) => {
7275
setValidationError("");
@@ -183,6 +186,7 @@ export function SwapInterface() {
183186
const newExchangeRate = tokenOutBuyPrice / newSellPrice;
184187

185188
setTokenInSellPrice(newSellPrice);
189+
tokenInSellPriceForRef.current = token;
186190
setEthInReserve(reserve?.ethReserve);
187191

188192
setSwapState((prev) => {
@@ -222,6 +226,7 @@ export function SwapInterface() {
222226
const newExchangeRate = newBuyPrice / tokenInSellPrice;
223227
setTokenOutReserve(reserve?.tokenReserve);
224228
setTokenOutBuyPrice(newBuyPrice);
229+
tokenOutBuyPriceForRef.current = token;
225230

226231
setSwapState((prev) => {
227232
const formattedExchangeRate =
@@ -250,20 +255,19 @@ export function SwapInterface() {
250255
setIsSwapping(true);
251256
setValidationError(""); // Clear validation error when swapping
252257
try {
253-
// Store the current tokens before swapping
254258
const currentTokenIn = swapState.tokenIn;
255259
const currentTokenOut = swapState.tokenOut;
256260

257-
// Swap the tokens in state first
261+
// Swap tokens but preserve amounts; recalc will run after rates update (useEffect)
258262
setSwapState((prev) => ({
263+
...prev,
259264
tokenIn: prev.tokenOut,
260265
tokenOut: prev.tokenIn,
261-
amountIn: "",
262-
amountOut: "",
263-
exchangeRate: prev.exchangeRate, // Keep current rate temporarily
266+
// Keep amountIn/amountOut so we can recalc for new direction after prices load
264267
}));
268+
swapJustHappenedRef.current = true;
265269

266-
// Now update the exchange rates for the swapped tokens
270+
// Update exchange rates for the swapped tokens (async)
267271
await handletokenInChange(currentTokenOut);
268272
await handletokenOutChange(currentTokenIn);
269273
} catch (error) {
@@ -273,6 +277,21 @@ export function SwapInterface() {
273277
}
274278
};
275279

280+
// After swap, recalc the other amount only when both prices match the current token pair
281+
useEffect(() => {
282+
if (!swapJustHappenedRef.current) return;
283+
if (!swapState.tokenIn || !swapState.tokenOut || !tokenInSellPrice || !tokenOutBuyPrice) return;
284+
const sellPriceForCurrentIn = tokenInSellPriceForRef.current?.address === swapState.tokenIn?.address;
285+
const buyPriceForCurrentOut = tokenOutBuyPriceForRef.current?.address === swapState.tokenOut?.address;
286+
if (!sellPriceForCurrentIn || !buyPriceForCurrentOut) return;
287+
swapJustHappenedRef.current = false;
288+
if (swapState.amountIn) {
289+
setSwapState((prev) => ({ ...prev, amountOut: calculateOutput(prev.amountIn, true) }));
290+
} else if (swapState.amountOut) {
291+
setSwapState((prev) => ({ ...prev, amountIn: calculateOutput(prev.amountOut, false) }));
292+
}
293+
}, [swapState.tokenIn, swapState.tokenOut, tokenInSellPrice, tokenOutBuyPrice, swapState.amountIn, swapState.amountOut]);
294+
276295
const handlePreviewSwap = () => {
277296
if (
278297
!swapState.amountIn ||

0 commit comments

Comments
 (0)