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

refactor: generalise useRoute hook #2491

Merged
merged 11 commits into from
Jan 10, 2025
17 changes: 17 additions & 0 deletions packages/checkout/widgets-lib/src/lib/squid/RouteError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export class RouteError extends Error {
constructor(
public message: string,
public data?: {
fromToken?: string;
toToken?: string;
fromChain?: string | number;
toChain?: string | number;
errorStatus?: number;
errorMessage?: string;
errorStack?: string;
},
) {
super(message);
Object.setPrototypeOf(this, RouteError.prototype);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Token } from '../types';

export const findToken = (
tokens: Token[],
address: string,
chainId: string,
): Token | undefined => tokens.find(
(value) => value.address.toLowerCase() === address.toLowerCase()
&& value.chainId === chainId,
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { RouteResponse } from '@0xsquid/squid-types';
import { BigNumber, utils } from 'ethers';

export const isRouteToAmountGreaterThanToAmount = (
routeResponse: RouteResponse,
toAmount: string,
) => {
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);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useMemo } from 'react';
import { utils } from 'ethers';
import { useSlippage } from './useSlippage';
import { Token } from '../types';

/**
* Hook to handle route amount calculations.
*/
export const useRouteCalculation = () => {
const { calculateAdjustedAmount } = useSlippage();

/**
* Calculate the fromAmount based on USD prices and slippage.
*/
const calculateFromAmount = (
fromToken: Token,
toToken: Token,
toAmount: string,
additionalBuffer: number = 0,
) => {
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 = calculateAdjustedAmount(baseFromAmount, toAmountInUsd, additionalBuffer);

return fromAmountWithBuffer.toString();
};

/**
* Calculate the fromAmount using exchange rate returned from the route.
*/
const calculateFromAmountFromRoute = (
exchangeRate: string,
toAmount: string,
toAmountUSD?: string,
) => {
const toAmountUSDNumber = toAmountUSD ? parseFloat(toAmountUSD) : 0;
const fromAmount = parseFloat(toAmount) / parseFloat(exchangeRate);
const fromAmountWithBuffer = calculateAdjustedAmount(fromAmount, toAmountUSDNumber);
return fromAmountWithBuffer.toString();
};

/**
* Convert a string amount to a formatted amount with the specified number of decimals.
*/
const convertToFormattedFromAmount = (amount: string, decimals: number) => {
const parsedFromAmount = parseFloat(amount).toFixed(decimals);
const formattedFromAmount = utils.parseUnits(parsedFromAmount, decimals);
return formattedFromAmount.toString();
};

return useMemo(() => ({
calculateFromAmount,
calculateFromAmountFromRoute,
convertToFormattedFromAmount,
}), []);
};
Loading
Loading