Skip to content

Commit

Permalink
refactor: generalise useRoute hook (#2491)
Browse files Browse the repository at this point in the history
  • Loading branch information
mimi-imtbl authored Jan 10, 2025
1 parent cf35f95 commit 281e100
Show file tree
Hide file tree
Showing 9 changed files with 386 additions and 344 deletions.
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);
}
}
10 changes: 10 additions & 0 deletions packages/checkout/widgets-lib/src/lib/squid/functions/findToken.ts
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

0 comments on commit 281e100

Please sign in to comment.