Skip to content

Commit

Permalink
[NO CHANGELOG] [Add Funds Widget] Refactor useRoutes to compare bignu…
Browse files Browse the repository at this point in the history
…ms (#2344)
  • Loading branch information
mimi-imtbl authored Oct 23, 2024
1 parent 7a8eea0 commit 24a7fd2
Showing 1 changed file with 25 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { TokenBalance } from '@0xsquid/sdk/dist/types';
import { RouteResponse } from '@0xsquid/squid-types';
import { Squid } from '@0xsquid/sdk';
import { utils } from 'ethers';
import { BigNumber, utils } from 'ethers';
import { useContext, useRef } from 'react';
import { delay } from '../functions/delay';
import {
Expand All @@ -10,7 +10,6 @@ import {
import { sortRoutesByFastestTime } from '../functions/sortRoutesByFastestTime';
import { AddFundsActions, AddFundsContext } from '../context/AddFundsContext';
import { retry } from '../../../lib/retry';
import { getFormattedNumber } from '../functions/getFormattedNumber';
import { useAnalytics, UserJourney } from '../../../context/analytics-provider/SegmentAnalyticsProvider';

const BASE_SLIPPAGE = 0.02;
Expand Down Expand Up @@ -50,18 +49,22 @@ export const useRoutes = () => {
toAmount: string,
additionalBuffer: number = 0,
) => {
const toAmountNumber = Number(toAmount);
const toAmountNumber = parseFloat(toAmount);
// Calculate the USD value of the toAmount
const toAmountInUsd = toAmountNumber * toToken.usdPrice;
// Calculate the amount of fromToken needed to match this USD value
const baseFromAmount = toAmountInUsd / fromToken.usdPrice;
// Add a buffer for price fluctuations and fees
const fromAmountWithBuffer = baseFromAmount * (1 + BASE_SLIPPAGE + additionalBuffer);

return fromAmountWithBuffer.toString();
};

const calculateFromAmountFromRoute = (
exchangeRate: string,
toAmount: string,
) => {
const fromAmount = Number(toAmount) / Number(exchangeRate);
const fromAmount = parseFloat(toAmount) / parseFloat(exchangeRate);
const fromAmountWithBuffer = fromAmount * (1 + BASE_SLIPPAGE);
return fromAmountWithBuffer.toString();
};
Expand All @@ -80,9 +83,11 @@ export const useRoutes = () => {
balance.chainId.toString(),
);
const toToken = findToken(tokens, toTokenAddress, toChainId);

if (!fromToken || !toToken) {
return undefined;
}

return {
fromToken,
fromAmount: calculateFromAmount(
Expand Down Expand Up @@ -111,6 +116,7 @@ export const useRoutes = () => {
&& balance.chainId === toChainId
),
);

const amountDataArray: AmountData[] = filteredBalances
.map((balance) => getAmountData(tokens, balance, toAmount, toChainId, toTokenAddress))
.filter((value) => value !== undefined);
Expand All @@ -120,6 +126,7 @@ export const useRoutes = () => {
data.balance.balance,
data.balance.decimals,
);

return (
parseFloat(formattedBalance.toString()) > parseFloat(data.fromAmount)
);
Expand Down Expand Up @@ -163,11 +170,13 @@ export const useRoutes = () => {
routeResponse: RouteResponse,
toAmount: string,
) => {
const routeToAmount = getFormattedNumber(
routeResponse?.route.estimate.toAmount,
routeResponse?.route.estimate.toToken.decimals,
);
return Number(routeToAmount) > Number(toAmount);
if (!routeResponse?.route?.estimate?.toAmount || !routeResponse?.route?.estimate?.toToken?.decimals) {
throw new Error('Invalid route response or token decimals');
}

const toAmountInBaseUnits = utils.parseUnits(toAmount, routeResponse?.route.estimate.toToken.decimals);
const routeToAmountInBaseUnits = BigNumber.from(routeResponse.route.estimate.toAmount);
return routeToAmountInBaseUnits.gt(toAmountInBaseUnits);
};

const getRoute = async (
Expand All @@ -194,13 +203,16 @@ export const useRoutes = () => {
if (!routeResponse?.route) {
return {};
}

if (isRouteToAmountGreaterThanToAmount(routeResponse, toAmount)) {
return { route: routeResponse };
}

const newFromAmount = calculateFromAmountFromRoute(
routeResponse.route.estimate.exchangeRate,
toAmount,
);

const newRoute = await getRouteWithRetry(
squid,
fromToken,
Expand All @@ -210,12 +222,15 @@ export const useRoutes = () => {
fromAddress,
quoteOnly,
);

if (!newRoute?.route) {
return {};
}

if (isRouteToAmountGreaterThanToAmount(newRoute, toAmount)) {
return { route: newRoute };
}

track({
userJourney: UserJourney.ADD_FUNDS,
screen: 'Routes',
Expand Down Expand Up @@ -265,6 +280,7 @@ export const useRoutes = () => {
})));

const routesData = await Promise.all(routePromises);

return routesData.filter(
(route): route is RouteData => route?.route !== undefined,
);
Expand Down

0 comments on commit 24a7fd2

Please sign in to comment.