Skip to content

Commit

Permalink
[NO CHANGELOGS] [Add funds Widget] Add additional buffer using aggreg…
Browse files Browse the repository at this point in the history
…atePriceImpact (#2307)
  • Loading branch information
jiyounglee authored Oct 15, 2024
1 parent 389df16 commit 1bbfa18
Show file tree
Hide file tree
Showing 5 changed files with 105 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export interface AddFundsReviewData {
toAmount: string;
toChainId: string;
toTokenAddress: string;
additionalBuffer: number;
}

export interface AddFundsConfirmationData {
Expand Down
123 changes: 94 additions & 29 deletions packages/checkout/widgets-lib/src/widgets/add-funds/hooks/useRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ import { Squid } from '@0xsquid/sdk';
import { utils } from 'ethers';
import { useContext, useRef } from 'react';
import { delay } from '../functions/delay';
import { AmountData, RouteData, Token } from '../types';
import {
AmountData, RouteData, RouteResponseData, Token,
} from '../types';
import { sortRoutesByFastestTime } from '../functions/sortRoutesByFastestTime';
import { AddFundsActions, AddFundsContext } from '../context/AddFundsContext';
import { retry } from '../../../lib/retry';
import { getFormattedNumber } from '../functions/getFormattedNumber';

export const useRoutes = () => {
const latestRequestIdRef = useRef<number>(0);
Expand Down Expand Up @@ -40,11 +43,12 @@ export const useRoutes = () => {
fromToken: Token,
toToken: Token,
toAmount: string,
additionalBuffer: number = 0,
) => {
const toAmountNumber = Number(toAmount);
const toAmountInUsd = toAmountNumber * toToken.usdPrice;
const baseFromAmount = toAmountInUsd / fromToken.usdPrice;
const fromAmountWithBuffer = baseFromAmount * 1.015;
const fromAmountWithBuffer = baseFromAmount * (1.02 + additionalBuffer);
return fromAmountWithBuffer.toString();
};

Expand All @@ -54,6 +58,7 @@ export const useRoutes = () => {
toAmount: string,
toChainId: string,
toTokenAddress: string,
additionalBuffer: number = 0,
): AmountData | undefined => {
const fromToken = findToken(
tokens,
Expand All @@ -66,10 +71,11 @@ export const useRoutes = () => {
}
return {
fromToken,
fromAmount: calculateFromAmount(fromToken, toToken, toAmount),
fromAmount: calculateFromAmount(fromToken, toToken, toAmount, additionalBuffer),
toToken,
toAmount,
balance,
additionalBuffer,
};
};

Expand Down Expand Up @@ -101,43 +107,101 @@ export const useRoutes = () => {
});
};

const convertToFormattedAmount = (amount : string, decimals:number) => {
const parsedFromAmount = parseFloat(amount).toFixed(
decimals,
);
const formattedFromAmount = utils.parseUnits(
parsedFromAmount,
decimals,
);
return formattedFromAmount.toString();
};

const getRouteWithRetry = async (
squid: Squid,
fromToken: Token,
toToken: Token,
toAddress: string,
fromAmount: string,
fromAddress?: string,
quoteOnly = true,
): Promise<RouteResponse | undefined> => await retry(
() => squid.getRoute({
fromChain: fromToken.chainId,
fromToken: fromToken.address,
fromAmount: convertToFormattedAmount(fromAmount, fromToken.decimals),
toChain: toToken.chainId,
toToken: toToken.address,
fromAddress,
toAddress,
quoteOnly,
enableBoost: true,
}),
{
retryIntervalMs: 1000,
retries: 5,
nonRetryable: (err: any) => err.response.status !== 429,
},
);

const isRouteToAmountGreaterThanToAmount = (routeResponse:RouteResponse, toAmount :string) => {
const routeToAmount = getFormattedNumber(
routeResponse?.route.estimate.toAmount,
routeResponse?.route.estimate.toToken.decimals,
);
return Number(routeToAmount) > Number(toAmount);
};

const getRoute = async (
squid: Squid,
fromToken: Token,
toToken: Token,
toAddress: string,
fromAmount: string,
toAmount: string,
fromAddress?: string,
quoteOnly = true,
): Promise<RouteResponse | undefined> => {
): Promise<RouteResponseData> => {
try {
const parsedFromAmount = parseFloat(fromAmount).toFixed(
fromToken.decimals,
const routeResponse = await getRouteWithRetry(
squid,
fromToken,
toToken,
toAddress,
fromAmount,
fromAddress,
quoteOnly,
);
const formattedFromAmount = utils.parseUnits(
parsedFromAmount,
fromToken.decimals,

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

const additionalBuffer = Math.abs(Number(routeResponse?.route.estimate.aggregatePriceImpact));
const newFromAmount = calculateFromAmount(
fromToken,
toToken,
toAmount,
additionalBuffer,
);
return await retry(
() => squid.getRoute({
fromChain: fromToken.chainId,
fromToken: fromToken.address,
fromAmount: formattedFromAmount.toString(),
toChain: toToken.chainId,
toToken: toToken.address,
fromAddress,
toAddress,
quoteOnly,
enableBoost: true,
}),
{
retryIntervalMs: 1000,
retries: 5,
nonRetryable: (err: any) => err.response.status !== 429,
},

const routeWithBufferResponse = await getRouteWithRetry(
squid,
fromToken,
toToken,
toAddress,
newFromAmount,
fromAddress,
quoteOnly,
);
if (isRouteToAmountGreaterThanToAmount(routeResponse, toAmount)) {
return { route: routeWithBufferResponse, additionalBuffer };
}
return {};
} catch (error) {
return undefined;
return {};
}
};

Expand All @@ -152,9 +216,10 @@ export const useRoutes = () => {
data.toToken,
toTokenAddress,
data.fromAmount,
data.toAmount,
).then((route) => ({
amountData: data,
route,
amountData: { ...data, additionalBuffer: route.additionalBuffer },
route: route.route,
})));

const routesData = await Promise.all(routePromises);
Expand Down
6 changes: 6 additions & 0 deletions packages/checkout/widgets-lib/src/widgets/add-funds/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,19 @@ export type AmountData = {
toToken: Token;
toAmount: string;
balance: TokenBalance;
additionalBuffer: number;
};

export type RouteData = {
amountData: AmountData;
route: RouteResponse;
};

export type RouteResponseData = {
route?: RouteResponse;
additionalBuffer?: number;
};

export enum FiatOptionType {
CREDIT = 'credit',
DEBIT = 'debit',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,7 @@ export function AddFunds({
toChainId: ChainId.IMTBL_ZKEVM_MAINNET.toString(),
toTokenAddress: selectedToken.address,
toAmount: selectedAmount,
additionalBuffer: selectedRouteData.amountData.additionalBuffer,
},
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ export function Review({
data.toTokenAddress === 'native'
? SQUID_NATIVE_TOKEN
: data.toTokenAddress,
data.additionalBuffer,
);

if (!amountData) return;

const routeResponse = await getRoute(
Expand All @@ -145,10 +145,11 @@ export function Review({
amountData?.toToken,
toAddress,
amountData.fromAmount,
amountData.toAmount,
fromAddress,
false,
);
setRoute(routeResponse);
setRoute(routeResponse.route);
setProceedDisabled(false);
};

Expand Down

0 comments on commit 1bbfa18

Please sign in to comment.